context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using BasicTestApp; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure; using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures; using Microsoft.AspNetCore.E2ETesting; using Microsoft.AspNetCore.Testing; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; using Xunit; using Xunit.Abstractions; namespace Microsoft.AspNetCore.Components.E2ETest.Tests { public class JSRootComponentsTest : ServerTestBase<ToggleExecutionModeServerFixture<Program>> { protected IWebElement app; public JSRootComponentsTest( BrowserFixture browserFixture, ToggleExecutionModeServerFixture<Program> serverFixture, ITestOutputHelper output) : base(browserFixture, serverFixture, output) { } protected override void InitializeAsyncCore() { Navigate(ServerPathBase, noReload: false); app = Browser.MountTestComponent<JavaScriptRootComponents>(); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] public void CanAddAndDisposeRootComponents(bool intoBlazorUi, bool attachShadowRoot) { var message = app.FindElement(By.Id("message")); if (attachShadowRoot) { app.FindElement(By.Id("add-shadow-root")).Click(); } // We can add root components with initial parameters var buttonId = intoBlazorUi ? "add-root-component-inside-blazor" : "add-root-component"; app.FindElement(By.Id(buttonId)).Click(); // They render and work var containerId = intoBlazorUi ? "container-rendered-by-blazor" : "root-container-1"; var dynamicRootContainer = Browser.FindElement(By.Id(containerId)); if (attachShadowRoot) { dynamicRootContainer = GetShadowRoot(dynamicRootContainer); } Browser.Equal("0", () => dynamicRootContainer.FindElement(By.ClassName("click-count")).Text); dynamicRootContainer.FindElement(By.ClassName("increment")).Click(); dynamicRootContainer.FindElement(By.ClassName("increment")).Click(); Browser.Equal("2", () => dynamicRootContainer.FindElement(By.ClassName("click-count")).Text); // We can dispose the root component app.FindElement(By.Id("remove-root-component")).Click(); Browser.Equal($"Disposed component in {(attachShadowRoot ? "ShadowDOM" : containerId)}", () => message.Text); // It's gone from the UI Browser.Empty(() => dynamicRootContainer.FindElements(By.CssSelector("*"))); AssertGlobalErrorState(false); } [Fact] public void CanAddAndRemoveMultipleRootComponentsToTheSameElement() { // Add, remove, re-add, all to the same element app.FindElement(By.Id("add-root-component-inside-blazor")).Click(); app.FindElement(By.Id("remove-root-component")).Click(); app.FindElement(By.Id("add-root-component-inside-blazor")).Click(); // It functions var dynamicRootContainer = Browser.FindElement(By.Id("container-rendered-by-blazor")); Browser.Equal("0", () => dynamicRootContainer.FindElement(By.ClassName("click-count")).Text); dynamicRootContainer.FindElement(By.ClassName("increment")).Click(); dynamicRootContainer.FindElement(By.ClassName("increment")).Click(); Browser.Equal("2", () => dynamicRootContainer.FindElement(By.ClassName("click-count")).Text); AssertGlobalErrorState(false); } [Fact] public void CannotAddMultipleRootComponentsToTheSameElementAtTheSameTime() { // Try adding a second without removing the first app.FindElement(By.Id("add-root-component-inside-blazor")).Click(); app.FindElement(By.Id("add-root-component-inside-blazor")).Click(); AssertGlobalErrorState(true); } [Fact] public void CanUpdateParameters() { // Create the initial component app.FindElement(By.Id("add-root-component")).Click(); var dynamicRootContainer = Browser.FindElement(By.Id("root-container-1")); var incrementButton = dynamicRootContainer.FindElement(By.ClassName("increment")); var clickCount = dynamicRootContainer.FindElement(By.ClassName("click-count")); incrementButton.Click(); Browser.Equal("1", () => clickCount.Text); // Supply updated parameters var incrementAmount = app.FindElement(By.Id("increment-amount")); incrementAmount.Clear(); incrementAmount.SendKeys("4"); app.FindElement(By.Id("set-increment-amount")).Click(); incrementButton.Click(); Browser.Equal("5", () => clickCount.Text); } [Fact] public void CanSupplyComplexParameters() { app.FindElement(By.Id("add-root-component")).Click(); app.FindElement(By.Id("set-complex-params")).Click(); var dynamicRootContainer = Browser.FindElement(By.Id("root-container-1")); Browser.Equal("123", () => dynamicRootContainer.FindElement(By.ClassName("increment-amount-value")).Text); Browser.Equal("Person is Bert, age 123.456", () => dynamicRootContainer.FindElement(By.ClassName("person-info")).Text); Browser.Equal("Value from JS object reference: You've added 1 components.", () => dynamicRootContainer.FindElement(By.ClassName("value-from-js")).Text); Browser.Equal("Value from .NET object reference: This is correct", () => dynamicRootContainer.FindElement(By.ClassName("value-from-dotnetobject")).Text); Browser.Equal("Byte array value: 2,3,5,7,11,13,17", () => dynamicRootContainer.FindElement(By.ClassName("value-from-bytearray")).Text); } [Fact] public void CanSupplyParametersIncrementally() { app.FindElement(By.Id("add-root-component")).Click(); app.FindElement(By.Id("set-complex-params")).Click(); var dynamicRootContainer = Browser.FindElement(By.Id("root-container-1")); Browser.Equal("123", () => dynamicRootContainer.FindElement(By.ClassName("increment-amount-value")).Text); // Supply updated parameters app.FindElement(By.Id("set-increment-amount")).Click(); // This parameter was provided explicitly Browser.Equal("1", () => dynamicRootContainer.FindElement(By.ClassName("increment-amount-value")).Text); // ... but this one remains from before Browser.Equal("Person is Bert, age 123.456", () => dynamicRootContainer.FindElement(By.ClassName("person-info")).Text); } [Fact] public void SetParametersThrowsIfParametersAreInvalid() { app.FindElement(By.Id("add-root-component")).Click(); app.FindElement(By.Id("set-invalid-params")).Click(); Browser.Contains("Error setting parameters", () => app.FindElement(By.Id("message")).Text); } [Fact] public void CanSupplyCatchAllParameters() { app.FindElement(By.Id("add-root-component")).Click(); app.FindElement(By.Id("set-catchall-params")).Click(); Browser.Equal("Finished setting catchall parameters on component in root-container-1", () => Browser.FindElement(By.Id("message")).Text); var dynamicRootContainer = Browser.FindElement(By.Id("root-container-1")); var catchAllParams = dynamicRootContainer.FindElements(By.ClassName("unmatched-value")); Assert.Collection(catchAllParams, param => { Assert.Equal("stringVal", param.FindElement(By.ClassName("unmatched-value-name")).Text); Assert.Equal("String", param.FindElement(By.ClassName("unmatched-value-type")).Text); Assert.Equal("Hello", param.FindElement(By.ClassName("unmatched-value-value")).Text); }, param => { Assert.Equal("wholeNumberVal", param.FindElement(By.ClassName("unmatched-value-name")).Text); Assert.Equal("Double", param.FindElement(By.ClassName("unmatched-value-type")).Text); Assert.Equal("1", param.FindElement(By.ClassName("unmatched-value-value")).Text); }, param => { Assert.Equal("fractionalNumberVal", param.FindElement(By.ClassName("unmatched-value-name")).Text); Assert.Equal("Double", param.FindElement(By.ClassName("unmatched-value-type")).Text); Assert.Equal("-123.456", param.FindElement(By.ClassName("unmatched-value-value")).Text); }, param => { Assert.Equal("trueVal", param.FindElement(By.ClassName("unmatched-value-name")).Text); Assert.Equal("Boolean", param.FindElement(By.ClassName("unmatched-value-type")).Text); Assert.Equal("True", param.FindElement(By.ClassName("unmatched-value-value")).Text); }, param => { Assert.Equal("falseVal", param.FindElement(By.ClassName("unmatched-value-name")).Text); Assert.Equal("Boolean", param.FindElement(By.ClassName("unmatched-value-type")).Text); Assert.Equal("False", param.FindElement(By.ClassName("unmatched-value-value")).Text); }, param => { Assert.Equal("nullVal", param.FindElement(By.ClassName("unmatched-value-name")).Text); Assert.Equal("null", param.FindElement(By.ClassName("unmatched-value-type")).Text); }); } [Fact] public void CanSupplyAndInvokeFunctionParameters() { var containerId = "root-container-1"; app.FindElement(By.Id("add-root-component")).Click(); app.FindElement(By.Id("set-callback-params")).Click(); Browser.Equal($"Finished setting callback parameters on component in {containerId}", () => app.FindElement(By.Id("message")).Text); var container = Browser.FindElement(By.Id(containerId)); // Invoke the callback without params. container.FindElement(By.ClassName("js-callback")).Click(); Browser.Equal($"JavaScript button callback invoked (id=0)", () => app.FindElement(By.Id("message")).Text); // Invoke the callback with params. container.FindElement(By.ClassName("js-callback-with-params")).Click(); Browser.Equal($"JavaScript button callback received mouse event args (id=0, buttons=0)", () => app.FindElement(By.Id("message")).Text); // Change the callback to one that displays the last ID (0) incremented by 1. app.FindElement(By.Id("set-callback-params")).Click(); // Invoke callback without params (id=1). container.FindElement(By.ClassName("js-callback")).Click(); Browser.Equal($"JavaScript button callback invoked (id=1)", () => app.FindElement(By.Id("message")).Text); // Remove all callbacks. app.FindElement(By.Id("remove-callback-params")).Click(); Browser.Equal($"Finished removing callback parameters on component in {containerId}", () => app.FindElement(By.Id("message")).Text); // Invoke the callback without params, assert that it no-ops. container.FindElement(By.ClassName("js-callback-with-params")).Click(); Browser.Equal($"Finished removing callback parameters on component in {containerId}", () => app.FindElement(By.Id("message")).Text); } [Fact] public void CallsJavaScriptInitializers() { app.FindElement(By.Id("show-initializer-call-log")).Click(); var expectedCallLog = "[{\"name\":\"component-with-many-parameters\",\"parameters\":[" + "{\"name\":\"StringParam\",\"type\":\"string\"}," + "{\"name\":\"IntParam\",\"type\":\"number\"}," + "{\"name\":\"LongParam\",\"type\":\"number\"}," + "{\"name\":\"FloatParam\",\"type\":\"number\"}," + "{\"name\":\"DoubleParam\",\"type\":\"number\"}," + "{\"name\":\"DecimalParam\",\"type\":\"number\"}," + "{\"name\":\"NullableIntParam\",\"type\":\"number?\"}," + "{\"name\":\"NullableLongParam\",\"type\":\"number?\"}," + "{\"name\":\"NullableFloatParam\",\"type\":\"number?\"}," + "{\"name\":\"NullableDoubleParam\",\"type\":\"number?\"}," + "{\"name\":\"NullableDecimalParam\",\"type\":\"number?\"}," + "{\"name\":\"BoolParam\",\"type\":\"boolean\"}," + "{\"name\":\"NullableBoolParam\",\"type\":\"boolean?\"}," + "{\"name\":\"DateTimeParam\",\"type\":\"object\"}," + "{\"name\":\"ComplexTypeParam\",\"type\":\"object\"}," + "{\"name\":\"JSObjectReferenceParam\",\"type\":\"object\"}]}" + "]"; Browser.Equal(expectedCallLog, () => Browser.FindElement(By.Id("message")).Text); } void AssertGlobalErrorState(bool hasGlobalError) { var globalErrorUi = Browser.Exists(By.Id("blazor-error-ui")); Browser.Equal(hasGlobalError ? "block" : "none", () => globalErrorUi.GetCssValue("display")); } IWebElement GetShadowRoot(IWebElement element) { var result = ((IJavaScriptExecutor)Browser).ExecuteScript("return arguments[0].shadowRoot", element); return (IWebElement)result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Globalization { using System; using System.Text; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// // // Used in HebrewNumber.ParseByChar to maintain the context information ( // the state in the state machine and current Hebrew number values, etc.) // when parsing Hebrew number character by character. // //////////////////////////////////////////////////////////////////////////// internal struct HebrewNumberParsingContext { // The current state of the state machine for parsing Hebrew numbers. internal HebrewNumber.HS state; // The current value of the Hebrew number. // The final value is determined when state is FoundEndOfHebrewNumber. internal int result; public HebrewNumberParsingContext(int result) { // Set the start state of the state machine for parsing Hebrew numbers. state = HebrewNumber.HS.Start; this.result = result; } } //////////////////////////////////////////////////////////////////////////// // // Please see ParseByChar() for comments about different states defined here. // //////////////////////////////////////////////////////////////////////////// internal enum HebrewNumberParsingState { InvalidHebrewNumber, NotHebrewDigit, FoundEndOfHebrewNumber, ContinueParsing, } //////////////////////////////////////////////////////////////////////////// // // class HebrewNumber // // Provides static methods for formatting integer values into // Hebrew text and parsing Hebrew number text. // // Limitations: // Parse can only handles value 1 ~ 999. // ToString() can only handles 1 ~ 999. If value is greater than 5000, // 5000 will be subtracted from the value. // //////////////////////////////////////////////////////////////////////////// internal class HebrewNumber { // This class contains only static methods. Add a private ctor so that // compiler won't generate a default one for us. private HebrewNumber() { } //////////////////////////////////////////////////////////////////////////// // // ToString // // Converts the given number to Hebrew letters according to the numeric // value of each Hebrew letter. Basically, this converts the lunar year // and the lunar month to letters. // // The character of a year is described by three letters of the Hebrew // alphabet, the first and third giving, respectively, the days of the // weeks on which the New Year occurs and Passover begins, while the // second is the initial of the Hebrew word for defective, normal, or // complete. // // Defective Year : Both Heshvan and Kislev are defective (353 or 383 days) // Normal Year : Heshvan is defective, Kislev is full (354 or 384 days) // Complete Year : Both Heshvan and Kislev are full (355 or 385 days) // //////////////////////////////////////////////////////////////////////////// internal static String ToString(int Number) { char cTens = '\x0'; char cUnits; // tens and units chars int Hundreds, Tens; // hundreds and tens values StringBuilder szHebrew = new StringBuilder(); // // Adjust the number if greater than 5000. // if (Number > 5000) { Number -= 5000; } Contract.Assert(Number > 0 && Number <= 999, "Number is out of range.");; // // Get the Hundreds. // Hundreds = Number / 100; if (Hundreds > 0) { Number -= Hundreds * 100; // \x05e7 = 100 // \x05e8 = 200 // \x05e9 = 300 // \x05ea = 400 // If the number is greater than 400, use the multiples of 400. for (int i = 0; i < (Hundreds / 4) ; i++) { szHebrew.Append('\x05ea'); } int remains = Hundreds % 4; if (remains > 0) { szHebrew.Append((char)((int)'\x05e6' + remains)); } } // // Get the Tens. // Tens = Number / 10; Number %= 10; switch (Tens) { case ( 0 ) : cTens = '\x0'; break; case ( 1 ) : cTens = '\x05d9'; // Hebrew Letter Yod break; case ( 2 ) : cTens = '\x05db'; // Hebrew Letter Kaf break; case ( 3 ) : cTens = '\x05dc'; // Hebrew Letter Lamed break; case ( 4 ) : cTens = '\x05de'; // Hebrew Letter Mem break; case ( 5 ) : cTens = '\x05e0'; // Hebrew Letter Nun break; case ( 6 ) : cTens = '\x05e1'; // Hebrew Letter Samekh break; case ( 7 ) : cTens = '\x05e2'; // Hebrew Letter Ayin break; case ( 8 ) : cTens = '\x05e4'; // Hebrew Letter Pe break; case ( 9 ) : cTens = '\x05e6'; // Hebrew Letter Tsadi break; } // // Get the Units. // cUnits = (char)(Number > 0 ? ((int)'\x05d0' + Number - 1) : 0); if ((cUnits == '\x05d4') && // Hebrew Letter He (5) (cTens == '\x05d9')) { // Hebrew Letter Yod (10) cUnits = '\x05d5'; // Hebrew Letter Vav (6) cTens = '\x05d8'; // Hebrew Letter Tet (9) } if ((cUnits == '\x05d5') && // Hebrew Letter Vav (6) (cTens == '\x05d9')) { // Hebrew Letter Yod (10) cUnits = '\x05d6'; // Hebrew Letter Zayin (7) cTens = '\x05d8'; // Hebrew Letter Tet (9) } // // Copy the appropriate info to the given buffer. // if (cTens != '\x0') { szHebrew.Append(cTens); } if (cUnits != '\x0') { szHebrew.Append(cUnits); } if (szHebrew.Length > 1) { szHebrew.Insert(szHebrew.Length - 1, '"'); } else { szHebrew.Append('\''); } // // Return success. // return (szHebrew.ToString()); } //////////////////////////////////////////////////////////////////////////// // // Token used to tokenize a Hebrew word into tokens so that we can use in the // state machine. // //////////////////////////////////////////////////////////////////////////// enum HebrewToken { Invalid = -1, Digit400 = 0, Digit200_300 = 1, Digit100 = 2, Digit10 = 3, // 10 ~ 90 Digit1 = 4, // 1, 2, 3, 4, 5, 8, Digit6_7 = 5, Digit7 = 6, Digit9 = 7, SingleQuote = 8, DoubleQuote = 9, }; //////////////////////////////////////////////////////////////////////////// // // This class is used to map a token into its Hebrew digit value. // //////////////////////////////////////////////////////////////////////////// class HebrewValue { internal HebrewToken token; internal int value; internal HebrewValue(HebrewToken token, int value) { this.token = token; this.value = value; } } // // Map a Hebrew character from U+05D0 ~ U+05EA to its digit value. // The value is -1 if the Hebrew character does not have a associated value. // static HebrewValue[] HebrewValues = { new HebrewValue(HebrewToken.Digit1, 1) , // '\x05d0 new HebrewValue(HebrewToken.Digit1, 2) , // '\x05d1 new HebrewValue(HebrewToken.Digit1, 3) , // '\x05d2 new HebrewValue(HebrewToken.Digit1, 4) , // '\x05d3 new HebrewValue(HebrewToken.Digit1, 5) , // '\x05d4 new HebrewValue(HebrewToken.Digit6_7,6) , // '\x05d5 new HebrewValue(HebrewToken.Digit6_7,7) , // '\x05d6 new HebrewValue(HebrewToken.Digit1, 8) , // '\x05d7 new HebrewValue(HebrewToken.Digit9, 9) , // '\x05d8 new HebrewValue(HebrewToken.Digit10, 10) , // '\x05d9; // Hebrew Letter Yod new HebrewValue(HebrewToken.Invalid, -1) , // '\x05da; new HebrewValue(HebrewToken.Digit10, 20) , // '\x05db; // Hebrew Letter Kaf new HebrewValue(HebrewToken.Digit10, 30) , // '\x05dc; // Hebrew Letter Lamed new HebrewValue(HebrewToken.Invalid, -1) , // '\x05dd; new HebrewValue(HebrewToken.Digit10, 40) , // '\x05de; // Hebrew Letter Mem new HebrewValue(HebrewToken.Invalid, -1) , // '\x05df; new HebrewValue(HebrewToken.Digit10, 50) , // '\x05e0; // Hebrew Letter Nun new HebrewValue(HebrewToken.Digit10, 60) , // '\x05e1; // Hebrew Letter Samekh new HebrewValue(HebrewToken.Digit10, 70) , // '\x05e2; // Hebrew Letter Ayin new HebrewValue(HebrewToken.Invalid, -1) , // '\x05e3; new HebrewValue(HebrewToken.Digit10, 80) , // '\x05e4; // Hebrew Letter Pe new HebrewValue(HebrewToken.Invalid, -1) , // '\x05e5; new HebrewValue(HebrewToken.Digit10, 90) , // '\x05e6; // Hebrew Letter Tsadi new HebrewValue(HebrewToken.Digit100, 100) , // '\x05e7; new HebrewValue(HebrewToken.Digit200_300, 200) , // '\x05e8; new HebrewValue(HebrewToken.Digit200_300, 300) , // '\x05e9; new HebrewValue(HebrewToken.Digit400, 400) , // '\x05ea; }; const int minHebrewNumberCh = 0x05d0; static char maxHebrewNumberCh = (char)(minHebrewNumberCh + HebrewValues.Length - 1); //////////////////////////////////////////////////////////////////////////// // // Hebrew number parsing State // The current state and the next token will lead to the next state in the state machine. // DQ = Double Quote // //////////////////////////////////////////////////////////////////////////// internal enum HS { _err = -1, // an error state Start = 0, S400 = 1, // a Hebrew digit 400 S400_400 = 2, // Two Hebrew digit 400 S400_X00 = 3, // Two Hebrew digit 400 and followed by 100 S400_X0 = 4, // Hebrew digit 400 and followed by 10 ~ 90 X00_DQ = 5, // A hundred number and followed by a double quote. S400_X00_X0 = 6, X0_DQ = 7, // A two-digit number and followed by a double quote. X = 8, // A single digit Hebrew number. X0 = 9, // A two-digit Hebrew number X00 = 10, // A three-digit Hebrew number S400_DQ = 11, // A Hebrew digit 400 and followed by a double quote. S400_400_DQ = 12, S400_400_100 = 13, S9 = 14, // Hebrew digit 9 X00_S9 = 15, // A hundered number and followed by a digit 9 S9_DQ = 16, // Hebrew digit 9 and followed by a double quote END = 100, // A terminial state is reached. } // // The state machine for Hebrew number pasing. // readonly static HS[][] NumberPasingState = { // 400 300/200 100 90~10 8~1 6, 7, 9, ' " /* 0 */ new HS[] {HS.S400, HS.X00, HS.X00, HS.X0, HS.X, HS.X, HS.X, HS.S9, HS._err, HS._err}, /* 1: S400 */ new HS[] {HS.S400_400, HS.S400_X00, HS.S400_X00, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS.END, HS.S400_DQ}, /* 2: S400_400 */ new HS[] {HS._err, HS._err, HS.S400_400_100,HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS._err, HS.S400_400_DQ}, /* 3: S400_X00 */ new HS[] {HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS._err, HS.X00_DQ}, /* 4: S400_X0 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ}, /* 5: X00_DQ */ new HS[] {HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err}, /* 6: S400_X00_X0 */new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ}, /* 7: X0_DQ */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err}, /* 8: X */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS._err}, /* 9: X0 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.X0_DQ}, /* 10: X00 */ new HS[] {HS._err, HS._err, HS._err, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS.END, HS.X00_DQ}, /* 11: S400_DQ */ new HS[] {HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err}, /* 12: S400_400_DQ*/new HS[] {HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err}, /* 13: S400_400_100*/new HS[]{HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.X00_DQ}, /* 14: S9 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err,HS.END, HS.S9_DQ}, /* 15: X00_S9 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.S9_DQ}, /* 16: S9_DQ */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS._err, HS._err, HS._err}, }; //////////////////////////////////////////////////////////////////////// // // Actions: // Parse the Hebrew number by passing one character at a time. // The state between characters are maintained at HebrewNumberPasingContext. // Returns: // Return a enum of HebrewNumberParsingState. // NotHebrewDigit: The specified ch is not a valid Hebrew digit. // InvalidHebrewNumber: After parsing the specified ch, it will lead into // an invalid Hebrew number text. // FoundEndOfHebrewNumber: A terminal state is reached. This means that // we find a valid Hebrew number text after the specified ch is parsed. // ContinueParsing: The specified ch is a valid Hebrew digit, and // it will lead into a valid state in the state machine, we should // continue to parse incoming characters. // //////////////////////////////////////////////////////////////////////// internal static HebrewNumberParsingState ParseByChar(char ch, ref HebrewNumberParsingContext context) { HebrewToken token; if (ch == '\'') { token = HebrewToken.SingleQuote; } else if (ch == '\"') { token = HebrewToken.DoubleQuote; } else { int index = (int)ch - minHebrewNumberCh; if (index >= 0 && index < HebrewValues.Length ) { token = HebrewValues[index].token; if (token == HebrewToken.Invalid) { return (HebrewNumberParsingState.NotHebrewDigit); } context.result += HebrewValues[index].value; } else { // Not in valid Hebrew digit range. return (HebrewNumberParsingState.NotHebrewDigit); } } context.state = NumberPasingState[(int)context.state][(int)token]; if (context.state == HS._err) { // Invalid Hebrew state. This indicates an incorrect Hebrew number. return (HebrewNumberParsingState.InvalidHebrewNumber); } if (context.state == HS.END) { // Reach a terminal state. return (HebrewNumberParsingState.FoundEndOfHebrewNumber); } // We should continue to parse. return (HebrewNumberParsingState.ContinueParsing); } //////////////////////////////////////////////////////////////////////// // // Actions: // Check if the ch is a valid Hebrew number digit. // This function will return true if the specified char is a legal Hebrew // digit character, single quote, or double quote. // Returns: // true if the specified character is a valid Hebrew number character. // //////////////////////////////////////////////////////////////////////// internal static bool IsDigit(char ch) { if (ch >= minHebrewNumberCh && ch <= maxHebrewNumberCh) { return (HebrewValues[ch - minHebrewNumberCh].value >= 0); } return (ch == '\'' || ch == '\"'); } } }
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC 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 EntitySpaces, LLC 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 EntitySpaces, LLC 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.Data; using System.Data.SqlClient; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using Tiraggo.DynamicQuery; using Tiraggo.Interfaces; namespace Tiraggo.SqlClientProvider { public class DataProvider : IDataProvider { public DataProvider() { } #region esTraceArguments private sealed class esTraceArguments : Tiraggo.Interfaces.ITraceArguments, IDisposable { static private long packetOrder = 0; private sealed class esTraceParameter : ITraceParameter { public string Name { get; set; } public string Direction { get; set; } public string ParamType { get; set; } public string BeforeValue { get; set; } public string AfterValue { get; set; } } public esTraceArguments() { } public esTraceArguments(tgDataRequest request, IDbCommand cmd, string action, string callStack) { PacketOrder = Interlocked.Increment(ref esTraceArguments.packetOrder); this.command = cmd; TraceChannel = DataProvider.sTraceChannel; Syntax = "MSSQL"; Request = request; ThreadId = Thread.CurrentThread.ManagedThreadId; Action = action; CallStack = callStack; SqlCommand = cmd; ApplicationName = System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location); IDataParameterCollection parameters = cmd.Parameters; if (parameters.Count > 0) { Parameters = new List<ITraceParameter>(parameters.Count); for (int i = 0; i < parameters.Count; i++) { SqlParameter param = parameters[i] as SqlParameter; esTraceParameter p = new esTraceParameter() { Name = param.ParameterName, Direction = param.Direction.ToString(), ParamType = param.SqlDbType.ToString().ToUpper(), BeforeValue = param.Value != null ? Convert.ToString(param.Value) : "null" }; this.Parameters.Add(p); } } stopwatch = Stopwatch.StartNew(); } // Temporary variable private IDbCommand command; public long PacketOrder { get; set; } public string Syntax { get; set; } public tgDataRequest Request { get; set; } public int ThreadId { get; set; } public string Action { get; set; } public string CallStack { get; set; } public IDbCommand SqlCommand { get; set; } public string ApplicationName { get; set; } public string TraceChannel { get; set; } public long Duration { get; set; } public long Ticks { get; set; } public string Exception { get; set; } public List<ITraceParameter> Parameters { get; set; } private Stopwatch stopwatch; void IDisposable.Dispose() { stopwatch.Stop(); Duration = stopwatch.ElapsedMilliseconds; Ticks = stopwatch.ElapsedTicks; // Gather Output Parameters if (this.Parameters != null && this.Parameters.Count > 0) { IDataParameterCollection parameters = command.Parameters; for (int i = 0; i < this.Parameters.Count; i++) { ITraceParameter esParam = this.Parameters[i]; IDbDataParameter param = parameters[esParam.Name] as IDbDataParameter; if (param.Direction == ParameterDirection.InputOutput || param.Direction == ParameterDirection.Output) { esParam.AfterValue = param.Value != null ? Convert.ToString(param.Value) : "null"; } } } DataProvider.sTraceHandler(this); } } #endregion esTraceArguments #region Profiling Logic /// <summary> /// The EventHandler used to decouple the profiling code from the core assemblies /// </summary> event TraceEventHandler IDataProvider.TraceHandler { add { DataProvider.sTraceHandler += value; } remove { DataProvider.sTraceHandler -= value; } } static private event TraceEventHandler sTraceHandler; /// <summary> /// Returns true if this Provider is current being profiled /// </summary> bool IDataProvider.IsTracing { get { return sTraceHandler != null ? true : false; } } /// <summary> /// Used to set the Channel this provider is to use during Profiling /// </summary> string IDataProvider.TraceChannel { get { return DataProvider.sTraceChannel; } set { DataProvider.sTraceChannel = value; } } static private string sTraceChannel = "Channel1"; #endregion Profiling Logic /// <summary> /// This method acts as a delegate for tgTransactionScope /// </summary> /// <returns></returns> static private IDbConnection CreateIDbConnectionDelegate() { return new SqlConnection(); } static private void CleanupCommand(SqlCommand cmd) { if (cmd != null && cmd.Connection != null) { if (cmd.Connection.State == ConnectionState.Open) { cmd.Connection.Close(); } } } #region IDataProvider Members tgDataResponse IDataProvider.esLoadDataTable(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { switch (request.QueryType) { case tgQueryType.StoredProcedure: response = LoadDataTableFromStoredProcedure(request); break; case tgQueryType.Text: response = LoadDataTableFromText(request); break; case tgQueryType.DynamicQuery: response = new tgDataResponse(); SqlCommand cmd = QueryBuilder.PrepareCommand(request); LoadDataTableFromDynamicQuery(request, response, cmd); break; case tgQueryType.DynamicQueryParseOnly: response = new tgDataResponse(); SqlCommand cmd1 = QueryBuilder.PrepareCommand(request); response.LastQuery = cmd1.CommandText; break; case tgQueryType.ManyToMany: response = LoadManyToMany(request); break; default: break; } } catch (Exception ex) { response.Exception = ex; } return response; } tgDataResponse IDataProvider.esSaveDataTable(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { if (request.BulkSave) { SaveBulkInsert(request); } else { if (request.SqlAccessType == tgSqlAccessType.StoredProcedure) { if (request.CollectionSavePacket != null) SaveStoredProcCollection(request); else SaveStoredProcEntity(request); } else { if (request.EntitySavePacket.CurrentValues == null) SaveDynamicCollection(request); else SaveDynamicEntity(request); } } } catch (SqlException ex) { tgException es = Shared.CheckForConcurrencyException(ex); if (es != null) response.Exception = es; else response.Exception = ex; } catch (DBConcurrencyException dbex) { response.Exception = new tgConcurrencyException("Error in SqlClientProvider.esSaveDataTable", dbex); } response.Table = request.Table; return response; } tgDataResponse IDataProvider.ExecuteNonQuery(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SqlCommand cmd = null; try { cmd = new SqlCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); switch (request.QueryType) { case tgQueryType.TableDirect: cmd.CommandType = CommandType.TableDirect; cmd.CommandText = request.QueryText; break; case tgQueryType.StoredProcedure: cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); break; case tgQueryType.Text: cmd.CommandType = CommandType.Text; cmd.CommandText = request.QueryText; break; } try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteNonQuery", System.Environment.StackTrace)) { try { response.RowsEffected = cmd.ExecuteNonQuery(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { response.RowsEffected = cmd.ExecuteNonQuery(); } } finally { tgTransactionScope.DeEnlist(cmd); } if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception ex) { CleanupCommand(cmd); response.Exception = ex; } return response; } tgDataResponse IDataProvider.ExecuteReader(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SqlCommand cmd = null; try { cmd = new SqlCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); switch (request.QueryType) { case tgQueryType.TableDirect: cmd.CommandType = CommandType.TableDirect; cmd.CommandText = request.QueryText; break; case tgQueryType.StoredProcedure: cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); break; case tgQueryType.Text: cmd.CommandType = CommandType.Text; cmd.CommandText = request.QueryText; break; case tgQueryType.DynamicQuery: cmd = QueryBuilder.PrepareCommand(request); break; } cmd.Connection = new SqlConnection(request.ConnectionString); cmd.Connection.Open(); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteReader", System.Environment.StackTrace)) { try { response.DataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { response.DataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } } catch (Exception ex) { CleanupCommand(cmd); response.Exception = ex; } return response; } tgDataResponse IDataProvider.ExecuteScalar(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SqlCommand cmd = null; try { cmd = new SqlCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); switch (request.QueryType) { case tgQueryType.TableDirect: cmd.CommandType = CommandType.TableDirect; cmd.CommandText = request.QueryText; break; case tgQueryType.StoredProcedure: cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); break; case tgQueryType.Text: cmd.CommandType = CommandType.Text; cmd.CommandText = request.QueryText; break; case tgQueryType.DynamicQuery: cmd = QueryBuilder.PrepareCommand(request); break; } try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteScalar", System.Environment.StackTrace)) { try { response.Scalar = cmd.ExecuteScalar(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { response.Scalar = cmd.ExecuteScalar(); } } finally { tgTransactionScope.DeEnlist(cmd); } if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch (Exception ex) { CleanupCommand(cmd); response.Exception = ex; } return response; } tgDataResponse IDataProvider.FillDataSet(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { switch (request.QueryType) { case tgQueryType.StoredProcedure: response = LoadDataSetFromStoredProcedure(request); break; case tgQueryType.Text: response = LoadDataSetFromText(request); break; default: break; } } catch (Exception ex) { response.Exception = ex; } return response; } tgDataResponse IDataProvider.FillDataTable(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); try { switch (request.QueryType) { case tgQueryType.StoredProcedure: response = LoadDataTableFromStoredProcedure(request); break; case tgQueryType.Text: response = LoadDataTableFromText(request); break; default: break; } } catch (Exception ex) { response.Exception = ex; } return response; } #endregion IDataProvider Members static private tgDataResponse LoadDataSetFromStoredProcedure(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SqlCommand cmd = null; try { DataSet dataSet = new DataSet(); cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromStoredProcedure", System.Environment.StackTrace)) { try { da.Fill(dataSet); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataSet); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.DataSet = dataSet; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadDataSetFromText(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SqlCommand cmd = null; try { DataSet dataSet = new DataSet(); cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); SqlDataAdapter da = new SqlDataAdapter(); cmd.CommandText = request.QueryText; da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadDataSetFromText", System.Environment.StackTrace)) { try { da.Fill(dataSet); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataSet); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.DataSet = dataSet; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadDataTableFromStoredProcedure(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SqlCommand cmd = null; try { DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Shared.CreateFullName(request); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromStoredProcedure", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadDataTableFromText(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SqlCommand cmd = null; try { DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; if (request.Parameters != null) Shared.AddParameters(cmd, request); SqlDataAdapter da = new SqlDataAdapter(); cmd.CommandText = request.QueryText; da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromText", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; if (request.Parameters != null) { Shared.GatherReturnParameters(cmd, request, response); } } catch { CleanupCommand(cmd); throw; } finally { } return response; } static private tgDataResponse LoadManyToMany(tgDataRequest request) { tgDataResponse response = new tgDataResponse(); SqlCommand cmd = null; try { DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; string mmQuery = request.QueryText; string[] sections = mmQuery.Split('|'); string[] tables = sections[0].Split(','); string[] columns = sections[1].Split(','); string prefix = String.Empty; if (request.Catalog != null || request.ProviderMetadata.Catalog != null) { prefix += Delimiters.TableOpen; prefix += request.Catalog != null ? request.Catalog : request.ProviderMetadata.Catalog; prefix += Delimiters.TableClose + "."; } if (request.Schema != null || request.ProviderMetadata.Schema != null) { prefix += Delimiters.TableOpen; prefix += request.Schema != null ? request.Schema : request.ProviderMetadata.Schema; prefix += Delimiters.TableClose + "."; } string table0 = prefix + Delimiters.TableOpen + tables[0] + Delimiters.TableClose; string table1 = prefix + Delimiters.TableOpen + tables[1] + Delimiters.TableClose; string sql = "SELECT * FROM " + table0 + " JOIN " + table1 + " ON " + table0 + ".[" + columns[0] + "] = "; sql += table1 + ".[" + columns[1] + "] WHERE " + table1 + ".[" + sections[2] + "] = @"; if (request.Parameters != null) { foreach (tgParameter esParam in request.Parameters) { sql += esParam.Name; } Shared.AddParameters(cmd, request); } SqlDataAdapter da = new SqlDataAdapter(); cmd.CommandText = sql; da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadManyToMany", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; } catch { CleanupCommand(cmd); throw; } finally { } return response; } // This is used only to execute the Dynamic Query API static private void LoadDataTableFromDynamicQuery(tgDataRequest request, tgDataResponse response, SqlCommand cmd) { try { response.LastQuery = cmd.CommandText; if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; DataTable dataTable = new DataTable(request.ProviderMetadata.Destination); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; try { tgTransactionScope.Enlist(da.SelectCommand, request.ConnectionString, CreateIDbConnectionDelegate); #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "LoadFromDynamicQuery", System.Environment.StackTrace)) { try { da.Fill(dataTable); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { da.Fill(dataTable); } } finally { tgTransactionScope.DeEnlist(da.SelectCommand); } response.Table = dataTable; // Special code to remove the ESRN column if paging is going on tgDynamicQuerySerializable.DynamicQueryProps es = request.DynamicQuery.tg; if (es.PageNumber.HasValue && es.PageSize.HasValue) { DataColumnCollection cols = response.Table.Columns; if (cols.Contains("ESRN")) { cols.Remove("ESRN"); } } } catch (Exception) { CleanupCommand(cmd); throw; } finally { } } static private DataTable SaveStoredProcCollection(tgDataRequest request) { if (request.CollectionSavePacket == null) return null; SqlCommand cmdInsert = null; SqlCommand cmdUpdate = null; SqlCommand cmdDelete = null; try { using (tgTransactionScope scope = new tgTransactionScope()) { SqlCommand cmd = null; bool exception = false; foreach (tgEntitySavePacket packet in request.CollectionSavePacket) { cmd = null; exception = false; #region Setup Commands switch (packet.RowState) { case tgDataRowState.Added: if (cmdInsert == null) { cmdInsert = Shared.BuildStoredProcInsertCommand(request, packet); tgTransactionScope.Enlist(cmdInsert, request.ConnectionString, CreateIDbConnectionDelegate); } cmd = cmdInsert; break; case tgDataRowState.Modified: if (cmdUpdate == null) { cmdUpdate = Shared.BuildStoredProcUpdateCommand(request, packet); tgTransactionScope.Enlist(cmdUpdate, request.ConnectionString, CreateIDbConnectionDelegate); } cmd = cmdUpdate; break; case tgDataRowState.Deleted: if (cmdDelete == null) { cmdDelete = Shared.BuildStoredProcDeleteCommand(request, packet); tgTransactionScope.Enlist(cmdDelete, request.ConnectionString, CreateIDbConnectionDelegate); } cmd = cmdDelete; break; case tgDataRowState.Unchanged: continue; } #endregion Setup Commands #region Preprocess Parameters if (cmd.Parameters != null) { foreach (SqlParameter param in cmd.Parameters) { if (param.Direction == ParameterDirection.Output) { param.Value = null; } else { if (packet.CurrentValues.ContainsKey(param.SourceColumn)) { param.Value = packet.CurrentValues[param.SourceColumn]; } else { param.Value = null; } } } } #endregion Preprocess Parameters #region Execute Command try { int count; #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "SaveCollectionStoredProcedure", System.Environment.StackTrace)) { try { count = cmd.ExecuteNonQuery(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { count = cmd.ExecuteNonQuery(); } if (count < 1) { throw new tgConcurrencyException("Update failed to update any records @ " + cmd.CommandText); } } catch (Exception ex) { exception = true; request.FireOnError(packet, ex.Message); if (!request.ContinueUpdateOnError) { throw; } } #endregion Execute Command #region Postprocess Parameters if (!exception && packet.RowState != tgDataRowState.Deleted && cmd.Parameters != null) { foreach (SqlParameter param in cmd.Parameters) { switch (param.Direction) { case ParameterDirection.Output: case ParameterDirection.InputOutput: packet.CurrentValues[param.SourceColumn] = param.Value; break; } } } #endregion Postprocess Parameters } scope.Complete(); } } finally { if (cmdInsert != null) tgTransactionScope.DeEnlist(cmdInsert); if (cmdUpdate != null) tgTransactionScope.DeEnlist(cmdUpdate); if (cmdDelete != null) tgTransactionScope.DeEnlist(cmdDelete); } return null; } static private DataTable SaveStoredProcEntity(tgDataRequest request) { SqlCommand cmd = null; switch (request.EntitySavePacket.RowState) { case tgDataRowState.Added: cmd = Shared.BuildStoredProcInsertCommand(request, request.EntitySavePacket); break; case tgDataRowState.Modified: cmd = Shared.BuildStoredProcUpdateCommand(request, request.EntitySavePacket); break; case tgDataRowState.Deleted: cmd = Shared.BuildStoredProcDeleteCommand(request, request.EntitySavePacket); break; case tgDataRowState.Unchanged: return null; } try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); int count = 0; #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "SaveEntityStoredProcedure", System.Environment.StackTrace)) { try { count = cmd.ExecuteNonQuery(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { count = cmd.ExecuteNonQuery(); } if (count < 1) { throw new tgConcurrencyException("Update failed to update any records @ " + cmd.CommandText); } } finally { tgTransactionScope.DeEnlist(cmd); cmd.Dispose(); } if (request.EntitySavePacket.RowState != tgDataRowState.Deleted && cmd.Parameters != null) { foreach (SqlParameter param in cmd.Parameters) { switch (param.Direction) { case ParameterDirection.Output: case ParameterDirection.InputOutput: request.EntitySavePacket.CurrentValues[param.SourceColumn] = param.Value; break; } } } return null; } static private DataTable SaveDynamicCollection(tgDataRequest request) { if (request.CollectionSavePacket == null) return null; using (tgTransactionScope scope = new tgTransactionScope()) { SqlCommand cmd = null; bool exception = false; foreach (tgEntitySavePacket packet in request.CollectionSavePacket) { exception = false; cmd = null; switch (packet.RowState) { case tgDataRowState.Added: cmd = Shared.BuildDynamicInsertCommand(request, packet); break; case tgDataRowState.Modified: cmd = Shared.BuildDynamicUpdateCommand(request, packet); break; case tgDataRowState.Deleted: cmd = Shared.BuildDynamicDeleteCommand(request, packet); break; case tgDataRowState.Unchanged: continue; } try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); int count; #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "SaveCollectionDynamic", System.Environment.StackTrace)) { try { count = cmd.ExecuteNonQuery(); ; } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { count = cmd.ExecuteNonQuery(); } if (count < 1) { throw new tgConcurrencyException("Update failed to update any records for Table " + Shared.CreateFullName(request)); } } catch (Exception ex) { exception = true; request.FireOnError(packet, ex.Message); if (!request.ContinueUpdateOnError) { throw; } } finally { tgTransactionScope.DeEnlist(cmd); cmd.Dispose(); } if (!exception && packet.RowState != tgDataRowState.Deleted && cmd.Parameters != null) { foreach (SqlParameter param in cmd.Parameters) { switch (param.Direction) { case ParameterDirection.Output: case ParameterDirection.InputOutput: packet.CurrentValues[param.SourceColumn] = param.Value; break; } } } } scope.Complete(); } return null; } static private DataTable SaveDynamicEntity(tgDataRequest request) { SqlCommand cmd = null; switch (request.EntitySavePacket.RowState) { case tgDataRowState.Added: cmd = Shared.BuildDynamicInsertCommand(request, request.EntitySavePacket); break; case tgDataRowState.Modified: cmd = Shared.BuildDynamicUpdateCommand(request, request.EntitySavePacket); break; case tgDataRowState.Deleted: cmd = Shared.BuildDynamicDeleteCommand(request, request.EntitySavePacket); break; } try { tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate); int count = 0; #region Profiling if (sTraceHandler != null) { using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "SaveEntityDynamic", System.Environment.StackTrace)) { try { count = cmd.ExecuteNonQuery(); } catch (Exception ex) { esTrace.Exception = ex.Message; throw; } } } else #endregion Profiling { count = cmd.ExecuteNonQuery(); } if (count < 1) { throw new tgConcurrencyException("Update failed to update any records for Table " + Shared.CreateFullName(request)); } } finally { tgTransactionScope.DeEnlist(cmd); cmd.Dispose(); } if (request.EntitySavePacket.RowState != tgDataRowState.Deleted && cmd.Parameters != null) { foreach (SqlParameter param in cmd.Parameters) { switch (param.Direction) { case ParameterDirection.Output: case ParameterDirection.InputOutput: request.EntitySavePacket.CurrentValues[param.SourceColumn] = param.Value; break; } } } return null; } static private DataTable SaveBulkInsert(tgDataRequest request) { if (request.CollectionSavePacket == null) return null; DataTable dataTable = CreateDataTableForBulkInsert(request); foreach (tgEntitySavePacket packet in request.CollectionSavePacket) { if (packet.RowState != tgDataRowState.Added) continue; DataRow row = dataTable.NewRow(); dataTable.Rows.Add(row); SetModifiedValues(request, packet, row); } SqlBulkCopyOptions options = SqlBulkCopyOptions.Default; bool first = true; if (request.BulkSaveOptions != null) { foreach (string opt in request.BulkSaveOptions) { if (first) { first = false; options = (SqlBulkCopyOptions)Enum.Parse(typeof(SqlBulkCopyOptions), opt); } else { options |= (SqlBulkCopyOptions)Enum.Parse(typeof(SqlBulkCopyOptions), opt); } } } if (first) { using (SqlBulkCopy bulkCopy = new SqlBulkCopy(request.ConnectionString)) { bulkCopy.DestinationTableName = Shared.CreateFullName(request); bulkCopy.WriteToServer(dataTable); } } else { using (SqlBulkCopy bulkCopy = new SqlBulkCopy(request.ConnectionString, options)) { bulkCopy.DestinationTableName = Shared.CreateFullName(request); bulkCopy.WriteToServer(dataTable); } } return null; } static private DataTable CreateDataTableForBulkInsert(tgDataRequest request) { DataTable dataTable = new DataTable(); DataColumnCollection dataColumns = dataTable.Columns; tgColumnMetadataCollection cols = request.Columns; if (request.SelectedColumns == null) { tgColumnMetadata col; for (int i = 0; i < cols.Count; i++) { col = cols[i]; dataColumns.Add(new DataColumn(col.Name, col.Type)); } } else { foreach (string col in request.SelectedColumns.Keys) { dataColumns.Add(new DataColumn(col, cols[col].Type)); } } return dataTable; } private static void SetModifiedValues(tgDataRequest request, tgEntitySavePacket packet, DataRow row) { foreach (string column in packet.ModifiedColumns) { if (request.Columns.FindByColumnName(column) != null) { row[column] = packet.CurrentValues[column]; } } } } }
using System.Security; using System; using System.Runtime.InteropServices; // For SafeHandle /// <summary> /// DangerousRelease /// </summary> [SecurityCritical] public class MySafeValidHandle : SafeHandle { public MySafeValidHandle() : base(IntPtr.Zero, true) { } public MySafeValidHandle(IntPtr handleValue) : base(IntPtr.Zero, true) { handle = handleValue; } public override bool IsInvalid { [SecurityCritical] get { return false; } } [SecurityCritical] protected override bool ReleaseHandle() { return true; } } [SecurityCritical] public class MySafeInValidHandle : SafeHandle { public MySafeInValidHandle() : base(IntPtr.Zero, true) { } public MySafeInValidHandle(IntPtr handleValue) : base(IntPtr.Zero, true) { handle = handleValue; } public override bool IsInvalid { [SecurityCritical] get { return true; } } [SecurityCritical] protected override bool ReleaseHandle() { return true; } } public class SafeHandleDangerousRelease { #region Public Methods [SecuritySafeCritical] public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases [SecuritySafeCritical] public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call DangerousRelease after call DangerousAddRef for valid handle"); try { SafeHandle handle = new MySafeValidHandle(); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("WARNING: Calling DangerousAddRef returns false"); } handle.DangerousRelease(); } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest2() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("PosTest2: Call DangerousRelease after call DangerousAddRef for valid handle"); try { randValue = TestLibrary.Generator.GetInt32(-55); SafeHandle handle = new MySafeValidHandle(new IntPtr(randValue)); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("WARNING: Calling DangerousAddRef returns false"); } handle.DangerousRelease(); } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue.ToString()); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call DangerousRelease after call DangerousAddRef for invalid handle"); try { SafeHandle handle = new MySafeInValidHandle(); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("WARNING: Calling DangerousAddRef returns false"); } handle.DangerousRelease(); } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest4() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("PosTest4: Call DangerousRelease after call DangerousAddRef for invalid handle"); try { randValue = TestLibrary.Generator.GetInt32(-55); SafeHandle handle = new MySafeInValidHandle(new IntPtr(randValue)); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("WARNING: Calling DangerousAddRef returns false"); } handle.DangerousRelease(); } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue.ToString()); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest5() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("PosTest5: Call DangerousAddRef after call DangerousRelease for valid handle"); try { randValue = TestLibrary.Generator.GetInt32(-55); SafeHandle handle = new MySafeValidHandle(new IntPtr(randValue)); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("WARNING: Calling DangerousAddRef returns false"); } handle.DangerousRelease(); handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogError("005.1", "Calling DangerousAddRef returns false after calling DangerousRelease"); } handle.DangerousRelease(); } catch (Exception e) { TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue.ToString()); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest6() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("PosTest6: Call DangerousAddRef after call DangerousRelease for invalid handle"); try { randValue = TestLibrary.Generator.GetInt32(-55); SafeHandle handle = new MySafeInValidHandle(new IntPtr(randValue)); bool success = false; handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("WARNING: Calling DangerousAddRef returns false"); } handle.DangerousRelease(); handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogError("006.1", "Calling DangerousAddRef returns false after calling DangerousRelease"); } handle.DangerousRelease(); } catch (Exception e) { TestLibrary.TestFramework.LogError("006.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue.ToString()); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases // The following two test case will cause a ObjectDispose exception occurs during process unload [SecuritySafeCritical] public bool NegTest1() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("NegTest1: Call DangerousRelease without call DangerousAddRef"); try { randValue = TestLibrary.Generator.GetInt32(-55); SafeHandle handle = new MySafeValidHandle(new IntPtr(randValue)); // if this object gets finalized it will throw an exception on the finalizer thread GC.SuppressFinalize(handle); handle.DangerousRelease(); } catch (Exception e) { TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue.ToString()); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool NegTest2() { bool retVal = true; int randValue = 0; TestLibrary.TestFramework.BeginScenario("NegTest2: Call DangerousRelease twice with one call DangerousAddRef for valid handle"); try { randValue = TestLibrary.Generator.GetInt32(-55); SafeHandle handle = new MySafeValidHandle(new IntPtr(randValue)); bool success = false; // if this object gets finalized it will throw an exception on the finalizer thread GC.SuppressFinalize(handle); handle.DangerousAddRef(ref success); if (!success) { TestLibrary.TestFramework.LogInformation("WARNING: Calling DangerousAddRef returns false"); } handle.DangerousRelease(); handle.DangerousRelease(); } catch (Exception e) { TestLibrary.TestFramework.LogError("102.1", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] randValue = " + randValue.ToString()); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion [SecuritySafeCritical] public static int Main() { SafeHandleDangerousRelease test = new SafeHandleDangerousRelease(); TestLibrary.TestFramework.BeginTestCase("SafeHandleDangerousRelease"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO.Pipelines; using System.Net; using System.Net.Http; using System.Net.WebSockets; using System.Runtime.Versioning; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; namespace Microsoft.AspNetCore.Http.Connections.Client { /// <summary> /// Options used to configure a <see cref="HttpConnection"/> instance. /// </summary> public class HttpConnectionOptions { private IDictionary<string, string> _headers; private X509CertificateCollection? _clientCertificates; private CookieContainer _cookies; private ICredentials? _credentials; private IWebProxy? _proxy; private bool? _useDefaultCredentials; private Action<ClientWebSocketOptions>? _webSocketConfiguration; private PipeOptions? _transportPipeOptions; private PipeOptions? _appPipeOptions; private long _transportMaxBufferSize; private long _applicationMaxBufferSize; // Selected because of the number of client connections is usually much lower than // server connections and therefore willing to use more memory. We'll default // to a maximum of 1MB buffer; private const int DefaultBufferSize = 1 * 1024 * 1024; /// <summary> /// Initializes a new instance of the <see cref="HttpConnectionOptions"/> class. /// </summary> public HttpConnectionOptions() { _headers = new Dictionary<string, string>(); // System.Security.Cryptography isn't supported on WASM currently if (!OperatingSystem.IsBrowser()) { _clientCertificates = new X509CertificateCollection(); } _cookies = new CookieContainer(); Transports = HttpTransports.All; TransportMaxBufferSize = DefaultBufferSize; ApplicationMaxBufferSize = DefaultBufferSize; } /// <summary> /// Gets or sets a delegate for wrapping or replacing the <see cref="HttpMessageHandlerFactory"/> /// that will make HTTP requests. /// </summary> public Func<HttpMessageHandler, HttpMessageHandler>? HttpMessageHandlerFactory { get; set; } /// <summary> /// Gets or sets a delegate for wrapping or replacing the <see cref="WebSocket"/> /// that will be used for the WebSocket transport. /// </summary> public Func<WebSocketConnectionContext, CancellationToken, ValueTask<WebSocket>>? WebSocketFactory { get; set; } /// <summary> /// Gets or sets a collection of headers that will be sent with HTTP requests. /// </summary> public IDictionary<string, string> Headers { get => _headers; set => _headers = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Gets or sets the maximum buffer size for data read by the application before backpressure is applied. /// </summary> /// <remarks> /// The default value is 1MB. /// </remarks> /// <value> /// The default value is 1MB. /// </value> public long TransportMaxBufferSize { get => _transportMaxBufferSize; set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _transportMaxBufferSize = value; } } /// <summary> /// Gets or sets the maximum buffer size for data written by the application before backpressure is applied. /// </summary> /// <remarks> /// The default value is 1MB. /// </remarks> /// <value> /// The default value is 1MB. /// </value> public long ApplicationMaxBufferSize { get => _applicationMaxBufferSize; set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _applicationMaxBufferSize = value; } } // We initialize these lazily based on the state of the options specified here. // Though these are mutable it's extremely rare that they would be mutated past the // call to initialize the routerware. internal PipeOptions TransportPipeOptions => _transportPipeOptions ??= new PipeOptions(pauseWriterThreshold: TransportMaxBufferSize, resumeWriterThreshold: TransportMaxBufferSize / 2, readerScheduler: PipeScheduler.ThreadPool, useSynchronizationContext: false); internal PipeOptions AppPipeOptions => _appPipeOptions ??= new PipeOptions(pauseWriterThreshold: ApplicationMaxBufferSize, resumeWriterThreshold: ApplicationMaxBufferSize / 2, readerScheduler: PipeScheduler.ThreadPool, useSynchronizationContext: false); /// <summary> /// Gets or sets a collection of client certificates that will be sent with HTTP requests. /// </summary> [UnsupportedOSPlatform("browser")] public X509CertificateCollection? ClientCertificates { get { ThrowIfUnsupportedPlatform(); return _clientCertificates; } set { ThrowIfUnsupportedPlatform(); _clientCertificates = value ?? throw new ArgumentNullException(nameof(value)); } } /// <summary> /// Gets or sets a collection of cookies that will be sent with HTTP requests. /// </summary> [UnsupportedOSPlatform("browser")] public CookieContainer Cookies { get { ThrowIfUnsupportedPlatform(); return _cookies; } set { ThrowIfUnsupportedPlatform(); _cookies = value ?? throw new ArgumentNullException(nameof(value)); } } /// <summary> /// Gets or sets the URL used to send HTTP requests. /// </summary> public Uri? Url { get; set; } /// <summary> /// Gets or sets a bitmask combining one or more <see cref="HttpTransportType"/> values that specify what transports the client should use to send HTTP requests. /// </summary> public HttpTransportType Transports { get; set; } /// <summary> /// Gets or sets a value indicating whether negotiation is skipped when connecting to the server. /// </summary> /// <remarks> /// Negotiation can only be skipped when using the <see cref="HttpTransportType.WebSockets"/> transport. /// </remarks> public bool SkipNegotiation { get; set; } /// <summary> /// Gets or sets an access token provider that will be called to return a token for each HTTP request. /// </summary> public Func<Task<string?>>? AccessTokenProvider { get; set; } /// <summary> /// Gets or sets a close timeout. /// </summary> public TimeSpan CloseTimeout { get; set; } = TimeSpan.FromSeconds(5); /// <summary> /// Gets or sets the credentials used when making HTTP requests. /// </summary> [UnsupportedOSPlatform("browser")] public ICredentials? Credentials { get { ThrowIfUnsupportedPlatform(); return _credentials; } set { ThrowIfUnsupportedPlatform(); _credentials = value; } } /// <summary> /// Gets or sets the proxy used when making HTTP requests. /// </summary> [UnsupportedOSPlatform("browser")] public IWebProxy? Proxy { get { ThrowIfUnsupportedPlatform(); return _proxy; } set { ThrowIfUnsupportedPlatform(); _proxy = value; } } /// <summary> /// Gets or sets a value indicating whether default credentials are used when making HTTP requests. /// </summary> [UnsupportedOSPlatform("browser")] public bool? UseDefaultCredentials { get { ThrowIfUnsupportedPlatform(); return _useDefaultCredentials; } set { ThrowIfUnsupportedPlatform(); _useDefaultCredentials = value; } } /// <summary> /// Gets or sets the default <see cref="TransferFormat" /> to use if <see cref="HttpConnection.StartAsync(CancellationToken)"/> /// is called instead of <see cref="HttpConnection.StartAsync(TransferFormat, CancellationToken)"/>. /// </summary> public TransferFormat DefaultTransferFormat { get; set; } = TransferFormat.Binary; /// <summary> /// Gets or sets a delegate that will be invoked with the <see cref="ClientWebSocketOptions"/> object used /// to configure the WebSocket when using the WebSockets transport. /// </summary> /// <remarks> /// This delegate is invoked after headers from <see cref="Headers"/> and the access token from <see cref="AccessTokenProvider"/> /// has been applied. /// </remarks> [UnsupportedOSPlatform("browser")] public Action<ClientWebSocketOptions>? WebSocketConfiguration { get { ThrowIfUnsupportedPlatform(); return _webSocketConfiguration; } set { ThrowIfUnsupportedPlatform(); _webSocketConfiguration = value; } } private static void ThrowIfUnsupportedPlatform() { if (OperatingSystem.IsBrowser()) { throw new PlatformNotSupportedException(); } } } }
using System; using NUnit.Framework; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Tests { /** * test for ECIES - Elliptic Curve Integrated Encryption Scheme */ [TestFixture] public class IesTest : SimpleTest { private static readonly IBigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); private static readonly IBigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); public override string Name { get { return "IES"; } } public override void PerformTest() { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECIES"); ECCurve curve = new FPCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g.Init( new ECKeyGenerationParameters( ecSpec, new SecureRandom())); IBufferedCipher c1 = CipherUtilities.GetCipher("ECIES"); IBufferedCipher c2 = CipherUtilities.GetCipher("ECIES"); doTest(g, c1, c2); g = GeneratorUtilities.GetKeyPairGenerator("ECIES"); g.Init(new KeyGenerationParameters(new SecureRandom(), 192)); doTest(g, c1, c2); g = GeneratorUtilities.GetKeyPairGenerator("ECIES"); g.Init(new KeyGenerationParameters(new SecureRandom(), 239)); doTest(g, c1, c2); g = GeneratorUtilities.GetKeyPairGenerator("ECIES"); g.Init(new KeyGenerationParameters(new SecureRandom(), 256)); doTest(g, c1, c2); doDefTest(g, c1, c2); c1 = CipherUtilities.GetCipher("IES"); c2 = CipherUtilities.GetCipher("IES"); g = GeneratorUtilities.GetKeyPairGenerator("DH"); // DHParameterSpec dhParams = new DHParameterSpec(p512, g512); // g.initialize(dhParams); g.Init( new DHKeyGenerationParameters( new SecureRandom(), new DHParameters(p512, g512))); doTest(g, c1, c2); doDefTest(g, c1, c2); } public void doTest( IAsymmetricCipherKeyPairGenerator g, IBufferedCipher c1, IBufferedCipher c2) { // // a side // IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); IAsymmetricKeyParameter aPub = aKeyPair.Public; IAsymmetricKeyParameter aPriv = aKeyPair.Private; // // b side // IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); IAsymmetricKeyParameter bPub = bKeyPair.Public; IAsymmetricKeyParameter bPriv = bKeyPair.Private; // TODO Put back in // // // // stream test // // // IEKeySpec c1Key = new IEKeySpec(aPriv, bPub); // IEKeySpec c2Key = new IEKeySpec(bPriv, aPub); // // byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; // byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; // // IESParameterSpec param = new IESParameterSpec(d, e, 128); // // c1.Init(true, c1Key, param); // // c2.Init(false, c2Key, param); // // byte[] message = Hex.Decode("1234567890abcdef"); // // byte[] out1 = c1.DoFinal(message, 0, message.Length); // // byte[] out2 = c2.DoFinal(out1, 0, out1.Length); // // if (!AreEqual(out2, message)) // { // Fail("stream cipher test failed"); // } } public void doDefTest( IAsymmetricCipherKeyPairGenerator g, IBufferedCipher c1, IBufferedCipher c2) { // // a side // IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); IAsymmetricKeyParameter aPub = aKeyPair.Public; IAsymmetricKeyParameter aPriv = aKeyPair.Private; // // b side // IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); IAsymmetricKeyParameter bPub = bKeyPair.Public; IAsymmetricKeyParameter bPriv = bKeyPair.Private; // TODO Put back in // // // // stream test // // // IEKeySpec c1Key = new IEKeySpec(aPriv, bPub); // IEKeySpec c2Key = new IEKeySpec(bPriv, aPub); // // c1.Init(true, c1Key); // // AlgorithmParameters param = c1.getParameters(); // // c2.Init(false, c2Key, param); // // byte[] message = Hex.Decode("1234567890abcdef"); // // byte[] out1 = c1.DoFinal(message, 0, message.Length); // // byte[] out2 = c2.DoFinal(out1, 0, out1.Length); // // if (!AreEqual(out2, message)) // { // Fail("stream cipher test failed"); // } // // // // // int DoFinal // // // int len1 = c1.DoFinal(message, 0, message.Length, out1, 0); // // if (len1 != out1.Length) // { // Fail("encryption length wrong"); // } // // int len2 = c2.DoFinal(out1, 0, out1.Length, out2, 0); // // if (len2 != out2.Length) // { // Fail("decryption length wrong"); // } // // if (!AreEqual(out2, message)) // { // Fail("stream cipher test failed"); // } // // // // // int DoFinal with update // // // len1 = c1.ProcessBytes(message, 0, 2, out1, 0); // // len1 += c1.DoFinal(message, 2, message.Length - 2, out1, len1); // // if (len1 != out1.Length) // { // Fail("update encryption length wrong"); // } // // len2 = c2.ProcessBytes(out1, 0, 2, out2, 0); // // len2 += c2.DoFinal(out1, 2, out1.Length - 2, out2, len2); // // if (len2 != out2.Length) // { // Fail("update decryption length wrong"); // } // // if (!AreEqual(out2, message)) // { // Fail("update stream cipher test failed"); // } } public static void Main( string[] args) { RunTest(new IesTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; namespace Avro { /// <summary> /// Class to store schema name, namespace and enclosing namespace /// </summary> public class SchemaName { /// <summary> /// Name of the schema /// </summary> public String Name { get; private set; } /// <summary> /// Namespace specified within the schema /// </summary> public String Space { get; private set; } /// <summary> /// Namespace from the most tightly enclosing schema /// </summary> public String EncSpace { get; private set; } /// <summary> /// Namespace.Name of the schema /// </summary> public String Fullname { get { return string.IsNullOrEmpty(Namespace) ? this.Name : Namespace + "." + this.Name; } } /// <summary> /// Namespace of the schema /// </summary> public String Namespace { get { return string.IsNullOrEmpty(this.Space) ? this.EncSpace : this.Space; } } /// <summary> /// Constructor for SchemaName /// </summary> /// <param name="name">name of the schema</param> /// <param name="space">namespace of the schema</param> /// <param name="encspace">enclosing namespace of the schema</param> public SchemaName(String name, String space, String encspace) { if (name == null) { // anonymous this.Name = this.Space = null; this.EncSpace = encspace; // need to save enclosing namespace for anonymous types, so named types within the anonymous type can be resolved } else if (!name.Contains(".")) { // unqualified name this.Space = space; // use default space this.Name = name; this.EncSpace = encspace; } else { string[] parts = name.Split('.'); this.Space = string.Join(".", parts, 0, parts.Length - 1); this.Name = parts[parts.Length - 1]; this.EncSpace = encspace; } } /// <summary> /// Returns the full name of the schema /// </summary> /// <returns></returns> public override string ToString() { return Fullname; } /// <summary> /// Writes the schema name in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schemas already written</param> /// <param name="encspace">enclosing namespace of the schema</param> internal void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace) { if (null != this.Name) // write only if not anonymous { JsonHelper.writeIfNotNullOrEmpty(writer, "name", this.Name); if (!String.IsNullOrEmpty(this.Space)) JsonHelper.writeIfNotNullOrEmpty(writer, "namespace", this.Space); else if (!String.IsNullOrEmpty(this.EncSpace)) // need to put enclosing name space for code generated classes JsonHelper.writeIfNotNullOrEmpty(writer, "namespace", this.EncSpace); } } /// <summary> /// Compares two schema names /// </summary> /// <param name="obj">SchameName object to compare against this object</param> /// <returns>true or false</returns> public override bool Equals(Object obj) { if (obj == this) return true; if (obj != null && obj is SchemaName) { SchemaName that = (SchemaName)obj; return areEqual(that.Name, Name) && areEqual(that.Namespace, Namespace); } return false; } /// <summary> /// Compares two objects /// </summary> /// <param name="obj1">first object</param> /// <param name="obj2">second object</param> /// <returns>true or false</returns> private static bool areEqual(object obj1, object obj2) { return obj1 == null ? obj2 == null : obj1.Equals(obj2); } public override int GetHashCode() { return string.IsNullOrEmpty(Fullname) ? 0 : 29 * Fullname.GetHashCode(); } } /// <summary> /// A class that contains a list of named schemas. This is used when reading or writing a schema/protocol. /// This prevents reading and writing of duplicate schema definitions within a protocol or schema file /// </summary> public class SchemaNames { /// <summary> /// Map of schema name and named schema objects /// </summary> public IDictionary<SchemaName, NamedSchema> Names { get; private set; } /// <summary> /// Constructor /// </summary> public SchemaNames() { Names = new Dictionary<SchemaName, NamedSchema>(); } /// <summary> /// Checks if given name is in the map /// </summary> /// <param name="name">schema name</param> /// <returns>true or false</returns> public bool Contains(SchemaName name) { if (Names.ContainsKey(name)) return true; return false; } /// <summary> /// Adds a schema name to the map if it doesn't exist yet /// </summary> /// <param name="name">schema name</param> /// <param name="schema">schema object</param> /// <returns>true if schema was added to the list, false if schema is already in the list</returns> public bool Add(SchemaName name, NamedSchema schema) { if (Names.ContainsKey(name)) return false; Names.Add(name, schema); return true; } /// <summary> /// Adds a named schema to the list /// </summary> /// <param name="schema">schema object</param> /// <returns>true if schema was added to the list, false if schema is already in the list</returns> public bool Add(NamedSchema schema) { SchemaName name = schema.SchemaName; return Add(name, schema); } /// <summary> /// Tries to get the value for the given name fields /// </summary> /// <param name="name">name of the schema</param> /// <param name="space">namespace of the schema</param> /// <param name="encspace">enclosing namespace of the schema</param> /// <param name="schema">schema object found</param> /// <returns>true if name is found in the map, false otherwise</returns> public bool TryGetValue(string name, string space, string encspace, out NamedSchema schema) { SchemaName schemaname = new SchemaName(name, space, encspace); return Names.TryGetValue(schemaname, out schema); } /// <summary> /// Returns the enumerator for the map /// </summary> /// <returns></returns> public IEnumerator<KeyValuePair<SchemaName, NamedSchema>> GetEnumerator() { return Names.GetEnumerator(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Backend.Areas.HelpPage.ModelDescriptions; using Backend.Areas.HelpPage.Models; namespace Backend.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Xml; using System.Collections; using System.IO; using System.Reflection; using System.Threading; using log4net.Appender; using log4net.Util; using log4net.Repository; namespace log4net.Config { /// <summary> /// Use this class to initialize the log4net environment using an Xml tree. /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// Configures a <see cref="ILoggerRepository"/> using an Xml tree. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> [Obsolete("Use XmlConfigurator instead of DOMConfigurator")] public sealed class DOMConfigurator { #region Private Instance Constructors /// <summary> /// Private constructor /// </summary> private DOMConfigurator() { } #endregion Protected Instance Constructors #region Configure static methods /// <summary> /// Automatically configures the log4net system based on the /// application's configuration settings. /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// Each application has a configuration file. This has the /// same name as the application with '.config' appended. /// This file is XML and calling this function prompts the /// configurator to look in that file for a section called /// <c>log4net</c> that contains the configuration data. /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure() { XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); } /// <summary> /// Automatically configures the <see cref="ILoggerRepository"/> using settings /// stored in the application's configuration file. /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// Each application has a configuration file. This has the /// same name as the application with '.config' appended. /// This file is XML and calling this function prompts the /// configurator to look in that file for a section called /// <c>log4net</c> that contains the configuration data. /// </remarks> /// <param name="repository">The repository to configure.</param> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(ILoggerRepository repository) { XmlConfigurator.Configure(repository); } /// <summary> /// Configures log4net using a <c>log4net</c> element /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// Loads the log4net configuration from the XML element /// supplied as <paramref name="element"/>. /// </remarks> /// <param name="element">The element to parse.</param> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(XmlElement element) { XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), element); } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified XML /// element. /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// Loads the log4net configuration from the XML element /// supplied as <paramref name="element"/>. /// </remarks> /// <param name="repository">The repository to configure.</param> /// <param name="element">The element to parse.</param> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(ILoggerRepository repository, XmlElement element) { XmlConfigurator.Configure(repository, element); } /// <summary> /// Configures log4net using the specified configuration file. /// </summary> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the log4net configuration data. /// </para> /// <para> /// The log4net configuration file can possible be specified in the application's /// configuration file (either <c>MyAppName.exe.config</c> for a /// normal application on <c>Web.config</c> for an ASP.NET application). /// </para> /// <example> /// The following example configures log4net using a configuration file, of which the /// location is stored in the application's configuration file : /// </example> /// <code lang="C#"> /// using log4net.Config; /// using System.IO; /// using System.Configuration; /// /// ... /// /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); /// </code> /// <para> /// In the <c>.config</c> file, the path to the log4net can be specified like this : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net-config-file" value="log.config"/> /// </appSettings> /// </configuration> /// </code> /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(FileInfo configFile) { XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); } /// <summary> /// Configures log4net using the specified configuration file. /// </summary> /// <param name="configStream">A stream to load the XML configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration data must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the log4net configuration data. /// </para> /// <para> /// Note that this method will NOT close the stream parameter. /// </para> /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(Stream configStream) { XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configStream); } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified configuration /// file. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The log4net configuration file can possible be specified in the application's /// configuration file (either <c>MyAppName.exe.config</c> for a /// normal application on <c>Web.config</c> for an ASP.NET application). /// </para> /// <example> /// The following example configures log4net using a configuration file, of which the /// location is stored in the application's configuration file : /// </example> /// <code lang="C#"> /// using log4net.Config; /// using System.IO; /// using System.Configuration; /// /// ... /// /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); /// </code> /// <para> /// In the <c>.config</c> file, the path to the log4net can be specified like this : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net-config-file" value="log.config"/> /// </appSettings> /// </configuration> /// </code> /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(ILoggerRepository repository, FileInfo configFile) { XmlConfigurator.Configure(repository, configFile); } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified configuration /// file. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configStream">The stream to load the XML configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration data must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// Note that this method will NOT close the stream parameter. /// </para> /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(ILoggerRepository repository, Stream configStream) { XmlConfigurator.Configure(repository, configStream); } #endregion Configure static methods #region ConfigureAndWatch static methods #if !NETCF /// <summary> /// Configures log4net using the file specified, monitors the file for changes /// and reloads the configuration if a change is detected. /// </summary> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The configuration file will be monitored using a <see cref="FileSystemWatcher"/> /// and depends on the behavior of that class. /// </para> /// <para> /// For more information on how to configure log4net using /// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>. /// </para> /// </remarks> /// <seealso cref="M:Configure(FileInfo)"/> [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")] static public void ConfigureAndWatch(FileInfo configFile) { XmlConfigurator.ConfigureAndWatch(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the file specified, /// monitors the file for changes and reloads the configuration if a change /// is detected. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The configuration file will be monitored using a <see cref="FileSystemWatcher"/> /// and depends on the behavior of that class. /// </para> /// <para> /// For more information on how to configure log4net using /// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>. /// </para> /// </remarks> /// <seealso cref="M:Configure(FileInfo)"/> [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")] static public void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) { XmlConfigurator.ConfigureAndWatch(repository, configFile); } #endif #endregion ConfigureAndWatch static methods } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Windows.Forms; using NBarCodes; namespace NBarCodes.Forms { /// <summary> /// Control to render bar codes. /// </summary> [//ToolboxBitmap(typeof(BarCodeControl), "BarCode.ico"), // Code...attribute, not to appear the visual designer Designer(typeof(BarCodeControlDesigner)), DefaultProperty("Data"), Description("Control to render barcodes.")] public class BarCodeControl : Control, IBarCodeSettings { private Font _errorFont; private Brush _errorBrush; private BarCodeGenerator _generator; /// <summary> /// Creates a new instance of the <see cref="BarCodeControl"/>. /// </summary> public BarCodeControl() { _errorFont = new Font("verdana", 16f, FontStyle.Bold); _errorBrush = Brushes.Red; _generator = new BarCodeGenerator(this); BackColor = Defaults.BackColor; Font = Defaults.Font; } #region Properties /// <summary> /// The type of barcode to render. /// </summary> [Description("The type of barcode to render."), Category("Appearance"), DefaultValue(BarCodeType.Code128)] public BarCodeType Type { get { return _type; } set { _type = value; Refresh(); } } BarCodeType _type = BarCodeType.Code128; /// <summary> /// The data to render in the barcode. /// </summary> [Bindable(true), Category("Appearance"), DefaultValue("12345"), Description("The data to render in the barcode.")] public string Data { get { return _data; } set { if (value == null) { throw new ArgumentNullException(); } _data = value; Refresh(); } } string _data = "12345"; /// <summary> /// The unit to use when rendering the barcode. Affects all sizing properties. /// </summary> [Description("The unit to use when rendering the barcode. Affects all sizing properties."), Category("Appearance"), RefreshProperties(RefreshProperties.All), DefaultValue(Defaults.Unit)] public BarCodeUnit Unit { get { return _unit; } set { BarCodeUnit oldUnit = _unit; _unit = value; if (oldUnit != _unit) { _generator.ConvertValues(oldUnit, _unit); Refresh(); } } } BarCodeUnit _unit = Defaults.Unit; /// <summary> /// The DPI (dots per inch) to use when rendering the barcode. Affects all sizing properties. /// </summary> [Description("The DPI (dots per inch) to use when rendering the barcode. Affects all sizing properties."), Category("Appearance"), RefreshProperties(RefreshProperties.All)] public int Dpi { get { return _dpi; } set { int oldDpi = _dpi; _dpi = value; if (oldDpi != _dpi) { _generator.ConvertDpi(oldDpi, _dpi); Refresh(); } } } int _dpi = Defaults.Dpi; /// <summary> /// The back color of the barcode. /// </summary> [TypeConverter(typeof(ColorConverter)), Bindable(true), Category("Appearance"), DefaultValue(typeof(Color), Defaults.BackColorName), Description("The back color of the barcode.")] public override Color BackColor { get { return base.BackColor; } set { base.BackColor = value; } } /// <summary> /// The color of the bar of the barcode. /// </summary> [TypeConverter(typeof(ColorConverter)), Bindable(true), Category("Appearance"), DefaultValue(typeof(Color), Defaults.BarColorName), Description("The color of the bar of the barcode.")] public Color BarColor { get { return _barColor; } set { _barColor = value; Refresh(); } } Color _barColor = Defaults.BarColor; /// <summary> /// The height of the bar. /// </summary> [Description("The height of the bar."), Category("Appearance"), Bindable(true), DefaultValue(Defaults.BarHeight)] public float BarHeight { get { return _barHeight; } set { _barHeight = value; Refresh(); } } float _barHeight = Defaults.BarHeight; /// <summary> /// The font color of the barcode. /// </summary> [TypeConverter(typeof(ColorConverter)), Bindable(true), Category("Appearance"), DefaultValue(typeof(Color), Defaults.FontColorName), Description("The font color of the barcode.")] public Color FontColor { get { return _fontColor; } set { _fontColor = value; Refresh(); } } Color _fontColor = Defaults.FontColor; /// <summary> /// The extra height of the guard on EAN or UPC barcodes. /// </summary> [Description("The extra height of the guard on EAN or UPC barcodes."), Category("Appearance"), Bindable(true), DefaultValue(Defaults.GuardExtraHeight)] public float GuardExtraHeight { get { return _guardExtraHeight; } set { _guardExtraHeight = value; Refresh(); } } float _guardExtraHeight = Defaults.GuardExtraHeight; /// <summary> /// The width of a bar in module-based barcodes. /// </summary> [Description("The width of a bar in module-based barcodes."), Category("Appearance"), Bindable(true), DefaultValue(Defaults.ModuleWidth)] public float ModuleWidth { get { return _moduleWidth; } set { _moduleWidth = value; Refresh(); } } float _moduleWidth = Defaults.ModuleWidth; /// <summary> /// The width of a narrow bar in thickness-based barcodes. /// </summary> [Description("The width of a narrow bar in thickness-based barcodes."), Category("Appearance"), Bindable(true), DefaultValue(Defaults.NarrowWidth)] public float NarrowWidth { get { return _narrowWidth; } set { _narrowWidth = value; Refresh(); } } float _narrowWidth = Defaults.NarrowWidth; /// <summary> /// The width of a wide bar in thickness-based barcodes. /// </summary> [Description("The width of a wide bar in thickness-based barcodes."), Category("Appearance"), Bindable(true), DefaultValue(Defaults.WideWidth)] public float WideWidth { get { return _wideWidth; } set { _wideWidth = value; Refresh(); } } float _wideWidth = Defaults.WideWidth; /// <summary> /// The height offset of the barcode. /// </summary> [Description("The height offset of the barcode."), Category("Appearance"), Bindable(true), DefaultValue(Defaults.OffsetHeight)] public float OffsetHeight { get { return _offsetHeight; } set { _offsetHeight = value; Refresh(); } } float _offsetHeight = Defaults.OffsetHeight; /// <summary> /// The width offset of the barcode. /// </summary> [Description("The width offset of the barcode."), Category("Appearance"), Bindable(true), DefaultValue(Defaults.OffsetWidth)] public float OffsetWidth { get { return _offsetWidth; } set { _offsetWidth = value; Refresh(); } } float _offsetWidth = Defaults.OffsetWidth; /// <summary> /// The font of the barcode text. /// </summary> [DefaultValue(typeof(Font), Defaults.FontName), Description("The font of the barcode text."), Category("Appearance")] public override Font Font { get { return base.Font; } set { base.Font = value; Refresh(); } } /// <summary> /// The position of the text. /// </summary> [Description("The position of the text."), Category("Appearance"), Bindable(true), DefaultValue(Defaults.TextPos)] public TextPosition TextPosition { get { return _textPosition; } set { _textPosition = value; Refresh(); } } TextPosition _textPosition = Defaults.TextPos; /// <summary> /// Whether to use a checksum on barcodes where it is optional. /// </summary> [Description("Whether to use a checksum on barcodes where it is optional."), Category("Behavior"), Bindable(true), DefaultValue(false)] public bool UseChecksum { get { return _useChecksum; } set { _useChecksum = value; Refresh(); } } bool _useChecksum = false; #endregion /// <summary> /// Renders the barcode. /// </summary> /// <param name="e">Paint event arguments.</param> protected override void OnPaint(PaintEventArgs e) { DrawBarCode(e.Graphics); } /// <summary> /// Draws the barcode in the canvas passed. /// </summary> /// <param name="canvas">Canvas to draw barcode into.</param> public void DrawBarCode(Graphics canvas) { string errorMessage; if (_generator.TestRender(out errorMessage)) { using (var barCodeImage = _generator.GenerateImage()) { Size = new Size(barCodeImage.Width, barCodeImage.Height); canvas.DrawImage(barCodeImage, 0, 0); } } else { Size = new Size(250, 50); canvas.DrawString(errorMessage, _errorFont, _errorBrush, new RectangleF(0, 0, 250, 50)); } } } }
/* Copyright (c) 2007 Michael Lidgren 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.Net; namespace Lidgren.Library.Network { /// <summary> /// A network server /// </summary> public class NetServer : NetBase { /// <summary> /// List of all connections to this server; may contain null entries and /// entries may have status disconnected /// </summary> public NetConnection[] Connections; private Dictionary<int, NetConnection> m_connectionsLookUpTable; /// <summary> /// Event fired just before a client is connected; allows the application to reject unwanted connections /// </summary> public event EventHandler<NetConnectRequestEventArgs> ConnectionRequest; /// <summary> /// Gets the number of client that are connected (or connecting!) /// </summary> public int NumConnected { get { int retval = 0; for (int i = 0; i < Connections.Length; i++) if (Connections[i] != null && Connections[i].Status != NetConnectionStatus.Disconnected) retval++; return retval; } } /// <summary> /// Constructor for a server instance /// </summary> public NetServer(NetAppConfiguration config, NetLog log) { NetBase.CurrentContext = this; InitBase(config, log); Connections = new NetConnection[config.MaximumConnections]; m_connectionsLookUpTable = new Dictionary<int, NetConnection>(); } /// <summary> /// Read messages from network and sends unsent messages, resends etc /// This method should be called as often as possible /// </summary> public void Heartbeat() { double now = NetTime.Now; NetBase.CurrentContext = this; // read all packets while(ReadPacket()); // connection heartbeats for (int i = 0; i < Connections.Length; i++) { NetConnection connection = Connections[i]; if (connection != null) { NetConnectionStatus status = connection.Status; if (status == NetConnectionStatus.Connected || status == NetConnectionStatus.Connecting || status == NetConnectionStatus.Reconnecting) connection.Heartbeat(now); } } } private NetConnection FindConnection(IPEndPoint endpoint) { NetConnection retval; if (m_connectionsLookUpTable.TryGetValue(endpoint.GetHashCode(), out retval)) return retval; return null; /* for (int i = 0; i < Connections.Length; i++) { if (Connections[i] != null && Connections[i].Status != NetConnectionStatus.Disconnected && Connections[i].RemoteEndpoint.Equals(endpoint)) return Connections[i]; } return null; */ } internal override void HandlePacket(NetBuffer buffer, int bytesReceived, IPEndPoint senderEndpoint) { double now = NetTime.Now; NetConnection sender = FindConnection(senderEndpoint); if (sender != null) { sender.m_lastHeardFromRemote = now; if (sender.m_encryption.SymmetricEncryptionKeyBytes != null) { bool ok = sender.m_encryption.DecryptSymmetric(buffer); if (!ok) { Log.Warning("Failed to decrypt packet from client " + sender); return; } } } try { NetMessage response; int messagesReceived = 0; int usrMessagesReceived = 0; int ackMessagesReceived = 0; while (buffer.ReadBitsLeft > 7) { NetMessage msg = NetMessage.Decode(buffer); if (msg == null) break; // done messagesReceived++; msg.Sender = sender; switch (msg.m_type) { case NetMessageType.Acknowledge: case NetMessageType.AcknowledgeBitField: if (sender == null) { Log.Warning("Received Ack from not-connected source!"); } else { //Log.Debug("Received ack " + msg.SequenceChannel + "|" + msg.SequenceNumber); sender.ReceiveAcknowledge(msg); ackMessagesReceived++; } break; case NetMessageType.Handshake: NetHandshakeType tp = (NetHandshakeType)msg.ReadByte(); if (tp == NetHandshakeType.ConnectResponse) { Log.Warning("Received ConnectResponse?!"); } else if (tp == NetHandshakeType.Connect) { if (sender == null) { NetHandshake.HandleConnect(msg, this, senderEndpoint); } else { // resend response NetHandshake.SendConnectResponse(this, sender, senderEndpoint); Log.Verbose("Redundant Connect received; resending response"); } } else if (tp == NetHandshakeType.ConnectionEstablished) { if (sender == null) { Log.Warning("Received ConnectionEstablished, but no sender connection?!"); } else { float rt = (float)(now - sender.m_firstSentHandshake); sender.m_ping.Initialize(rt); ushort remoteValue = msg.ReadUInt16(); sender.RemoteClockOffset = NetTime.CalculateOffset(now, remoteValue, rt); Log.Verbose("Reinitializing remote clock offset to " + sender.RemoteClockOffset + " ms (roundtrip " + NetUtil.SecToMil(rt) + " ms)"); if (sender.Status == NetConnectionStatus.Connected) { Log.Verbose("Redundant ConnectionEstablished received"); } else { Log.Debug("Connection established"); sender.SetStatus(NetConnectionStatus.Connected, "Connected by established"); } } } else { // disconnected if (sender == null) { Log.Warning("Disconnected received from unconnected source: " + senderEndpoint); return; } string reason = msg.ReadString(); sender.Disconnected(reason); } break; case NetMessageType.Discovery: Log.Debug("Answering discovery response from " + senderEndpoint); response = NetDiscovery.EncodeResponse(this); SendSingleMessageAtOnce(response, null, senderEndpoint); break; case NetMessageType.PingPong: if (sender == null) return; bool isPong = msg.ReadBoolean(); bool isOptimizeInfo = msg.ReadBoolean(); if (isOptimizeInfo) { // DON'T handle optimizeinfo... only clients should adapt to server ping info } else if (isPong) { if (sender.Status == NetConnectionStatus.Connected) sender.m_ping.HandlePong(now, msg); } else { NetPing.ReplyPong(msg, sender); // send pong } break; case NetMessageType.User: case NetMessageType.UserFragmented: usrMessagesReceived++; if (sender == null) { Log.Warning("User message received from unconnected source: " + senderEndpoint); return; // don't handle user messages from unconnected sources } if (sender.Status == NetConnectionStatus.Connecting) sender.SetStatus(NetConnectionStatus.Connected, "Connected by user message"); sender.ReceiveMessage(now, msg); break; default: Log.Warning("Bad message type: " + msg); break; } } if (sender != null) { NetStatistics stats = sender.Statistics; stats.PacketsReceived++; stats.MessagesReceived += messagesReceived; stats.UserMessagesReceived += usrMessagesReceived; stats.AckMessagesReceived += ackMessagesReceived; stats.BytesReceived += bytesReceived; } } catch (Exception ex) { Log.Error("Failed to parse packet correctly; read/write mismatch? " + ex); } } /// <summary> /// Reads a received message from any connection to the server /// </summary> public NetMessage ReadMessage() { NetBase.CurrentContext = this; for (int i = 0; i < Connections.Length; i++) { if (Connections[i] != null && Connections[i].Status != NetConnectionStatus.Disconnected) { if (Connections[i].m_receivedMessages.Count > 0) return Connections[i].m_receivedMessages.Dequeue(); } } return null; } internal override void HandleConnectionReset(IPEndPoint ep) { NetConnection conn = FindConnection(ep); if (conn == null) return; // gulp if (conn.Status == NetConnectionStatus.Disconnected) { Log.Verbose("ConnectionReset from already disconnected connection " + conn); return; } // oi! disconnect conn.SetStatus(NetConnectionStatus.Disconnected, "Connection Reset"); } internal NetConnection AddConnection(IPEndPoint remoteEndpoint, int remoteClockOffset) { // find empty slot for (int i = 0; i < Connections.Length; i++) { if (Connections[i] == null) { NetConnection conn = new NetConnection(this, remoteEndpoint); conn.RemoteClockOffset = remoteClockOffset; Log.Verbose("Initializing remote clock offset to " + remoteClockOffset + " ms"); conn.m_firstSentHandshake = NetTime.Now; conn.m_lastSentHandshake = conn.m_firstSentHandshake; int hash = remoteEndpoint.GetHashCode(); NetConnection existingConn; if (m_connectionsLookUpTable.TryGetValue(hash, out existingConn)) { if (existingConn.Status != NetConnectionStatus.Disconnected) throw new NetException("Ack thphth; Connections lookup hash value taken!"); // disconnected; just remove it RemoveConnection(existingConn); } Connections[i] = conn; m_connectionsLookUpTable[hash] = conn; conn.SetStatus(NetConnectionStatus.Connecting, "Connecting from " + remoteEndpoint); return conn; } } Log.Warning("Failed to add new connection!"); return null; } /// <summary> /// Sends a message to a certain connection using the channel specified /// </summary> public bool SendMessage(NetMessage msg, NetConnection connection, NetChannel channel) { if (connection == null) throw new ArgumentNullException("connection"); if (connection.Status == NetConnectionStatus.Disconnected) { Log.Warning("SendMessage failed - Connection is Disconnected!"); return false; } connection.SendMessage(msg, channel); return true; } /// <summary> /// Sends a message to several connections using the channel specified; should NOT be /// used for messages which uses the string table read/write methods! /// </summary> /// <returns>number of messages sent</returns> public int SendMessage(NetMessage msg, IEnumerable<NetConnection> connections, NetChannel channel) { if (connections == null) throw new ArgumentNullException("connection"); int numSentTo = 0; bool originalSent = false; foreach (NetConnection connection in connections) { if (connection == null || (connection.Status != NetConnectionStatus.Connected && connection.Status != NetConnectionStatus.Reconnecting)) continue; if (!originalSent) { connection.SendMessage(msg, channel); originalSent = true; } else { // send refcloned message NetMessage clone = NetMessage.CreateReferenceClone(msg); connection.SendMessage(clone, channel); } numSentTo++; } // Log.Debug("Broadcast to " + numSentTo + " connections..."); return numSentTo; } /// <summary> /// Broadcasts a message to all connections except specified; should NOT be used for /// messages which uses the string table read/write methods! /// </summary> public int Broadcast(NetMessage msg, NetChannel channel, NetConnection except) { int numSentTo = 0; bool originalSent = false; foreach (NetConnection conn in Connections) { if (conn == null || conn == except || (conn.Status != NetConnectionStatus.Connected && conn.Status != NetConnectionStatus.Reconnecting)) continue; numSentTo++; if (!originalSent) { // send original conn.SendMessage(msg, channel); originalSent = true; } else { // send refcloned message NetMessage clone = NetMessage.CreateReferenceClone(msg); conn.SendMessage(clone, channel); numSentTo++; } } return numSentTo; } /// <summary> /// Broadcasts a message to all connections; should NOT be used for messages which /// uses the string table read/write methods! /// </summary> public int Broadcast(NetMessage msg, NetChannel channel) { return SendMessage(msg, Connections, channel); } /// <summary> /// Sends all unsent messages for all connections; may interfere with proper throttling! /// </summary> public void FlushMessages() { for (int i = 0; i < Connections.Length; i++) { NetConnection connection = Connections[i]; if (connection != null && connection.Status != NetConnectionStatus.Disconnected) connection.SendUnsentMessages(true, 0.01f); } } /// <summary> /// Sends disconnect to all connections and stops listening for new connections /// </summary> public override void Shutdown(string reason) { for (int i = 0; i < Connections.Length; i++) { if (Connections[i] != null) { Log.Debug("Statistics for " + Connections[i]); Connections[i].DumpStatisticsToLog(Log); if (Connections[i].Status != NetConnectionStatus.Disconnected) Connections[i].Disconnect(reason); Connections[i] = null; } } if (m_lagLoss != null) { Log.Debug("Artificially delayed packets still in queue: " + m_lagLoss.m_delayed.Count); foreach (NetLogLossInducer.DelayedPacket dm in m_lagLoss.m_delayed) Log.Debug("... " + dm); } base.Shutdown(reason); } internal bool ApproveConnection(IPEndPoint senderEndpoint, byte[] customData, out string failReason) { if (ConnectionRequest != null) { NetConnectRequestEventArgs ea = new NetConnectRequestEventArgs(); ea.EndPoint = senderEndpoint; ea.CustomData = customData; ea.MayConnect = true; ea.DenialReason = null; // ask application ConnectionRequest(this, ea); failReason = ea.DenialReason; return ea.MayConnect; } failReason = null; return true; } /// <summary> /// Remove connection from Connections list(s) /// </summary> internal void RemoveConnection(NetConnection conn) { if (conn == null) return; Log.Debug("Removing connection " + conn); for(int i=0;i<Connections.Length;i++) if (Connections[i] == conn) Connections[i] = null; // also remove lookup entry int hash = conn.RemoteEndpoint.GetHashCode(); if (m_connectionsLookUpTable.ContainsKey(hash)) m_connectionsLookUpTable.Remove(hash); } public override string ToString() { return "[NetServer " + this.NumConnected.ToString() + " of " + this.Configuration.MaximumConnections.ToString() + " connected]"; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type UserCalendarsCollectionRequest. /// </summary> public partial class UserCalendarsCollectionRequest : BaseRequest, IUserCalendarsCollectionRequest { /// <summary> /// Constructs a new UserCalendarsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public UserCalendarsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Calendar to the collection via POST. /// </summary> /// <param name="calendar">The Calendar to add.</param> /// <returns>The created Calendar.</returns> public System.Threading.Tasks.Task<Calendar> AddAsync(Calendar calendar) { return this.AddAsync(calendar, CancellationToken.None); } /// <summary> /// Adds the specified Calendar to the collection via POST. /// </summary> /// <param name="calendar">The Calendar to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Calendar.</returns> public System.Threading.Tasks.Task<Calendar> AddAsync(Calendar calendar, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Calendar>(calendar, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IUserCalendarsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IUserCalendarsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<UserCalendarsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Expand(Expression<Func<Calendar, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Select(Expression<Func<Calendar, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using NuGet.Resources; namespace NuGet { public abstract class PackageWalker { private readonly Dictionary<IPackage, PackageWalkInfo> _packageLookup = new Dictionary<IPackage, PackageWalkInfo>(); protected PackageWalker() { Marker = new PackageMarker(); } protected virtual bool RaiseErrorOnCycle { get { return true; } } protected virtual bool SkipDependencyResolveError { get { return false; } } protected virtual bool IgnoreDependencies { get { return false; } } protected virtual bool AllowPrereleaseVersions { get { return true; } } protected PackageMarker Marker { get; private set; } protected virtual bool IgnoreWalkInfo { get { return false; } } public void Walk(IPackage package) { // Do nothing if we saw this package already if (Marker.IsVisited(package)) { ProcessPackageTarget(package); return; } OnBeforePackageWalk(package); // Mark the package as processing Marker.MarkProcessing(package); if (!IgnoreDependencies) { foreach (var dependency in package.Dependencies) { // Try to resolve the dependency from the visited packages first IPackage resolvedDependency = Marker.ResolveDependency(dependency, AllowPrereleaseVersions, preferListedPackages: false) ?? ResolveDependency(dependency); if (resolvedDependency == null) { OnDependencyResolveError(dependency); // If we're skipping dependency resolve errors then move on to the next // dependency if (SkipDependencyResolveError) { continue; } return; } if (!IgnoreWalkInfo) { // Set the parent PackageWalkInfo dependencyInfo = GetPackageInfo(resolvedDependency); dependencyInfo.Parent = package; } Marker.AddDependent(package, resolvedDependency); if (!OnAfterResolveDependency(package, resolvedDependency)) { continue; } if (Marker.IsCycle(resolvedDependency) || Marker.IsVersionCycle(resolvedDependency.Id)) { if (RaiseErrorOnCycle) { List<IPackage> packages = Marker.Packages.ToList(); packages.Add(resolvedDependency); throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.CircularDependencyDetected, String.Join(" => ", packages.Select(p => p.GetFullName())))); } continue; } Walk(resolvedDependency); } } // Mark the package as visited Marker.MarkVisited(package); ProcessPackageTarget(package); OnAfterPackageWalk(package); } /// <summary> /// Resolve the package target (i.e. if the parent package was a meta package then set the parent to the current project type) /// </summary> private void ProcessPackageTarget(IPackage package) { if (IgnoreWalkInfo) { return; } PackageWalkInfo info = GetPackageInfo(package); // If our parent is an unknown then we need to bubble up the type if (info.Parent != null) { PackageWalkInfo parentInfo = GetPackageInfo(info.Parent); Debug.Assert(parentInfo != null); if (parentInfo.InitialTarget == PackageTargets.None) { // Update the parent target type parentInfo.Target |= info.Target; // If we ended up with both that means we found a dependency only packages // that has a mix of solution and project level packages if (parentInfo.Target == PackageTargets.All) { throw new InvalidOperationException(NuGetResources.DependencyOnlyCannotMixDependencies); } } // Solution packages can't depend on project level packages if (parentInfo.Target == PackageTargets.External && info.Target.HasFlag(PackageTargets.Project)) { throw new InvalidOperationException(NuGetResources.ExternalPackagesCannotDependOnProjectLevelPackages); } } } protected virtual bool OnAfterResolveDependency(IPackage package, IPackage dependency) { return true; } protected virtual void OnBeforePackageWalk(IPackage package) { } protected virtual void OnAfterPackageWalk(IPackage package) { } protected virtual void OnDependencyResolveError(PackageDependency dependency) { } protected abstract IPackage ResolveDependency(PackageDependency dependency); protected internal PackageWalkInfo GetPackageInfo(IPackage package) { PackageWalkInfo info; if (!_packageLookup.TryGetValue(package, out info)) { info = new PackageWalkInfo(GetPackageTarget(package)); _packageLookup.Add(package, info); } return info; } private static PackageTargets GetPackageTarget(IPackage package) { if (package.HasProjectContent()) { return PackageTargets.Project; } if (package.IsDependencyOnly()) { return PackageTargets.None; } return PackageTargets.External; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.Logging; using Orleans.Clustering.AzureStorage; using Orleans.Clustering.AzureStorage.Utilities; using Orleans.Runtime; namespace Orleans.AzureUtils { internal class OrleansSiloInstanceManager { public string TableName { get; } private const string INSTANCE_STATUS_CREATED = nameof(SiloStatus.Created); //"Created"; private const string INSTANCE_STATUS_ACTIVE = nameof(SiloStatus.Active); //"Active"; private const string INSTANCE_STATUS_DEAD = nameof(SiloStatus.Dead); //"Dead"; private readonly AzureTableDataManager<SiloInstanceTableEntry> storage; private readonly ILogger logger; private readonly AzureStoragePolicyOptions storagePolicyOptions; public string DeploymentId { get; private set; } private OrleansSiloInstanceManager( string clusterId, ILoggerFactory loggerFactory, AzureStorageOperationOptions options) { DeploymentId = clusterId; TableName = options.TableName; logger = loggerFactory.CreateLogger<OrleansSiloInstanceManager>(); storage = new AzureTableDataManager<SiloInstanceTableEntry>( options, loggerFactory.CreateLogger<AzureTableDataManager<SiloInstanceTableEntry>>()); this.storagePolicyOptions = options.StoragePolicyOptions; } public static async Task<OrleansSiloInstanceManager> GetManager( string clusterId, ILoggerFactory loggerFactory, AzureStorageOperationOptions options) { var instance = new OrleansSiloInstanceManager(clusterId, loggerFactory, options); try { await instance.storage.InitTableAsync(); } catch (Exception ex) { string errorMsg = string.Format("Exception trying to create or connect to the Azure table: {0}", ex.Message); instance.logger.Error((int)TableStorageErrorCode.AzureTable_33, errorMsg, ex); throw new OrleansException(errorMsg, ex); } return instance; } public SiloInstanceTableEntry CreateTableVersionEntry(int tableVersion) { return new SiloInstanceTableEntry { DeploymentId = DeploymentId, PartitionKey = DeploymentId, RowKey = SiloInstanceTableEntry.TABLE_VERSION_ROW, MembershipVersion = tableVersion.ToString(CultureInfo.InvariantCulture) }; } public void RegisterSiloInstance(SiloInstanceTableEntry entry) { entry.Status = INSTANCE_STATUS_CREATED; logger.Info(ErrorCode.Runtime_Error_100270, "Registering silo instance: {0}", entry.ToString()); Task.WaitAll(new Task[] { storage.UpsertTableEntryAsync(entry) }); } public Task<string> UnregisterSiloInstance(SiloInstanceTableEntry entry) { entry.Status = INSTANCE_STATUS_DEAD; logger.Info(ErrorCode.Runtime_Error_100271, "Unregistering silo instance: {0}", entry.ToString()); return storage.UpsertTableEntryAsync(entry); } public Task<string> ActivateSiloInstance(SiloInstanceTableEntry entry) { logger.Info(ErrorCode.Runtime_Error_100272, "Activating silo instance: {0}", entry.ToString()); entry.Status = INSTANCE_STATUS_ACTIVE; return storage.UpsertTableEntryAsync(entry); } /// <summary> /// Represent a silo instance entry in the gateway URI format. /// </summary> /// <param name="gateway">The input silo instance</param> /// <returns></returns> private static Uri ConvertToGatewayUri(SiloInstanceTableEntry gateway) { int proxyPort = 0; if (!string.IsNullOrEmpty(gateway.ProxyPort)) int.TryParse(gateway.ProxyPort, out proxyPort); int gen = 0; if (!string.IsNullOrEmpty(gateway.Generation)) int.TryParse(gateway.Generation, out gen); SiloAddress address = SiloAddress.New(new IPEndPoint(IPAddress.Parse(gateway.Address), proxyPort), gen); return address.ToGatewayUri(); } public async Task<IList<Uri>> FindAllGatewayProxyEndpoints() { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Runtime_Error_100277, "Searching for active gateway silos for deployment {0}.", this.DeploymentId); const string zeroPort = "0"; try { string filterOnPartitionKey = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.PartitionKey), QueryComparisons.Equal, this.DeploymentId); string filterOnStatus = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.Status), QueryComparisons.Equal, INSTANCE_STATUS_ACTIVE); string filterOnProxyPort = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.ProxyPort), QueryComparisons.NotEqual, zeroPort); string query = TableQuery.CombineFilters(filterOnPartitionKey, TableOperators.And, TableQuery.CombineFilters(filterOnStatus, TableOperators.And, filterOnProxyPort)); var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query); var gatewaySiloInstances = queryResults.Select(entity => ConvertToGatewayUri(entity.Item1)).ToList(); logger.Info(ErrorCode.Runtime_Error_100278, "Found {0} active Gateway Silos for deployment {1}.", gatewaySiloInstances.Count, this.DeploymentId); return gatewaySiloInstances; }catch(Exception exc) { logger.Error(ErrorCode.Runtime_Error_100331, string.Format("Error searching for active gateway silos for deployment {0} ", this.DeploymentId), exc); throw; } } public async Task<string> DumpSiloInstanceTable() { var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId); SiloInstanceTableEntry[] entries = queryResults.Select(entry => entry.Item1).ToArray(); var sb = new StringBuilder(); sb.Append(String.Format("Deployment {0}. Silos: ", DeploymentId)); // Loop through the results, displaying information about the entity Array.Sort(entries, (e1, e2) => { if (e1 == null) return (e2 == null) ? 0 : -1; if (e2 == null) return (e1 == null) ? 0 : 1; if (e1.SiloName == null) return (e2.SiloName == null) ? 0 : -1; if (e2.SiloName == null) return (e1.SiloName == null) ? 0 : 1; return String.CompareOrdinal(e1.SiloName, e2.SiloName); }); foreach (SiloInstanceTableEntry entry in entries) { sb.AppendLine(String.Format("[IP {0}:{1}:{2}, {3}, Instance={4}, Status={5}]", entry.Address, entry.Port, entry.Generation, entry.HostName, entry.SiloName, entry.Status)); } return sb.ToString(); } internal Task<string> MergeTableEntryAsync(SiloInstanceTableEntry data) { return storage.MergeTableEntryAsync(data, AzureTableUtils.ANY_ETAG); // we merge this without checking eTags. } internal Task<Tuple<SiloInstanceTableEntry, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey) { return storage.ReadSingleTableEntryAsync(partitionKey, rowKey); } internal async Task<int> DeleteTableEntries(string clusterId) { if (clusterId == null) throw new ArgumentNullException(nameof(clusterId)); var entries = await storage.ReadAllTableEntriesForPartitionAsync(clusterId); var entriesList = new List<Tuple<SiloInstanceTableEntry, string>>(entries); await DeleteEntriesBatch(entriesList); return entriesList.Count; } public async Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate) { var entriesList = (await FindAllSiloEntries()) .Where(entry => !string.Equals(SiloInstanceTableEntry.TABLE_VERSION_ROW, entry.Item1.RowKey) && entry.Item1.Status != INSTANCE_STATUS_ACTIVE && entry.Item1.Timestamp < beforeDate) .ToList(); await DeleteEntriesBatch(entriesList); } private async Task DeleteEntriesBatch(List<Tuple<SiloInstanceTableEntry, string>> entriesList) { if (entriesList.Count <= this.storagePolicyOptions.MaxBulkUpdateRows) { await storage.DeleteTableEntriesAsync(entriesList); } else { var tasks = new List<Task>(); foreach (var batch in entriesList.BatchIEnumerable(this.storagePolicyOptions.MaxBulkUpdateRows)) { tasks.Add(storage.DeleteTableEntriesAsync(batch)); } await Task.WhenAll(tasks); } } internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindSiloEntryAndTableVersionRow(SiloAddress siloAddress) { string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress); string filterOnPartitionKey = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.PartitionKey), QueryComparisons.Equal, this.DeploymentId); string filterOnRowKey1 = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.RowKey), QueryComparisons.Equal, rowKey); string filterOnRowKey2 = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.RowKey), QueryComparisons.Equal, SiloInstanceTableEntry.TABLE_VERSION_ROW); string query = TableQuery.CombineFilters(filterOnPartitionKey, TableOperators.And, TableQuery.CombineFilters(filterOnRowKey1, TableOperators.Or, filterOnRowKey2)); var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query); var asList = queryResults.ToList(); if (asList.Count < 1 || asList.Count > 2) throw new KeyNotFoundException(string.Format("Could not find table version row or found too many entries. Was looking for key {0}, found = {1}", siloAddress.ToLongString(), Utils.EnumerableToString(asList))); int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW); if (numTableVersionRows < 1) throw new KeyNotFoundException(string.Format("Did not read table version row. Read = {0}", Utils.EnumerableToString(asList))); if (numTableVersionRows > 1) throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList))); return asList; } internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindAllSiloEntries() { var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId); var asList = queryResults.ToList(); if (asList.Count < 1) throw new KeyNotFoundException(string.Format("Could not find enough rows in the FindAllSiloEntries call. Found = {0}", Utils.EnumerableToString(asList))); int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW); if (numTableVersionRows < 1) throw new KeyNotFoundException(string.Format("Did not find table version row. Read = {0}", Utils.EnumerableToString(asList))); if (numTableVersionRows > 1) throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList))); return asList; } /// <summary> /// Insert (create new) row entry /// </summary> internal async Task<bool> TryCreateTableVersionEntryAsync() { try { var versionRow = await storage.ReadSingleTableEntryAsync(DeploymentId, SiloInstanceTableEntry.TABLE_VERSION_ROW); if (versionRow != null && versionRow.Item1 != null) { return false; } SiloInstanceTableEntry entry = CreateTableVersionEntry(0); await storage.CreateTableEntryAsync(entry); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureTableUtils.IsContentionError(httpStatusCode)) return false; throw; } } /// <summary> /// Insert (create new) row entry /// </summary> /// <param name="siloEntry">Silo Entry to be written</param> /// <param name="tableVersionEntry">Version row to update</param> /// <param name="tableVersionEtag">Version row eTag</param> internal async Task<bool> InsertSiloEntryConditionally(SiloInstanceTableEntry siloEntry, SiloInstanceTableEntry tableVersionEntry, string tableVersionEtag) { try { await storage.InsertTwoTableEntriesConditionallyAsync(siloEntry, tableVersionEntry, tableVersionEtag); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureTableUtils.IsContentionError(httpStatusCode)) return false; throw; } } /// <summary> /// Conditionally update the row for this entry, but only if the eTag matches with the current record in data store /// </summary> /// <param name="siloEntry">Silo Entry to be written</param> /// <param name="entryEtag">ETag value for the entry being updated</param> /// <param name="tableVersionEntry">Version row to update</param> /// <param name="versionEtag">ETag value for the version row</param> /// <returns></returns> internal async Task<bool> UpdateSiloEntryConditionally(SiloInstanceTableEntry siloEntry, string entryEtag, SiloInstanceTableEntry tableVersionEntry, string versionEtag) { try { await storage.UpdateTwoTableEntriesConditionallyAsync(siloEntry, entryEtag, tableVersionEntry, versionEtag); return true; } catch (Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (!AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("UpdateSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureTableUtils.IsContentionError(httpStatusCode)) return false; throw; } } } }
// 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.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using NativeLong=System.IntPtr; using NativeULong=System.UIntPtr; internal static partial class Interop { internal static partial class libcrypto { [DllImport(Libraries.LibCrypto)] internal static extern void X509_free(IntPtr a); [DllImport(Libraries.LibCrypto)] internal static extern unsafe int i2d_X509(SafeX509Handle x, byte** @out); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509Handle X509_dup(IntPtr handle); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509Handle X509_dup(SafeX509Handle handle); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509Handle PEM_read_bio_X509_AUX(SafeBioHandle bio, IntPtr zero, IntPtr zero1, IntPtr zero2); [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_get_serialNumber(SafeX509Handle x); [DllImport(Libraries.LibCrypto)] internal static extern int X509_NAME_print_ex(SafeBioHandle @out, SafeX509NameHandle nm, int indent, NativeULong flags); [DllImport(Libraries.LibCrypto)] internal static extern void X509_NAME_free(IntPtr a); [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_get_issuer_name(SafeX509Handle a); [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_get_subject_name(SafeX509Handle a); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_check_purpose(SafeX509Handle x, int id, int ca); [DllImport(Libraries.LibCrypto)] internal static extern int X509_check_issued(SafeX509Handle issuer, SafeX509Handle subject); [DllImport(Libraries.LibCrypto)] internal static extern NativeULong X509_issuer_name_hash(SafeX509Handle x); [DllImport(Libraries.LibCrypto)] internal static extern int X509_get_ext_count(SafeX509Handle x); // Returns a pointer already being tracked by the SafeX509Handle, shouldn't be SafeHandle tracked/freed. // Bounds checking is in place for "loc", IntPtr.Zero is returned on violations. [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_get_ext(SafeX509Handle x, int loc); // Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed. [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_EXTENSION_get_object(IntPtr ex); // Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed. [DllImport(Libraries.LibCrypto)] internal static extern IntPtr X509_EXTENSION_get_data(IntPtr ex); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_EXTENSION_get_critical(IntPtr ex); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509StoreHandle X509_STORE_new(); [DllImport(Libraries.LibCrypto)] internal static extern void X509_STORE_free(IntPtr v); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_STORE_add_cert(SafeX509StoreHandle ctx, SafeX509Handle x); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_STORE_add_crl(SafeX509StoreHandle ctx, SafeX509CrlHandle x); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_STORE_set_flags(SafeX509StoreHandle ctx, X509VerifyFlags flags); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509StoreCtxHandle X509_STORE_CTX_new(); [DllImport(Libraries.LibCrypto)] internal static extern void X509_STORE_CTX_free(IntPtr v); [DllImport(Libraries.LibCrypto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509_STORE_CTX_init(SafeX509StoreCtxHandle ctx, SafeX509StoreHandle store, SafeX509Handle x509, IntPtr zero); [DllImport(Libraries.LibCrypto)] internal static extern int X509_verify_cert(SafeX509StoreCtxHandle ctx); [DllImport(Libraries.LibCrypto)] internal static extern SafeX509StackHandle X509_STORE_CTX_get1_chain(SafeX509StoreCtxHandle ctx); [DllImport(Libraries.LibCrypto)] internal static extern X509VerifyStatusCode X509_STORE_CTX_get_error(SafeX509StoreCtxHandle ctx); [DllImport(Libraries.LibCrypto)] internal static extern int X509_STORE_CTX_get_error_depth(SafeX509StoreCtxHandle ctx); internal static string X509_verify_cert_error_string(X509VerifyStatusCode n) { IntPtr ptr = X509_verify_cert_error_string_private(n); return ptr != null ? Marshal.PtrToStringAnsi(ptr) : null; } [DllImport(Libraries.LibCrypto, EntryPoint = "X509_verify_cert_error_string")] private static extern IntPtr X509_verify_cert_error_string_private(X509VerifyStatusCode n); [DllImport(Libraries.LibCrypto)] internal static extern void X509_CRL_free(IntPtr a); [DllImport(Libraries.LibCrypto)] internal static extern int PEM_write_bio_X509_CRL(SafeBioHandle bio, SafeX509CrlHandle crl); [DllImport(Libraries.LibCrypto)] private static extern SafeX509CrlHandle PEM_read_bio_X509_CRL(SafeBioHandle bio, IntPtr zero, IntPtr zero1, IntPtr zero2); internal static SafeX509CrlHandle PEM_read_bio_X509_CRL(SafeBioHandle bio) { return PEM_read_bio_X509_CRL(bio, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } // This is "unsigned long" in native, which means ulong on x64, uint on x86 // But we only support x64 for now. [Flags] internal enum X509VerifyFlags : ulong { None = 0, X509_V_FLAG_CB_ISSUER_CHECK = 0x0001, X509_V_FLAG_USE_CHECK_TIME = 0x0002, X509_V_FLAG_CRL_CHECK = 0x0004, X509_V_FLAG_CRL_CHECK_ALL = 0x0008, X509_V_FLAG_IGNORE_CRITICAL = 0x0010, X509_V_FLAG_X509_STRICT = 0x0020, X509_V_FLAG_ALLOW_PROXY_CERTS = 0x0040, X509_V_FLAG_POLICY_CHECK = 0x0080, X509_V_FLAG_EXPLICIT_POLICY = 0x0100, X509_V_FLAG_INHIBIT_ANY = 0x0200, X509_V_FLAG_INHIBIT_MAP = 0x0400, X509_V_FLAG_NOTIFY_POLICY = 0x0800, X509_V_FLAG_CHECK_SS_SIGNATURE = 0x4000, } internal enum X509VerifyStatusCode { X509_V_OK = 0, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2, X509_V_ERR_UNABLE_TO_GET_CRL = 3, X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE = 4, X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6, X509_V_ERR_CERT_SIGNATURE_FAILURE = 7, X509_V_ERR_CRL_SIGNATURE_FAILURE = 8, X509_V_ERR_CERT_NOT_YET_VALID = 9, X509_V_ERR_CERT_HAS_EXPIRED = 10, X509_V_ERR_CRL_NOT_YET_VALID = 11, X509_V_ERR_CRL_HAS_EXPIRED = 12, X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14, X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 15, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16, X509_V_ERR_OUT_OF_MEM = 17, X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18, X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20, X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21, X509_V_ERR_CERT_CHAIN_TOO_LONG = 22, X509_V_ERR_CERT_REVOKED = 23, X509_V_ERR_INVALID_CA = 24, X509_V_ERR_PATH_LENGTH_EXCEEDED = 25, X509_V_ERR_INVALID_PURPOSE = 26, X509_V_ERR_CERT_UNTRUSTED = 27, X509_V_ERR_CERT_REJECTED = 28, X509_V_ERR_AKID_SKID_MISMATCH = 30, X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH = 31, X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33, X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34, X509_V_ERR_KEYUSAGE_NO_CRL_SIGN = 35, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = 36, X509_V_ERR_INVALID_NON_CA = 37, X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED = 38, X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 39, X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED = 40, X509_V_ERR_INVALID_EXTENSION = 41, X509_V_ERR_INVALID_POLICY_EXTENSION = 42, X509_V_ERR_NO_EXPLICIT_POLICY = 43, X509_V_ERR_UNNESTED_RESOURCE = 44, X509_V_ERR_APPLICATION_VERIFICATION = 50, } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Conn.Params.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Conn.Params { /// <summary> /// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRoutePNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnRoutePNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Parameter for the default proxy. The default value will be used by some HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// DEFAULT_PROXY /// </java-name> [Dot42.DexImport("DEFAULT_PROXY", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_PROXY = "http.route.default-proxy"; /// <summary> /// <para>Parameter for the local address. On machines with multiple network interfaces, this parameter can be used to select the network interface from which the connection originates. It will be interpreted by the standard HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type java.net.InetAddress. </para> /// </summary> /// <java-name> /// LOCAL_ADDRESS /// </java-name> [Dot42.DexImport("LOCAL_ADDRESS", "Ljava/lang/String;", AccessFlags = 25)] public const string LOCAL_ADDRESS = "http.route.local-address"; /// <summary> /// <para>Parameter for an forced route. The forced route will be interpreted by the standard HttpRoutePlanner implementations. Instead of computing a route, the given forced route will be returned, even if it points to the wrong target host. </para><para>This parameter expects a value of type HttpRoute. </para> /// </summary> /// <java-name> /// FORCED_ROUTE /// </java-name> [Dot42.DexImport("FORCED_ROUTE", "Ljava/lang/String;", AccessFlags = 25)] public const string FORCED_ROUTE = "http.route.forced-route"; } /// <summary> /// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRoutePNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537)] public partial interface IConnRoutePNames /* scope: __dot42__ */ { } /// <summary> /// <para>An adaptor for accessing route related parameters in HttpParams. See ConnRoutePNames for parameter name definitions.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRouteParams /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRouteParams", AccessFlags = 33)] public partial class ConnRouteParams : global::Org.Apache.Http.Conn.Params.IConnRoutePNames /* scope: __dot42__ */ { /// <summary> /// <para>A special value indicating "no host". This relies on a nonsense scheme name to avoid conflicts with actual hosts. Note that this is a <b>valid</b> host. </para> /// </summary> /// <java-name> /// NO_HOST /// </java-name> [Dot42.DexImport("NO_HOST", "Lorg/apache/http/HttpHost;", AccessFlags = 25)] public static readonly global::Org.Apache.Http.HttpHost NO_HOST; /// <summary> /// <para>A special value indicating "no route". This is a route with NO_HOST as the target. </para> /// </summary> /// <java-name> /// NO_ROUTE /// </java-name> [Dot42.DexImport("NO_ROUTE", "Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 25)] public static readonly global::Org.Apache.Http.Conn.Routing.HttpRoute NO_ROUTE; /// <summary> /// <para>Disabled default constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal ConnRouteParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the DEFAULT_PROXY parameter value. NO_HOST will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the default proxy set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getDefaultProxy /// </java-name> [Dot42.DexImport("getDefaultProxy", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/HttpHost;", AccessFlags = 9)] public static global::Org.Apache.Http.HttpHost GetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.HttpHost); } /// <summary> /// <para>Sets the DEFAULT_PROXY parameter value.</para><para></para> /// </summary> /// <java-name> /// setDefaultProxy /// </java-name> [Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/HttpHost;)V", AccessFlags = 9)] public static void SetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.HttpHost proxy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the FORCED_ROUTE parameter value. NO_ROUTE will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the forced route set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getForcedRoute /// </java-name> [Dot42.DexImport("getForcedRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Routing.HttpRoute GetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Routing.HttpRoute); } /// <summary> /// <para>Sets the FORCED_ROUTE parameter value.</para><para></para> /// </summary> /// <java-name> /// setForcedRoute /// </java-name> [Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 9)] public static void SetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the LOCAL_ADDRESS parameter value. There is no special value that would automatically be mapped to <code>null</code>. You can use the wildcard address (0.0.0.0 for IPv4, :: for IPv6) to override a specific local address in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the local address set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getLocalAddress /// </java-name> [Dot42.DexImport("getLocalAddress", "(Lorg/apache/http/params/HttpParams;)Ljava/net/InetAddress;", AccessFlags = 9)] public static global::Java.Net.InetAddress GetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Java.Net.InetAddress); } /// <summary> /// <para>Sets the LOCAL_ADDRESS parameter value.</para><para></para> /// </summary> /// <java-name> /// setLocalAddress /// </java-name> [Dot42.DexImport("setLocalAddress", "(Lorg/apache/http/params/HttpParams;Ljava/net/InetAddress;)V", AccessFlags = 9)] public static void SetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params, global::Java.Net.InetAddress local) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Allows for setting parameters relating to connections on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionParamBean", AccessFlags = 33)] public partial class ConnConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnConnectionPNames::MAX_STATUS_LINE_GARBAGE </para></para> /// </summary> /// <java-name> /// setMaxStatusLineGarbage /// </java-name> [Dot42.DexImport("setMaxStatusLineGarbage", "(I)V", AccessFlags = 1)] public virtual void SetMaxStatusLineGarbage(int maxStatusLineGarbage) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnConnectionPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the maximum number of ignorable lines before we expect a HTTP response's status line. </para><para>With HTTP/1.1 persistent connections, the problem arises that broken scripts could return a wrong Content-Length (there are more bytes sent than specified). Unfortunately, in some cases, this cannot be detected after the bad response, but only before the next one. So HttpClient must be able to skip those surplus lines this way. </para><para>This parameter expects a value of type Integer. 0 disallows all garbage/empty lines before the status line. Use java.lang.Integer#MAX_VALUE for unlimited (default in lenient mode). </para> /// </summary> /// <java-name> /// MAX_STATUS_LINE_GARBAGE /// </java-name> [Dot42.DexImport("MAX_STATUS_LINE_GARBAGE", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage"; } /// <summary> /// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537)] public partial interface IConnConnectionPNames /* scope: __dot42__ */ { } /// <summary> /// <para>This class maintains a map of HTTP routes to maximum number of connections allowed for those routes. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>652947 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnPerRouteBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnPerRouteBean", AccessFlags = 49)] public sealed partial class ConnPerRouteBean : global::Org.Apache.Http.Conn.Params.IConnPerRoute /* scope: __dot42__ */ { /// <summary> /// <para>The default maximum number of connections allowed per host </para> /// </summary> /// <java-name> /// DEFAULT_MAX_CONNECTIONS_PER_ROUTE /// </java-name> [Dot42.DexImport("DEFAULT_MAX_CONNECTIONS_PER_ROUTE", "I", AccessFlags = 25)] public const int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 2; [Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)] public ConnPerRouteBean(int defaultMax) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ConnPerRouteBean() /* MethodBuilder.Create */ { } /// <java-name> /// getDefaultMax /// </java-name> [Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)] public int GetDefaultMax() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setDefaultMaxPerRoute /// </java-name> [Dot42.DexImport("setDefaultMaxPerRoute", "(I)V", AccessFlags = 1)] public void SetDefaultMaxPerRoute(int max) /* MethodBuilder.Create */ { } /// <java-name> /// setMaxForRoute /// </java-name> [Dot42.DexImport("setMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;I)V", AccessFlags = 1)] public void SetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route, int max) /* MethodBuilder.Create */ { } /// <java-name> /// getMaxForRoute /// </java-name> [Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1)] public int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setMaxForRoutes /// </java-name> [Dot42.DexImport("setMaxForRoutes", "(Ljava/util/Map;)V", AccessFlags = 1, Signature = "(Ljava/util/Map<Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Integer;>;)V")] public void SetMaxForRoutes(global::Java.Util.IMap<global::Org.Apache.Http.Conn.Routing.HttpRoute, int?> map) /* MethodBuilder.Create */ { } /// <java-name> /// getDefaultMax /// </java-name> public int DefaultMax { [Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)] get{ return GetDefaultMax(); } } } /// <summary> /// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnManagerPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the timeout in milliseconds used when retrieving an instance of org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager. </para><para>This parameter expects a value of type Long. </para> /// </summary> /// <java-name> /// TIMEOUT /// </java-name> [Dot42.DexImport("TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string TIMEOUT = "http.conn-manager.timeout"; /// <summary> /// <para>Defines the maximum number of connections per route. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type ConnPerRoute. </para> /// </summary> /// <java-name> /// MAX_CONNECTIONS_PER_ROUTE /// </java-name> [Dot42.DexImport("MAX_CONNECTIONS_PER_ROUTE", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_CONNECTIONS_PER_ROUTE = "http.conn-manager.max-per-route"; /// <summary> /// <para>Defines the maximum number of connections in total. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_TOTAL_CONNECTIONS /// </java-name> [Dot42.DexImport("MAX_TOTAL_CONNECTIONS", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_TOTAL_CONNECTIONS = "http.conn-manager.max-total"; } /// <summary> /// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537)] public partial interface IConnManagerPNames /* scope: __dot42__ */ { } /// <summary> /// <para>Allows for setting parameters relating to connection managers on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerParamBean", AccessFlags = 33)] public partial class ConnManagerParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnManagerParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setTimeout /// </java-name> [Dot42.DexImport("setTimeout", "(J)V", AccessFlags = 1)] public virtual void SetTimeout(long timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <java-name> /// setMaxTotalConnections /// </java-name> [Dot42.DexImport("setMaxTotalConnections", "(I)V", AccessFlags = 1)] public virtual void SetMaxTotalConnections(int maxConnections) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <java-name> /// setConnectionsPerRoute /// </java-name> [Dot42.DexImport("setConnectionsPerRoute", "(Lorg/apache/http/conn/params/ConnPerRouteBean;)V", AccessFlags = 1)] public virtual void SetConnectionsPerRoute(global::Org.Apache.Http.Conn.Params.ConnPerRouteBean connPerRoute) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnManagerParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Allows for setting parameters relating to connection routes on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRouteParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRouteParamBean", AccessFlags = 33)] public partial class ConnRouteParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnRouteParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::DEFAULT_PROXY </para></para> /// </summary> /// <java-name> /// setDefaultProxy /// </java-name> [Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetDefaultProxy(global::Org.Apache.Http.HttpHost defaultProxy) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::LOCAL_ADDRESS </para></para> /// </summary> /// <java-name> /// setLocalAddress /// </java-name> [Dot42.DexImport("setLocalAddress", "(Ljava/net/InetAddress;)V", AccessFlags = 1)] public virtual void SetLocalAddress(global::Java.Net.InetAddress address) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::FORCED_ROUTE </para></para> /// </summary> /// <java-name> /// setForcedRoute /// </java-name> [Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 1)] public virtual void SetForcedRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnRouteParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>This class represents a collection of HTTP protocol parameters applicable to client-side connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke</para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0</para><para>ConnManagerPNames </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerParams /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerParams", AccessFlags = 49)] public sealed partial class ConnManagerParams : global::Org.Apache.Http.Conn.Params.IConnManagerPNames /* scope: __dot42__ */ { /// <summary> /// <para>The default maximum number of connections allowed overall </para> /// </summary> /// <java-name> /// DEFAULT_MAX_TOTAL_CONNECTIONS /// </java-name> [Dot42.DexImport("DEFAULT_MAX_TOTAL_CONNECTIONS", "I", AccessFlags = 25)] public const int DEFAULT_MAX_TOTAL_CONNECTIONS = 20; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ConnManagerParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds. </para> /// </returns> /// <java-name> /// getTimeout /// </java-name> [Dot42.DexImport("getTimeout", "(Lorg/apache/http/params/HttpParams;)J", AccessFlags = 9)] public static long GetTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(long); } /// <summary> /// <para>Sets the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para> /// </summary> /// <java-name> /// setTimeout /// </java-name> [Dot42.DexImport("setTimeout", "(Lorg/apache/http/params/HttpParams;J)V", AccessFlags = 9)] public static void SetTimeout(global::Org.Apache.Http.Params.IHttpParams @params, long timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <java-name> /// setMaxConnectionsPerRoute /// </java-name> [Dot42.DexImport("setMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/params/ConnPerRoute;)V", AccessFlags = 9)] public static void SetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Params.IConnPerRoute connPerRoute) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <returns> /// <para>lookup interface for maximum number of connections allowed per route.</para> /// </returns> /// <java-name> /// getMaxConnectionsPerRoute /// </java-name> [Dot42.DexImport("getMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/params/ConnPerRoute;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Params.IConnPerRoute GetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Params.IConnPerRoute); } /// <summary> /// <para>Sets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <java-name> /// setMaxTotalConnections /// </java-name> [Dot42.DexImport("setMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params, int maxTotalConnections) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <returns> /// <para>The maximum number of connections allowed.</para> /// </returns> /// <java-name> /// getMaxTotalConnections /// </java-name> [Dot42.DexImport("getMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } } /// <summary> /// <para>This interface is intended for looking up maximum number of connections allowed for for a given route. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>651813 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnPerRoute /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnPerRoute", AccessFlags = 1537)] public partial interface IConnPerRoute /* scope: __dot42__ */ { /// <java-name> /// getMaxForRoute /// </java-name> [Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1025)] int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ ; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Reflection.Metadata; using System.Runtime.InteropServices; using System.Text; namespace System.Reflection.Internal { /// <summary> /// Provides helpers to decode strings from unmanaged memory to System.String while avoiding /// intermediate allocation. /// /// This has three components: /// /// (1) Light-up Encoding.GetString(byte*, int) via reflection and resurface it as extension /// method. /// /// This is a new API that will provide API convergence across all platforms for /// this scenario. It is already on .NET 4.6+ and ASP.NET vNext, but not yet available /// on every platform we support. See below for how we fall back. /// /// (2) Deal with WinRT prefixes. /// /// When reading managed winmds with projections enabled, the metadata reader needs to prepend /// a WinRT prefix in some case . Doing this without allocation poses a problem /// as we don't have the prefix and input in contiguous data that we can pass to the /// Encoding.GetString. We handle this case using pooled managed scratch buffers where we copy /// the prefix and input and decode using Encoding.GetString(byte[], int, int). /// /// (3) Deal with platforms that don't yet have Encoding.GetString(byte*, int). /// /// If we're running on a full framework earlier than 4.6, we will bind to the internal /// String.CreateStringFromEncoding which is equivalent and Encoding.GetString is just a trivial /// wrapper around it in .NET 4.6. This means that we always have the fast path on every /// full framework version we support. /// /// If we can't bind to it via reflection, then we emulate it using what is effectively (2) and /// with an empty prefix. /// /// For both (2) and (3), the pooled buffers have a fixed size deemed large enough for the /// vast majority of metadata strings. In the rare worst case (byteCount > threshold and /// (lightUpAttemptFailed || prefix != null), we give up and allocate a temporary array, /// copy to it, decode, and throw it away. /// </summary> internal static unsafe class EncodingHelper { // Size of pooled buffers. Input larger than that is prefixed or given to us on a // platform that doesn't have unsafe Encoding.GetString, will cause us to // allocate and throw away a temporary buffer. The vast majority of metadata strings // are quite small so we don't need to waste memory with large buffers. public const int PooledBufferSize = 200; // The pooled buffers for (2) and (3) above. Use AcquireBuffer(int) and ReleaseBuffer(byte[]) // instead of the pool directly to implement the size check. private static readonly ObjectPool<byte[]> s_pool = new ObjectPool<byte[]>(() => new byte[PooledBufferSize]); public static string DecodeUtf8(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder) { Debug.Assert(utf8Decoder != null); if (prefix != null) { return DecodeUtf8Prefixed(bytes, byteCount, prefix, utf8Decoder); } if (byteCount == 0) { return string.Empty; } return utf8Decoder.GetString(bytes, byteCount); } private static string DecodeUtf8Prefixed(byte* bytes, int byteCount, byte[] prefix, MetadataStringDecoder utf8Decoder) { Debug.Assert(utf8Decoder != null); int prefixedByteCount = byteCount + prefix.Length; if (prefixedByteCount == 0) { return string.Empty; } byte[] buffer = AcquireBuffer(prefixedByteCount); prefix.CopyTo(buffer, 0); Marshal.Copy((IntPtr)bytes, buffer, prefix.Length, byteCount); string result; fixed (byte* prefixedBytes = &buffer[0]) { result = utf8Decoder.GetString(prefixedBytes, prefixedByteCount); } ReleaseBuffer(buffer); return result; } private static byte[] AcquireBuffer(int byteCount) { if (byteCount > PooledBufferSize) { return new byte[byteCount]; } return s_pool.Allocate(); } private static void ReleaseBuffer(byte[] buffer) { if (buffer.Length == PooledBufferSize) { s_pool.Free(buffer); } } // TODO: Remove everything in this region when we can retarget and use the real // Encoding.GetString(byte*, int) without reflection. #region Light-Up internal delegate string Encoding_GetString(Encoding encoding, byte* bytes, int byteCount); // only internal for test hook private delegate string String_CreateStringFromEncoding(byte* bytes, int byteCount, Encoding encoding); private static Encoding_GetString s_getStringPlatform = LoadGetStringPlatform(); // only non-readonly for test hook public static string GetString(this Encoding encoding, byte* bytes, int byteCount) { Debug.Assert(encoding != null); if (s_getStringPlatform == null) { return GetStringPortable(encoding, bytes, byteCount); } return s_getStringPlatform(encoding, bytes, byteCount); } private static unsafe string GetStringPortable(Encoding encoding, byte* bytes, int byteCount) { // This implementation can leak publicly (by design) to MetadataStringDecoder.GetString. // Therefore we implement the same validation. Debug.Assert(encoding != null); // validated by MetadataStringDecoder constructor. if (bytes == null) { throw new ArgumentNullException(nameof(bytes)); } if (byteCount < 0) { throw new ArgumentOutOfRangeException(nameof(byteCount)); } byte[] buffer = AcquireBuffer(byteCount); Marshal.Copy((IntPtr)bytes, buffer, 0, byteCount); string result = encoding.GetString(buffer, 0, byteCount); ReleaseBuffer(buffer); return result; } private static Encoding_GetString LoadGetStringPlatform() { // .NET Framework 4.6+ and recent versions of other .NET platforms. // // Try to bind to Encoding.GetString(byte*, int); MethodInfo getStringInfo = LightUpHelper.GetMethod(typeof(Encoding), "GetString", typeof(byte*), typeof(int)); if (getStringInfo != null && getStringInfo.ReturnType == typeof(string)) { try { return (Encoding_GetString)getStringInfo.CreateDelegate(typeof(Encoding_GetString), null); } catch (MemberAccessException) { } catch (InvalidOperationException) { // thrown when accessing unapproved API in a Windows Store app } } // .NET Framework < 4.6 // // Try to bind to String.CreateStringFromEncoding(byte*, int, Encoding) // // Note that this one is internal and GetRuntimeMethod only searches public methods, which accounts for the different // pattern from above. // // NOTE: Another seeming equivalent is new string(sbyte*, int, Encoding), but don't be fooled. First of all, we can't get // a delegate to a constructor. Worst than that, even if we could, it is actually about 4x slower than both of these // and even the portable version (only ~20% slower than these) crushes it. // // It spends an inordinate amount of time transitioning to managed code from the VM and then lands in String.CreateString // (note no FromEncoding suffix), which defensively copies to a new byte array on every call -- defeating the entire purpose // of this class! // // For this reason, desktop callers should not implement an interner that falls back to the unsafe string ctor but instead // return null and let us find the best decoding approach for the current platform. // // Yet another approach is to use new string('\0', GetCharCount) and use unsafe GetChars to fill it. // However, on .NET < 4.6, there isn't no-op fast path for zero-initialization case so we'd slow down. // Plus, mutating a System.String is no better than the reflection here. IEnumerable<MethodInfo> createStringInfos = typeof(String).GetTypeInfo().GetDeclaredMethods("CreateStringFromEncoding"); foreach (var methodInfo in createStringInfos) { var parameters = methodInfo.GetParameters(); if (parameters.Length == 3 && parameters[0].ParameterType == typeof(byte*) && parameters[1].ParameterType == typeof(int) && parameters[2].ParameterType == typeof(Encoding) && methodInfo.ReturnType == typeof(string)) { try { var createStringFromEncoding = (String_CreateStringFromEncoding)methodInfo.CreateDelegate(typeof(String_CreateStringFromEncoding), null); return (encoding, bytes, byteCount) => GetStringUsingCreateStringFromEncoding(createStringFromEncoding, bytes, byteCount, encoding); } catch (MemberAccessException) { } catch (InvalidOperationException) { // thrown when accessing unapproved API in a Windows Store app } } } // Other platforms: Give up and fall back to GetStringPortable above. return null; } private static unsafe string GetStringUsingCreateStringFromEncoding( String_CreateStringFromEncoding createStringFromEncoding, byte* bytes, int byteCount, Encoding encoding) { // String.CreateStringFromEncoding is an internal method that does not validate // arguments, but this implementation can leak publicly (by design) via // MetadataStringDecoder.GetString. Therefore, we implement the same validation // that Encoding.GetString would do if it were available directly. Debug.Assert(encoding != null); // validated by MetadataStringDecoder constructor. if (bytes == null) { throw new ArgumentNullException(nameof(bytes)); } if (byteCount < 0) { throw new ArgumentOutOfRangeException(nameof(byteCount)); } return createStringFromEncoding(bytes, byteCount, encoding); } // Test hook to force portable implementation and ensure light is functioning. internal static bool TestOnly_LightUpEnabled { get { return s_getStringPlatform != null; } set { s_getStringPlatform = value ? LoadGetStringPlatform() : null; } } #endregion } }
// 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.Graph.RBAC.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Graph.RBAC.Fluent.CertificateCredential.Definition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.CertificateCredential.UpdateDefinition; using Microsoft.Azure.Management.Graph.RBAC.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update; using System; using ResourceManager.Fluent.Core.ResourceActions; using System.IO; using ResourceManager.Fluent; using ResourceManager.Fluent.Authentication; /// <summary> /// Implementation for ServicePrincipal and its parent interfaces. /// </summary> public partial class CertificateCredentialImpl<T> : IndexableRefreshableWrapper<Microsoft.Azure.Management.Graph.RBAC.Fluent.ICertificateCredential, Models.KeyCredential>, ICertificateCredential, IDefinition<T>, IUpdateDefinition<T> { private string name; private IHasCredential<T> parent; private StreamWriter authFile; private string privateKeyPath; private string privateKeyPassword; public CertificateCredentialImpl<T> WithSymmetricEncryption() { Inner.Type = CertificateType.Symmetric.Value; return this; } public CertificateCredentialImpl<T> WithAsymmetricX509Certificate() { Inner.Type = CertificateType.AsymmetricX509Cert.Value; return this; } public DateTime EndDate() { return Inner.EndDate ?? DateTime.MinValue; } public CertificateCredentialImpl<T> WithPrivateKeyPassword(string privateKeyPassword) { this.privateKeyPassword = privateKeyPassword; return this; } protected override async Task<Models.KeyCredential> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException("Cannot refresh credentials."); } public CertificateCredentialImpl<T> WithDuration(TimeSpan duration) { Inner.EndDate = StartDate().Add(duration); return this; } internal async Task ExportAuthFileAsync(ServicePrincipalImpl servicePrincipal, CancellationToken cancellationToken = default(CancellationToken)) { if (authFile == null) { return; } RestClient restClient = servicePrincipal.Manager().restClient; AzureEnvironment environment = null; if (restClient.Credentials is AzureCredentials) { environment = restClient.Credentials.Environment; } else { string baseUrl = restClient.BaseUri; if (AzureEnvironment.AzureGlobalCloud.ResourceManagerEndpoint.ToLower().Contains(baseUrl.ToLower())) { environment = AzureEnvironment.AzureGlobalCloud; } else if (AzureEnvironment.AzureChinaCloud.ResourceManagerEndpoint.ToLower().Contains(baseUrl.ToLower())) { environment = AzureEnvironment.AzureChinaCloud; } else if (AzureEnvironment.AzureGermanCloud.ResourceManagerEndpoint.ToLower().Contains(baseUrl.ToLower())) { environment = AzureEnvironment.AzureGermanCloud; } else if (AzureEnvironment.AzureUSGovernment.ResourceManagerEndpoint.ToLower().Contains(baseUrl.ToLower())) { environment = AzureEnvironment.AzureUSGovernment; } if (environment == null) { throw new NotSupportedException("Unknown resource manager endpoint " + baseUrl); } } try { await authFile.WriteLineAsync("{"); await authFile.WriteLineAsync(string.Format(" \"clientId\": \"{0}\",", servicePrincipal.ApplicationId())); await authFile.WriteLineAsync(string.Format(" \"clientCertificate\": \"{0}\",", NormalizeAuthFilePath(privateKeyPath))); await authFile.WriteLineAsync(string.Format(" \"clientCertificatePassword\": \"{0}\",", privateKeyPassword)); await authFile.WriteLineAsync(string.Format(" \"tenantId\": \"{0}\",", servicePrincipal.Manager().tenantId)); await authFile.WriteLineAsync(string.Format(" \"subscriptionId\": \"{0}\",", servicePrincipal.assignedSubscription)); await authFile.WriteLineAsync(string.Format(" \"activeDirectoryEndpointUrl\": \"{0}\",", environment.AuthenticationEndpoint)); await authFile.WriteLineAsync(string.Format(" \"resourceManagerEndpointUrl\": \"{0}\",", environment.ResourceManagerEndpoint)); await authFile.WriteLineAsync(string.Format(" \"activeDirectoryGraphResourceId\": \"{0}\",", environment.GraphEndpoint)); await authFile.WriteLineAsync(string.Format(" \"managementEndpointUrl\": \"{0}\"", environment.ManagementEndpoint)); await authFile.WriteLineAsync("}"); } finally { authFile.Dispose(); } } public CertificateCredentialImpl<T> WithSecretKey(byte[] secret) { Inner.Value = System.Convert.ToBase64String(secret); return this; } internal CertificateCredentialImpl(KeyCredential keyCredential) : base(!String.IsNullOrEmpty(keyCredential.CustomKeyIdentifier) ? System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(keyCredential.CustomKeyIdentifier)) : keyCredential.KeyId, keyCredential) { if (!String.IsNullOrEmpty(keyCredential.CustomKeyIdentifier)) { this.name = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(keyCredential.CustomKeyIdentifier)); } else { this.name = keyCredential.KeyId; } } internal CertificateCredentialImpl(string name, IHasCredential<T> parent) : base(name, new KeyCredential() { Usage = "Verify", CustomKeyIdentifier = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(name)), StartDate = DateTime.Now, EndDate = DateTime.Now.AddYears(1) }) { this.name = name; this.parent = parent; } private string NormalizeAuthFileUrl(string url) { if (!url.EndsWith("/")) { url = url + "/"; } return url.Replace("\\", "\\\\").Replace("://", "\\://"); } private string NormalizeAuthFilePath(string path) { return path.Replace("\\", "\\\\"); } public CertificateCredentialImpl<T> WithPrivateKeyFile(string privateKeyPath) { this.privateKeyPath = Path.GetFullPath(privateKeyPath).ToString(); return this; } public CertificateCredentialImpl<T> WithStartDate(DateTime startDate) { DateTime original = StartDate(); Inner.StartDate = startDate; // Adjust end time WithDuration(EndDate().Subtract(original)); return this; } public string Name() { return name; } public async override Task<Microsoft.Azure.Management.Graph.RBAC.Fluent.ICertificateCredential> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken)) { throw new NotSupportedException("Cannot refresh credentials."); } public string Id() { return Inner.KeyId; } public T Attach() { parent.WithCertificateCredential(this); return (T)parent; } public CertificateCredentialImpl<T> WithPublicKey(byte[] certificate) { Inner.Value = System.Convert.ToBase64String(certificate); return this; } public string Value() { return Inner.Value; } public CertificateCredentialImpl<T> WithAuthFileToExport(StreamWriter outputStream) { this.authFile = outputStream; return this; } public DateTime StartDate() { return Inner.StartDate ?? DateTime.MinValue; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.TagHelpers; using Xunit; namespace Microsoft.AspNetCore.Razor.Runtime.TagHelpers { public class TagHelperRunnerTest { [Fact] public async Task RunAsync_CallsInitPriorToProcessAsync() { // Arrange var runner = new TagHelperRunner(); var executionContext = new TagHelperExecutionContext("p", TagMode.StartTagAndEndTag); var incrementer = 0; var callbackTagHelper = new CallbackTagHelper( initCallback: () => { Assert.Equal(0, incrementer); incrementer++; }, processAsyncCallback: () => { Assert.Equal(1, incrementer); incrementer++; }); executionContext.Add(callbackTagHelper); // Act await runner.RunAsync(executionContext); // Assert Assert.Equal(2, incrementer); } public static TheoryData TagHelperOrderData { get { // tagHelperOrders, expectedTagHelperOrders return new TheoryData<int[], int[]> { { new[] { 1000, int.MaxValue, 0 }, new[] { 0, 1000, int.MaxValue } }, { new[] { int.MaxValue, int.MaxValue, int.MinValue }, new[] { int.MinValue, int.MaxValue, int.MaxValue } }, { new[] { 0, 0, int.MinValue }, new[] { int.MinValue, 0, 0 } }, { new[] { int.MinValue, -1000, 0 }, new[] { int.MinValue, -1000, 0 } }, { new[] { 0, 1000, int.MaxValue }, new[] { 0, 1000, int.MaxValue } }, { new[] { int.MaxValue, int.MinValue, int.MaxValue, -1000, int.MaxValue, 0 }, new[] { int.MinValue, -1000, 0, int.MaxValue, int.MaxValue, int.MaxValue } }, { new[] { 0, 0, 0, 0 }, new[] { 0, 0, 0, 0 } }, { new[] { 1000, int.MaxValue, 0, -1000, int.MinValue }, new[] { int.MinValue, -1000, 0, 1000, int.MaxValue } }, }; } } [Theory] [MemberData(nameof(TagHelperOrderData))] public async Task RunAsync_OrdersTagHelpers( int[] tagHelperOrders, int[] expectedTagHelperOrders) { // Arrange var runner = new TagHelperRunner(); var executionContext = new TagHelperExecutionContext("p", TagMode.StartTagAndEndTag); var processOrder = new List<int>(); foreach (var order in tagHelperOrders) { var orderedTagHelper = new OrderedTagHelper(order) { ProcessOrderTracker = processOrder }; executionContext.Add(orderedTagHelper); } // Act await runner.RunAsync(executionContext); // Assert Assert.Equal(expectedTagHelperOrders, processOrder); } [Theory] [InlineData(TagMode.SelfClosing)] [InlineData(TagMode.StartTagAndEndTag)] [InlineData(TagMode.StartTagOnly)] public async Task RunAsync_SetsTagHelperOutputTagMode(TagMode tagMode) { // Arrange var runner = new TagHelperRunner(); var executionContext = new TagHelperExecutionContext("p", tagMode); var tagHelper = new TagHelperContextTouchingTagHelper(); executionContext.Add(tagHelper); executionContext.AddTagHelperAttribute("foo", true, HtmlAttributeValueStyle.DoubleQuotes); // Act await runner.RunAsync(executionContext); // Assert Assert.Equal(tagMode, executionContext.Output.TagMode); } [Fact] public async Task RunAsync_ProcessesAllTagHelpers() { // Arrange var runner = new TagHelperRunner(); var executionContext = new TagHelperExecutionContext("p", TagMode.StartTagAndEndTag); var executableTagHelper1 = new ExecutableTagHelper(); var executableTagHelper2 = new ExecutableTagHelper(); // Act executionContext.Add(executableTagHelper1); executionContext.Add(executableTagHelper2); await runner.RunAsync(executionContext); // Assert Assert.True(executableTagHelper1.Processed); Assert.True(executableTagHelper2.Processed); } [Fact] public async Task RunAsync_AllowsModificationOfTagHelperOutput() { // Arrange var runner = new TagHelperRunner(); var executionContext = new TagHelperExecutionContext("p", TagMode.StartTagAndEndTag); var executableTagHelper = new ExecutableTagHelper(); // Act executionContext.Add(executableTagHelper); executionContext.AddHtmlAttribute("class", "btn", HtmlAttributeValueStyle.DoubleQuotes); await runner.RunAsync(executionContext); // Assert var output = executionContext.Output; Assert.Equal("foo", output.TagName); Assert.Equal("somethingelse", output.Attributes["class"].Value); Assert.Equal("world", output.Attributes["hello"].Value); Assert.Equal(TagMode.SelfClosing, output.TagMode); } [Fact] public async Task RunAsync_AllowsDataRetrievalFromTagHelperContext() { // Arrange var runner = new TagHelperRunner(); var executionContext = new TagHelperExecutionContext("p", TagMode.StartTagAndEndTag); var tagHelper = new TagHelperContextTouchingTagHelper(); // Act executionContext.Add(tagHelper); executionContext.AddTagHelperAttribute("foo", true, HtmlAttributeValueStyle.DoubleQuotes); await runner.RunAsync(executionContext); // Assert Assert.Equal("True", executionContext.Output.Attributes["foo"].Value); } [Fact] public async Task RunAsync_ConfiguresTagHelperContextWithExecutionContextsItems() { // Arrange var runner = new TagHelperRunner(); var executionContext = new TagHelperExecutionContext("p", TagMode.StartTagAndEndTag); var tagHelper = new ContextInspectingTagHelper(); executionContext.Add(tagHelper); // Act await runner.RunAsync(executionContext); // Assert Assert.NotNull(tagHelper.ContextProcessedWith); Assert.Same(tagHelper.ContextProcessedWith.Items, executionContext.Items); } private class ExecutableTagHelper : TagHelper { public bool Processed { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { Processed = true; output.TagName = "foo"; var classIndex = output.Attributes.IndexOfName("class"); if (classIndex != -1) { output.Attributes[classIndex] = new TagHelperAttribute("class", "somethingelse"); } output.Attributes.Add("hello", "world"); output.TagMode = TagMode.SelfClosing; } } private class ContextInspectingTagHelper : TagHelper { public TagHelperContext ContextProcessedWith { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { ContextProcessedWith = context; } } private class TagHelperContextTouchingTagHelper : TagHelper { public override void Process(TagHelperContext context, TagHelperOutput output) { output.Attributes.Add("foo", context.AllAttributes["foo"].Value.ToString()); } } private class OrderedTagHelper : TagHelper { public OrderedTagHelper(int order) { Order = order; } public override int Order { get; } public IList<int> ProcessOrderTracker { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { // If using this class for testing, ensure that ProcessOrderTracker is always set prior to Process // execution. Debug.Assert(ProcessOrderTracker != null); ProcessOrderTracker.Add(Order); } } private class CallbackTagHelper : TagHelper { private readonly Action _initCallback; private readonly Action _processAsyncCallback; public CallbackTagHelper(Action initCallback, Action processAsyncCallback) { _initCallback = initCallback; _processAsyncCallback = processAsyncCallback; } public override void Init(TagHelperContext context) { _initCallback(); } public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { _processAsyncCallback(); return base.ProcessAsync(context, output); } } } }
// // MetadataSystem.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Cecil.Metadata; namespace Mono.Cecil { struct Range { public uint Start; public uint Length; public Range (uint index, uint length) { this.Start = index; this.Length = length; } } sealed class MetadataSystem { internal AssemblyNameReference [] AssemblyReferences; internal ModuleReference [] ModuleReferences; internal TypeDefinition [] Types; internal TypeReference [] TypeReferences; internal FieldDefinition [] Fields; internal MethodDefinition [] Methods; internal MemberReference [] MemberReferences; internal Dictionary<uint, uint []> NestedTypes; internal Dictionary<uint, uint> ReverseNestedTypes; internal Dictionary<uint, MetadataToken []> Interfaces; internal Dictionary<uint, Row<ushort, uint>> ClassLayouts; internal Dictionary<uint, uint> FieldLayouts; internal Dictionary<uint, uint> FieldRVAs; internal Dictionary<MetadataToken, uint> FieldMarshals; internal Dictionary<MetadataToken, Row<ElementType, uint>> Constants; internal Dictionary<uint, MetadataToken []> Overrides; internal Dictionary<MetadataToken, Range> CustomAttributes; internal Dictionary<MetadataToken, Range> SecurityDeclarations; internal Dictionary<uint, Range> Events; internal Dictionary<uint, Range> Properties; internal Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> Semantics; internal Dictionary<uint, Row<PInvokeAttributes, uint, uint>> PInvokes; internal Dictionary<MetadataToken, Range> GenericParameters; internal Dictionary<uint, MetadataToken []> GenericConstraints; static Dictionary<string, Row<ElementType, bool>> primitive_value_types; static void InitializePrimitives () { primitive_value_types = new Dictionary<string, Row<ElementType, bool>> (18, StringComparer.Ordinal) { { "Void", new Row<ElementType, bool> (ElementType.Void, false) }, { "Boolean", new Row<ElementType, bool> (ElementType.Boolean, true) }, { "Char", new Row<ElementType, bool> (ElementType.Char, true) }, { "SByte", new Row<ElementType, bool> (ElementType.I1, true) }, { "Byte", new Row<ElementType, bool> (ElementType.U1, true) }, { "Int16", new Row<ElementType, bool> (ElementType.I2, true) }, { "UInt16", new Row<ElementType, bool> (ElementType.U2, true) }, { "Int32", new Row<ElementType, bool> (ElementType.I4, true) }, { "UInt32", new Row<ElementType, bool> (ElementType.U4, true) }, { "Int64", new Row<ElementType, bool> (ElementType.I8, true) }, { "UInt64", new Row<ElementType, bool> (ElementType.U8, true) }, { "Single", new Row<ElementType, bool> (ElementType.R4, true) }, { "Double", new Row<ElementType, bool> (ElementType.R8, true) }, { "String", new Row<ElementType, bool> (ElementType.String, false) }, { "TypedReference", new Row<ElementType, bool> (ElementType.TypedByRef, false) }, { "IntPtr", new Row<ElementType, bool> (ElementType.I, true) }, { "UIntPtr", new Row<ElementType, bool> (ElementType.U, true) }, { "Object", new Row<ElementType, bool> (ElementType.Object, false) }, }; } public static void TryProcessPrimitiveTypeReference (TypeReference type) { if (type.Namespace != "System") return; var scope = type.scope; if (scope == null || scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference) return; Row<ElementType, bool> primitive_data; if (!TryGetPrimitiveData (type, out primitive_data)) return; type.etype = primitive_data.Col1; type.IsValueType = primitive_data.Col2; } public static bool TryGetPrimitiveElementType (TypeDefinition type, out ElementType etype) { etype = ElementType.None; if (type.Namespace != "System") return false; Row<ElementType, bool> primitive_data; if (TryGetPrimitiveData (type, out primitive_data) && primitive_data.Col1.IsPrimitive ()) { etype = primitive_data.Col1; return true; } return false; } static bool TryGetPrimitiveData (TypeReference type, out Row<ElementType, bool> primitive_data) { if (primitive_value_types == null) InitializePrimitives (); return primitive_value_types.TryGetValue (type.Name, out primitive_data); } public void Clear () { if (NestedTypes != null) NestedTypes.Clear (); if (ReverseNestedTypes != null) ReverseNestedTypes.Clear (); if (Interfaces != null) Interfaces.Clear (); if (ClassLayouts != null) ClassLayouts.Clear (); if (FieldLayouts != null) FieldLayouts.Clear (); if (FieldRVAs != null) FieldRVAs.Clear (); if (FieldMarshals != null) FieldMarshals.Clear (); if (Constants != null) Constants.Clear (); if (Overrides != null) Overrides.Clear (); if (CustomAttributes != null) CustomAttributes.Clear (); if (SecurityDeclarations != null) SecurityDeclarations.Clear (); if (Events != null) Events.Clear (); if (Properties != null) Properties.Clear (); if (Semantics != null) Semantics.Clear (); if (PInvokes != null) PInvokes.Clear (); if (GenericParameters != null) GenericParameters.Clear (); if (GenericConstraints != null) GenericConstraints.Clear (); } public TypeDefinition GetTypeDefinition (uint rid) { if (rid < 1 || rid > Types.Length) return null; return Types [rid - 1]; } public void AddTypeDefinition (TypeDefinition type) { Types [type.token.RID - 1] = type; } public TypeReference GetTypeReference (uint rid) { if (rid < 1 || rid > TypeReferences.Length) return null; return TypeReferences [rid - 1]; } public void AddTypeReference (TypeReference type) { TypeReferences [type.token.RID - 1] = type; } public FieldDefinition GetFieldDefinition (uint rid) { if (rid < 1 || rid > Fields.Length) return null; return Fields [rid - 1]; } public void AddFieldDefinition (FieldDefinition field) { Fields [field.token.RID - 1] = field; } public MethodDefinition GetMethodDefinition (uint rid) { if (rid < 1 || rid > Methods.Length) return null; return Methods [rid - 1]; } public void AddMethodDefinition (MethodDefinition method) { Methods [method.token.RID - 1] = method; } public MemberReference GetMemberReference (uint rid) { if (rid < 1 || rid > MemberReferences.Length) return null; return MemberReferences [rid - 1]; } public void AddMemberReference (MemberReference member) { MemberReferences [member.token.RID - 1] = member; } public bool TryGetNestedTypeMapping (TypeDefinition type, out uint [] mapping) { return NestedTypes.TryGetValue (type.token.RID, out mapping); } public void SetNestedTypeMapping (uint type_rid, uint [] mapping) { NestedTypes [type_rid] = mapping; } public void RemoveNestedTypeMapping (TypeDefinition type) { NestedTypes.Remove (type.token.RID); } public bool TryGetReverseNestedTypeMapping (TypeDefinition type, out uint declaring) { return ReverseNestedTypes.TryGetValue (type.token.RID, out declaring); } public void SetReverseNestedTypeMapping (uint nested, uint declaring) { ReverseNestedTypes.Add (nested, declaring); } public void RemoveReverseNestedTypeMapping (TypeDefinition type) { ReverseNestedTypes.Remove (type.token.RID); } public bool TryGetInterfaceMapping (TypeDefinition type, out MetadataToken [] mapping) { return Interfaces.TryGetValue (type.token.RID, out mapping); } public void SetInterfaceMapping (uint type_rid, MetadataToken [] mapping) { Interfaces [type_rid] = mapping; } public void RemoveInterfaceMapping (TypeDefinition type) { Interfaces.Remove (type.token.RID); } public void AddPropertiesRange (uint type_rid, Range range) { Properties.Add (type_rid, range); } public bool TryGetPropertiesRange (TypeDefinition type, out Range range) { return Properties.TryGetValue (type.token.RID, out range); } public void RemovePropertiesRange (TypeDefinition type) { Properties.Remove (type.token.RID); } public void AddEventsRange (uint type_rid, Range range) { Events.Add (type_rid, range); } public bool TryGetEventsRange (TypeDefinition type, out Range range) { return Events.TryGetValue (type.token.RID, out range); } public void RemoveEventsRange (TypeDefinition type) { Events.Remove (type.token.RID); } public bool TryGetGenericParameterRange (IGenericParameterProvider owner, out Range range) { return GenericParameters.TryGetValue (owner.MetadataToken, out range); } public void RemoveGenericParameterRange (IGenericParameterProvider owner) { GenericParameters.Remove (owner.MetadataToken); } public bool TryGetCustomAttributeRange (ICustomAttributeProvider owner, out Range range) { return CustomAttributes.TryGetValue (owner.MetadataToken, out range); } public void RemoveCustomAttributeRange (ICustomAttributeProvider owner) { CustomAttributes.Remove (owner.MetadataToken); } public bool TryGetSecurityDeclarationRange (ISecurityDeclarationProvider owner, out Range range) { return SecurityDeclarations.TryGetValue (owner.MetadataToken, out range); } public void RemoveSecurityDeclarationRange (ISecurityDeclarationProvider owner) { SecurityDeclarations.Remove (owner.MetadataToken); } public bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out MetadataToken [] mapping) { return GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping); } public void SetGenericConstraintMapping (uint gp_rid, MetadataToken [] mapping) { GenericConstraints [gp_rid] = mapping; } public void RemoveGenericConstraintMapping (GenericParameter generic_parameter) { GenericConstraints.Remove (generic_parameter.token.RID); } public bool TryGetOverrideMapping (MethodDefinition method, out MetadataToken [] mapping) { return Overrides.TryGetValue (method.token.RID, out mapping); } public void SetOverrideMapping (uint rid, MetadataToken [] mapping) { Overrides [rid] = mapping; } public void RemoveOverrideMapping (MethodDefinition method) { Overrides.Remove (method.token.RID); } public TypeDefinition GetFieldDeclaringType (uint field_rid) { return BinaryRangeSearch (Types, field_rid, true); } public TypeDefinition GetMethodDeclaringType (uint method_rid) { return BinaryRangeSearch (Types, method_rid, false); } static TypeDefinition BinaryRangeSearch (TypeDefinition [] types, uint rid, bool field) { int min = 0; int max = types.Length - 1; while (min <= max) { int mid = min + ((max - min) / 2); var type = types [mid]; var range = field ? type.fields_range : type.methods_range; if (rid < range.Start) max = mid - 1; else if (rid >= range.Start + range.Length) min = mid + 1; else return type; } return null; } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Q42.HueApi.Extensions; using Newtonsoft.Json; using Q42.HueApi.Models.Groups; using Q42.HueApi.Models; using System.Dynamic; using Q42.HueApi.Interfaces; namespace Q42.HueApi { /// <summary> /// Partial HueClient, contains requests to the /scenes/ url /// </summary> public partial class HueClient : IHueClient_Sensors { /// <summary> /// Asynchronously gets all sensors registered with the bridge. /// </summary> /// <returns>An enumerable of <see cref="Sensor"/>s registered with the bridge.</returns> public async Task<IReadOnlyCollection<Sensor>> GetSensorsAsync() { CheckInitialized(); HttpClient client = await GetHttpClient().ConfigureAwait(false); string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}sensors", ApiBase))).ConfigureAwait(false); //#if DEBUG // stringResult = "{ \"1\": { \"state\": { \"daylight\": false, \"lastupdated\": \"2014-06-27T07:38:51\" }, \"config\": { \"on\": true, \"long\": \"none\", \"lat\": \"none\", \"sunriseoffset\": 50, \"sunsetoffset\": 50 }, \"name\": \"Daylight\", \"type\": \"Daylight\", \"modelid\": \"PHDL00\", \"manufacturername\": \"Philips\", \"swversion\": \"1.0\" }, \"2\": { \"state\": { \"buttonevent\": 0, \"lastupdated\": \"none\" }, \"config\": { \"on\": true }, \"name\": \"Tap Switch 2\", \"type\": \"ZGPSwitch\", \"modelid\": \"ZGPSWITCH\", \"manufacturername\": \"Philips\", \"uniqueid\": \"00:00:00:00:00:40:03:50-f2\" }}"; //#endif List<Sensor> results = new List<Sensor>(); JToken token = JToken.Parse(stringResult); if (token.Type == JTokenType.Object) { //Each property is a scene var jsonResult = (JObject)token; foreach (var prop in jsonResult.Properties()) { Sensor? scene = JsonConvert.DeserializeObject<Sensor>(prop.Value.ToString()); if (scene != null) { scene.Id = prop.Name; results.Add(scene); } } } return results; } public async Task<string?> CreateSensorAsync(Sensor sensor) { if (sensor == null) throw new ArgumentNullException(nameof(sensor)); CheckInitialized(); //Set fields to null sensor.Id = null!; string sensorJson = JsonConvert.SerializeObject(sensor, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); HttpClient client = await GetHttpClient().ConfigureAwait(false); //Create sensor var result = await client.PostAsync(new Uri(String.Format("{0}sensors", ApiBase)), new JsonContent(sensorJson)).ConfigureAwait(false); var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultHueResult[]? sensorResult = JsonConvert.DeserializeObject<DefaultHueResult[]>(jsonResult); if (sensorResult != null && sensorResult.Length > 0 && sensorResult[0].Success != null && !string.IsNullOrEmpty(sensorResult[0].Success.Id)) { var id = sensorResult[0].Success.Id; sensor.Id = id; return id; } return null; } /// <summary> /// Starts a search for new sensors. /// </summary> /// <returns></returns> public async Task<HueResults> FindNewSensorsAsync() { CheckInitialized(); HttpClient client = await GetHttpClient().ConfigureAwait(false); var response = await client.PostAsync(new Uri(String.Format("{0}sensors", ApiBase)), new StringContent(string.Empty)).ConfigureAwait(false); var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return DeserializeDefaultHueResult(jsonResult); } /// <summary> /// Gets a list of sensors that were discovered the last time a search for new sensors was performed. The list of new sensors is always deleted when a new search is started. /// </summary> /// <returns></returns> public async Task<IReadOnlyCollection<Sensor>> GetNewSensorsAsync() { CheckInitialized(); HttpClient client = await GetHttpClient().ConfigureAwait(false); string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}sensors/new", ApiBase))).ConfigureAwait(false); //#if DEBUG // //stringResult = "{\"7\": {\"name\": \"Hue Lamp 7\"}, \"8\": {\"name\": \"Hue Lamp 8\"}, \"lastscan\": \"2012-10-29T12:00:00\"}"; //#endif List<Sensor> results = new List<Sensor>(); JToken token = JToken.Parse(stringResult); if (token.Type == JTokenType.Object) { //Each property is a light var jsonResult = (JObject)token; foreach (var prop in jsonResult.Properties()) { if (prop.Name != "lastscan") { Sensor? newSensor = JsonConvert.DeserializeObject<Sensor>(prop.Value.ToString()); if (newSensor != null) { newSensor.Id = prop.Name; results.Add(newSensor); } } } } return results; } /// <summary> /// Asynchronously gets single sensor /// </summary> /// <returns><see cref="Sensor"/></returns> public async Task<Sensor?> GetSensorAsync(string id) { if (id == null) throw new ArgumentNullException(nameof(id)); if (id.Trim() == String.Empty) throw new ArgumentException("id can not be empty or a blank string", nameof(id)); CheckInitialized(); HttpClient client = await GetHttpClient().ConfigureAwait(false); string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}sensors/{1}", ApiBase, id))).ConfigureAwait(false); //#if DEBUG // stringResult = "{\"state\":{ \"buttonevent\": 34, \"lastupdated\":\"2013-03-25T13:32:34\", },\"name\": \"Wall tap 1\", \"modelid\":\"ZGPSWITCH\", \"uniqueid\":\"01:23:45:67:89:AB-12\",\"manufacturername\": \"Philips\",\"swversion\":\"1.0\", \"type\": \"ZGPSwitch\"}"; //#endif JToken token = JToken.Parse(stringResult); if (token.Type == JTokenType.Array) { // Hue gives back errors in an array for this request JToken? error = token.First?["error"]; if (error != null) { if (error["type"]?.Value<int>() == 3) // Rule not found return null; throw new HueException(error["description"]?.Value<string>()); } } var sensor = token.ToObject<Sensor>(); if(sensor != null) sensor.Id = id; return sensor; } /// <summary> /// Update a sensor /// </summary> /// <param name="id"></param> /// <param name="newName"></param> /// <returns></returns> public async Task<HueResults> UpdateSensorAsync(string id, string newName) { CheckInitialized(); if (id == null) throw new ArgumentNullException(nameof(id)); if (id.Trim() == String.Empty) throw new ArgumentException("id must not be empty", nameof(id)); if (string.IsNullOrEmpty(newName)) throw new ArgumentNullException(nameof(newName)); JObject jsonObj = new JObject(); jsonObj.Add("name", newName); string jsonString = JsonConvert.SerializeObject(jsonObj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); HttpClient client = await GetHttpClient().ConfigureAwait(false); //Update sensor var result = await client.PutAsync(new Uri(string.Format("{0}sensors/{1}", ApiBase, id)), new JsonContent(jsonString)).ConfigureAwait(false); var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false); return DeserializeDefaultHueResult(jsonResult); } /// <summary> /// Changes the Sensor configuration /// </summary> /// <param name="id"></param> /// <param name="config"></param> /// <returns></returns> public async Task<HueResults> ChangeSensorConfigAsync(string id, SensorConfig config) { CheckInitialized(); if (id == null) throw new ArgumentNullException(nameof(id)); if (id.Trim() == String.Empty) throw new ArgumentException("id must not be empty", nameof(id)); if (config == null) throw new ArgumentNullException(nameof(config)); var updateJson = JObject.FromObject(config, new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore }); //Remove properties from json that are readonly updateJson.Remove("battery"); updateJson.Remove("reachable"); updateJson.Remove("configured"); updateJson.Remove("pending"); updateJson.Remove("sensitivitymax"); string jsonString = JsonConvert.SerializeObject(updateJson, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); HttpClient client = await GetHttpClient().ConfigureAwait(false); //Change sensor config var result = await client.PutAsync(new Uri(string.Format("{0}sensors/{1}/config", ApiBase, id)), new JsonContent(jsonString)).ConfigureAwait(false); var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false); return DeserializeDefaultHueResult(jsonResult); } public async Task<HueResults> ChangeSensorStateAsync(string id, SensorState state) { CheckInitialized(); if (id == null) throw new ArgumentNullException(nameof(id)); if (id.Trim() == String.Empty) throw new ArgumentException("id must not be empty", nameof(id)); if (state == null) throw new ArgumentNullException(nameof(state)); string jsonString = JsonConvert.SerializeObject(state, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); HttpClient client = await GetHttpClient().ConfigureAwait(false); //Change sensor state var result = await client.PutAsync(new Uri(string.Format("{0}sensors/{1}/state", ApiBase, id)), new JsonContent(jsonString)).ConfigureAwait(false); var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false); return DeserializeDefaultHueResult(jsonResult); } /// <summary> /// Deletes a single sensor /// </summary> /// <param name="groupId"></param> /// <returns></returns> public async Task<IReadOnlyCollection<DeleteDefaultHueResult>> DeleteSensorAsync(string id) { CheckInitialized(); if (id == null) throw new ArgumentNullException(nameof(id)); if (id.Trim() == String.Empty) throw new ArgumentException("id must not be empty", nameof(id)); HttpClient client = await GetHttpClient().ConfigureAwait(false); //Delete sensor var result = await client.DeleteAsync(new Uri(ApiBase + string.Format("sensors/{0}", id))).ConfigureAwait(false); string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false); //#if DEBUG // jsonResult = "[{\"success\":\"/sensors/" + id + " deleted\"}]"; //#endif return DeserializeDefaultHueResult<DeleteDefaultHueResult>(jsonResult); } } }
/** * MetroFramework - Modern UI for WinForms * * The MIT License (MIT) * Copyright (c) 2011 Sven Walter, http://github.com/viperneo * * 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.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.ComponentModel; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Windows.Forms; using MetroFramework.Components; using MetroFramework.Drawing; using MetroFramework.Interfaces; using MetroFramework.Native; namespace MetroFramework.Forms { #region Enums public enum MetroFormTextAlign { Left, Center, Right } public enum MetroFormShadowType { None, Flat, DropShadow, SystemShadow, AeroShadow } public enum MetroFormBorderStyle { None, FixedSingle } public enum BackLocation { TopLeft, TopRight, BottomLeft, BottomRight } #endregion public class MetroForm : Form, IMetroForm, IDisposable { #region Interface private MetroColorStyle metroStyle = MetroColorStyle.Blue; [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroColorStyle Style { get { if (StyleManager != null) return StyleManager.Style; return metroStyle; } set { metroStyle = value; } } private MetroThemeStyle metroTheme = MetroThemeStyle.Light; [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroThemeStyle Theme { get { if (StyleManager != null) return StyleManager.Theme; return metroTheme; } set { metroTheme = value; } } private MetroStyleManager metroStyleManager = null; [Browsable(false)] public MetroStyleManager StyleManager { get { return metroStyleManager; } set { metroStyleManager = value; } } #endregion #region Fields private MetroFormTextAlign textAlign = MetroFormTextAlign.Left; [Browsable(true)] [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroFormTextAlign TextAlign { get { return textAlign; } set { textAlign = value; } } [Browsable(false)] public override Color BackColor { get { return MetroPaint.BackColor.Form(Theme); } } private MetroFormBorderStyle formBorderStyle = MetroFormBorderStyle.None; [DefaultValue(MetroFormBorderStyle.None)] [Browsable(true)] [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroFormBorderStyle BorderStyle { get { return formBorderStyle; } set { formBorderStyle = value; } } private bool isMovable = true; [Category(MetroDefaults.PropertyCategory.Appearance)] public bool Movable { get { return isMovable; } set { isMovable = value; } } public new Padding Padding { get { return base.Padding; } set { value.Top = Math.Max(value.Top, DisplayHeader ? 60 : 30); base.Padding = value; } } protected override Padding DefaultPadding { get { return new Padding(20, DisplayHeader ? 60 : 20, 20, 20); } } private bool displayHeader = true; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(true)] public bool DisplayHeader { get { return displayHeader; } set { if (value != displayHeader) { Padding p = base.Padding; p.Top += value ? 30 : -30; base.Padding = p; } displayHeader = value; } } private bool isResizable = true; [Category(MetroDefaults.PropertyCategory.Appearance)] public bool Resizable { get { return isResizable; } set { isResizable = value; } } private MetroFormShadowType shadowType = MetroFormShadowType.Flat; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroFormShadowType.Flat)] public MetroFormShadowType ShadowType { get { return IsMdiChild ? MetroFormShadowType.None : shadowType; } set { shadowType = value; } } [Browsable(false)] public new FormBorderStyle FormBorderStyle { get { return base.FormBorderStyle; } set { base.FormBorderStyle = value; } } public new Form MdiParent { get { return base.MdiParent; } set { if (value != null) { RemoveShadow(); shadowType = MetroFormShadowType.None; } base.MdiParent = value; } } private const int borderWidth = 5; private Bitmap _image = null; private Image backImage; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(null)] public Image BackImage { get { return backImage; } set { backImage = value; _image = ApplyInvert(new Bitmap(value)); Refresh(); } } private Padding backImagePadding; [Category(MetroDefaults.PropertyCategory.Appearance)] public Padding BackImagePadding { get { return backImagePadding; } set { backImagePadding = value; Refresh(); } } private int backMaxSize; [Category(MetroDefaults.PropertyCategory.Appearance)] public int BackMaxSize { get { return backMaxSize; } set { backMaxSize = value; Refresh(); } } private BackLocation backLocation; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(BackLocation.TopLeft)] public BackLocation BackLocation { get { return backLocation; } set { backLocation = value; Refresh(); } } private bool _imageinvert; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(true)] public bool ApplyImageInvert { get { return _imageinvert; } set { _imageinvert = value; Refresh(); } } #endregion #region Constructor public MetroForm() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); FormBorderStyle = FormBorderStyle.None; Name = "MetroForm"; StartPosition = FormStartPosition.CenterScreen; TransparencyKey = Color.Lavender; } protected override void Dispose(bool disposing) { if (disposing) { RemoveShadow(); } base.Dispose(disposing); } #endregion #region Paint Methods public Bitmap ApplyInvert(Bitmap bitmapImage) { byte A, R, G, B; Color pixelColor; for (int y = 0; y < bitmapImage.Height; y++) { for (int x = 0; x < bitmapImage.Width; x++) { pixelColor = bitmapImage.GetPixel(x, y); A = pixelColor.A; R = (byte)(255 - pixelColor.R); G = (byte)(255 - pixelColor.G); B = (byte)(255 - pixelColor.B); if (R <= 0) R= 17; if (G <= 0) G= 17; if (B <= 0) B= 17; //bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B)); bitmapImage.SetPixel(x, y, Color.FromArgb((int)R, (int)G, (int)B)); } } return bitmapImage; } protected override void OnPaint(PaintEventArgs e) { Color backColor = MetroPaint.BackColor.Form(Theme); Color foreColor = MetroPaint.ForeColor.Title(Theme); e.Graphics.Clear(backColor); using (SolidBrush b = MetroPaint.GetStyleBrush(Style)) { Rectangle topRect = new Rectangle(0, 0, Width, borderWidth); e.Graphics.FillRectangle(b, topRect); } if (BorderStyle != MetroFormBorderStyle.None) { Color c = MetroPaint.BorderColor.Form(Theme); using (Pen pen = new Pen(c)) { e.Graphics.DrawLines(pen, new[] { new Point(0, borderWidth), new Point(0, Height - 1), new Point(Width - 1, Height - 1), new Point(Width - 1, borderWidth) }); } } if (backImage != null && backMaxSize != 0) { Image img = MetroImage.ResizeImage(backImage, new Rectangle(0, 0, backMaxSize, backMaxSize)); if (_imageinvert) { img = MetroImage.ResizeImage((Theme == MetroThemeStyle.Dark) ? _image : backImage, new Rectangle(0, 0, backMaxSize, backMaxSize)); } switch (backLocation) { case BackLocation.TopLeft: e.Graphics.DrawImage(img, 0 + backImagePadding.Left, 0 + backImagePadding.Top); break; case BackLocation.TopRight: e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width), 0 + backImagePadding.Top); break; case BackLocation.BottomLeft: e.Graphics.DrawImage(img, 0 + backImagePadding.Left, ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom)); break; case BackLocation.BottomRight: e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width), ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom)); break; } } if (displayHeader) { Rectangle bounds = new Rectangle(20, 20, ClientRectangle.Width - 2 * 20, 40); TextFormatFlags flags = TextFormatFlags.EndEllipsis | GetTextFormatFlags(); TextRenderer.DrawText(e.Graphics, Text, MetroFonts.Title, bounds, foreColor, flags); } if (Resizable && (SizeGripStyle == SizeGripStyle.Auto || SizeGripStyle == SizeGripStyle.Show)) { using (SolidBrush b = new SolidBrush(MetroPaint.ForeColor.Button.Disabled(Theme))) { Size resizeHandleSize = new Size(2, 2); e.Graphics.FillRectangles(b, new Rectangle[] { new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-10), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-10), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-14,ClientRectangle.Height-6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-14), resizeHandleSize) }); } } } private TextFormatFlags GetTextFormatFlags() { switch (TextAlign) { case MetroFormTextAlign.Left: return TextFormatFlags.Left; case MetroFormTextAlign.Center: return TextFormatFlags.HorizontalCenter; case MetroFormTextAlign.Right: return TextFormatFlags.Right; } throw new InvalidOperationException(); } #endregion #region Management Methods protected override void OnClosing(CancelEventArgs e) { if (!(this is MetroTaskWindow)) MetroTaskWindow.ForceClose(); base.OnClosing(e); } protected override void OnClosed(EventArgs e) { RemoveShadow(); base.OnClosed(e); } [SecuritySafeCritical] public bool FocusMe() { return WinApi.SetForegroundWindow(Handle); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (DesignMode) return; switch (StartPosition) { case FormStartPosition.CenterParent: CenterToParent(); break; case FormStartPosition.CenterScreen: if (IsMdiChild) { CenterToParent(); } else { CenterToScreen(); } break; } RemoveCloseButton(); if (ControlBox) { AddWindowButton(WindowButtons.Close); if (MaximizeBox) AddWindowButton(WindowButtons.Maximize); if (MinimizeBox) AddWindowButton(WindowButtons.Minimize); UpdateWindowButtonPosition(); } CreateShadow(); } protected override void OnActivated(EventArgs e) { base.OnActivated(e); if (shadowType == MetroFormShadowType.AeroShadow && IsAeroThemeEnabled() && IsDropShadowSupported()) { int val = 2; DwmApi.DwmSetWindowAttribute(Handle, 2, ref val, 4); var m = new DwmApi.MARGINS { cyBottomHeight = 1, cxLeftWidth = 0, cxRightWidth = 0, cyTopHeight = 0 }; DwmApi.DwmExtendFrameIntoClientArea(Handle, ref m); } } protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); Invalidate(); } protected override void OnResizeEnd(EventArgs e) { base.OnResizeEnd(e); UpdateWindowButtonPosition(); } protected override void WndProc(ref Message m) { if (DesignMode) { base.WndProc(ref m); return; } switch (m.Msg) { case (int)WinApi.Messages.WM_SYSCOMMAND: int sc = m.WParam.ToInt32() & 0xFFF0; switch (sc) { case (int)WinApi.Messages.SC_MOVE: if (!Movable) return; break; case (int)WinApi.Messages.SC_MAXIMIZE: break; case (int)WinApi.Messages.SC_RESTORE: break; } break; case (int)WinApi.Messages.WM_NCLBUTTONDBLCLK: case (int)WinApi.Messages.WM_LBUTTONDBLCLK: if (!MaximizeBox) return; break; case (int)WinApi.Messages.WM_NCHITTEST: WinApi.HitTest ht = HitTestNCA(m.HWnd, m.WParam, m.LParam); if (ht != WinApi.HitTest.HTCLIENT) { m.Result = (IntPtr)ht; return; } break; case (int)WinApi.Messages.WM_DWMCOMPOSITIONCHANGED: break; } base.WndProc(ref m); switch (m.Msg) { case (int)WinApi.Messages.WM_GETMINMAXINFO: OnGetMinMaxInfo(m.HWnd, m.LParam); break; } } [SecuritySafeCritical] private unsafe void OnGetMinMaxInfo(IntPtr hwnd, IntPtr lParam) { WinApi.MINMAXINFO* pmmi = (WinApi.MINMAXINFO*)lParam; Screen s = Screen.FromHandle(hwnd); pmmi->ptMaxSize.x = s.WorkingArea.Width; pmmi->ptMaxSize.y = s.WorkingArea.Height; pmmi->ptMaxPosition.x = Math.Abs(s.WorkingArea.Left - s.Bounds.Left); pmmi->ptMaxPosition.y = Math.Abs(s.WorkingArea.Top - s.Bounds.Top); //if (MinimumSize.Width > 0) pmmi->ptMinTrackSize.x = MinimumSize.Width; //if (MinimumSize.Height > 0) pmmi->ptMinTrackSize.y = MinimumSize.Height; //if (MaximumSize.Width > 0) pmmi->ptMaxTrackSize.x = MaximumSize.Width; //if (MaximumSize.Height > 0) pmmi->ptMaxTrackSize.y = MaximumSize.Height; } private WinApi.HitTest HitTestNCA(IntPtr hwnd, IntPtr wparam, IntPtr lparam) { //Point vPoint = PointToClient(new Point((int)lparam & 0xFFFF, (int)lparam >> 16 & 0xFFFF)); //Point vPoint = PointToClient(new Point((Int16)lparam, (Int16)((int)lparam >> 16))); Point vPoint = new Point((Int16)lparam, (Int16)((int)lparam >> 16)); int vPadding = Math.Max(Padding.Right, Padding.Bottom); if (Resizable) { if (RectangleToScreen(new Rectangle(ClientRectangle.Width - vPadding, ClientRectangle.Height - vPadding, vPadding, vPadding)).Contains(vPoint)) return WinApi.HitTest.HTBOTTOMRIGHT; } if (RectangleToScreen(new Rectangle(borderWidth, borderWidth, ClientRectangle.Width - 2 * borderWidth, 50)).Contains(vPoint)) return WinApi.HitTest.HTCAPTION; return WinApi.HitTest.HTCLIENT; } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left && Movable) { if (WindowState == FormWindowState.Maximized) return; if (Width - borderWidth > e.Location.X && e.Location.X > borderWidth && e.Location.Y > borderWidth) { MoveControl(); } } } [SecuritySafeCritical] private void MoveControl() { WinApi.ReleaseCapture(); WinApi.SendMessage(Handle, (int)WinApi.Messages.WM_NCLBUTTONDOWN, (int)WinApi.HitTest.HTCAPTION, 0); } [SecuritySafeCritical] private static bool IsAeroThemeEnabled() { if (Environment.OSVersion.Version.Major <= 5) return false; bool aeroEnabled; DwmApi.DwmIsCompositionEnabled(out aeroEnabled); return aeroEnabled; } private static bool IsDropShadowSupported() { return Environment.OSVersion.Version.Major > 5 && SystemInformation.IsDropShadowEnabled; } #endregion #region Window Buttons private enum WindowButtons { Minimize, Maximize, Close } private Dictionary<WindowButtons, MetroFormButton> windowButtonList; private void AddWindowButton(WindowButtons button) { if (windowButtonList == null) windowButtonList = new Dictionary<WindowButtons, MetroFormButton>(); if (windowButtonList.ContainsKey(button)) return; MetroFormButton newButton = new MetroFormButton(); if (button == WindowButtons.Close) { newButton.Text = "r"; } else if (button == WindowButtons.Minimize) { newButton.Text = "0"; } else if (button == WindowButtons.Maximize) { if (WindowState == FormWindowState.Normal) newButton.Text = "1"; else newButton.Text = "2"; } newButton.Style = Style; newButton.Theme = Theme; newButton.Tag = button; newButton.Size = new Size(25, 20); newButton.Anchor = AnchorStyles.Top | AnchorStyles.Right; newButton.TabStop = false; //remove the form controls from the tab stop newButton.Click += WindowButton_Click; Controls.Add(newButton); windowButtonList.Add(button, newButton); } private void WindowButton_Click(object sender, EventArgs e) { var btn = sender as MetroFormButton; if (btn != null) { var btnFlag = (WindowButtons)btn.Tag; if (btnFlag == WindowButtons.Close) { Close(); } else if (btnFlag == WindowButtons.Minimize) { WindowState = FormWindowState.Minimized; } else if (btnFlag == WindowButtons.Maximize) { if (WindowState == FormWindowState.Normal) { WindowState = FormWindowState.Maximized; btn.Text = "2"; } else { WindowState = FormWindowState.Normal; btn.Text = "1"; } } } } private void UpdateWindowButtonPosition() { if (!ControlBox) return; Dictionary<int, WindowButtons> priorityOrder = new Dictionary<int, WindowButtons>(3) { {0, WindowButtons.Close}, {1, WindowButtons.Maximize}, {2, WindowButtons.Minimize} }; Point firstButtonLocation = new Point(ClientRectangle.Width - borderWidth - 25, borderWidth); int lastDrawedButtonPosition = firstButtonLocation.X - 25; MetroFormButton firstButton = null; if (windowButtonList.Count == 1) { foreach (KeyValuePair<WindowButtons, MetroFormButton> button in windowButtonList) { button.Value.Location = firstButtonLocation; } } else { foreach (KeyValuePair<int, WindowButtons> button in priorityOrder) { bool buttonExists = windowButtonList.ContainsKey(button.Value); if (firstButton == null && buttonExists) { firstButton = windowButtonList[button.Value]; firstButton.Location = firstButtonLocation; continue; } if (firstButton == null || !buttonExists) continue; windowButtonList[button.Value].Location = new Point(lastDrawedButtonPosition, borderWidth); lastDrawedButtonPosition = lastDrawedButtonPosition - 25; } } Refresh(); } private class MetroFormButton : Button, IMetroControl { #region Interface [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaintBackground; protected virtual void OnCustomPaintBackground(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaintBackground != null) { CustomPaintBackground(this, e); } } [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaint; protected virtual void OnCustomPaint(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaint != null) { CustomPaint(this, e); } } [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaintForeground; protected virtual void OnCustomPaintForeground(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaintForeground != null) { CustomPaintForeground(this, e); } } private MetroColorStyle metroStyle = MetroColorStyle.Default; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroColorStyle.Default)] public MetroColorStyle Style { get { if (DesignMode || metroStyle != MetroColorStyle.Default) { return metroStyle; } if (StyleManager != null && metroStyle == MetroColorStyle.Default) { return StyleManager.Style; } if (StyleManager == null && metroStyle == MetroColorStyle.Default) { return MetroDefaults.Style; } return metroStyle; } set { metroStyle = value; } } private MetroThemeStyle metroTheme = MetroThemeStyle.Default; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroThemeStyle.Default)] public MetroThemeStyle Theme { get { if (DesignMode || metroTheme != MetroThemeStyle.Default) { return metroTheme; } if (StyleManager != null && metroTheme == MetroThemeStyle.Default) { return StyleManager.Theme; } if (StyleManager == null && metroTheme == MetroThemeStyle.Default) { return MetroDefaults.Theme; } return metroTheme; } set { metroTheme = value; } } private MetroStyleManager metroStyleManager = null; [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public MetroStyleManager StyleManager { get { return metroStyleManager; } set { metroStyleManager = value; } } private bool useCustomBackColor = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseCustomBackColor { get { return useCustomBackColor; } set { useCustomBackColor = value; } } private bool useCustomForeColor = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseCustomForeColor { get { return useCustomForeColor; } set { useCustomForeColor = value; } } private bool useStyleColors = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseStyleColors { get { return useStyleColors; } set { useStyleColors = value; } } [Browsable(false)] [Category(MetroDefaults.PropertyCategory.Behaviour)] [DefaultValue(false)] public bool UseSelectable { get { return GetStyle(ControlStyles.Selectable); } set { SetStyle(ControlStyles.Selectable, value); } } #endregion #region Fields private bool isHovered = false; private bool isPressed = false; #endregion #region Constructor public MetroFormButton() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); } #endregion #region Paint Methods protected override void OnPaint(PaintEventArgs e) { Color backColor, foreColor; MetroThemeStyle _Theme = Theme; if (Parent != null) { if (Parent is IMetroForm) { _Theme = ((IMetroForm)Parent).Theme; backColor = MetroPaint.BackColor.Form(_Theme); } else if (Parent is IMetroControl) { backColor = MetroPaint.GetStyleColor(Style); } else { backColor = Parent.BackColor; } } else { backColor = MetroPaint.BackColor.Form(_Theme); } if (isHovered && !isPressed && Enabled) { foreColor = MetroPaint.ForeColor.Button.Normal(_Theme); backColor = MetroPaint.BackColor.Button.Normal(_Theme); } else if (isHovered && isPressed && Enabled) { foreColor = MetroPaint.ForeColor.Button.Press(_Theme); backColor = MetroPaint.GetStyleColor(Style); } else if (!Enabled) { foreColor = MetroPaint.ForeColor.Button.Disabled(_Theme); backColor = MetroPaint.BackColor.Button.Disabled(_Theme); } else { foreColor = MetroPaint.ForeColor.Button.Normal(_Theme); } e.Graphics.Clear(backColor); Font buttonFont = new Font("Webdings", 9.25f); TextRenderer.DrawText(e.Graphics, Text, buttonFont, ClientRectangle, foreColor, backColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); } #endregion #region Mouse Methods protected override void OnMouseEnter(EventArgs e) { isHovered = true; Invalidate(); base.OnMouseEnter(e); } protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { isPressed = true; Invalidate(); } base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { isPressed = false; Invalidate(); base.OnMouseUp(e); } protected override void OnMouseLeave(EventArgs e) { isHovered = false; Invalidate(); base.OnMouseLeave(e); } #endregion } #endregion #region Shadows private const int CS_DROPSHADOW = 0x20000; const int WS_MINIMIZEBOX = 0x20000; protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.Style |= WS_MINIMIZEBOX; if (ShadowType == MetroFormShadowType.SystemShadow) cp.ClassStyle |= CS_DROPSHADOW; return cp; } } private Form shadowForm; private void CreateShadow() { switch (ShadowType) { case MetroFormShadowType.Flat: shadowForm = new MetroFlatDropShadow(this); return; case MetroFormShadowType.DropShadow: shadowForm = new MetroRealisticDropShadow(this); return; } } private void RemoveShadow() { if (shadowForm == null || shadowForm.IsDisposed) return; shadowForm.Visible = false; Owner = shadowForm.Owner; shadowForm.Owner = null; shadowForm.Dispose(); shadowForm = null; } #region MetroShadowBase protected abstract class MetroShadowBase : Form { protected Form TargetForm { get; private set; } private readonly int shadowSize; private readonly int wsExStyle; protected MetroShadowBase(Form targetForm, int shadowSize, int wsExStyle) { TargetForm = targetForm; this.shadowSize = shadowSize; this.wsExStyle = wsExStyle; TargetForm.Activated += OnTargetFormActivated; TargetForm.ResizeBegin += OnTargetFormResizeBegin; TargetForm.ResizeEnd += OnTargetFormResizeEnd; TargetForm.VisibleChanged += OnTargetFormVisibleChanged; TargetForm.SizeChanged += OnTargetFormSizeChanged; TargetForm.Move += OnTargetFormMove; TargetForm.Resize += OnTargetFormResize; if (TargetForm.Owner != null) Owner = TargetForm.Owner; TargetForm.Owner = this; MaximizeBox = false; MinimizeBox = false; ShowInTaskbar = false; ShowIcon = false; FormBorderStyle = FormBorderStyle.None; Bounds = GetShadowBounds(); } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= wsExStyle; return cp; } } private Rectangle GetShadowBounds() { Rectangle r = TargetForm.Bounds; r.Inflate(shadowSize, shadowSize); return r; } protected abstract void PaintShadow(); protected abstract void ClearShadow(); #region Event Handlers private bool isBringingToFront; protected override void OnDeactivate(EventArgs e) { base.OnDeactivate(e); isBringingToFront = true; } private void OnTargetFormActivated(object sender, EventArgs e) { if (Visible) Update(); if (isBringingToFront) { Visible = true; isBringingToFront = false; return; } BringToFront(); } private void OnTargetFormVisibleChanged(object sender, EventArgs e) { Visible = TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized; Update(); } private long lastResizedOn; private bool IsResizing { get { return lastResizedOn > 0; } } private void OnTargetFormResizeBegin(object sender, EventArgs e) { lastResizedOn = DateTime.Now.Ticks; } private void OnTargetFormMove(object sender, EventArgs e) { if (!TargetForm.Visible || TargetForm.WindowState != FormWindowState.Normal) { Visible = false; } else { Bounds = GetShadowBounds(); } } private void OnTargetFormResize(object sender, EventArgs e) { ClearShadow(); } private void OnTargetFormSizeChanged(object sender, EventArgs e) { Bounds = GetShadowBounds(); if (IsResizing) { return; } PaintShadowIfVisible(); } private void OnTargetFormResizeEnd(object sender, EventArgs e) { lastResizedOn = 0; PaintShadowIfVisible(); } private void PaintShadowIfVisible() { if (TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized) PaintShadow(); } #endregion #region Constants protected const int WS_EX_TRANSPARENT = 0x20; protected const int WS_EX_LAYERED = 0x80000; protected const int WS_EX_NOACTIVATE = 0x8000000; private const int TICKS_PER_MS = 10000; private const long RESIZE_REDRAW_INTERVAL = 1000 * TICKS_PER_MS; #endregion } #endregion #region Aero DropShadow protected class MetroAeroDropShadow : MetroShadowBase { public MetroAeroDropShadow(Form targetForm) : base(targetForm, 0, WS_EX_TRANSPARENT | WS_EX_NOACTIVATE ) { FormBorderStyle = FormBorderStyle.SizableToolWindow; } protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { if (specified == BoundsSpecified.Size) return; base.SetBoundsCore(x, y, width, height, specified); } protected override void PaintShadow() { Visible = true; } protected override void ClearShadow() { } } #endregion #region Flat DropShadow protected class MetroFlatDropShadow : MetroShadowBase { private Point Offset = new Point(-6, -6); public MetroFlatDropShadow(Form targetForm) : base(targetForm, 6, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE) { } protected override void OnLoad(EventArgs e) { base.OnLoad(e); PaintShadow(); } protected override void OnPaint(PaintEventArgs e) { Visible = true; PaintShadow(); } protected override void PaintShadow() { using( Bitmap getShadow = DrawBlurBorder() ) SetBitmap(getShadow, 255); } protected override void ClearShadow() { Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.Clear(Color.Transparent); g.Flush(); g.Dispose(); SetBitmap(img, 255); img.Dispose(); } #region Drawing methods [SecuritySafeCritical] private void SetBitmap(Bitmap bitmap, byte opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) throw new ApplicationException("The bitmap must be 32ppp with alpha-channel."); IntPtr screenDc = WinApi.GetDC(IntPtr.Zero); IntPtr memDc = WinApi.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); oldBitmap = WinApi.SelectObject(memDc, hBitmap); WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height); WinApi.POINT pointSource = new WinApi.POINT(0, 0); WinApi.POINT topPos = new WinApi.POINT(Left, Top); WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION(); blend.BlendOp = WinApi.AC_SRC_OVER; blend.BlendFlags = 0; blend.SourceConstantAlpha = opacity; blend.AlphaFormat = WinApi.AC_SRC_ALPHA; WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA); } finally { WinApi.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { WinApi.SelectObject(memDc, oldBitmap); WinApi.DeleteObject(hBitmap); } WinApi.DeleteDC(memDc); } } private Bitmap DrawBlurBorder() { return (Bitmap)DrawOutsetShadow(Color.Black, new Rectangle(0, 0, ClientRectangle.Width, ClientRectangle.Height)); } private Image DrawOutsetShadow(Color color, Rectangle shadowCanvasArea) { Rectangle rOuter = shadowCanvasArea; Rectangle rInner = new Rectangle(shadowCanvasArea.X + (-Offset.X - 1), shadowCanvasArea.Y + (-Offset.Y - 1), shadowCanvasArea.Width - (-Offset.X * 2 - 1), shadowCanvasArea.Height - (-Offset.Y * 2 - 1)); Bitmap img = new Bitmap(rOuter.Width, rOuter.Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; using (Brush bgBrush = new SolidBrush(Color.FromArgb(30, Color.Black))) { g.FillRectangle(bgBrush, rOuter); } using (Brush bgBrush = new SolidBrush(Color.FromArgb(60, Color.Black))) { g.FillRectangle(bgBrush, rInner); } g.Flush(); g.Dispose(); return img; } #endregion } #endregion #region Realistic DropShadow protected class MetroRealisticDropShadow : MetroShadowBase { public MetroRealisticDropShadow(Form targetForm) : base(targetForm, 15, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE) { } protected override void OnLoad(EventArgs e) { base.OnLoad(e); PaintShadow(); } protected override void OnPaint(PaintEventArgs e) { Visible = true; PaintShadow(); } protected override void PaintShadow() { using( Bitmap getShadow = DrawBlurBorder() ) SetBitmap(getShadow, 255); } protected override void ClearShadow() { Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.Clear(Color.Transparent); g.Flush(); g.Dispose(); SetBitmap(img, 255); img.Dispose(); } #region Drawing methods [SecuritySafeCritical] private void SetBitmap(Bitmap bitmap, byte opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) throw new ApplicationException("The bitmap must be 32ppp with alpha-channel."); IntPtr screenDc = WinApi.GetDC(IntPtr.Zero); IntPtr memDc = WinApi.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); oldBitmap = WinApi.SelectObject(memDc, hBitmap); WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height); WinApi.POINT pointSource = new WinApi.POINT(0, 0); WinApi.POINT topPos = new WinApi.POINT(Left, Top); WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION { BlendOp = WinApi.AC_SRC_OVER, BlendFlags = 0, SourceConstantAlpha = opacity, AlphaFormat = WinApi.AC_SRC_ALPHA }; WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA); } finally { WinApi.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { WinApi.SelectObject(memDc, oldBitmap); WinApi.DeleteObject(hBitmap); } WinApi.DeleteDC(memDc); } } private Bitmap DrawBlurBorder() { return (Bitmap)DrawOutsetShadow(0, 0, 40, 1, Color.Black, new Rectangle(1, 1, ClientRectangle.Width, ClientRectangle.Height)); } private Image DrawOutsetShadow(int hShadow, int vShadow, int blur, int spread, Color color, Rectangle shadowCanvasArea) { Rectangle rOuter = shadowCanvasArea; Rectangle rInner = shadowCanvasArea; rInner.Offset(hShadow, vShadow); rInner.Inflate(-blur, -blur); rOuter.Inflate(spread, spread); rOuter.Offset(hShadow, vShadow); Rectangle originalOuter = rOuter; Bitmap img = new Bitmap(originalOuter.Width, originalOuter.Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; var currentBlur = 0; do { var transparency = (rOuter.Height - rInner.Height) / (double)(blur * 2 + spread * 2); var shadowColor = Color.FromArgb(((int)(200 * (transparency * transparency))), color); var rOutput = rInner; rOutput.Offset(-originalOuter.Left, -originalOuter.Top); DrawRoundedRectangle(g, rOutput, currentBlur, Pens.Transparent, shadowColor); rInner.Inflate(1, 1); currentBlur = (int)((double)blur * (1 - (transparency * transparency))); } while (rOuter.Contains(rInner)); g.Flush(); g.Dispose(); return img; } private void DrawRoundedRectangle(Graphics g, Rectangle bounds, int cornerRadius, Pen drawPen, Color fillColor) { int strokeOffset = Convert.ToInt32(Math.Ceiling(drawPen.Width)); bounds = Rectangle.Inflate(bounds, -strokeOffset, -strokeOffset); var gfxPath = new GraphicsPath(); if (cornerRadius > 0) { gfxPath.AddArc(bounds.X, bounds.Y, cornerRadius, cornerRadius, 180, 90); gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y, cornerRadius, cornerRadius, 270, 90); gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 0, 90); gfxPath.AddArc(bounds.X, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 90, 90); } else { gfxPath.AddRectangle(bounds); } gfxPath.CloseAllFigures(); if (cornerRadius > 5) { using (SolidBrush b = new SolidBrush(fillColor)) { g.FillPath(b, gfxPath); } } if (drawPen != Pens.Transparent) { using (Pen p = new Pen(drawPen.Color)) { p.EndCap = p.StartCap = LineCap.Round; g.DrawPath(p, gfxPath); } } } #endregion } #endregion #endregion #region Helper Methods [SecuritySafeCritical] public void RemoveCloseButton() { IntPtr hMenu = WinApi.GetSystemMenu(Handle, false); if (hMenu == IntPtr.Zero) return; int n = WinApi.GetMenuItemCount(hMenu); if (n <= 0) return; WinApi.RemoveMenu(hMenu, (uint)(n - 1), WinApi.MfByposition | WinApi.MfRemove); WinApi.RemoveMenu(hMenu, (uint)(n - 2), WinApi.MfByposition | WinApi.MfRemove); WinApi.DrawMenuBar(Handle); } private Rectangle MeasureText(Graphics g, Rectangle clientRectangle, Font font, string text, TextFormatFlags flags) { var proposedSize = new Size(int.MaxValue, int.MinValue); var actualSize = TextRenderer.MeasureText(g, text, font, proposedSize, flags); return new Rectangle(clientRectangle.X, clientRectangle.Y, actualSize.Width, actualSize.Height); } #endregion } }
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using System; using System.Collections.Generic; using System.IO; using Com.Drew.Imaging; using Com.Drew.Lang; using Com.Drew.Metadata; using Com.Drew.Metadata.Exif; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Tools { /// <author>Drew Noakes https://drewnoakes.com</author> public class ProcessAllImagesInFolderUtility { /// <exception cref="System.IO.IOException"/> /// <exception cref="Com.Drew.Imaging.Jpeg.JpegProcessingException"/> public static void Main(string[] args) { if (args.Length == 0) { System.Console.Error.Println("Expects one or more directories as arguments."); System.Environment.Exit(1); } IList<string> directories = new AList<string>(); ProcessAllImagesInFolderUtility.FileHandler handler = null; foreach (string arg in args) { if (Sharpen.Runtime.EqualsIgnoreCase(arg, "-text")) { // If "-text" is specified, write the discovered metadata into a sub-folder relative to the image handler = new ProcessAllImagesInFolderUtility.TextFileOutputHandler(); } else { if (Sharpen.Runtime.EqualsIgnoreCase(arg, "-markdown")) { // If "-markdown" is specified, write a summary table in markdown format to standard out handler = new ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler(); } else { if (Sharpen.Runtime.EqualsIgnoreCase(arg, "-unknown")) { // If "-unknown" is specified, write CSV tallying unknown tag counts handler = new ProcessAllImagesInFolderUtility.UnknownTagHandler(); } else { // Treat this argument as a directory directories.Add(arg); } } } } if (handler == null) { handler = new ProcessAllImagesInFolderUtility.BasicFileHandler(); } long start = Runtime.NanoTime(); // Order alphabetically so that output is stable across invocations directories.Sort(); foreach (string directory in directories) { ProcessDirectory(new FilePath(directory), handler, string.Empty); } handler.OnCompleted(); System.Console.Out.Println(Sharpen.Extensions.StringFormat("Completed in %d ms", (Runtime.NanoTime() - start) / 1000000)); } private static void ProcessDirectory([NotNull] FilePath path, [NotNull] ProcessAllImagesInFolderUtility.FileHandler handler, [NotNull] string relativePath) { string[] pathItems = path.List(); if (pathItems == null) { return; } // Order alphabetically so that output is stable across invocations Arrays.Sort(pathItems); foreach (string pathItem in pathItems) { FilePath file = new FilePath(path, pathItem); if (file.IsDirectory()) { ProcessDirectory(file, handler, relativePath.Length == 0 ? pathItem : relativePath + "/" + pathItem); } else { if (handler.ShouldProcess(file)) { handler.OnProcessingStarting(file); // Read metadata Com.Drew.Metadata.Metadata metadata; try { metadata = ImageMetadataReader.ReadMetadata(file); } catch (Exception t) { handler.OnException(file, t); continue; } handler.OnExtracted(file, metadata, relativePath); } } } } internal interface FileHandler { bool ShouldProcess([NotNull] FilePath file); void OnException([NotNull] FilePath file, [NotNull] Exception throwable); void OnExtracted([NotNull] FilePath file, [NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] string relativePath); void OnCompleted(); void OnProcessingStarting([NotNull] FilePath file); } internal abstract class FileHandlerBase : ProcessAllImagesInFolderUtility.FileHandler { private readonly ICollection<string> _supportedExtensions = new HashSet<string>(Arrays.AsList("jpg", "jpeg", "png", "gif", "bmp", "ico", "webp", "pcx", "ai", "eps", "nef", "crw", "cr2", "orf", "arw", "raf", "srw", "x3f", "rw2", "rwl", "tif", "tiff", "psd", "dng")); private int _processedFileCount = 0; private int _exceptionCount = 0; private int _errorCount = 0; private long _processedByteCount = 0; public virtual bool ShouldProcess([NotNull] FilePath file) { string extension = GetExtension(file); return extension != null && _supportedExtensions.Contains(extension.ToLower()); } public virtual void OnProcessingStarting([NotNull] FilePath file) { _processedFileCount++; _processedByteCount += file.Length(); } public virtual void OnException([NotNull] FilePath file, [NotNull] Exception throwable) { _exceptionCount++; if (throwable is ImageProcessingException) { // this is an error in the Jpeg segment structure. we're looking for bad handling of // metadata segments. in this case, we didn't even get a segment. System.Console.Error.Printf("%s: %s [Error Extracting Metadata]\n\t%s%n", throwable.GetType().FullName, file, throwable.Message); } else { // general, uncaught exception during processing of jpeg segments System.Console.Error.Printf("%s: %s [Error Extracting Metadata]%n", throwable.GetType().FullName, file); Sharpen.Runtime.PrintStackTrace(throwable, System.Console.Error); } } public virtual void OnExtracted([NotNull] FilePath file, [NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] string relativePath) { if (metadata.HasErrors()) { System.Console.Error.Println(file); foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { if (!directory.HasErrors()) { continue; } foreach (string error in directory.GetErrors()) { System.Console.Error.Printf("\t[%s] %s%n", directory.GetName(), error); _errorCount++; } } } } public virtual void OnCompleted() { if (_processedFileCount > 0) { System.Console.Out.Println(Sharpen.Extensions.StringFormat("Processed %,d files (%,d bytes) with %,d exceptions and %,d file errors", _processedFileCount, _processedByteCount, _exceptionCount, _errorCount)); } } [CanBeNull] protected internal virtual string GetExtension([NotNull] FilePath file) { string fileName = file.GetName(); int i = fileName.LastIndexOf('.'); if (i == -1) { return null; } if (i == fileName.Length - 1) { return null; } return Sharpen.Runtime.Substring(fileName, i + 1); } } /// <summary>Writes a text file containing the extracted metadata for each input file.</summary> internal class TextFileOutputHandler : ProcessAllImagesInFolderUtility.FileHandlerBase { public override void OnExtracted([NotNull] FilePath file, [NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] string relativePath) { base.OnExtracted(file, metadata, relativePath); try { PrintWriter writer = null; try { writer = OpenWriter(file); // Build a list of all directories IList<Com.Drew.Metadata.Directory> directories = new AList<Com.Drew.Metadata.Directory>(); foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { directories.Add(directory); } // Sort them by name directories.Sort(new _IComparer_235()); // Write any errors if (metadata.HasErrors()) { foreach (Com.Drew.Metadata.Directory directory_1 in directories) { if (!directory_1.HasErrors()) { continue; } foreach (string error in directory_1.GetErrors()) { writer.Format("[ERROR: %s] %s\n", directory_1.GetName(), error); } } writer.Write("\n"); } // Write tag values for each directory foreach (Com.Drew.Metadata.Directory directory_2 in directories) { string directoryName = directory_2.GetName(); foreach (Tag tag in directory_2.GetTags()) { string tagName = tag.GetTagName(); string description = tag.GetDescription(); writer.Format("[%s - %s] %s = %s%n", directoryName, tag.GetTagTypeHex(), tagName, description); } if (directory_2.GetTagCount() != 0) { writer.Write('\n'); } } } finally { CloseWriter(writer); } } catch (IOException e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _IComparer_235 : IComparer<Com.Drew.Metadata.Directory> { public _IComparer_235() { } public int Compare(Com.Drew.Metadata.Directory o1, Com.Drew.Metadata.Directory o2) { return string.CompareOrdinal(o1.GetName(), o2.GetName()); } } public override void OnException([NotNull] FilePath file, [NotNull] Exception throwable) { base.OnException(file, throwable); try { PrintWriter writer = null; try { writer = OpenWriter(file); Sharpen.Runtime.PrintStackTrace(throwable, writer); writer.Write('\n'); } finally { CloseWriter(writer); } } catch (IOException e) { System.Console.Error.Printf("IO exception writing metadata file: %s%n", e.Message); } } /// <exception cref="System.IO.IOException"/> [NotNull] private static PrintWriter OpenWriter([NotNull] FilePath file) { // Create the output directory if it doesn't exist FilePath metadataDir = new FilePath(Sharpen.Extensions.StringFormat("%s/metadata", file.GetParent())); if (!metadataDir.Exists()) { metadataDir.Mkdir(); } string outputPath = Sharpen.Extensions.StringFormat("%s/metadata/%s.txt", file.GetParent(), file.GetName().ToLower()); FileWriter writer = new FileWriter(outputPath, false); writer.Write("FILE: " + file.GetName() + "\n"); writer.Write('\n'); return new PrintWriter(writer); } /// <exception cref="System.IO.IOException"/> private static void CloseWriter([CanBeNull] TextWriter writer) { if (writer != null) { writer.Write("Generated using metadata-extractor\n"); writer.Write("https://drewnoakes.com/code/exif/\n"); writer.Flush(); writer.Close(); } } } /// <summary>Creates a table describing sample images using Wiki markdown.</summary> internal class MarkdownTableOutputHandler : ProcessAllImagesInFolderUtility.FileHandlerBase { private readonly IDictionary<string, string> _extensionEquivalence = new Dictionary<string, string>(); private readonly IDictionary<string, IList<ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row>> _rowListByExtension = new Dictionary<string, IList<ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row>>(); internal class Row { internal readonly FilePath file; internal readonly Com.Drew.Metadata.Metadata metadata; [NotNull] internal readonly string relativePath; [CanBeNull] internal string manufacturer; [CanBeNull] internal string model; [CanBeNull] internal string exifVersion; [CanBeNull] internal string thumbnail; [CanBeNull] internal string makernote; internal Row(MarkdownTableOutputHandler _enclosing, [NotNull] FilePath file, [NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] string relativePath) { this._enclosing = _enclosing; this.file = file; this.metadata = metadata; this.relativePath = relativePath; ExifIFD0Directory ifd0Dir = metadata.GetFirstDirectoryOfType<ExifIFD0Directory>(); ExifSubIFDDirectory subIfdDir = metadata.GetFirstDirectoryOfType<ExifSubIFDDirectory>(); ExifThumbnailDirectory thumbDir = metadata.GetFirstDirectoryOfType<ExifThumbnailDirectory>(); if (ifd0Dir != null) { this.manufacturer = ifd0Dir.GetDescription(ExifIFD0Directory.TagMake); this.model = ifd0Dir.GetDescription(ExifIFD0Directory.TagModel); } bool hasMakernoteData = false; if (subIfdDir != null) { this.exifVersion = subIfdDir.GetDescription(ExifSubIFDDirectory.TagExifVersion); hasMakernoteData = subIfdDir.ContainsTag(ExifSubIFDDirectory.TagMakernote); } if (thumbDir != null) { int? width = thumbDir.GetInteger(ExifThumbnailDirectory.TagImageWidth); int? height = thumbDir.GetInteger(ExifThumbnailDirectory.TagImageHeight); this.thumbnail = width != null && height != null ? Sharpen.Extensions.StringFormat("Yes (%s x %s)", width, height) : "Yes"; } foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { if (directory.GetType().FullName.Contains("Makernote")) { this.makernote = Sharpen.Extensions.Trim(directory.GetName().Replace("Makernote", string.Empty)); } } if (this.makernote == null) { this.makernote = hasMakernoteData ? "(Unknown)" : "N/A"; } } private readonly MarkdownTableOutputHandler _enclosing; } public MarkdownTableOutputHandler() { _extensionEquivalence.Put("jpeg", "jpg"); } public override void OnExtracted([NotNull] FilePath file, [NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] string relativePath) { base.OnExtracted(file, metadata, relativePath); string extension = GetExtension(file); if (extension == null) { return; } // Sanitise the extension extension = extension.ToLower(); if (_extensionEquivalence.ContainsKey(extension)) { extension = _extensionEquivalence.Get(extension); } IList<ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row> list = _rowListByExtension.Get(extension); if (list == null) { list = new AList<ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row>(); _rowListByExtension.Put(extension, list); } list.Add(new ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row(this, file, metadata, relativePath)); } public override void OnCompleted() { base.OnCompleted(); OutputStream outputStream = null; PrintStream stream = null; try { outputStream = new FileOutputStream("../wiki/ImageDatabaseSummary.md", false); stream = new PrintStream(outputStream, false); WriteOutput(stream); stream.Flush(); } catch (IOException e) { Sharpen.Runtime.PrintStackTrace(e); } finally { if (stream != null) { stream.Close(); } if (outputStream != null) { try { outputStream.Close(); } catch (IOException e) { Sharpen.Runtime.PrintStackTrace(e); } } } } /// <exception cref="System.IO.IOException"/> private void WriteOutput([NotNull] PrintStream stream) { TextWriter writer = new OutputStreamWriter(stream); writer.Write("# Image Database Summary\n\n"); foreach (string extension in _rowListByExtension.Keys) { writer.Write("## " + extension.ToUpper() + " Files\n\n"); writer.Write("File|Manufacturer|Model|Dir Count|Exif?|Makernote|Thumbnail|All Data\n"); writer.Write("----|------------|-----|---------|-----|---------|---------|--------\n"); IList<ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row> rows = _rowListByExtension.Get(extension); // Order by manufacturer, then model rows.Sort(new _IComparer_441()); foreach (ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row row in rows) { writer.Write(Sharpen.Extensions.StringFormat("[%s](https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s/%s)|%s|%s|%d|%s|%s|%s|[metadata](https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s/metadata/%s.txt)%n" , row.file.GetName(), row.relativePath, StringUtil.UrlEncode(row.file.GetName()), row.manufacturer == null ? string.Empty : row.manufacturer, row.model == null ? string.Empty : row.model, row.metadata.GetDirectoryCount(), row.exifVersion == null ? string.Empty : row.exifVersion, row.makernote == null ? string.Empty : row.makernote, row.thumbnail == null ? string.Empty : row.thumbnail, row.relativePath, StringUtil.UrlEncode(row.file.GetName()).ToLower())); } writer.Write('\n'); } writer.Flush(); } private sealed class _IComparer_441 : IComparer<ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row> { public _IComparer_441() { } public int Compare(ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row o1, ProcessAllImagesInFolderUtility.MarkdownTableOutputHandler.Row o2) { int c1 = StringUtil.Compare(o1.manufacturer, o2.manufacturer); return c1 != 0 ? c1 : StringUtil.Compare(o1.model, o2.model); } } } /// <summary>Keeps track of unknown tags.</summary> internal class UnknownTagHandler : ProcessAllImagesInFolderUtility.FileHandlerBase { private Dictionary<string, Dictionary<int?, int?>> _occurrenceCountByTagByDirectory = new Dictionary<string, Dictionary<int?, int?>>(); public override void OnExtracted([NotNull] FilePath file, [NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] string relativePath) { base.OnExtracted(file, metadata, relativePath); foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { foreach (Tag tag in directory.GetTags()) { // Only interested in unknown tags (those without names) if (tag.HasTagName()) { continue; } Dictionary<int?, int?> occurrenceCountByTag = _occurrenceCountByTagByDirectory.Get(directory.GetName()); if (occurrenceCountByTag == null) { occurrenceCountByTag = new Dictionary<int?, int?>(); _occurrenceCountByTagByDirectory.Put(directory.GetName(), occurrenceCountByTag); } int? count = occurrenceCountByTag.Get(tag.GetTagType()); if (count == null) { count = 0; occurrenceCountByTag.Put(tag.GetTagType(), 0); } occurrenceCountByTag.Put(tag.GetTagType(), (int)count + 1); } } } public override void OnCompleted() { base.OnCompleted(); foreach (KeyValuePair<string, Dictionary<int?, int?>> pair1 in _occurrenceCountByTagByDirectory.EntrySet()) { string directoryName = pair1.Key; IList<KeyValuePair<int?, int?>> counts = new AList<KeyValuePair<int?, int?>>(pair1.Value.EntrySet()); counts.Sort(new _IComparer_516()); foreach (KeyValuePair<int?, int?> pair2 in counts) { int? tagType = pair2.Key; int? count = pair2.Value; System.Console.Out.Format("%s, 0x%04X, %d\n", directoryName, tagType, count); } } } private sealed class _IComparer_516 : IComparer<KeyValuePair<int?, int?>> { public _IComparer_516() { } public int Compare(KeyValuePair<int?, int?> o1, KeyValuePair<int?, int?> o2) { return o2.Value.CompareTo(o1.Value); } } } /// <summary>Does nothing with the output except enumerate it in memory and format descriptions.</summary> /// <remarks> /// Does nothing with the output except enumerate it in memory and format descriptions. This is useful in order to /// flush out any potential exceptions raised during the formatting of extracted value descriptions. /// </remarks> internal class BasicFileHandler : ProcessAllImagesInFolderUtility.FileHandlerBase { public override void OnExtracted([NotNull] FilePath file, [NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] string relativePath) { base.OnExtracted(file, metadata, relativePath); // Iterate through all values, calling toString to flush out any formatting exceptions foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { directory.GetName(); foreach (Tag tag in directory.GetTags()) { tag.GetTagName(); tag.GetDescription(); } } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace WinterIsComing.WebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Net.WebSockets; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Owin; using Owin.WebSocket.Extensions; using Owin.WebSocket.Handlers; namespace Owin.WebSocket { public abstract class WebSocketConnection { private readonly CancellationTokenSource mCancellToken; private IWebSocket mWebSocket; /// <summary> /// Owin context for the web socket /// </summary> public IOwinContext Context { get; private set; } /// <summary> /// Maximum message size in bytes for the receive buffer /// </summary> public int MaxMessageSize { get; private set; } /// <summary> /// Arguments captured from URI using Regex /// </summary> public Dictionary<string, string> Arguments { get; private set; } /// <summary> /// Queue of send operations to the client /// </summary> public TaskQueue QueueSend { get { return mWebSocket.SendQueue;} } protected WebSocketConnection(int maxMessageSize = 1024*64) { mCancellToken = new CancellationTokenSource(); MaxMessageSize = maxMessageSize; } /// <summary> /// Closes the websocket connection /// </summary> public Task Close(WebSocketCloseStatus status, string reason) { return mWebSocket.Close(status, reason, CancellationToken.None); } /// <summary> /// Sends data to the client with binary message type /// </summary> /// <param name="buffer">Data to send</param> /// <param name="endOfMessage">End of the message?</param> /// <returns>Task to send the data</returns> public Task SendBinary(byte[] buffer, bool endOfMessage) { return SendBinary(new ArraySegment<byte>(buffer), endOfMessage); } /// <summary> /// Sends data to the client with binary message type /// </summary> /// <param name="buffer">Data to send</param> /// <param name="endOfMessage">End of the message?</param> /// <returns>Task to send the data</returns> public Task SendBinary(ArraySegment<byte> buffer, bool endOfMessage) { return mWebSocket.SendBinary(buffer, endOfMessage, CancellationToken.None); } /// <summary> /// Sends data to the client with the text message type /// </summary> /// <param name="buffer">Data to send</param> /// <param name="endOfMessage">End of the message?</param> /// <returns>Task to send the data</returns> public Task SendText(byte[] buffer, bool endOfMessage) { return SendText(new ArraySegment<byte>(buffer), endOfMessage); } /// <summary> /// Sends data to the client with the text message type /// </summary> /// <param name="buffer">Data to send</param> /// <param name="endOfMessage">End of the message?</param> /// <returns>Task to send the data</returns> public Task SendText(ArraySegment<byte> buffer, bool endOfMessage) { return mWebSocket.SendText(buffer, endOfMessage, CancellationToken.None); } /// <summary> /// Sends data to the client /// </summary> /// <param name="buffer">Data to send</param> /// <param name="endOfMessage">End of the message?</param> /// <param name="type">Message type of the data</param> /// <returns>Task to send the data</returns> public Task Send(ArraySegment<byte> buffer, bool endOfMessage, WebSocketMessageType type) { return mWebSocket.Send(buffer, type, endOfMessage, CancellationToken.None); } /// <summary> /// Verify the request /// </summary> /// <param name="request">Websocket request</param> /// <returns>True if the request is authenticated else false to throw unauthenticated and deny the connection</returns> public virtual bool AuthenticateRequest(IOwinRequest request) { return true; } /// <summary> /// Verify the request asynchronously. Fires after AuthenticateRequest /// </summary> /// <param name="request">Websocket request</param> /// <returns>True if the request is authenticated else false to throw unauthenticated and deny the connection</returns> public virtual Task<bool> AuthenticateRequestAsync(IOwinRequest request) { return Task.FromResult(true); } /// <summary> /// Fires after the websocket has been opened with the client /// </summary> public virtual void OnOpen() { } /// <summary> /// Fires after the websocket has been opened with the client and after OnOpen /// </summary> public virtual Task OnOpenAsync() { return Task.Delay(0); } /// <summary> /// Fires when data is received from the client /// </summary> /// <param name="message">Data that was received</param> /// <param name="type">Message type of the data</param> public virtual Task OnMessageReceived(ArraySegment<byte> message, WebSocketMessageType type) { return Task.Delay(0); } /// <summary> /// Fires with the connection with the client has closed /// </summary> public virtual void OnClose(WebSocketCloseStatus? closeStatus, string closeStatusDescription) { } /// <summary> /// Fires with the connection with the client has closed and after OnClose /// </summary> public virtual Task OnCloseAsync(WebSocketCloseStatus? closeStatus, string closeStatusDescription) { return Task.Delay(0); } /// <summary> /// Fires when an exception occurs in the message reading loop /// </summary> /// <param name="error">Error that occured</param> public virtual void OnReceiveError(Exception error) { } /// <summary> /// Receive one entire message from the web socket /// </summary> internal async Task AcceptSocketAsync(IOwinContext context, IDictionary<string, string> argumentMatches) { var accept = context.Get<Action<IDictionary<string, object>, Func<IDictionary<string, object>, Task>>>("websocket.Accept"); if (accept == null) { // Bad Request context.Response.StatusCode = 400; context.Response.Write("Not a valid websocket request"); return; } Arguments = new Dictionary<string, string>(argumentMatches); var responseBuffering = context.Environment.Get<Action>("server.DisableResponseBuffering"); if (responseBuffering != null) responseBuffering(); var responseCompression = context.Environment.Get<Action>("systemweb.DisableResponseCompression"); if (responseCompression != null) responseCompression(); context.Response.Headers.Set("X-Content-Type-Options", "nosniff"); Context = context; if (AuthenticateRequest(context.Request)) { var authorized = await AuthenticateRequestAsync(context.Request); if (authorized) { //user was authorized so accept the socket accept(null, RunWebSocket); return; } } //see if user was forbidden or unauthorized from previous authenticate request failure if (context.Request.User != null && context.Request.User.Identity.IsAuthenticated) { context.Response.StatusCode = 403; } else { context.Response.StatusCode = 401; } } private async Task RunWebSocket(IDictionary<string, object> websocketContext) { object value; if (websocketContext.TryGetValue(typeof (WebSocketContext).FullName, out value)) { mWebSocket = new NetWebSocket(((WebSocketContext) value).WebSocket); } else { mWebSocket = new OwinWebSocket(websocketContext); } OnOpen(); await OnOpenAsync(); var buffer = new byte[MaxMessageSize]; Tuple<ArraySegment<byte>, WebSocketMessageType> received = null; do { try { received = await mWebSocket.ReceiveMessage(buffer, mCancellToken.Token); if (received.Item1.Count > 0) await OnMessageReceived(received.Item1, received.Item2); } catch (TaskCanceledException) { break; } catch (OperationCanceledException oce) { if (!mCancellToken.IsCancellationRequested) { OnReceiveError(oce); } break; } catch (ObjectDisposedException) { break; } catch (Exception ex) { if (IsFatalSocketException(ex)) { OnReceiveError(ex); } break; } } while (received.Item2 != WebSocketMessageType.Close); try { await mWebSocket.Close(WebSocketCloseStatus.NormalClosure, string.Empty, mCancellToken.Token); } catch { //Ignore } if(!mCancellToken.IsCancellationRequested) mCancellToken.Cancel(); OnClose(mWebSocket.CloseStatus, mWebSocket.CloseStatusDescription); await OnCloseAsync(mWebSocket.CloseStatus, mWebSocket.CloseStatusDescription); } internal static bool IsFatalSocketException(Exception ex) { // If this exception is due to the underlying TCP connection going away, treat as a normal close // rather than a fatal exception. var ce = ex as COMException; if (ce != null) { switch ((uint)ce.ErrorCode) { case 0x800703e3: case 0x800704cd: case 0x80070026: return false; } } // unknown exception; treat as fatal return true; } } }
namespace android.graphics { [global::MonoJavaBridge.JavaClass()] public sealed partial class Rect : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal Rect(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public sealed override bool equals(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Rect.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::android.graphics.Rect._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public sealed override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.graphics.Rect.staticClass, "toString", "()Ljava/lang/String;", ref global::android.graphics.Rect._m1) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m2; public void offset(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "offset", "(II)V", ref global::android.graphics.Rect._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m3; public bool isEmpty() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Rect.staticClass, "isEmpty", "()Z", ref global::android.graphics.Rect._m3); } private static global::MonoJavaBridge.MethodId _m4; public bool contains(android.graphics.Rect arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Rect.staticClass, "contains", "(Landroid/graphics/Rect;)Z", ref global::android.graphics.Rect._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public bool contains(int arg0, int arg1, int arg2, int arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Rect.staticClass, "contains", "(IIII)Z", ref global::android.graphics.Rect._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m6; public bool contains(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Rect.staticClass, "contains", "(II)Z", ref global::android.graphics.Rect._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m7; public void set(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "set", "(IIII)V", ref global::android.graphics.Rect._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m8; public void set(android.graphics.Rect arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "set", "(Landroid/graphics/Rect;)V", ref global::android.graphics.Rect._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public void sort() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "sort", "()V", ref global::android.graphics.Rect._m9); } private static global::MonoJavaBridge.MethodId _m10; public static bool intersects(android.graphics.Rect arg0, android.graphics.Rect arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Rect._m10.native == global::System.IntPtr.Zero) global::android.graphics.Rect._m10 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Rect.staticClass, "intersects", "(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z"); return @__env.CallStaticBooleanMethod(android.graphics.Rect.staticClass, global::android.graphics.Rect._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m11; public bool intersects(int arg0, int arg1, int arg2, int arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Rect.staticClass, "intersects", "(IIII)Z", ref global::android.graphics.Rect._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m12; public void union(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "union", "(II)V", ref global::android.graphics.Rect._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m13; public void union(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "union", "(IIII)V", ref global::android.graphics.Rect._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m14; public void union(android.graphics.Rect arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "union", "(Landroid/graphics/Rect;)V", ref global::android.graphics.Rect._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m15; public int centerX() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Rect.staticClass, "centerX", "()I", ref global::android.graphics.Rect._m15); } private static global::MonoJavaBridge.MethodId _m16; public int centerY() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Rect.staticClass, "centerY", "()I", ref global::android.graphics.Rect._m16); } private static global::MonoJavaBridge.MethodId _m17; public int height() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Rect.staticClass, "height", "()I", ref global::android.graphics.Rect._m17); } private static global::MonoJavaBridge.MethodId _m18; public int width() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Rect.staticClass, "width", "()I", ref global::android.graphics.Rect._m18); } private static global::MonoJavaBridge.MethodId _m19; public void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.graphics.Rect._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m20; public int describeContents() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Rect.staticClass, "describeContents", "()I", ref global::android.graphics.Rect._m20); } private static global::MonoJavaBridge.MethodId _m21; public void readFromParcel(android.os.Parcel arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V", ref global::android.graphics.Rect._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; public global::java.lang.String flattenToString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.graphics.Rect.staticClass, "flattenToString", "()Ljava/lang/String;", ref global::android.graphics.Rect._m22) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m23; public static global::android.graphics.Rect unflattenFromString(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Rect._m23.native == global::System.IntPtr.Zero) global::android.graphics.Rect._m23 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Rect.staticClass, "unflattenFromString", "(Ljava/lang/String;)Landroid/graphics/Rect;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Rect>(@__env.CallStaticObjectMethod(android.graphics.Rect.staticClass, global::android.graphics.Rect._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Rect; } private static global::MonoJavaBridge.MethodId _m24; public global::java.lang.String toShortString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.graphics.Rect.staticClass, "toShortString", "()Ljava/lang/String;", ref global::android.graphics.Rect._m24) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m25; public void setEmpty() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "setEmpty", "()V", ref global::android.graphics.Rect._m25); } private static global::MonoJavaBridge.MethodId _m26; public float exactCenterX() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.graphics.Rect.staticClass, "exactCenterX", "()F", ref global::android.graphics.Rect._m26); } private static global::MonoJavaBridge.MethodId _m27; public float exactCenterY() { return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.graphics.Rect.staticClass, "exactCenterY", "()F", ref global::android.graphics.Rect._m27); } private static global::MonoJavaBridge.MethodId _m28; public void offsetTo(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "offsetTo", "(II)V", ref global::android.graphics.Rect._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m29; public void inset(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Rect.staticClass, "inset", "(II)V", ref global::android.graphics.Rect._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m30; public bool intersect(int arg0, int arg1, int arg2, int arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Rect.staticClass, "intersect", "(IIII)Z", ref global::android.graphics.Rect._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m31; public bool intersect(android.graphics.Rect arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Rect.staticClass, "intersect", "(Landroid/graphics/Rect;)Z", ref global::android.graphics.Rect._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m32; public bool setIntersect(android.graphics.Rect arg0, android.graphics.Rect arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Rect.staticClass, "setIntersect", "(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z", ref global::android.graphics.Rect._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m33; public Rect() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Rect._m33.native == global::System.IntPtr.Zero) global::android.graphics.Rect._m33 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Rect.staticClass, global::android.graphics.Rect._m33); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m34; public Rect(int arg0, int arg1, int arg2, int arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Rect._m34.native == global::System.IntPtr.Zero) global::android.graphics.Rect._m34 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "<init>", "(IIII)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Rect.staticClass, global::android.graphics.Rect._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m35; public Rect(android.graphics.Rect arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Rect._m35.native == global::System.IntPtr.Zero) global::android.graphics.Rect._m35 = @__env.GetMethodIDNoThrow(global::android.graphics.Rect.staticClass, "<init>", "(Landroid/graphics/Rect;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Rect.staticClass, global::android.graphics.Rect._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _left2391; public int left { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _left2391); } set { } } internal static global::MonoJavaBridge.FieldId _top2392; public int top { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _top2392); } set { } } internal static global::MonoJavaBridge.FieldId _right2393; public int right { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _right2393); } set { } } internal static global::MonoJavaBridge.FieldId _bottom2394; public int bottom { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _bottom2394); } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR2395; public static global::android.os.Parcelable_Creator CREATOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.graphics.Rect.staticClass, _CREATOR2395)) as android.os.Parcelable_Creator; } } static Rect() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.Rect.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Rect")); global::android.graphics.Rect._left2391 = @__env.GetFieldIDNoThrow(global::android.graphics.Rect.staticClass, "left", "I"); global::android.graphics.Rect._top2392 = @__env.GetFieldIDNoThrow(global::android.graphics.Rect.staticClass, "top", "I"); global::android.graphics.Rect._right2393 = @__env.GetFieldIDNoThrow(global::android.graphics.Rect.staticClass, "right", "I"); global::android.graphics.Rect._bottom2394 = @__env.GetFieldIDNoThrow(global::android.graphics.Rect.staticClass, "bottom", "I"); global::android.graphics.Rect._CREATOR2395 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.Rect.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;"); } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System.Linq; using Boo.Lang.Compiler.TypeSystem.Builders; using Boo.Lang.Compiler.TypeSystem.Internal; namespace Boo.Lang.Compiler.Steps { using System.Collections; using Boo.Lang; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.TypeSystem; public class ProcessSharedLocals : AbstractTransformerCompilerStep { Method _currentMethod; ClassDefinition _sharedLocalsClass; Hashtable _mappings = new Hashtable(); readonly List<ReferenceExpression> _references = new List<ReferenceExpression>(); readonly List<ILocalEntity> _shared = new List<ILocalEntity>(); int _closureDepth; override public void Dispose() { _shared.Clear(); _references.Clear(); _mappings.Clear(); base.Dispose(); } override public void OnField(Field node) { } override public void OnInterfaceDefinition(InterfaceDefinition node) { } override public void OnEnumDefinition(EnumDefinition node) { } override public void OnConstructor(Constructor node) { OnMethod(node); } override public void OnMethod(Method node) { _references.Clear(); _mappings.Clear(); _currentMethod = node; _sharedLocalsClass = null; _closureDepth = 0; Visit(node.Body); CreateSharedLocalsClass(); if (null != _sharedLocalsClass) { node.DeclaringType.Members.Add(_sharedLocalsClass); Map(); } } override public void OnBlockExpression(BlockExpression node) { ++_closureDepth; Visit(node.Body); --_closureDepth; } override public void OnGeneratorExpression(GeneratorExpression node) { ++_closureDepth; Visit(node.Iterator); Visit(node.Expression); Visit(node.Filter); --_closureDepth; } override public void OnReferenceExpression(ReferenceExpression node) { ILocalEntity local = node.Entity as ILocalEntity; if (null == local) return; if (local.IsPrivateScope) return; _references.Add(node); if (_closureDepth == 0) return; local.IsShared = _currentMethod.Locals.ContainsEntity(local) || _currentMethod.Parameters.ContainsEntity(local); } void Map() { IType type = (IType)_sharedLocalsClass.Entity; InternalLocal locals = CodeBuilder.DeclareLocal(_currentMethod, "$locals", type); foreach (ReferenceExpression reference in _references) { IField mapped = (IField)_mappings[reference.Entity]; if (null == mapped) continue; reference.ParentNode.Replace( reference, CodeBuilder.CreateMemberReference( CodeBuilder.CreateReference(locals), mapped)); } Block initializationBlock = new Block(); initializationBlock.Add(CodeBuilder.CreateAssignment( CodeBuilder.CreateReference(locals), CodeBuilder.CreateConstructorInvocation(type.GetConstructors().First()))); InitializeSharedParameters(initializationBlock, locals); _currentMethod.Body.Statements.Insert(0, initializationBlock); foreach (IEntity entity in _mappings.Keys) { _currentMethod.Locals.RemoveByEntity(entity); } } void InitializeSharedParameters(Block block, InternalLocal locals) { foreach (Node node in _currentMethod.Parameters) { InternalParameter param = (InternalParameter)node.Entity; if (param.IsShared) { block.Add( CodeBuilder.CreateAssignment( CodeBuilder.CreateMemberReference( CodeBuilder.CreateReference(locals), (IField)_mappings[param]), CodeBuilder.CreateReference(param))); } } } void CreateSharedLocalsClass() { _shared.Clear(); CollectSharedLocalEntities(_currentMethod.Locals); CollectSharedLocalEntities(_currentMethod.Parameters); if (_shared.Count > 0) { BooClassBuilder builder = CodeBuilder.CreateClass(Context.GetUniqueName(_currentMethod.Name, "locals")); builder.Modifiers |= TypeMemberModifiers.Internal; builder.AddBaseType(TypeSystemServices.ObjectType); int i=0; foreach (ILocalEntity local in _shared) { Field field = builder.AddInternalField( string.Format("${0}", local.Name), local.Type); ++i; _mappings[local] = field.Entity; } builder.AddConstructor().Body.Add( CodeBuilder.CreateSuperConstructorInvocation(TypeSystemServices.ObjectType)); _sharedLocalsClass = builder.ClassDefinition; } } void CollectSharedLocalEntities<T>(System.Collections.Generic.IEnumerable<T> nodes) where T : Node { foreach (T node in nodes) { var local = (ILocalEntity)node.Entity; if (local.IsShared) _shared.Add(local); } } } }
using System; using System.IO; using System.Linq; using NUnit.Framework; using StructureMap.Configuration.DSL; using StructureMap.Graph; using StructureMap.Testing.DocumentationExamples; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget3; using StructureMap.Testing.Widget5; using StructureMap.TypeRules; namespace StructureMap.Testing.Graph { public class TestingRegistry : Registry { public static bool WasUsed; public TestingRegistry() { WasUsed = true; ForRequestedType<Rule>().TheDefault.IsThis(new ColorRule("Green")); } public static void Reset() { WasUsed = false; } } [TestFixture] public class AssemblyScannerTester { #region Setup/Teardown [SetUp] public void SetUp() { TestingRegistry.Reset(); theGraph = null; } #endregion [TestFixtureSetUp] public void FixtureSetUp() { string binFolder = Path.GetDirectoryName(GetType().Assembly.Location); assemblyScanningFolder = Path.Combine(binFolder, "DynamicallyLoaded"); if (!Directory.Exists(assemblyScanningFolder)) Directory.CreateDirectory(assemblyScanningFolder); string assembly1 = typeof (RedGreenRegistry).Assembly.Location; string assembly2 = typeof (IWorker).Assembly.Location; File.Copy(assembly1, Path.Combine(assemblyScanningFolder, Path.GetFileName(assembly1)), true); File.Copy(assembly2, Path.Combine(assemblyScanningFolder, Path.GetFileName(assembly2)), true); } private PluginGraph theGraph; private string assemblyScanningFolder; private void Scan(Action<AssemblyScanner> action) { var scanner = new AssemblyScanner(); action(scanner); theGraph = new PluginGraph(); scanner.ExcludeNamespaceContainingType<ScanningRegistry>(); scanner.ScanForAll(theGraph); theGraph.Log.AssertFailures(); } private void shouldHaveFamily<T>() { theGraph.PluginFamilies.Contains(typeof (T)).ShouldBeTrue(); } private void shouldNotHaveFamily<T>() { theGraph.PluginFamilies.Contains(typeof (T)).ShouldBeFalse(); } private void shouldHaveFamilyWithSameName<T>() { // The Types may not be "Equal" if their assemblies were loaded in different load contexts (.LoadFrom) // so we will consider them equal if their names match. theGraph.PluginFamilies.Any(family => family.PluginType.FullName == typeof (T).FullName).ShouldBeTrue(); } private void shouldNotHaveFamilyWithSameName<T>() { theGraph.PluginFamilies.Any(family => family.PluginType.FullName == typeof (T).FullName).ShouldBeFalse(); } [Test] public void AssemblyScanner_will_scan_for_attributes_by_default() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); }); shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void is_in_namespace() { GetType().IsInNamespace("blah").ShouldBeFalse(); GetType().IsInNamespace("StructureMap").ShouldBeTrue(); GetType().IsInNamespace("StructureMap.Testing").ShouldBeTrue(); GetType().IsInNamespace("StructureMap.Testing.Graph").ShouldBeTrue(); GetType().IsInNamespace("StructureMap.Testing.Graph.Something").ShouldBeFalse(); } [Test] public void class_outside_namespace_doesnt_match_any_namespace_check() { typeof(class_outside_namespace).IsInNamespace("blah").ShouldBeFalse(); typeof(class_outside_namespace).IsInNamespace("StructureMap").ShouldBeFalse(); } [Test] public void Only_scan_for_registries_ignores_attributes() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.IgnoreStructureMapAttributes(); }); shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void scan_all_assemblies_in_a_folder() { Scan(x => x.AssembliesFromPath(assemblyScanningFolder)); shouldHaveFamilyWithSameName<IInterfaceInWidget5>(); shouldHaveFamilyWithSameName<IWorker>(); } [Test, Explicit] public void scan_all_assemblies_in_application_base_directory() { Scan(x => x.AssembliesFromApplicationBaseDirectory()); shouldHaveFamilyWithSameName<IInterfaceInWidget5>(); shouldHaveFamilyWithSameName<IWorker>(); } [Test] public void scan_but_ignore_registries_by_default() { Scan(x => { x.TheCallingAssembly(); }); TestingRegistry.WasUsed.ShouldBeFalse(); } [Test] public void scan_specific_assemblies_in_a_folder() { string assemblyToSpecificallyExclude = typeof (IWorker).Assembly.GetName().Name; Scan( x => x.AssembliesFromPath(assemblyScanningFolder, asm => asm.GetName().Name != assemblyToSpecificallyExclude)); shouldHaveFamilyWithSameName<IInterfaceInWidget5>(); shouldNotHaveFamilyWithSameName<IWorker>(); } [Test] public void scan_specific_assemblies_in_application_base_directory() { string assemblyToSpecificallyExclude = typeof (IWorker).Assembly.GetName().Name; Scan( x => x.AssembliesFromPath(assemblyScanningFolder, asm => asm.GetName().Name != assemblyToSpecificallyExclude)); shouldHaveFamilyWithSameName<IInterfaceInWidget5>(); shouldNotHaveFamilyWithSameName<IWorker>(); } [Test] public void Search_for_registries_when_explicitly_told() { Scan(x => { x.TheCallingAssembly(); x.LookForRegistries(); }); TestingRegistry.WasUsed.ShouldBeTrue(); } [Test] public void test_the_family_attribute_scanner() { var scanner = new FamilyAttributeScanner(); var graph = new PluginGraph(); var registry = new Registry(); scanner.Process(typeof (ITypeThatHasAttributeButIsNotInRegistry), registry); registry.ConfigurePluginGraph(graph); graph.PluginFamilies.Contains(typeof (ITypeThatHasAttributeButIsNotInRegistry)).ShouldBeTrue(); graph = new PluginGraph(); registry = new Registry(); scanner.Process(GetType(), registry); registry.ConfigurePluginGraph(graph); graph.PluginFamilies.Contains(GetType()).ShouldBeFalse(); } [Test] public void use_a_dual_exclude() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.Exclude(type => type == typeof (ITypeThatHasAttributeButIsNotInRegistry)); x.Exclude(type => type == typeof (IInterfaceInWidget5)); }); shouldNotHaveFamily<IInterfaceInWidget5>(); shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void use_a_dual_exclude2() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.Exclude(type => type == typeof (ITypeThatHasAttributeButIsNotInRegistry)); x.Exclude(type => type == GetType()); }); shouldHaveFamily<IInterfaceInWidget5>(); shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void use_a_single_exclude() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.Exclude(type => type == typeof (ITypeThatHasAttributeButIsNotInRegistry)); }); shouldHaveFamily<IInterfaceInWidget5>(); shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void use_a_single_exclude_of_type() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.ExcludeType<ITypeThatHasAttributeButIsNotInRegistry>(); }); shouldHaveFamily<IInterfaceInWidget5>(); shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void use_a_single_exclude2() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.ExcludeNamespace("StructureMap.Testing.Widget5"); }); shouldNotHaveFamily<IInterfaceInWidget5>(); shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void use_a_single_exclude3() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.ExcludeNamespaceContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); }); shouldNotHaveFamily<IInterfaceInWidget5>(); shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void Use_a_single_include_predicate() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); }); shouldHaveFamily<IInterfaceInWidget5>(); shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.Include(type => type == typeof (ITypeThatHasAttributeButIsNotInRegistry)); }); shouldNotHaveFamily<IInterfaceInWidget5>(); shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void Use_a_single_include_predicate_2() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); }); shouldHaveFamily<IInterfaceInWidget5>(); shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.IncludeNamespace(typeof (ITypeThatHasAttributeButIsNotInRegistry).Namespace); }); shouldHaveFamily<IInterfaceInWidget5>(); shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void Use_a_single_include_predicate_3() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); }); shouldHaveFamily<IInterfaceInWidget5>(); shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.IncludeNamespaceContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); }); shouldHaveFamily<IInterfaceInWidget5>(); shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void use_two_predicates_for_includes() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.Include(type => type == typeof (ITypeThatHasAttributeButIsNotInRegistry)); x.Include(type => type == typeof (IInterfaceInWidget5)); }); shouldHaveFamily<IInterfaceInWidget5>(); shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } [Test] public void use_two_predicates_for_includes2() { Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); x.Include(type => type == typeof (ITypeThatHasAttributeButIsNotInRegistry)); x.Include(type => type == GetType()); }); shouldNotHaveFamily<IInterfaceInWidget5>(); shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>(); } } public interface IController { } public class AddressController : IController { } public class SiteController : IController { } [TestFixture] public class when_attaching_types_with_naming_pattern { #region Setup/Teardown [SetUp] public void SetUp() { container = new Container(x => { x.Scan(o => { o.TheCallingAssembly(); o.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", "")); }); }); } #endregion private IContainer container; [Test] public void can_find_objects_later_by_name() { container.GetInstance<IController>("Address") .ShouldBeOfType<AddressController>(); container.GetInstance<IController>("Site") .ShouldBeOfType<SiteController>(); } } } public class class_outside_namespace { }
using System; using System.Collections.Generic; using System.Reflection; namespace GodLesZ.Library.Controls { /// <summary> /// An instance of Munger gets a value from or puts a value into a target object. The property /// to be peeked (or poked) is determined from a string. The peeking or poking is done using reflection. /// </summary> /// <remarks> /// Name of the aspect to be peeked can be a field, property or parameterless method. The name of an /// aspect to poke can be a field, writable property or single parameter method. /// <para> /// Aspect names can be dotted to chain a series of references. /// </para> /// <example>Order.Customer.HomeAddress.State</example> /// </remarks> public class Munger { #region Life and death /// <summary> /// Create a do nothing Munger /// </summary> public Munger() { } /// <summary> /// Create a Munger that works on the given aspect name /// </summary> /// <param name="aspectName">The name of the </param> public Munger(String aspectName) { this.AspectName = aspectName; } #endregion #region Static utility methods /// <summary> /// A helper method to put the given value into the given aspect of the given object. /// </summary> /// <remarks>This method catches and silently ignores any errors that occur /// while modifying the target object</remarks> /// <param name="target">The object to be modified</param> /// <param name="propertyName">The name of the property/field to be modified</param> /// <param name="value">The value to be assigned</param> /// <returns>Did the modification work?</returns> public static bool PutProperty(object target, string propertyName, object value) { try { Munger munger = new Munger(propertyName); return munger.PutValue(target, value); } catch (MungerException) { // Not a lot we can do about this. Something went wrong in the bowels // of the property. Let's take the ostrich approach and just ignore it :-) } return false; } #endregion #region Public properties /// <summary> /// The name of the aspect that is to be peeked or poked. /// </summary> /// <remarks> /// <para> /// This name can be a field, property or parameter-less method. /// </para> /// <para> /// The name can be dotted, which chains references. If any link in the chain returns /// null, the entire chain is considered to return null. /// </para> /// </remarks> /// <example>"DateOfBirth"</example> /// <example>"Owner.HomeAddress.Postcode"</example> public string AspectName { get { return aspectName; } set { aspectName = value; // Clear any cache aspectParts = null; } } private string aspectName; #endregion #region Public interface /// <summary> /// Extract the value indicated by our AspectName from the given target. /// </summary> /// <remarks>If the aspect name is null or empty, this will return null.</remarks> /// <param name="target">The object that will be peeked</param> /// <returns>The value read from the target</returns> public Object GetValue(Object target) { if (this.Parts.Count == 0) return null; try { return this.EvaluateParts(target, this.Parts); } catch (MungerException ex) { return String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", ex.Munger.AspectName, ex.Target.GetType()); } } /// <summary> /// Poke the given value into the given target indicated by our AspectName. /// </summary> /// <remarks> /// <para> /// If the AspectName is a dotted path, all the selectors bar the last /// are used to find the object that should be updated, and the last /// selector is used as the property to update on that object. /// </para> /// <para> /// So, if 'target' is a Person and the AspectName is "HomeAddress.Postcode", /// this method will first fetch "HomeAddress" property, and then try to set the /// "Postcode" property on the home address object. /// </para> /// </remarks> /// <param name="target">The object that will be poked</param> /// <param name="value">The value that will be poked into the target</param> /// <returns>bool indicating whether the put worked</returns> public bool PutValue(Object target, Object value) { if (this.Parts.Count == 0) return false; SimpleMunger lastPart = this.Parts[this.Parts.Count - 1]; if (this.Parts.Count > 1) { List<SimpleMunger> parts = new List<SimpleMunger>(this.Parts); parts.RemoveAt(parts.Count - 1); try { target = this.EvaluateParts(target, parts); } catch (MungerException ex) { this.ReportPutValueException(ex); return false; } } if (target != null) { try { return lastPart.PutValue(target, value); } catch (MungerException ex) { this.ReportPutValueException(ex); } } return false; } #endregion #region Implementation /// <summary> /// Gets the list of SimpleMungers that match our AspectName /// </summary> private IList<SimpleMunger> Parts { get { if (aspectParts == null) aspectParts = BuildParts(this.AspectName); return aspectParts; } } private IList<SimpleMunger> aspectParts; /// <summary> /// Convert a possibly dotted AspectName into a list of SimpleMungers /// </summary> /// <param name="aspect"></param> /// <returns></returns> private IList<SimpleMunger> BuildParts(string aspect) { List<SimpleMunger> parts = new List<SimpleMunger>(); if (!String.IsNullOrEmpty(aspect)) { foreach (string part in aspect.Split('.')) { parts.Add(new SimpleMunger(part.Trim())); } } return parts; } /// <summary> /// Evaluate the given chain of SimpleMungers against an initial target. /// </summary> /// <param name="target"></param> /// <param name="parts"></param> /// <returns></returns> private object EvaluateParts(object target, IList<SimpleMunger> parts) { foreach (SimpleMunger part in parts) { if (target == null) break; target = part.GetValue(target); } return target; } private void ReportPutValueException(MungerException ex) { //TODO: How should we report this error? System.Diagnostics.Debug.WriteLine("PutValue failed"); System.Diagnostics.Debug.WriteLine(String.Format("- Culprit aspect: {0}", ex.Munger.AspectName)); System.Diagnostics.Debug.WriteLine(String.Format("- Target: {0} of type {1}", ex.Target, ex.Target.GetType())); System.Diagnostics.Debug.WriteLine(String.Format("- Inner exception: {0}", ex.InnerException)); } #endregion } /// <summary> /// A SimpleMunger deals with a single property/field/method on its target. /// </summary> /// <remarks> /// Munger uses a chain of these resolve a dotted aspect name. /// </remarks> public class SimpleMunger { #region Life and death /// <summary> /// Create a SimpleMunger /// </summary> /// <param name="aspectName"></param> public SimpleMunger(String aspectName) { this.aspectName = aspectName; } #endregion #region Public properties /// <summary> /// The name of the aspect that is to be peeked or poked. /// </summary> /// <remarks> /// <para> /// This name can be a field, property or method. /// When using a method to get a value, the method must be parameter-less. /// When using a method to set a value, the method must accept 1 parameter. /// </para> /// <para> /// It cannot be a dotted name. /// </para> /// </remarks> public string AspectName { get { return aspectName; } } private string aspectName; #endregion #region Public interface /// <summary> /// Get a value from the given target /// </summary> /// <param name="target"></param> /// <returns></returns> public Object GetValue(Object target) { if (target == null) return null; this.ResolveName(target, this.AspectName, 0); try { if (this.resolvedPropertyInfo != null) return this.resolvedPropertyInfo.GetValue(target, null); if (this.resolvedMethodInfo != null) return this.resolvedMethodInfo.Invoke(target, null); if (this.resolvedFieldInfo != null) return this.resolvedFieldInfo.GetValue(target); // If that didn't work, try to use the indexer property. // This covers things like arrays, dictionaries and DataRows if (this.indexerPropertyInfo != null) return this.indexerPropertyInfo.GetValue(target, new object[] { this.AspectName }); } catch (Exception ex) { // Lots of things can do wrong in these invocations throw new MungerException(this, target, ex); } // If we get to here, we couldn't find a match for the aspect throw new MungerException(this, target, new MissingMethodException()); } /// <summary> /// Poke the given value into the given target indicated by our AspectName. /// </summary> /// <param name="target">The object that will be poked</param> /// <param name="value">The value that will be poked into the target</param> /// <returns>bool indicating if the put worked</returns> public bool PutValue(object target, object value) { if (target == null) return false; this.ResolveName(target, this.AspectName, 1); try { if (this.resolvedPropertyInfo != null) { this.resolvedPropertyInfo.SetValue(target, value, null); return true; } if (this.resolvedMethodInfo != null) { this.resolvedMethodInfo.Invoke(target, new object[] { value }); return true; } if (this.resolvedFieldInfo != null) { this.resolvedFieldInfo.SetValue(target, value); return true; } // If that didn't work, try to use the indexer property. // This covers things like arrays, dictionaries and DataRows if (this.indexerPropertyInfo != null) { this.indexerPropertyInfo.SetValue(target, value, new object[] { this.AspectName }); return true; } } catch (Exception ex) { // Lots of things can do wrong in these invocations throw new MungerException(this, target, ex); } return false; } #endregion #region Implementation private void ResolveName(object target, string name, int numberMethodParameters) { if (cachedTargetType == target.GetType() && cachedName == name) return; cachedTargetType = target.GetType(); cachedName = name; resolvedFieldInfo = null; resolvedPropertyInfo = null; resolvedMethodInfo = null; indexerPropertyInfo = null; const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance /*| BindingFlags.NonPublic*/; foreach (PropertyInfo pinfo in target.GetType().GetProperties(flags)) { if (pinfo.Name == name) { resolvedPropertyInfo = pinfo; return; } // See if we can find an indexer property while we are here if (indexerPropertyInfo == null && pinfo.Name == "Item") indexerPropertyInfo = pinfo; } foreach (FieldInfo info in target.GetType().GetFields(flags)) { if (info.Name == name) { resolvedFieldInfo = info; return; } } foreach (MethodInfo info in target.GetType().GetMethods(flags)) { if (info.Name == name && info.GetParameters().Length == numberMethodParameters) { resolvedMethodInfo = info; return; } } } private Type cachedTargetType; private string cachedName; private FieldInfo resolvedFieldInfo; private PropertyInfo resolvedPropertyInfo; private MethodInfo resolvedMethodInfo; private PropertyInfo indexerPropertyInfo; #endregion } /// <summary> /// These exceptions are raised when a munger finds something it cannot process /// </summary> public class MungerException : ApplicationException { /// <summary> /// Create a MungerException /// </summary> /// <param name="munger"></param> /// <param name="target"></param> /// <param name="ex"></param> public MungerException(SimpleMunger munger, object target, Exception ex) : base("Munger failed", ex) { this.munger = munger; this.target = target; } /// <summary> /// Get the munger that raised the exception /// </summary> public SimpleMunger Munger { get { return munger; } } private SimpleMunger munger; /// <summary> /// Gets the target that threw the exception /// </summary> public object Target { get { return target; } } private object target; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace AzureVmFarmer.Service.Areas.HelpPage.SampleGeneration { /// <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); } } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System { public sealed partial class DBNull { internal DBNull() { } public static readonly System.DBNull Value; public override string ToString() { return default(string); } public string ToString(System.IFormatProvider provider) { return default(string); } } } namespace System.Data { [System.FlagsAttribute] public enum CommandBehavior { CloseConnection = 32, Default = 0, KeyInfo = 4, SchemaOnly = 2, SequentialAccess = 16, SingleResult = 1, SingleRow = 8, } public enum CommandType { StoredProcedure = 4, TableDirect = 512, Text = 1, } [System.FlagsAttribute] public enum ConnectionState { Broken = 16, Closed = 0, Connecting = 2, Executing = 4, Fetching = 8, Open = 1, } public enum DbType { AnsiString = 0, AnsiStringFixedLength = 22, Binary = 1, Boolean = 3, Byte = 2, Currency = 4, Date = 5, DateTime = 6, DateTime2 = 26, DateTimeOffset = 27, Decimal = 7, Double = 8, Guid = 9, Int16 = 10, Int32 = 11, Int64 = 12, Object = 13, SByte = 14, Single = 15, String = 16, StringFixedLength = 23, Time = 17, UInt16 = 18, UInt32 = 19, UInt64 = 20, VarNumeric = 21, Xml = 25, } public enum IsolationLevel { Chaos = 16, ReadCommitted = 4096, ReadUncommitted = 256, RepeatableRead = 65536, Serializable = 1048576, Snapshot = 16777216, Unspecified = -1, } public enum ParameterDirection { Input = 1, InputOutput = 3, Output = 2, ReturnValue = 6, } public sealed partial class StateChangeEventArgs : System.EventArgs { public StateChangeEventArgs(System.Data.ConnectionState originalState, System.Data.ConnectionState currentState) { } public System.Data.ConnectionState CurrentState { get { return default(System.Data.ConnectionState); } } public System.Data.ConnectionState OriginalState { get { return default(System.Data.ConnectionState); } } } public delegate void StateChangeEventHandler(object sender, System.Data.StateChangeEventArgs e); public enum UpdateRowSource { Both = 3, FirstReturnedRecord = 2, None = 0, OutputParameters = 1, } } namespace System.Data.Common { public abstract partial class DbCommand : System.IDisposable { protected DbCommand() { } public abstract string CommandText { get; set; } public abstract int CommandTimeout { get; set; } public abstract System.Data.CommandType CommandType { get; set; } public System.Data.Common.DbConnection Connection { get { return default(System.Data.Common.DbConnection); } set { } } protected abstract System.Data.Common.DbConnection DbConnection { get; set; } protected abstract System.Data.Common.DbParameterCollection DbParameterCollection { get; } protected abstract System.Data.Common.DbTransaction DbTransaction { get; set; } public abstract bool DesignTimeVisible { get; set; } public System.Data.Common.DbParameterCollection Parameters { get { return default(System.Data.Common.DbParameterCollection); } } public System.Data.Common.DbTransaction Transaction { get { return default(System.Data.Common.DbTransaction); } set { } } public abstract System.Data.UpdateRowSource UpdatedRowSource { get; set; } public abstract void Cancel(); protected abstract System.Data.Common.DbParameter CreateDbParameter(); public System.Data.Common.DbParameter CreateParameter() { return default(System.Data.Common.DbParameter); } protected abstract System.Data.Common.DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior behavior); protected virtual System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteDbDataReaderAsync(System.Data.CommandBehavior behavior, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); } public abstract int ExecuteNonQuery(); public System.Threading.Tasks.Task<int> ExecuteNonQueryAsync() { return default(System.Threading.Tasks.Task<int>); } public virtual System.Threading.Tasks.Task<int> ExecuteNonQueryAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); } public System.Data.Common.DbDataReader ExecuteReader() { return default(System.Data.Common.DbDataReader); } public System.Data.Common.DbDataReader ExecuteReader(System.Data.CommandBehavior behavior) { return default(System.Data.Common.DbDataReader); } public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync() { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); } public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync(System.Data.CommandBehavior behavior) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); } public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync(System.Data.CommandBehavior behavior, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); } public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); } public abstract object ExecuteScalar(); public System.Threading.Tasks.Task<object> ExecuteScalarAsync() { return default(System.Threading.Tasks.Task<object>); } public virtual System.Threading.Tasks.Task<object> ExecuteScalarAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<object>); } public abstract void Prepare(); } public abstract partial class DbConnection : System.IDisposable { protected DbConnection() { } public abstract string ConnectionString { get; set; } public virtual int ConnectionTimeout { get { return default(int); } } public abstract string Database { get; } public abstract string DataSource { get; } public abstract string ServerVersion { get; } public abstract System.Data.ConnectionState State { get; } public virtual event System.Data.StateChangeEventHandler StateChange { add { } remove { } } protected abstract System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel); public System.Data.Common.DbTransaction BeginTransaction() { return default(System.Data.Common.DbTransaction); } public System.Data.Common.DbTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel) { return default(System.Data.Common.DbTransaction); } public abstract void ChangeDatabase(string databaseName); public abstract void Close(); public System.Data.Common.DbCommand CreateCommand() { return default(System.Data.Common.DbCommand); } protected abstract System.Data.Common.DbCommand CreateDbCommand(); protected virtual void OnStateChange(System.Data.StateChangeEventArgs stateChange) { } public abstract void Open(); public System.Threading.Tasks.Task OpenAsync() { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task OpenAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } } public partial class DbConnectionStringBuilder : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public DbConnectionStringBuilder() { } public string ConnectionString { get { return default(string); } set { } } public virtual int Count { get { return default(int); } } public virtual object this[string keyword] { get { return default(object); } set { } } public virtual 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.IsReadOnly { get { return default(bool); } } object System.Collections.IDictionary.this[object keyword] { get { return default(object); } set { } } public virtual System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } public void Add(string keyword, object value) { } public static void AppendKeyValuePair(System.Text.StringBuilder builder, string keyword, string value) { } public virtual void Clear() { } public virtual bool ContainsKey(string keyword) { return default(bool); } public virtual bool EquivalentTo(System.Data.Common.DbConnectionStringBuilder connectionStringBuilder) { return default(bool); } public virtual bool Remove(string keyword) { return default(bool); } public virtual bool ShouldSerialize(string keyword) { return default(bool); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object keyword, object value) { } bool System.Collections.IDictionary.Contains(object keyword) { return default(bool); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } void System.Collections.IDictionary.Remove(object keyword) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public override string ToString() { return default(string); } public virtual bool TryGetValue(string keyword, out object value) { value = default(object); return default(bool); } } public abstract partial class DbDataReader : System.Collections.IEnumerable, System.IDisposable { protected DbDataReader() { } public abstract int Depth { get; } public abstract int FieldCount { get; } public abstract bool HasRows { get; } public abstract bool IsClosed { get; } public abstract object this[int ordinal] { get; } public abstract object this[string name] { get; } public abstract int RecordsAffected { get; } public virtual int VisibleFieldCount { get { return default(int); } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract bool GetBoolean(int ordinal); public abstract byte GetByte(int ordinal); public abstract long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length); public abstract char GetChar(int ordinal); public abstract long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length); public System.Data.Common.DbDataReader GetData(int ordinal) { return default(System.Data.Common.DbDataReader); } public abstract string GetDataTypeName(int ordinal); public abstract System.DateTime GetDateTime(int ordinal); protected virtual System.Data.Common.DbDataReader GetDbDataReader(int ordinal) { return default(System.Data.Common.DbDataReader); } public abstract decimal GetDecimal(int ordinal); public abstract double GetDouble(int ordinal); public abstract System.Collections.IEnumerator GetEnumerator(); public abstract System.Type GetFieldType(int ordinal); public virtual T GetFieldValue<T>(int ordinal) { return default(T); } public System.Threading.Tasks.Task<T> GetFieldValueAsync<T>(int ordinal) { return default(System.Threading.Tasks.Task<T>); } public virtual System.Threading.Tasks.Task<T> GetFieldValueAsync<T>(int ordinal, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<T>); } public abstract float GetFloat(int ordinal); public abstract System.Guid GetGuid(int ordinal); public abstract short GetInt16(int ordinal); public abstract int GetInt32(int ordinal); public abstract long GetInt64(int ordinal); public abstract string GetName(int ordinal); public abstract int GetOrdinal(string name); public virtual System.Type GetProviderSpecificFieldType(int ordinal) { return default(System.Type); } public virtual object GetProviderSpecificValue(int ordinal) { return default(object); } public virtual int GetProviderSpecificValues(object[] values) { return default(int); } public virtual System.IO.Stream GetStream(int ordinal) { return default(System.IO.Stream); } public abstract string GetString(int ordinal); public virtual System.IO.TextReader GetTextReader(int ordinal) { return default(System.IO.TextReader); } public abstract object GetValue(int ordinal); public abstract int GetValues(object[] values); public abstract bool IsDBNull(int ordinal); public System.Threading.Tasks.Task<bool> IsDBNullAsync(int ordinal) { return default(System.Threading.Tasks.Task<bool>); } public virtual System.Threading.Tasks.Task<bool> IsDBNullAsync(int ordinal, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<bool>); } public abstract bool NextResult(); public System.Threading.Tasks.Task<bool> NextResultAsync() { return default(System.Threading.Tasks.Task<bool>); } public virtual System.Threading.Tasks.Task<bool> NextResultAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<bool>); } public abstract bool Read(); public System.Threading.Tasks.Task<bool> ReadAsync() { return default(System.Threading.Tasks.Task<bool>); } public virtual System.Threading.Tasks.Task<bool> ReadAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<bool>); } } public abstract partial class DbException : System.Exception { protected DbException() { } protected DbException(string message) { } protected DbException(string message, System.Exception innerException) { } } public abstract partial class DbParameter { protected DbParameter() { } public abstract System.Data.DbType DbType { get; set; } public abstract System.Data.ParameterDirection Direction { get; set; } public abstract bool IsNullable { get; set; } public abstract string ParameterName { get; set; } public virtual byte Precision { get { return default(byte); } set { } } public virtual byte Scale { get { return default(byte); } set { } } public abstract int Size { get; set; } public abstract string SourceColumn { get; set; } public abstract bool SourceColumnNullMapping { get; set; } public abstract object Value { get; set; } public abstract void ResetDbType(); } public abstract partial class DbParameterCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { protected DbParameterCollection() { } public abstract int Count { get; } public System.Data.Common.DbParameter this[int index] { get { return default(System.Data.Common.DbParameter); } set { } } public System.Data.Common.DbParameter this[string parameterName] { get { return default(System.Data.Common.DbParameter); } set { } } public abstract object SyncRoot { get; } object System.Collections.IList.this[int index] { get { return default(object); } set { } } public abstract int Add(object value); public abstract void AddRange(System.Array values); public abstract void Clear(); public abstract bool Contains(object value); public abstract bool Contains(string value); public abstract void CopyTo(System.Array array, int index); public abstract System.Collections.IEnumerator GetEnumerator(); protected abstract System.Data.Common.DbParameter GetParameter(int index); protected abstract System.Data.Common.DbParameter GetParameter(string parameterName); public abstract int IndexOf(object value); public abstract int IndexOf(string parameterName); public abstract void Insert(int index, object value); public abstract void Remove(object value); public abstract void RemoveAt(int index); public abstract void RemoveAt(string parameterName); protected abstract void SetParameter(int index, System.Data.Common.DbParameter value); protected abstract void SetParameter(string parameterName, System.Data.Common.DbParameter value); } public abstract partial class DbProviderFactory { protected DbProviderFactory() { } public virtual System.Data.Common.DbCommand CreateCommand() { return default(System.Data.Common.DbCommand); } public virtual System.Data.Common.DbConnection CreateConnection() { return default(System.Data.Common.DbConnection); } public virtual System.Data.Common.DbConnectionStringBuilder CreateConnectionStringBuilder() { return default(System.Data.Common.DbConnectionStringBuilder); } public virtual System.Data.Common.DbParameter CreateParameter() { return default(System.Data.Common.DbParameter); } } public abstract partial class DbTransaction : System.IDisposable { protected DbTransaction() { } public System.Data.Common.DbConnection Connection { get { return default(System.Data.Common.DbConnection); } } protected abstract System.Data.Common.DbConnection DbConnection { get; } public abstract System.Data.IsolationLevel IsolationLevel { get; } public abstract void Commit(); public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract void Rollback(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Reflection; using System.Collections.Generic; #pragma warning disable 0414 #pragma warning disable 0067 namespace System.Reflection.Tests { [System.Runtime.InteropServices.Guid("FD80F123-BEDD-4492-B50A-5D46AE94DD4E")] public class TypeInfoPropertyTests { // Verify BaseType() method [Fact] public static void TestBaseType1() { Type t = typeof(TypeInfoPropertyDerived).Project(); TypeInfo ti = t.GetTypeInfo(); Type basetype = ti.BaseType; Assert.Equal(basetype, typeof(TypeInfoPropertyBase).Project()); } // Verify BaseType() method [Fact] public static void TestBaseType2() { Type t = typeof(TypeInfoPropertyBase).Project(); TypeInfo ti = t.GetTypeInfo(); Type basetype = ti.BaseType; Assert.Equal(basetype, typeof(object).Project()); } // Verify ContainsGenericParameter [Fact] public static void TestContainsGenericParameter1() { Type t = typeof(ClassWithConstraints<,>).Project(); TypeInfo ti = t.GetTypeInfo(); bool hasgenericParam = ti.ContainsGenericParameters; Assert.True(hasgenericParam, string.Format("Failed!! TestContainsGenericParameter did not return correct result. ")); } // Verify ContainsGenericParameter [Fact] public static void TestContainsGenericParameter2() { Type t = typeof(TypeInfoPropertyBase).Project(); TypeInfo ti = t.GetTypeInfo(); bool hasgenericParam = ti.ContainsGenericParameters; Assert.False(hasgenericParam, string.Format("Failed!! TestContainsGenericParameter did not return correct result. ")); } // Verify FullName [Fact] public static void TestFullName() { Type t = typeof(int).Project(); TypeInfo ti = t.GetTypeInfo(); string fname = ti.FullName; Assert.Equal(fname, "System.Int32"); } // Verify Guid [Fact] public static void TestGuid() { Type t = typeof(TypeInfoPropertyTests).Project(); TypeInfo ti = t.GetTypeInfo(); Guid myguid = ti.GUID; Assert.NotNull(myguid); } // Verify HasElementType [Fact] public static void TestHasElementType() { Type t = typeof(int).Project(); TypeInfo ti = t.GetTypeInfo(); Assert.False(ti.HasElementType, "Failed!! .HasElementType returned true for a type that does not contain element "); int[] nums = { 1, 1, 2, 3 }; Type te = nums.GetType(); TypeInfo tei = te.GetTypeInfo(); Assert.True(tei.HasElementType, "Failed!! .HasElementType returned false for a type that contains element "); } //Verify IsAbstract [Fact] public static void TestIsAbstract() { Assert.True(typeof(abstractClass).Project().GetTypeInfo().IsAbstract, "Failed!! .IsAbstract returned false for a type that is abstract."); Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsAbstract, "Failed!! .IsAbstract returned true for a type that is not abstract."); } //Verify IsAnsiClass [Fact] public static void TestIsAnsiClass() { string mystr = "A simple string"; Type t = mystr.GetType(); TypeInfo ti = t.GetTypeInfo(); Assert.True(ti.IsAnsiClass, "Failed!! .IsAnsiClass returned false."); } //Verify IsAray [Fact] public static void TestIsArray() { int[] myarray = { 1, 2, 3 }; Type arraytype = myarray.GetType(); Assert.True(arraytype.GetTypeInfo().IsArray, "Failed!! .IsArray returned false for a type that is array."); Assert.False(typeof(int).Project().GetTypeInfo().IsArray, "Failed!! .IsArray returned true for a type that is not an array."); } // VerifyIsByRef [Fact] public static void TestIsByRefType() { TypeInfo ti = typeof(int).Project().GetTypeInfo(); Type byreftype = ti.MakeByRefType(); Assert.NotNull(byreftype); Assert.True(byreftype.IsByRef, "Failed!! IsByRefType() returned false"); Assert.False(typeof(int).Project().GetTypeInfo().IsByRef, "Failed!! IsByRefType() returned true"); } // VerifyIsClass [Fact] public static void TestIsClass() { Assert.True(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsClass, "Failed!! IsClass returned false for a class Type"); Assert.False(typeof(MYENUM).Project().GetTypeInfo().IsClass, "Failed!! IsClass returned true for a non-class Type"); } // VerifyIsEnum [Fact] public static void TestIsEnum() { Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsEnum, "Failed!! IsEnum returned true for a class Type"); Assert.True(typeof(MYENUM).Project().GetTypeInfo().IsEnum, "Failed!! IsEnum returned false for a Enum Type"); } // VerifyIsInterface [Fact] public static void TestIsInterface() { Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsInterface, "Failed!! IsInterface returned true for a class Type"); Assert.True(typeof(ITest).Project().GetTypeInfo().IsInterface, "Failed!! IsInterface returned false for a interface Type"); } // VerifyIsNested [Fact] public static void TestIsNested() { Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsNested, "Failed!! IsNested returned true for a non nested class Type"); Assert.True(typeof(PublicClass.PublicNestedType).Project().GetTypeInfo().IsNested, "Failed!! IsNested returned false for a nested class Type"); } // Verify IsPointer [Fact] public static void TestIsPointer() { TypeInfo ti = typeof(int).Project().GetTypeInfo(); Type ptrtype = ti.MakePointerType(); Assert.NotNull(ptrtype); Assert.True(ptrtype.IsPointer, "Failed!! IsPointer returned false for pointer type"); Assert.False(typeof(int).Project().GetTypeInfo().IsPointer, "Failed!! IsPointer returned true for non -pointer type"); } // VerifyIsPrimitive [Fact] public static void TestIsPrimitive() { Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsPrimitive, "Failed!! IsPrimitive returned true for a non primitive Type"); Assert.True(typeof(int).Project().GetTypeInfo().IsPrimitive, "Failed!! IsPrimitive returned true for a primitive Type"); Assert.True(typeof(char).Project().GetTypeInfo().IsPrimitive, "Failed!! IsPrimitive returned true for a primitive Type"); } // VerifyIsPublic [Fact] public static void TestIsPublic() { Assert.True(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); Assert.True(typeof(TypeInfoPropertyDerived).Project().GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); Assert.True(typeof(PublicClass).Project().GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); Assert.True(typeof(ITest).Project().GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); Assert.True(typeof(ImplClass).Project().GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); } // VerifyIsNotPublic [Fact] public static void TestIsNotPublic() { Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); Assert.False(typeof(TypeInfoPropertyDerived).Project().GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); Assert.False(typeof(PublicClass).Project().GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); Assert.False(typeof(ITest).Project().GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); Assert.False(typeof(ImplClass).Project().GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); } // VerifyIsNestedPublic [Fact] public static void TestIsNestedPublic() { Assert.True(typeof(PublicClass.publicNestedClass).Project().GetTypeInfo().IsNestedPublic, "Failed!! IsNestedPublic returned false for a nested public Type"); } // VerifyIsNestedPrivate [Fact] public static void TestIsNestedPrivate() { Assert.False(typeof(PublicClass.publicNestedClass).Project().GetTypeInfo().IsNestedPrivate, "Failed!! IsNestedPrivate returned true for a nested public Type"); } // Verify IsSealed [Fact] public static void TestIsSealed() { Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsSealed, "Failed!! IsSealed returned true for a Type that is not sealed"); Assert.True(typeof(sealedClass).Project().GetTypeInfo().IsSealed, "Failed!! IsSealed returned false for a Type that is sealed"); } // Verify IsSerializable [Fact] public static void TestIsSerializable() { Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsSerializable, "Failed!! IsSerializable returned true for a Type that is not serializable"); } // VerifyIsValueType [Fact] public static void TestIsValueType() { Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsValueType, "Failed!! IsValueType returned true for a class Type"); Assert.True(typeof(MYENUM).Project().GetTypeInfo().IsValueType, "Failed!! IsValueType returned false for a Enum Type"); } // VerifyIsValueType [Fact] public static void TestIsVisible() { Assert.True(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); Assert.True(typeof(ITest).Project().GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); Assert.True(typeof(MYENUM).Project().GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); Assert.True(typeof(PublicClass).Project().GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); Assert.True(typeof(PublicClass.publicNestedClass).Project().GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); } // Verify Namespace property [Fact] public static void TestNamespace() { Assert.Equal(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(ITest).Project().GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(MYENUM).Project().GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(PublicClass).Project().GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(PublicClass.publicNestedClass).Project().GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(int).Project().GetTypeInfo().Namespace, "System"); } // VerifyIsImport [Fact] public static void TestIsImport() { Assert.False(typeof(TypeInfoPropertyBase).Project().GetTypeInfo().IsImport, "Failed!! IsImport returned true for a class Type that is not imported."); Assert.False(typeof(MYENUM).Project().GetTypeInfo().IsImport, "Failed!! IsImport returned true for a non-class Type that is not imported."); } // VerifyIsUnicodeClass [Fact] public static void TestIsUnicodeClass() { string str = "mystring"; Type type = str.GetType(); Type ref_type = type.MakeByRefType(); Assert.False(type.GetTypeInfo().IsUnicodeClass, "Failed!! IsUnicodeClass returned true for string."); Assert.False(ref_type.GetTypeInfo().IsUnicodeClass, "Failed!! IsUnicodeClass returned true for string."); } // Verify IsAutoClass [Fact] public static void TestIsAutoClass() { string str = "mystring"; Type type = str.GetType(); Type ref_type = type.MakeByRefType(); Assert.False(type.GetTypeInfo().IsAutoClass, "Failed!! IsAutoClass returned true for string."); Assert.False(ref_type.GetTypeInfo().IsAutoClass, "Failed!! IsAutoClass returned true for string."); } [Fact] public static void TestIsMarshalByRef() { string str = "mystring"; Type type = str.GetType(); Type ptr_type = type.MakePointerType(); Type ref_type = type.MakeByRefType(); Assert.False(type.GetTypeInfo().IsMarshalByRef, "Failed!! IsMarshalByRef returned true."); Assert.False(ptr_type.GetTypeInfo().IsMarshalByRef, "Failed!! IsMarshalByRef returned true."); Assert.False(ref_type.GetTypeInfo().IsMarshalByRef, "Failed!! IsMarshalByRef returned true."); } // VerifyIsNestedAssembly [Fact] public static void TestIsNestedAssembly() { Assert.False(typeof(PublicClass).Project().GetTypeInfo().IsNestedAssembly, "Failed!! IsNestedAssembly returned true for a class with public visibility."); } // VerifyIsNestedFamily [Fact] public static void TestIsNestedFamily() { Assert.False(typeof(PublicClass).Project().GetTypeInfo().IsNestedFamily, "Failed!! IsNestedFamily returned true for a class with private visibility."); } // VerifyIsNestedFamANDAssem [Fact] public static void TestIsNestedFamAndAssem() { Assert.False(typeof(PublicClass).Project().GetTypeInfo().IsNestedFamANDAssem, "Failed!! IsNestedFamAndAssem returned true for a class with private visibility."); } // VerifyIsNestedFamOrAssem [Fact] public static void TestIsNestedFamOrAssem() { Assert.False(typeof(PublicClass).Project().GetTypeInfo().IsNestedFamORAssem, "Failed!! IsNestedFamOrAssem returned true for a class with private visibility."); } } //Metadata for Reflection public class PublicClass { public int PublicField; public static int PublicStaticField; public PublicClass() { } public void PublicMethod() { } public void overRiddenMethod() { } public void overRiddenMethod(int i) { } public void overRiddenMethod(string s) { } public void overRiddenMethod(object o) { } public static void PublicStaticMethod() { } public class PublicNestedType { } public int PublicProperty { get { return default(int); } set { } } public class publicNestedClass { } } public sealed class sealedClass { } public abstract class abstractClass { } public interface ITest { } public class TypeInfoPropertyBase { } public class TypeInfoPropertyDerived : TypeInfoPropertyBase { } public class ImplClass : ITest { } public class TypeInfoPropertyGenericClass<T> { } public class ClassWithConstraints<T, U> where T : TypeInfoPropertyBase, ITest where U : class, new() { } public enum MYENUM { one = 1, Two = 2 } }
// 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.Concurrent; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Elfie.Model; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.VisualStudio.RemoteControl; using Roslyn.Utilities; using static System.FormattableString; namespace Microsoft.CodeAnalysis.SymbolSearch { /// <summary> /// A service which enables searching for packages matching certain criteria. /// It works against a <see cref="Microsoft.CodeAnalysis.Elfie"/> database to find results. /// /// This implementation also spawns a task which will attempt to keep that database up to /// date by downloading patches on a daily basis. /// </summary> internal partial class SymbolSearchUpdateEngine { // Internal for testing purposes. internal const string ContentAttributeName = "content"; internal const string ChecksumAttributeName = "checksum"; internal const string UpToDateAttributeName = "upToDate"; internal const string TooOldAttributeName = "tooOld"; internal const string NugetOrgSource = "nuget.org"; public const string HostId = "RoslynNuGetSearch"; private const string MicrosoftAssemblyReferencesName = "MicrosoftAssemblyReferences"; /// <summary> /// Cancellation support for the task we use to keep the local database up to date. /// When VS shuts down it will dispose us. We'll cancel the task at that point. /// </summary> private readonly CancellationToken _updateCancellationToken; private readonly ConcurrentDictionary<string, object> _sourceToUpdateSentinel = new ConcurrentDictionary<string, object>(); // Interfaces that abstract out the external functionality we need. Used so we can easily // mock behavior during tests. private readonly IDelayService _delayService; private readonly IIOService _ioService; private readonly ISymbolSearchLogService _logService; private readonly ISymbolSearchProgressService _progressService; private readonly IRemoteControlService _remoteControlService; private readonly IPatchService _patchService; private readonly IDatabaseFactoryService _databaseFactoryService; private readonly Func<Exception, bool> _reportAndSwallowException; private Task LogInfoAsync(string text) => _logService.LogInfoAsync(text); private Task LogExceptionAsync(Exception e, string text) => _logService.LogExceptionAsync(e.ToString(), text); public Task UpdateContinuouslyAsync(string source, string localSettingsDirectory) { // Only the first thread to try to update this source should succeed // and cause us to actually begin the update loop. var ourSentinel = new object(); var currentSentinel = _sourceToUpdateSentinel.GetOrAdd(source, ourSentinel); if (ourSentinel != currentSentinel) { // We already have an update loop for this source. Nothing for us to do. return Task.CompletedTask; } // We were the first ones to try to update this source. Spawn off a task to do // the updating. return new Updater(this, source, localSettingsDirectory).UpdateInBackgroundAsync(); } private class Updater { private readonly SymbolSearchUpdateEngine _service; private readonly string _source; private readonly DirectoryInfo _cacheDirectoryInfo; private readonly FileInfo _databaseFileInfo; public Updater(SymbolSearchUpdateEngine service, string source, string localSettingsDirectory) { _service = service; _source = source; _cacheDirectoryInfo = new DirectoryInfo(Path.Combine( localSettingsDirectory, "PackageCache", string.Format(Invariant($"Format{AddReferenceDatabase.TextFileFormatVersion}")))); _databaseFileInfo = new FileInfo( Path.Combine(_cacheDirectoryInfo.FullName, ConvertToFileName(source) + ".txt")); } /// <summary> /// Internal for testing purposes. /// </summary> internal async Task UpdateInBackgroundAsync() { // We only support this single source currently. if (_source != NugetOrgSource) { return; } // Keep on looping until we're told to shut down. while (!_service._updateCancellationToken.IsCancellationRequested) { await _service.LogInfoAsync("Starting update").ConfigureAwait(false); try { var delayUntilNextUpdate = await UpdateDatabaseInBackgroundWorkerAsync().ConfigureAwait(false); await _service.LogInfoAsync($"Waiting {delayUntilNextUpdate} until next update").ConfigureAwait(false); await Task.Delay(delayUntilNextUpdate, _service._updateCancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { await _service.LogInfoAsync("Update canceled. Ending update loop").ConfigureAwait(false); return; } } } private string ConvertToFileName(string source) { // Replace all occurrences of a single underscore with a double underscore. // Now we know any single underscores in the text come from escaping some // character. source = source.Replace("_", "__"); var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars()); var builder = new StringBuilder(); // Escape any character not allowed in a path. Escaping is simple, we just // use a single underscore followed by the ASCII numeric value of the character, // followed by another underscore. // i.e. ":" is 58 is ASCII, and becomes _58_ in the final name. foreach (var c in source) { if (invalidChars.Contains(c)) { builder.Append("_" + (int)c + "_"); } else { builder.Append(c); } } return builder.ToString(); } /// <returns>The timespan the caller should wait until calling this method again.</returns> private async Task<TimeSpan> UpdateDatabaseInBackgroundWorkerAsync() { // Attempt to update the local db if we have one, or download a full db // if we don't. In the event of any error back off a minute and try // again. Lot of errors are possible here as IO/network/other-libraries // are involved. For example, we might get errors trying to write to // disk. try { await CleanCacheDirectoryAsync().ConfigureAwait(false); // If we have a local database, then see if it needs to be patched. // Otherwise download the full database. // // (intentionally not wrapped in IOUtilities. If this throws we want to restart). if (_service._ioService.Exists(_databaseFileInfo)) { await _service.LogInfoAsync("Local database file exists. Patching local database").ConfigureAwait(false); return await PatchLocalDatabaseAsync().ConfigureAwait(false); } else { await _service.LogInfoAsync("Local database file does not exist. Downloading full database").ConfigureAwait(false); return await DownloadFullDatabaseAsync().ConfigureAwait(false); } } catch (OperationCanceledException) { // Just allow our caller to handle this (they will use this to stop their loop). throw; } catch (Exception e) when (_service._reportAndSwallowException(e)) { // Something bad happened (IO Exception, network exception etc.). // ask our caller to try updating again a minute from now. // // Note: we skip OperationCanceledException because it's not 'bad'. // It's the standard way to indicate that we've been asked to shut // down. var delay = _service._delayService.ExpectedFailureDelay; await _service.LogExceptionAsync(e, $"Error occurred updating. Retrying update in {delay}").ConfigureAwait(false); return delay; } } private async Task CleanCacheDirectoryAsync() { await _service.LogInfoAsync("Cleaning cache directory").ConfigureAwait(false); // (intentionally not wrapped in IOUtilities. If this throws we want to restart). if (!_service._ioService.Exists(_cacheDirectoryInfo)) { await _service.LogInfoAsync("Creating cache directory").ConfigureAwait(false); // (intentionally not wrapped in IOUtilities. If this throws we want to restart). _service._ioService.Create(_cacheDirectoryInfo); await _service.LogInfoAsync("Cache directory created").ConfigureAwait(false); } _service._updateCancellationToken.ThrowIfCancellationRequested(); } private async Task<TimeSpan> DownloadFullDatabaseAsync() { try { var title = string.Format(EditorFeaturesWpfResources.Downloading_IntelliSense_index_for_0, _source); await _service._progressService.OnDownloadFullDatabaseStartedAsync(title).ConfigureAwait(false); var (succeeded, delay) = await DownloadFullDatabaseWorkerAsync().ConfigureAwait(false); if (succeeded) { await _service._progressService.OnDownloadFullDatabaseSucceededAsync().ConfigureAwait(false); } else { await _service._progressService.OnDownloadFullDatabaseFailedAsync( EditorFeaturesWpfResources.Downloading_index_failed).ConfigureAwait(false); } return delay; } catch (OperationCanceledException) { await _service._progressService.OnDownloadFullDatabaseCanceledAsync().ConfigureAwait(false); throw; } catch (Exception e) { var message = string.Format( EditorFeaturesWpfResources.Downloading_index_failed_0, "\r\n" + e.ToString()); await _service._progressService.OnDownloadFullDatabaseFailedAsync(message).ConfigureAwait(false); throw; } } private async Task<(bool succeeded, TimeSpan delay)> DownloadFullDatabaseWorkerAsync() { var serverPath = Invariant($"Elfie_V{AddReferenceDatabase.TextFileFormatVersion}/Latest.xml"); await _service.LogInfoAsync($"Downloading and processing full database: {serverPath}").ConfigureAwait(false); var element = await DownloadFileAsync(serverPath).ConfigureAwait(false); var result = await ProcessFullDatabaseXElementAsync(element).ConfigureAwait(false); await _service.LogInfoAsync("Downloading and processing full database completed").ConfigureAwait(false); return result; } private async Task<(bool succeeded, TimeSpan delay)> ProcessFullDatabaseXElementAsync(XElement element) { await _service.LogInfoAsync("Processing full database element").ConfigureAwait(false); // Convert the database contents in the XML to a byte[]. var result = await TryParseDatabaseElementAsync(element).ConfigureAwait(false); if (!result.succeeded) { // Something was wrong with the full database. Trying again soon after won't // really help. We'll just get the same busted XML from the remote service // cache. So we want to actually wait some long enough amount of time so that // we can retrieve good data the next time around. var failureDelay = _service._delayService.CatastrophicFailureDelay; await _service.LogInfoAsync($"Unable to parse full database element. Update again in {failureDelay}").ConfigureAwait(false); return (succeeded: false, failureDelay); } var bytes = result.contentBytes; // Make a database out of that and set it to our in memory database that we'll be // searching. try { await CreateAndSetInMemoryDatabaseAsync(bytes).ConfigureAwait(false); } catch (Exception e) when (_service._reportAndSwallowException(e)) { // We retrieved bytes from the server, but we couldn't make a DB // out of it. That's very bad. Just trying again one minute later // isn't going to help. We need to wait until there is good data // on the server for us to download. var failureDelay = _service._delayService.CatastrophicFailureDelay; await _service.LogInfoAsync($"Unable to create database from full database element. Update again in {failureDelay}").ConfigureAwait(false); return (succeeded: false, failureDelay); } // Write the file out to disk so we'll have it the next time we launch VS. Do this // after we set the in-memory instance so we at least have something to search while // we're waiting to write. await WriteDatabaseFile(bytes).ConfigureAwait(false); var delay = _service._delayService.UpdateSucceededDelay; await _service.LogInfoAsync($"Processing full database element completed. Update again in {delay}").ConfigureAwait(false); return (succeeded: true, delay); } private async Task WriteDatabaseFile(byte[] bytes) { await _service.LogInfoAsync("Writing database file").ConfigureAwait(false); await RepeatIOAsync( async () => { var guidString = Guid.NewGuid().ToString(); var tempFilePath = Path.Combine(_cacheDirectoryInfo.FullName, guidString + ".tmp"); await _service.LogInfoAsync($"Temp file path: {tempFilePath}").ConfigureAwait(false); try { // First, write to a temporary file next to the actual database file. // Note that we explicitly use FileStream so that we can call .Flush to ensure the // file has been completely written to disk (at least as well as the OS can guarantee // things). await _service.LogInfoAsync("Writing temp file").ConfigureAwait(false); // (intentionally not wrapped in IOUtilities. If this throws we want to retry writing). _service._ioService.WriteAndFlushAllBytes(tempFilePath, bytes); await _service.LogInfoAsync("Writing temp file completed").ConfigureAwait(false); // If we have an existing db file, try to replace it file with the temp file. // Otherwise, just move the temp file into place. if (_service._ioService.Exists(_databaseFileInfo)) { await _service.LogInfoAsync("Replacing database file").ConfigureAwait(false); _service._ioService.Replace(tempFilePath, _databaseFileInfo.FullName, destinationBackupFileName: null, ignoreMetadataErrors: true); await _service.LogInfoAsync("Replace database file completed").ConfigureAwait(false); } else { await _service.LogInfoAsync("Moving database file").ConfigureAwait(false); _service._ioService.Move(tempFilePath, _databaseFileInfo.FullName); await _service.LogInfoAsync("Moving database file completed").ConfigureAwait(false); } } finally { // Try to delete the temp file if it is still around. // If this fails, that's unfortunately, but just proceed. IOUtilities.PerformIO(() => _service._ioService.Delete(new FileInfo(tempFilePath))); } }).ConfigureAwait(false); await _service.LogInfoAsync("Writing database file completed").ConfigureAwait(false); } private async Task<TimeSpan> PatchLocalDatabaseAsync() { await _service.LogInfoAsync("Patching local database").ConfigureAwait(false); await _service.LogInfoAsync("Reading in local database").ConfigureAwait(false); // (intentionally not wrapped in IOUtilities. If this throws we want to restart). var databaseBytes = _service._ioService.ReadAllBytes(_databaseFileInfo.FullName); await _service.LogInfoAsync($"Reading in local database completed. databaseBytes.Length={databaseBytes.Length}").ConfigureAwait(false); // Make a database instance out of those bytes and set is as the current in memory database // that searches will run against. If we can't make a database instance from these bytes // then our local database is corrupt and we need to download the full database to get back // into a good state. AddReferenceDatabase database; try { database = await CreateAndSetInMemoryDatabaseAsync(databaseBytes).ConfigureAwait(false); } catch (Exception e) when (_service._reportAndSwallowException(e)) { await _service.LogExceptionAsync(e, "Error creating database from local copy. Downloading full database").ConfigureAwait(false); return await DownloadFullDatabaseAsync().ConfigureAwait(false); } var databaseVersion = database.DatabaseVersion; // Now attempt to download and apply patch file. var serverPath = Invariant($"Elfie_V{AddReferenceDatabase.TextFileFormatVersion}/{database.DatabaseVersion}_Patch.xml"); await _service.LogInfoAsync("Downloading and processing patch file: " + serverPath).ConfigureAwait(false); var element = await DownloadFileAsync(serverPath).ConfigureAwait(false); var delayUntilUpdate = await ProcessPatchXElementAsync(element, databaseBytes).ConfigureAwait(false); await _service.LogInfoAsync("Downloading and processing patch file completed").ConfigureAwait(false); await _service.LogInfoAsync("Patching local database completed").ConfigureAwait(false); return delayUntilUpdate; } /// <summary> /// Creates a database instance with the bytes passed in. If creating the database succeeds, /// then it will be set as the current in memory version. In the case of failure (which /// indicates that our data is corrupt), the exception will bubble up and must be appropriately /// dealt with by the caller. /// </summary> private async Task<AddReferenceDatabase> CreateAndSetInMemoryDatabaseAsync(byte[] bytes) { var database = await CreateDatabaseFromBytesAsync(bytes).ConfigureAwait(false); _service._sourceToDatabase[_source] = new AddReferenceDatabaseWrapper(database); return database; } private async Task<TimeSpan> ProcessPatchXElementAsync(XElement patchElement, byte[] databaseBytes) { try { await _service.LogInfoAsync("Processing patch element").ConfigureAwait(false); var delayUntilUpdate = await TryProcessPatchXElementAsync(patchElement, databaseBytes).ConfigureAwait(false); if (delayUntilUpdate != null) { await _service.LogInfoAsync($"Processing patch element completed. Update again in {delayUntilUpdate.Value}").ConfigureAwait(false); return delayUntilUpdate.Value; } // Fall through and download full database. } catch (Exception e) when (_service._reportAndSwallowException(e)) { await _service.LogExceptionAsync(e, "Error occurred while processing patch element. Downloading full database").ConfigureAwait(false); // Fall through and download full database. } return await DownloadFullDatabaseAsync().ConfigureAwait(false); } private async Task<TimeSpan?> TryProcessPatchXElementAsync(XElement patchElement, byte[] databaseBytes) { ParsePatchElement(patchElement, out var upToDate, out var tooOld, out var patchBytes); if (upToDate) { await _service.LogInfoAsync("Local version is up to date").ConfigureAwait(false); return _service._delayService.UpdateSucceededDelay; } if (tooOld) { await _service.LogInfoAsync("Local version too old").ConfigureAwait(false); return null; } await _service.LogInfoAsync($"Got patch. databaseBytes.Length={databaseBytes.Length} patchBytes.Length={patchBytes.Length}.").ConfigureAwait(false); // We have patch data. Apply it to our current database bytes to produce the new // database. await _service.LogInfoAsync("Applying patch").ConfigureAwait(false); var finalBytes = _service._patchService.ApplyPatch(databaseBytes, patchBytes); await _service.LogInfoAsync($"Applying patch completed. finalBytes.Length={finalBytes.Length}").ConfigureAwait(false); await CreateAndSetInMemoryDatabaseAsync(finalBytes).ConfigureAwait(false); await WriteDatabaseFile(finalBytes).ConfigureAwait(false); return _service._delayService.UpdateSucceededDelay; } private void ParsePatchElement(XElement patchElement, out bool upToDate, out bool tooOld, out byte[] patchBytes) { patchBytes = null; var upToDateAttribute = patchElement.Attribute(UpToDateAttributeName); upToDate = upToDateAttribute != null && (bool)upToDateAttribute; var tooOldAttribute = patchElement.Attribute(TooOldAttributeName); tooOld = tooOldAttribute != null && (bool)tooOldAttribute; var contentsAttribute = patchElement.Attribute(ContentAttributeName); if (contentsAttribute != null) { var contents = contentsAttribute.Value; patchBytes = Convert.FromBase64String(contents); } var hasPatchBytes = patchBytes != null; var value = (upToDate ? 1 : 0) + (tooOld ? 1 : 0) + (hasPatchBytes ? 1 : 0); if (value != 1) { throw new FormatException($"Patch format invalid. {nameof(upToDate)}={upToDate} {nameof(tooOld)}={tooOld} {nameof(hasPatchBytes)}={hasPatchBytes}"); } } private async Task<AddReferenceDatabase> CreateDatabaseFromBytesAsync(byte[] bytes) { await _service.LogInfoAsync("Creating database from bytes").ConfigureAwait(false); var result = _service._databaseFactoryService.CreateDatabaseFromBytes(bytes); await _service.LogInfoAsync("Creating database from bytes completed").ConfigureAwait(false); return result; } private async Task<XElement> DownloadFileAsync(string serverPath) { await _service.LogInfoAsync("Creating download client: " + serverPath).ConfigureAwait(false); // Create a client that will attempt to download the specified file. The client works // in the following manner: // // 1) If the file is not cached locally it will download it in the background. // Until the file is downloaded, null will be returned from client.ReadFile. // 2) If the file is cached locally and was downloaded less than (24 * 60) // minutes ago, then the client will do nothing (until that time has elapsed). // Calls to client.ReadFile will return the cached file. // 3) If the file is cached locally and was downloaded more than (24 * 60) // minutes ago, then the client will attempt to download the file. // In the interim period null will be returned from client.ReadFile. var pollingMinutes = (int)TimeSpan.FromDays(1).TotalMinutes; using (var client = _service._remoteControlService.CreateClient(HostId, serverPath, pollingMinutes)) { await _service.LogInfoAsync("Creating download client completed").ConfigureAwait(false); // Poll the client every minute until we get the file. while (true) { _service._updateCancellationToken.ThrowIfCancellationRequested(); var resultOpt = await TryDownloadFileAsync(client).ConfigureAwait(false); if (resultOpt == null) { var delay = _service._delayService.CachePollDelay; await _service.LogInfoAsync($"File not downloaded. Trying again in {delay}").ConfigureAwait(false); await Task.Delay(delay, _service._updateCancellationToken).ConfigureAwait(false); } else { // File was downloaded. return resultOpt; } } } } /// <summary>Returns 'null' if download is not available and caller should keep polling.</summary> private async Task<XElement> TryDownloadFileAsync(IRemoteControlClient client) { await _service.LogInfoAsync("Read file from client").ConfigureAwait(false); // "ReturnsNull": Only return a file if we have it locally *and* it's not older than our polling time (1 day). using (var stream = await client.ReadFileAsync(BehaviorOnStale.ReturnNull).ConfigureAwait(false)) { if (stream == null) { await _service.LogInfoAsync("Read file completed. Client returned no data").ConfigureAwait(false); return null; } await _service.LogInfoAsync("Read file completed. Client returned data").ConfigureAwait(false); await _service.LogInfoAsync("Converting data to XElement").ConfigureAwait(false); // We're reading in our own XML file, but even so, use conservative settings // just to be on the safe side. First, disallow DTDs entirely (we will never // have one ourself). And also, prevent any external resolution of files when // processing the XML. var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; using (var reader = XmlReader.Create(stream, settings)) { var result = XElement.Load(reader); await _service.LogInfoAsync("Converting data to XElement completed").ConfigureAwait(false); return result; } } } private async Task RepeatIOAsync(Func<Task> action) { const int repeat = 6; for (var i = 0; i < repeat; i++) { _service._updateCancellationToken.ThrowIfCancellationRequested(); try { await action().ConfigureAwait(false); return; } catch (Exception e) when (IOUtilities.IsNormalIOException(e) || _service._reportAndSwallowException(e)) { // The exception filter above might be a little funny looking. We always // want to enter this catch block, but if we ran into a normal IO exception // we shouldn't bother reporting it. We don't want to get lots of hits just // because something like an anti-virus tool locked the file and we // couldn't write to it. The call to IsNormalIOException will shortcut // around the reporting in this case. var delay = _service._delayService.FileWriteDelay; await _service.LogExceptionAsync(e, $"Operation failed. Trying again after {delay}").ConfigureAwait(false); await Task.Delay(delay, _service._updateCancellationToken).ConfigureAwait(false); } } } private async Task<(bool succeeded, byte[] contentBytes)> TryParseDatabaseElementAsync(XElement element) { await _service.LogInfoAsync("Parsing database element").ConfigureAwait(false); var contentsAttribute = element.Attribute(ContentAttributeName); if (contentsAttribute == null) { _service._reportAndSwallowException(new FormatException($"Database element invalid. Missing '{ContentAttributeName}' attribute")); return (succeeded: false, (byte[])null); } var contentBytes = await ConvertContentAttributeAsync(contentsAttribute).ConfigureAwait(false); var checksumAttribute = element.Attribute(ChecksumAttributeName); if (checksumAttribute != null) { var expectedChecksum = checksumAttribute.Value; string actualChecksum; using (var sha256 = SHA256.Create()) { actualChecksum = Convert.ToBase64String(sha256.ComputeHash(contentBytes)); } if (!StringComparer.Ordinal.Equals(expectedChecksum, actualChecksum)) { _service._reportAndSwallowException(new FormatException($"Checksum mismatch: expected != actual. {expectedChecksum} != {actualChecksum}")); return (succeeded: false, (byte[])null); } } return (succeeded: true, contentBytes); } private async Task<byte[]> ConvertContentAttributeAsync(XAttribute contentsAttribute) { var text = contentsAttribute.Value; var compressedBytes = Convert.FromBase64String(text); using (var outStream = new MemoryStream()) { using (var inStream = new MemoryStream(compressedBytes)) using (var deflateStream = new DeflateStream(inStream, CompressionMode.Decompress)) { await deflateStream.CopyToAsync(outStream).ConfigureAwait(false); } var bytes = outStream.ToArray(); await _service.LogInfoAsync($"Parsing complete. bytes.length={bytes.Length}").ConfigureAwait(false); return bytes; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; namespace System.Globalization { //////////////////////////////////////////////////////////////////////////// // // Notes about JapaneseLunisolarCalendar // //////////////////////////////////////////////////////////////////////////// /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1960/01/28 2050/01/22 ** JapaneseLunisolar 1960/01/01 2049/12/29 */ [Serializable] public class JapaneseLunisolarCalendar : EastAsianLunisolarCalendar { // // The era value for the current era. // public const int JapaneseEra = 1; internal GregorianCalendarHelper helper; internal const int MIN_LUNISOLAR_YEAR = 1960; internal const int MAX_LUNISOLAR_YEAR = 2049; internal const int MIN_GREGORIAN_YEAR = 1960; internal const int MIN_GREGORIAN_MONTH = 1; internal const int MIN_GREGORIAN_DAY = 28; internal const int MAX_GREGORIAN_YEAR = 2050; internal const int MAX_GREGORIAN_MONTH = 1; internal const int MAX_GREGORIAN_DAY = 22; internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY); internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } protected override int DaysInYearBeforeMinSupportedYear { get { // 1959 from ChineseLunisolarCalendar return 354; } } static readonly int[,] yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1960 */ { 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */{ 0 , 2 , 5 , 19808 },/* 29 30 29 29 30 30 29 30 29 30 30 29 0 354 1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */{ 0 , 2 , 2 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 1966 */{ 3 , 1 , 22 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */{ 7 , 1 , 30 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384 1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */{ 0 , 2 , 6 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355 1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */{ 0 , 2 , 15 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 1973 */{ 0 , 2 , 3 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */{ 8 , 1 , 31 , 54600 },/* 30 30 29 30 29 30 29 30 29 30 29 29 30 384 1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */{ 0 , 2 , 7 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */{ 4 , 1 , 25 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384 1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */{ 6 , 1 , 29 , 46504 },/* 30 29 30 30 29 30 29 30 30 29 30 29 30 385 1988 */{ 0 , 2 , 18 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1989 */{ 0 , 2 , 6 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1990 */{ 5 , 1 , 27 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */{ 8 , 1 , 31 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1996 */{ 0 , 2 , 19 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1997 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1998 */{ 5 , 1 , 28 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */{ 4 , 1 , 24 , 58536 },/* 30 30 30 29 29 30 29 29 30 29 30 29 30 384 2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */{ 0 , 2 , 9 , 22208 },/* 29 30 29 30 29 30 30 29 30 30 29 29 0 354 2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */{ 3 , 1 , 23 , 47696 },/* 30 29 30 30 30 29 30 29 29 30 29 30 29 384 2013 */{ 0 , 2 , 10 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */{ 5 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */{ 0 , 2 , 5 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2020 */{ 4 , 1 , 25 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */{ 2 , 1 , 22 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */{ 0 , 2 , 17 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 2027 */{ 0 , 2 , 7 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 2028 */{ 5 , 1 , 27 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 2029 */{ 0 , 2 , 13 , 55600 },/* 30 30 29 30 30 29 29 30 29 29 30 30 0 355 2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */{ 3 , 1 , 23 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384 2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */{ 6 , 1 , 28 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */{ 0 , 2 , 12 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 2041 */{ 0 , 2 , 1 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */{ 0 , 2 , 6 , 45648 },/* 30 29 30 30 29 29 30 29 29 30 29 30 0 354 2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */{ 0 , 2 , 14 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 */ }; internal override int MinCalendarYear { get { return (MIN_LUNISOLAR_YEAR); } } internal override int MaxCalendarYear { get { return (MAX_LUNISOLAR_YEAR); } } internal override DateTime MinDate { get { return (minDate); } } internal override DateTime MaxDate { get { return (maxDate); } } internal override EraInfo[] CalEraInfo { get { return (JapaneseCalendar.GetEraInfo()); } } internal override int GetYearInfo(int LunarYear, int Index) { if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } Contract.EndContractBlock(); return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index]; } internal override int GetYear(int year, DateTime time) { return helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return helper.GetGregorianYear(year, era); } // Trim off the eras that are before our date range private static EraInfo[] TrimEras(EraInfo[] baseEras) { EraInfo[] newEras = new EraInfo[baseEras.Length]; int newIndex = 0; // Eras have most recent first, so start with that for (int i = 0; i < baseEras.Length; i++) { // If this one's minimum year is bigger than our maximum year // then we can't use it. if (baseEras[i].yearOffset + baseEras[i].minEraYear >= MAX_LUNISOLAR_YEAR) { // skip this one. continue; } // If this one's maximum era is less than our minimum era // then we've gotten too low in the era #s, so we're done if (baseEras[i].yearOffset + baseEras[i].maxEraYear < MIN_LUNISOLAR_YEAR) { break; } // Wasn't too large or too small, can use this one newEras[newIndex] = baseEras[i]; newIndex++; } // If we didn't copy any then something was wrong, just return base if (newIndex == 0) return baseEras; // Resize the output array Array.Resize(ref newEras, newIndex); return newEras; } // Construct an instance of JapaneseLunisolar calendar. public JapaneseLunisolarCalendar() { helper = new GregorianCalendarHelper(this, TrimEras(JapaneseCalendar.GetEraInfo())); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } internal override CalendarId BaseCalendarID { get { return (CalendarId.JAPAN); } } internal override CalendarId ID { get { return (CalendarId.JAPANESELUNISOLAR); } } public override int[] Eras { get { return (helper.Eras); } } } }
using J2N; using J2N.Text; using Lucene.Net.Diagnostics; using System; using System.Runtime.CompilerServices; using System.Text; namespace Lucene.Net.Util { /* * 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. */ /* * Some of this code came from the excellent Unicode * conversion examples from: * * http://www.unicode.org/Public/PROGRAMS/CVTUTF * * Full Copyright for that code follows: */ /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * this source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute this Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /* * Additional code came from the IBM ICU library. * * http://www.icu-project.org * * Full Copyright for that code follows. */ /* * Copyright (C) 1999-2010, International Business Machines * Corporation and others. All Rights Reserved. * * 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, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * provided that the above copyright notice(s) and this permission notice appear * in all copies of the Software and that both the above copyright notice(s) and * this permission notice appear in supporting documentation. * * 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 OF THIRD PARTY RIGHTS. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN this NOTICE BE * LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF this SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall not * be used in advertising or otherwise to promote the sale, use or other * dealings in this Software without prior written authorization of the * copyright holder. */ /// <summary> /// Class to encode .NET's UTF16 <see cref="T:char[]"/> into UTF8 <see cref="T:byte[]"/> /// without always allocating a new <see cref="T:byte[]"/> as /// <see cref="Encoding.GetBytes(string)"/> of <see cref="Encoding.UTF8"/> does. /// <para/> /// @lucene.internal /// </summary> public static class UnicodeUtil { /// <summary> /// A binary term consisting of a number of 0xff bytes, likely to be bigger than other terms /// (e.g. collation keys) one would normally encounter, and definitely bigger than any UTF-8 terms. /// <para/> /// WARNING: this is not a valid UTF8 Term /// </summary> public static readonly BytesRef BIG_TERM = new BytesRef(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }); // TODO this is unrelated here find a better place for it public const int UNI_SUR_HIGH_START = 0xD800; public const int UNI_SUR_HIGH_END = 0xDBFF; public const int UNI_SUR_LOW_START = 0xDC00; public const int UNI_SUR_LOW_END = 0xDFFF; public const int UNI_REPLACEMENT_CHAR = 0xFFFD; private const long UNI_MAX_BMP = 0x0000FFFF; private const long HALF_SHIFT = 10; private const long HALF_MASK = 0x3FFL; private const int SURROGATE_OFFSET = Character.MinSupplementaryCodePoint - (UNI_SUR_HIGH_START << (int)HALF_SHIFT) - UNI_SUR_LOW_START; /// <summary> /// Encode characters from a <see cref="T:char[]"/> <paramref name="source"/>, starting at /// <paramref name="offset"/> for <paramref name="length"/> chars. After encoding, <c>result.Offset</c> will always be 0. /// </summary> // TODO: broken if incoming result.offset != 0 public static void UTF16toUTF8(char[] source, int offset, int length, BytesRef result) { int upto = 0; int i = offset; int end = offset + length; var @out = result.Bytes; // Pre-allocate for worst case 4-for-1 int maxLen = length * 4; if (@out.Length < maxLen) { @out = result.Bytes = new byte[maxLen]; } result.Offset = 0; while (i < end) { int code = (int)source[i++]; if (code < 0x80) { @out[upto++] = (byte)code; } else if (code < 0x800) { @out[upto++] = (byte)(0xC0 | (code >> 6)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { @out[upto++] = (byte)(0xE0 | (code >> 12)); @out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && i < end) { var utf32 = (int)source[i]; // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = (code << 10) + utf32 + SURROGATE_OFFSET; i++; @out[upto++] = (byte)(0xF0 | (utf32 >> 18)); @out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); @out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character @out[upto++] = 0xEF; @out[upto++] = 0xBF; @out[upto++] = 0xBD; } } //assert matches(source, offset, length, out, upto); result.Length = upto; } /// <summary> /// Encode characters from this <see cref="ICharSequence"/>, starting at <paramref name="offset"/> /// for <paramref name="length"/> characters. After encoding, <c>result.Offset</c> will always be 0. /// </summary> // TODO: broken if incoming result.offset != 0 public static void UTF16toUTF8(ICharSequence s, int offset, int length, BytesRef result) { int end = offset + length; var @out = result.Bytes; result.Offset = 0; // Pre-allocate for worst case 4-for-1 int maxLen = length * 4; if (@out.Length < maxLen) { @out = result.Bytes = new byte[maxLen]; } int upto = 0; for (int i = offset; i < end; i++) { var code = (int)s[i]; if (code < 0x80) { @out[upto++] = (byte)code; } else if (code < 0x800) { @out[upto++] = (byte)(0xC0 | (code >> 6)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { @out[upto++] = (byte)(0xE0 | (code >> 12)); @out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && (i < end - 1)) { int utf32 = (int)s[i + 1]; // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = (code << 10) + utf32 + SURROGATE_OFFSET; i++; @out[upto++] = (byte)(0xF0 | (utf32 >> 18)); @out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); @out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character @out[upto++] = 0xEF; @out[upto++] = 0xBF; @out[upto++] = 0xBD; } } //assert matches(s, offset, length, out, upto); result.Length = upto; } /// <summary> /// Encode characters from this <see cref="string"/>, starting at <paramref name="offset"/> /// for <paramref name="length"/> characters. After encoding, <c>result.Offset</c> will always be 0. /// <para/> /// LUCENENET specific. /// </summary> // TODO: broken if incoming result.offset != 0 public static void UTF16toUTF8(string s, int offset, int length, BytesRef result) { int end = offset + length; var @out = result.Bytes; result.Offset = 0; // Pre-allocate for worst case 4-for-1 int maxLen = length * 4; if (@out.Length < maxLen) { @out = result.Bytes = new byte[maxLen]; } int upto = 0; for (int i = offset; i < end; i++) { var code = (int)s[i]; if (code < 0x80) { @out[upto++] = (byte)code; } else if (code < 0x800) { @out[upto++] = (byte)(0xC0 | (code >> 6)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else if (code < 0xD800 || code > 0xDFFF) { @out[upto++] = (byte)(0xE0 | (code >> 12)); @out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (code & 0x3F)); } else { // surrogate pair // confirm valid high surrogate if (code < 0xDC00 && (i < end - 1)) { int utf32 = (int)s[i + 1]; // confirm valid low surrogate and write pair if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { utf32 = (code << 10) + utf32 + SURROGATE_OFFSET; i++; @out[upto++] = (byte)(0xF0 | (utf32 >> 18)); @out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); @out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); @out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); continue; } } // replace unpaired surrogate or out-of-order low surrogate // with substitution character @out[upto++] = 0xEF; @out[upto++] = 0xBF; @out[upto++] = 0xBD; } } //assert matches(s, offset, length, out, upto); result.Length = upto; } // Only called from assert /* private static boolean matches(char[] source, int offset, int length, byte[] result, int upto) { try { String s1 = new String(source, offset, length); String s2 = new String(result, 0, upto, StandardCharsets.UTF_8); if (!s1.equals(s2, StringComparison.Ordinal)) { //System.out.println("DIFF: s1 len=" + s1.length()); //for(int i=0;i<s1.length();i++) // System.out.println(" " + i + ": " + (int) s1.charAt(i)); //System.out.println("s2 len=" + s2.length()); //for(int i=0;i<s2.length();i++) // System.out.println(" " + i + ": " + (int) s2.charAt(i)); // If the input string was invalid, then the // difference is OK if (!validUTF16String(s1)) return true; return false; } return s1.equals(s2, StringComparison.Ordinal); } catch (UnsupportedEncodingException uee) { return false; } } // Only called from assert private static boolean matches(String source, int offset, int length, byte[] result, int upto) { try { String s1 = source.substring(offset, offset+length); String s2 = new String(result, 0, upto, StandardCharsets.UTF_8); if (!s1.equals(s2, StringComparison.Ordinal)) { // Allow a difference if s1 is not valid UTF-16 //System.out.println("DIFF: s1 len=" + s1.length()); //for(int i=0;i<s1.length();i++) // System.out.println(" " + i + ": " + (int) s1.charAt(i)); //System.out.println(" s2 len=" + s2.length()); //for(int i=0;i<s2.length();i++) // System.out.println(" " + i + ": " + (int) s2.charAt(i)); // If the input string was invalid, then the // difference is OK if (!validUTF16String(s1)) return true; return false; } return s1.equals(s2, StringComparison.Ordinal); } catch (UnsupportedEncodingException uee) { return false; } } */ public static bool ValidUTF16String(ICharSequence s) { int size = s.Length; for (int i = 0; i < size; i++) { char ch = s[i]; if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size - 1) { i++; char nextCH = s[i]; if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else // Unmatched high surrogate { return false; } } else // Unmatched high surrogate { return false; } } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate { return false; } } return true; } public static bool ValidUTF16String(string s) // LUCENENET specific overload because string doesn't implement ICharSequence { int size = s.Length; for (int i = 0; i < size; i++) { char ch = s[i]; if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size - 1) { i++; char nextCH = s[i]; if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else // Unmatched high surrogate { return false; } } else // Unmatched high surrogate { return false; } } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate { return false; } } return true; } public static bool ValidUTF16String(StringBuilder s) // LUCENENET specific overload because StringBuilder doesn't implement ICharSequence { int size = s.Length; for (int i = 0; i < size; i++) { char ch = s[i]; if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size - 1) { i++; char nextCH = s[i]; if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else // Unmatched high surrogate { return false; } } else // Unmatched high surrogate { return false; } } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate { return false; } } return true; } public static bool ValidUTF16String(char[] s, int size) { for (int i = 0; i < size; i++) { char ch = s[i]; if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { if (i < size - 1) { i++; char nextCH = s[i]; if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { // Valid surrogate pair } else { return false; } } else { return false; } } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) // Unmatched low surrogate { return false; } } return true; } // Borrowed from Python's 3.1.2 sources, // Objects/unicodeobject.c, and modified (see commented // out section, and the -1s) to disallow the reserved for // future (RFC 3629) 5/6 byte sequence characters, and // invalid 0xFE and 0xFF bytes. /* Map UTF-8 encoded prefix byte to sequence length. -1 (0xFF) * means illegal prefix. see RFC 2279 for details */ internal static readonly int[] utf8CodeLength = LoadUTF8CodeLength(); private static int[] LoadUTF8CodeLength() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { int v = int.MinValue; return new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4 }; } /// <summary> /// Returns the number of code points in this UTF8 sequence. /// /// <para/>This method assumes valid UTF8 input. This method /// <b>does not perform</b> full UTF8 validation, it will check only the /// first byte of each codepoint (for multi-byte sequences any bytes after /// the head are skipped). /// </summary> /// <exception cref="ArgumentException"> If invalid codepoint header byte occurs or the /// content is prematurely truncated. </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CodePointCount(BytesRef utf8) { int pos = utf8.Offset; int limit = pos + utf8.Length; var bytes = utf8.Bytes; int codePointCount = 0; for (; pos < limit; codePointCount++) { int v = bytes[pos] & 0xFF; if (v < /* 0xxx xxxx */ 0x80) { pos += 1; continue; } if (v >= /* 110x xxxx */ 0xc0) { if (v < /* 111x xxxx */ 0xe0) { pos += 2; continue; } if (v < /* 1111 xxxx */ 0xf0) { pos += 3; continue; } if (v < /* 1111 1xxx */ 0xf8) { pos += 4; continue; } // fallthrough, consider 5 and 6 byte sequences invalid. } // Anything not covered above is invalid UTF8. throw new ArgumentException(); } // Check if we didn't go over the limit on the last character. if (pos > limit) throw new ArgumentException(); return codePointCount; } /// <summary> /// This method assumes valid UTF8 input. This method /// <b>does not perform</b> full UTF8 validation, it will check only the /// first byte of each codepoint (for multi-byte sequences any bytes after /// the head are skipped). /// </summary> /// <exception cref="ArgumentException"> If invalid codepoint header byte occurs or the /// content is prematurely truncated. </exception> public static void UTF8toUTF32(BytesRef utf8, Int32sRef utf32) { // TODO: broken if incoming result.offset != 0 // pre-alloc for worst case // TODO: ints cannot be null, should be an assert if (utf32.Int32s == null || utf32.Int32s.Length < utf8.Length) { utf32.Int32s = new int[utf8.Length]; } int utf32Count = 0; int utf8Upto = utf8.Offset; int[] ints = utf32.Int32s; var bytes = utf8.Bytes; int utf8Limit = utf8.Offset + utf8.Length; while (utf8Upto < utf8Limit) { int numBytes = utf8CodeLength[bytes[utf8Upto] & 0xFF]; int v /*= 0*/; switch (numBytes) { case 1: ints[utf32Count++] = bytes[utf8Upto++]; continue; case 2: // 5 useful bits v = bytes[utf8Upto++] & 31; break; case 3: // 4 useful bits v = bytes[utf8Upto++] & 15; break; case 4: // 3 useful bits v = bytes[utf8Upto++] & 7; break; default: throw new ArgumentException("invalid utf8"); } // TODO: this may read past utf8's limit. int limit = utf8Upto + numBytes - 1; while (utf8Upto < limit) { v = v << 6 | bytes[utf8Upto++] & 63; } ints[utf32Count++] = v; } utf32.Offset = 0; utf32.Length = utf32Count; } /// <summary> /// Shift value for lead surrogate to form a supplementary character. </summary> private const int LEAD_SURROGATE_SHIFT_ = 10; /// <summary> /// Mask to retrieve the significant value from a trail surrogate. </summary> private const int TRAIL_SURROGATE_MASK_ = 0x3FF; /// <summary> /// Trail surrogate minimum value. </summary> private const int TRAIL_SURROGATE_MIN_VALUE = 0xDC00; /// <summary> /// Lead surrogate minimum value. </summary> private const int LEAD_SURROGATE_MIN_VALUE = 0xD800; /// <summary> /// The minimum value for Supplementary code points. </summary> private const int SUPPLEMENTARY_MIN_VALUE = 0x10000; /// <summary> /// Value that all lead surrogate starts with. </summary> private const int LEAD_SURROGATE_OFFSET_ = LEAD_SURROGATE_MIN_VALUE - (SUPPLEMENTARY_MIN_VALUE >> LEAD_SURROGATE_SHIFT_); /// <summary> /// Cover JDK 1.5 API. Create a String from an array of <paramref name="codePoints"/>. /// </summary> /// <param name="codePoints"> The code array. </param> /// <param name="offset"> The start of the text in the code point array. </param> /// <param name="count"> The number of code points. </param> /// <returns> a String representing the code points between offset and count. </returns> /// <exception cref="ArgumentException"> If an invalid code point is encountered. </exception> /// <exception cref="IndexOutOfRangeException"> If the offset or count are out of bounds. </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string NewString(int[] codePoints, int offset, int count) { char[] chars = ToCharArray(codePoints, offset, count); return new string(chars); } /// <summary> /// Generates char array that represents the provided input code points. /// <para/> /// LUCENENET specific. /// </summary> /// <param name="codePoints"> The code array. </param> /// <param name="offset"> The start of the text in the code point array. </param> /// <param name="count"> The number of code points. </param> /// <returns> a char array representing the code points between offset and count. </returns> // LUCENENET NOTE: This code was originally in the NewString() method (above). // It has been refactored from the original to remove the exception throw/catch and // instead proactively resizes the array instead of relying on excpetions + copy operations public static char[] ToCharArray(int[] codePoints, int offset, int count) { if (count < 0) { throw new ArgumentException(); } int countThreashold = 1024; // If the number of chars exceeds this, we count them instead of allocating count * 2 // LUCENENET: as a first approximation, assume each codepoint // is 2 characters (since it cannot be longer than this) int arrayLength = count * 2; // LUCENENET: if we go over the threashold, count the number of // chars we will need so we can allocate the precise amount of memory if (count > countThreashold) { arrayLength = 0; for (int r = offset, e = offset + count; r < e; ++r) { arrayLength += codePoints[r] < 0x010000 ? 1 : 2; } if (arrayLength < 1) { arrayLength = count * 2; } } // Initialize our array to our exact or oversized length. // It is now safe to assume we have enough space for all of the characters. char[] chars = new char[arrayLength]; int w = 0; for (int r = offset, e = offset + count; r < e; ++r) { int cp = codePoints[r]; if (cp < 0 || cp > 0x10ffff) { throw new ArgumentException(); } if (cp < 0x010000) { chars[w++] = (char)cp; } else { chars[w++] = (char)(LEAD_SURROGATE_OFFSET_ + (cp >> LEAD_SURROGATE_SHIFT_)); chars[w++] = (char)(TRAIL_SURROGATE_MIN_VALUE + (cp & TRAIL_SURROGATE_MASK_)); } } var result = new char[w]; Array.Copy(chars, result, w); return result; } // for debugging public static string ToHexString(string s) { var sb = new StringBuilder(); for (int i = 0; i < s.Length; i++) { char ch = s[i]; if (i > 0) { sb.Append(' '); } if (ch < 128) { sb.Append(ch); } else { if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { sb.Append("H:"); } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { sb.Append("L:"); } else if (ch > UNI_SUR_LOW_END) { if (ch == 0xffff) { sb.Append("F:"); } else { sb.Append("E:"); } } sb.Append("0x" + ((short)ch).ToString("X")); } } return sb.ToString(); } /// <summary> /// Interprets the given byte array as UTF-8 and converts to UTF-16. The <see cref="CharsRef"/> will be extended if /// it doesn't provide enough space to hold the worst case of each byte becoming a UTF-16 codepoint. /// <para/> /// NOTE: Full characters are read, even if this reads past the length passed (and /// can result in an <see cref="IndexOutOfRangeException"/> if invalid UTF-8 is passed). /// Explicit checks for valid UTF-8 are not performed. /// </summary> // TODO: broken if chars.offset != 0 public static void UTF8toUTF16(byte[] utf8, int offset, int length, CharsRef chars) { int out_offset = chars.Offset = 0; char[] @out = chars.Chars = ArrayUtil.Grow(chars.Chars, length); int limit = offset + length; while (offset < limit) { int b = utf8[offset++] & 0xff; if (b < 0xc0) { if (Debugging.AssertsEnabled) Debugging.Assert(b < 0x80); @out[out_offset++] = (char)b; } else if (b < 0xe0) { @out[out_offset++] = (char)(((b & 0x1f) << 6) + (utf8[offset++] & 0x3f)); } else if (b < 0xf0) { @out[out_offset++] = (char)(((b & 0xf) << 12) + ((utf8[offset] & 0x3f) << 6) + (utf8[offset + 1] & 0x3f)); offset += 2; } else { if (Debugging.AssertsEnabled) Debugging.Assert(b < 0xf8, () => "b = 0x" + b.ToString("x")); int ch = ((b & 0x7) << 18) + ((utf8[offset] & 0x3f) << 12) + ((utf8[offset + 1] & 0x3f) << 6) + (utf8[offset + 2] & 0x3f); offset += 3; if (ch < UNI_MAX_BMP) { @out[out_offset++] = (char)ch; } else { int chHalf = ch - 0x0010000; @out[out_offset++] = (char)((chHalf >> 10) + 0xD800); @out[out_offset++] = (char)((chHalf & HALF_MASK) + 0xDC00); } } } chars.Length = out_offset - chars.Offset; } /// <summary> /// Utility method for <see cref="UTF8toUTF16(byte[], int, int, CharsRef)"/> </summary> /// <seealso cref="UTF8toUTF16(byte[], int, int, CharsRef)"/> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void UTF8toUTF16(BytesRef bytesRef, CharsRef chars) { UTF8toUTF16(bytesRef.Bytes, bytesRef.Offset, bytesRef.Length, chars); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MessageWindowViewModel.cs" company="Jan-Cornelius Molnar"> // The MIT License (MIT) // // Copyright (c) 2015 Jan-Cornelius Molnar // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Threading; using Jcq.Core; using Jcq.IcqProtocol; using Jcq.IcqProtocol.Contracts; using Jcq.Ux.ViewModel.Contracts; namespace Jcq.Ux.ViewModel { public class MessageWindowViewModel : INotifyPropertyChanged { private readonly ObservableCollection<MessageViewModel> _messages; private readonly CountDownTimer _typingNotificationTimer; private string _statusText; public MessageWindowViewModel(ContactViewModel contact) { Contact = contact; ApplicationService.Current.Context.GetService<IUserInformationService>().RequestShortUserInfo(contact.Model); _messages = new ObservableCollection<MessageViewModel>(); Messages = new ReadOnlyObservableCollection<MessageViewModel>(_messages); ApplicationService.Current.Context.GetService<IIconService>().RequestContactIcon(contact.Model); _typingNotificationTimer = new CountDownTimer(TimeSpan.FromSeconds(6)); _typingNotificationTimer.Tick += OnTypingNotificationTimer_Tick; } public ContactViewModel Contact { get; } public ReadOnlyObservableCollection<MessageViewModel> Messages { get; private set; } public string StatusText { get { return _statusText; } set { _statusText = value; OnPropertyChanged("StatusText"); } } public event PropertyChangedEventHandler PropertyChanged; public event EventHandler ConatctInformationWindowRequested; public event EventHandler ContactHistoryWindowRequested; public event EventHandler ShowRequested; public static void RegisterEventHandlers() { var svMessaging = ApplicationService.Current.Context.GetService<IMessageService>(); var svNotification = ApplicationService.Current.Context.GetService<INotificationService>(); var svStorage = ApplicationService.Current.Context.GetService<IStorageService>(); svMessaging.MessageReceived += OnMessageReceived; svNotification.TypingNotification += OnTypingNotification; svStorage.ContactStatusChanged += OnContactStatusChanged; } public void RequestContactInformationWindow() { if (ConatctInformationWindowRequested != null) { ConatctInformationWindowRequested(this, EventArgs.Empty); } } public void RequestChatHistoryWindow() { if (ContactHistoryWindowRequested != null) { ContactHistoryWindowRequested(this, EventArgs.Empty); } } public void SendMessage(string text) { foreach (Match m in EmojiHelper.EmojiRegex.Matches(text)) { string key1 = m.Value; string key2 = EmojiHelper.EmojiMappings[key1].ToUpper(); string value = EmojiHelper.EmojiToUnicodeMappings[key2]; text = text.Replace(m.Value, value); } var msg = new IcqMessage { Sender = ApplicationService.Current.Context.Identity, Recipient = Contact.Model, Text = text }; ApplicationService.Current.Context.GetService<IMessageService>().SendMessage(msg); var message = new TextMessageViewModel(msg, MessageColors.IdentityColor); DisplayMessage(message); } public void Show() { if (ShowRequested != null) { ShowRequested(this, EventArgs.Empty); } } public void Close() { ApplicationService.Current.Context.GetService<IContactWindowViewModelService>() .RemoveMessageWindowViewModel( Contact); } private void DisplayTypingNotification(NotificationType status) { switch (status) { case NotificationType.TypingFinished: StatusText = string.Format("{0} finished typing a message.", Contact.Name); break; case NotificationType.TypingStarted: StatusText = string.Format("{0} is typing a message.", Contact.Name); break; case NotificationType.TypingCanceled: StatusText = string.Format("{0} cleared the entered text.", Contact.Name); break; } } private void DisplayMessage(TextMessageViewModel message) { ApplicationService.Current.Context.GetService<IContactHistoryService>().AppendMessage(Contact, message); if (message.Sender == Contact) { StatusText = string.Format("Last message received on {0}.", message.DateCreated.ToShortTimeString()); } else { StatusText = string.Format("Last message sent on {0}.", message.DateCreated.ToShortTimeString()); } _messages.Add(message); if (DocumentScrollRequired != null) { DocumentScrollRequired(this, EventArgs.Empty); } } private void DisplayStatus(StatusChangedMessageViewModel message) { _messages.Add(message); } public void SendTypingNotification(TextChangedAction action) { switch (action) { case TextChangedAction.Changed: if (_typingNotificationTimer.IsRunning) { _typingNotificationTimer.Reset(); } else { _typingNotificationTimer.Start(); SendTypingNotification(NotificationType.TypingStarted); } break; case TextChangedAction.Cleared: _typingNotificationTimer.Stop(); SendTypingNotification(NotificationType.TypingCanceled); break; } } /// <summary> /// Sends a notification that the user is typing something, has finished typing and cleared his text. /// </summary> private void SendTypingNotification(NotificationType type) { var svNotification = ApplicationService.Current.Context.GetService<INotificationService>(); svNotification.SendNotification(Contact.Model, type); } protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public event EventHandler DocumentScrollRequired; private void OnTypingNotificationTimer_Tick(object sender, EventArgs e) { try { SendTypingNotification(NotificationType.TypingFinished); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } #region Shared Event Handlers private static void OnMessageReceived(object sender, MessageEventArgs e) { try { Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action<IMessage>(ProcessMessageReceived), e.Message); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private static void OnContactStatusChanged(object sender, StatusChangedEventArgs e) { try { Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action<StatusChangedEventArgs>(ProcessStatusChanged), e); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private static void OnTypingNotification(object sender, TypingNotificationEventArgs e) { try { Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action<TypingNotificationEventArgs>(ProcessTypingNotification), e); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } #endregion #region Shared Event Processors private static void ProcessMessageReceived(IMessage msg) { try { ContactViewModel contact = ContactViewModelCache.GetViewModel(msg.Sender); MessageWindowViewModel vm = ApplicationService.Current.Context .GetService<IContactWindowViewModelService>() .GetMessageWindowViewModel(contact); var offlineMsg = msg as IcqOfflineMessage; TextMessageViewModel message; if (offlineMsg != null) { message = new OfflineTextMessageViewModel(offlineMsg, MessageColors.Contact1Color); } else { message = new TextMessageViewModel(msg, MessageColors.Contact1Color); } vm.DisplayMessage(message); vm.Show(); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private static void ProcessStatusChanged(StatusChangedEventArgs e) { try { ContactViewModel contact = ContactViewModelCache.GetViewModel(e.Contact); if (!ApplicationService.Current.Context.GetService<IContactWindowViewModelService>() .IsMessageWindowViewModelAvailable(contact)) return; MessageWindowViewModel vm = ApplicationService.Current.Context .GetService<IContactWindowViewModelService>() .GetMessageWindowViewModel(contact); var message = new StatusChangedMessageViewModel(DateTime.Now, contact, vm.Contact, e.Status, MessageColors.SystemColor); vm.DisplayStatus(message); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } private static void ProcessTypingNotification(TypingNotificationEventArgs e) { try { ContactViewModel contact = ContactViewModelCache.GetViewModel(e.Contact); if (!ApplicationService.Current.Context.GetService<IContactWindowViewModelService>() .IsMessageWindowViewModelAvailable(contact)) return; MessageWindowViewModel vm = ApplicationService.Current.Context .GetService<IContactWindowViewModelService>() .GetMessageWindowViewModel(contact); vm.DisplayTypingNotification(e.NotificationType); } catch (Exception ex) { Kernel.Exceptions.PublishException(ex); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; namespace Umbraco.Core.Services { /// <summary> /// Content service extension methods /// </summary> public static class ContentServiceExtensions { public static IEnumerable<IContent> GetByIds(this IContentService contentService, IEnumerable<Udi> ids) { var guids = new List<GuidUdi>(); foreach (var udi in ids) { var guidUdi = udi as GuidUdi; if (guidUdi == null) throw new InvalidOperationException("The UDI provided isn't of type " + typeof(GuidUdi) + " which is required by content"); guids.Add(guidUdi); } return contentService.GetByIds(guids.Select(x => x.Guid)); } /// <summary> /// Method to create an IContent object based on the Udi of a parent /// </summary> /// <param name="contentService"></param> /// <param name="name"></param> /// <param name="parentId"></param> /// <param name="mediaTypeAlias"></param> /// <param name="userId"></param> /// <returns></returns> public static IContent CreateContent(this IContentService contentService, string name, Udi parentId, string mediaTypeAlias, int userId = 0) { var guidUdi = parentId as GuidUdi; if (guidUdi == null) throw new InvalidOperationException("The UDI provided isn't of type " + typeof(GuidUdi) + " which is required by content"); var parent = contentService.GetById(guidUdi.Guid); return contentService.CreateContent(name, parent, mediaTypeAlias, userId); } /// <summary> /// Remove all permissions for this user for all nodes /// </summary> /// <param name="contentService"></param> /// <param name="contentId"></param> public static void RemoveContentPermissions(this IContentService contentService, int contentId) { contentService.ReplaceContentPermissions(new EntityPermissionSet(contentId, new EntityPermissionCollection())); } /// <summary> /// Returns true if there is any content in the recycle bin /// </summary> /// <param name="contentService"></param> /// <returns></returns> public static bool RecycleBinSmells(this IContentService contentService) { return contentService.CountChildren(Constants.System.RecycleBinContent) > 0; } /// <summary> /// Returns true if there is any media in the recycle bin /// </summary> /// <param name="mediaService"></param> /// <returns></returns> public static bool RecycleBinSmells(this IMediaService mediaService) { return mediaService.CountChildren(Constants.System.RecycleBinMedia) > 0; } /// <summary> /// Used for the DeleteContentOfType(s) methods to find content items to be deleted based on the content type ids passed in /// </summary> /// <typeparam name="TContent"></typeparam> /// <param name="contentService"></param> /// <param name="contentTypeIds">The content type ids being deleted</param> /// <param name="repository"></param> /// <param name="rootItems"> /// Returns a dictionary (path, TContent) of the root items discovered in the data set of items to be deleted, this can then be used /// to search for content that needs to be trashed as a result of this. /// </param> /// <returns> /// The content items to be deleted /// </returns> /// <remarks> /// An internal extension method used for the DeleteContentOfTypes (DeleteMediaOfTypes) methods so that logic can be shared to avoid code duplication. /// </remarks> internal static IEnumerable<TContent> TrackDeletionsForDeleteContentOfTypes<TContent>(this IContentServiceBase contentService, IEnumerable<int> contentTypeIds, IRepositoryVersionable<int, TContent> repository, out IDictionary<string, TContent> rootItems) where TContent: IContentBase { var contentToDelete = new List<TContent>(); //track the 'root' items of the collection of nodes discovered to delete, we need to use //these items to lookup descendants that are not of this doc type so they can be transfered //to the recycle bin rootItems = new Dictionary<string, TContent>(); var query = Query<TContent>.Builder.Where(x => contentTypeIds.Contains(x.ContentTypeId)); //TODO: What about content that has the contenttype as part of its composition? long pageIndex = 0; const int pageSize = 10000; int currentPageSize; do { long total; //start at the highest level var contents = repository.GetPagedResultsByQuery(query, pageIndex, pageSize, out total, "umbracoNode.level", Direction.Ascending, true).ToArray(); // need to store decendants count before filtering, in order for loop to work correctly currentPageSize = contents.Length; //loop through the items, check if if the item exists already in the hierarchy of items tracked //and if not, we need to add it as a 'root' item to be used to lookup later foreach (var content in contents) { var pathParts = content.Path.Split(','); var found = false; for (int i = 1; i < pathParts.Length; i++) { var currPath = "-1," + string.Join(",", Enumerable.Range(1, i).Select(x => pathParts[x])); if (rootItems.Keys.Contains(currPath)) { //this content item's ancestor already exists in the root collection found = true; break; } } if (found == false) { rootItems[content.Path] = content; } //track content for deletion contentToDelete.Add(content); } pageIndex++; } while (currentPageSize == pageSize); return contentToDelete; } /// <summary> /// Used for the DeleteContentOfType(s) methods to find content items to be trashed based on the content type ids passed in /// </summary> /// <typeparam name="TContent"></typeparam> /// <param name="contentService"></param> /// <param name="contentTypeIds">The content type ids being deleted</param> /// <param name="rootItems"></param> /// <param name="repository"></param> /// <returns> /// The content items to be trashed /// </returns> /// <remarks> /// An internal extension method used for the DeleteContentOfTypes (DeleteMediaOfTypes) methods so that logic can be shared to avoid code duplication. /// </remarks> internal static IEnumerable<TContent> TrackTrashedForDeleteContentOfTypes<TContent>(this IContentServiceBase contentService, IEnumerable<int> contentTypeIds, IDictionary<string, TContent> rootItems, IRepositoryVersionable<int, TContent> repository) where TContent : IContentBase { const int pageSize = 10000; var contentToRecycle = new List<TContent>(); //iterate over the root items found in the collection to be deleted, then discover which descendant items //need to be moved to the recycle bin foreach (var content in rootItems) { //Look for children of current content and move that to trash before the current content is deleted var c = content; var pathMatch = string.Format("{0},", c.Value.Path); var descendantQuery = Query<TContent>.Builder.Where(x => x.Path.StartsWith(pathMatch)); long pageIndex = 0; int currentPageSize; do { long total; var descendants = repository.GetPagedResultsByQuery(descendantQuery, pageIndex, pageSize, out total, "umbracoNode.id", Direction.Ascending, true).ToArray(); foreach (var d in descendants) { //track for recycling if this item is not of a contenttype that is being deleted if (contentTypeIds.Contains(d.ContentTypeId) == false) { contentToRecycle.Add(d); } } // need to store decendants count before filtering, in order for loop to work correctly currentPageSize = descendants.Length; pageIndex++; } while (currentPageSize == pageSize); } return contentToRecycle; } } }
// // SqliteModelProviderTests.cs // // Author: // Scott Peterson <lunchtimemama@gmail.com> // // Copyright (C) 2008 Scott Peterson // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if ENABLE_TESTS using System; using System.IO; using NUnit.Framework; using Hyena.Data.Sqlite; namespace Hyena.Data.Sqlite.Tests { [TestFixture] public class SqliteModelProviderTests { private HyenaSqliteConnection connection; private ModelProvider provider; [TestFixtureSetUp] public void Init () { connection = new HyenaSqliteConnection ("test.db"); provider = new ModelProvider (connection); } [TestFixtureTearDown] public void Dispose () { connection.Dispose (); File.Delete ("test.db"); } [Test] public void IntMembers () { DbBoundType newed_item = new DbBoundType (); newed_item.PublicIntField = 3141592; newed_item.PublicIntProperty = 13; newed_item.SetPrivateIntField (128); newed_item.SetPrivateIntProperty (42); provider.Save (newed_item); DbBoundType loaded_item = provider.FetchSingle (newed_item.PrimaryKey); Assert.AreEqual (newed_item.PublicIntField, loaded_item.PublicIntField); Assert.AreEqual (newed_item.PublicIntProperty, loaded_item.PublicIntProperty); Assert.AreEqual (newed_item.GetPrivateIntField (), loaded_item.GetPrivateIntField ()); Assert.AreEqual (newed_item.GetPrivateIntProperty (), loaded_item.GetPrivateIntProperty ()); } [Test] public void LongMembers () { DbBoundType newed_item = new DbBoundType (); newed_item.PublicLongField = 4926227057; newed_item.PublicLongProperty = -932; newed_item.SetPrivateLongField (3243); newed_item.SetPrivateLongProperty (1); provider.Save (newed_item); DbBoundType loaded_item = provider.FetchSingle (newed_item.PrimaryKey); Assert.AreEqual (newed_item.PublicLongField, loaded_item.PublicLongField); Assert.AreEqual (newed_item.PublicLongProperty, loaded_item.PublicLongProperty); Assert.AreEqual (newed_item.GetPrivateLongField (), loaded_item.GetPrivateLongField ()); Assert.AreEqual (newed_item.GetPrivateLongProperty (), loaded_item.GetPrivateLongProperty ()); } [Test] public void StringMembers () { DbBoundType newed_item = new DbBoundType (); newed_item.PublicStringField = "Surely you're joking, Mr. Feynman."; newed_item.PublicStringProperty = "Even as a splitted bark, so sunder we: This way fall I to death."; newed_item.SetPrivateStringField ("Who is John Galt?"); newed_item.SetPrivateStringProperty ("The most formidable weapon against errors of every kind is Reason."); provider.Save (newed_item); DbBoundType loaded_item = provider.FetchSingle (newed_item.PrimaryKey); Assert.AreEqual (newed_item.PublicStringField, loaded_item.PublicStringField); Assert.AreEqual (newed_item.PublicStringProperty, loaded_item.PublicStringProperty); Assert.AreEqual (newed_item.GetPrivateStringField (), loaded_item.GetPrivateStringField ()); Assert.AreEqual (newed_item.GetPrivateStringProperty (), loaded_item.GetPrivateStringProperty ()); } [Test] public void BlankStringMembers () { DbBoundType newed_item = new DbBoundType (); newed_item.PublicStringField = ""; newed_item.PublicStringProperty = null; newed_item.SetPrivateStringField (" \t "); newed_item.SetPrivateStringProperty (" foo "); provider.Save (newed_item); DbBoundType loaded_item = provider.FetchSingle (newed_item.PrimaryKey); Assert.AreEqual (null, loaded_item.PublicStringField); Assert.AreEqual (null, loaded_item.PublicStringProperty); Assert.AreEqual (null, loaded_item.GetPrivateStringField ()); Assert.AreEqual (" foo ", loaded_item.GetPrivateStringProperty ()); } [Test] public void NullStringMembers () { DbBoundType newed_item = new DbBoundType (); newed_item.PublicStringField = null; newed_item.PublicStringProperty = null; newed_item.SetPrivateStringField (null); newed_item.SetPrivateStringProperty (null); provider.Save (newed_item); DbBoundType loaded_item = provider.FetchSingle (newed_item.PrimaryKey); Assert.AreEqual (newed_item.PublicStringField, loaded_item.PublicStringField); Assert.AreEqual (newed_item.PublicStringProperty, loaded_item.PublicStringProperty); Assert.AreEqual (newed_item.GetPrivateStringField (), loaded_item.GetPrivateStringField ()); Assert.AreEqual (newed_item.GetPrivateStringProperty (), loaded_item.GetPrivateStringProperty ()); } // Some fidelity is lost in the conversion from DT to DB time format private void AssertArePrettyClose (DateTime time1, DateTime time2) { Assert.AreEqual (time1.Year, time2.Year); Assert.AreEqual (time1.Month, time2.Month); Assert.AreEqual (time1.Day, time2.Day); Assert.AreEqual (time1.Hour, time2.Hour); Assert.AreEqual (time1.Minute, time2.Minute); Assert.AreEqual (time1.Second, time2.Second); } [Test] public void DateTimeMembers () { DbBoundType newed_item = new DbBoundType (); newed_item.PublicDateTimeField = DateTime.Now; newed_item.PublicDateTimeProperty = new DateTime (1986, 4, 23); newed_item.SetPrivateDateTimeField (DateTime.MinValue); newed_item.SetPrivateDateTimeProperty (DateTime.Now); provider.Save (newed_item); string command = String.Format ("SELECT PrivateDateTimeField FROM {0} WHERE PrimaryKey = {1}", provider.TableName, newed_item.PrimaryKey); using (IDataReader reader = connection.Query (command)) { reader.Read (); Assert.IsTrue (reader[0] == null); } DbBoundType loaded_item = provider.FetchSingle (newed_item.PrimaryKey); AssertArePrettyClose (newed_item.PublicDateTimeField, loaded_item.PublicDateTimeField); AssertArePrettyClose (newed_item.PublicDateTimeProperty, loaded_item.PublicDateTimeProperty); AssertArePrettyClose (newed_item.GetPrivateDateTimeField (), loaded_item.GetPrivateDateTimeField ()); AssertArePrettyClose (newed_item.GetPrivateDateTimeProperty (), loaded_item.GetPrivateDateTimeProperty ()); } [Test] public void TimeSpanMembers () { DbBoundType newed_item = new DbBoundType (); newed_item.PublicTimeSpanField = new TimeSpan (0, 0, 1); newed_item.PublicTimeSpanProperty = new TimeSpan (1, 0, 0); newed_item.SetPrivateTimeSpanField (new TimeSpan (1, 39, 12)); newed_item.SetPrivateTimeSpanProperty (TimeSpan.MinValue); provider.Save (newed_item); string command = String.Format ("SELECT PrivateTimeSpanProperty FROM {0} WHERE PrimaryKey = {1}", provider.TableName, newed_item.PrimaryKey); using (IDataReader reader = connection.Query (command)) { reader.Read (); Assert.IsTrue (reader[0] == null); } // NUnit boxes and uses reference equality, rather than Equals() DbBoundType loaded_item = provider.FetchSingle (newed_item.PrimaryKey); Assert.AreEqual (newed_item.PublicTimeSpanField, loaded_item.PublicTimeSpanField); Assert.AreEqual (newed_item.PublicTimeSpanProperty, loaded_item.PublicTimeSpanProperty); Assert.AreEqual (newed_item.GetPrivateTimeSpanField (), loaded_item.GetPrivateTimeSpanField ()); Assert.AreEqual (newed_item.GetPrivateTimeSpanProperty (), loaded_item.GetPrivateTimeSpanProperty ()); } [Test] public void IntEnumMembers () { DbBoundType newed_item = new DbBoundType (); newed_item.PublicIntEnumField = IntEnum.Zero; newed_item.PublicIntEnumProperty = IntEnum.One; newed_item.SetPrivateIntEnumField (IntEnum.Two); newed_item.SetPrivateIntEnumProperty (IntEnum.Three); provider.Save (newed_item); DbBoundType loaded_item = provider.FetchSingle (newed_item.PrimaryKey); Assert.AreEqual (newed_item.PublicIntEnumField, loaded_item.PublicIntEnumField); Assert.AreEqual (newed_item.PublicIntEnumProperty, loaded_item.PublicIntEnumProperty); Assert.AreEqual (newed_item.GetPrivateIntEnumField (), loaded_item.GetPrivateIntEnumField ()); Assert.AreEqual (newed_item.GetPrivateIntEnumProperty (), loaded_item.GetPrivateIntEnumProperty ()); } [Test] public void LongEnumMembers () { DbBoundType newed_item = new DbBoundType (); newed_item.PublicLongEnumField = LongEnum.Cero; newed_item.PublicLongEnumProperty = LongEnum.Uno; newed_item.SetPrivateLongEnumField (LongEnum.Dos); newed_item.SetPrivateLongEnumProperty (LongEnum.Tres); provider.Save (newed_item); DbBoundType loaded_item = provider.FetchSingle (newed_item.PrimaryKey); Assert.AreEqual (newed_item.PublicLongEnumField, loaded_item.PublicLongEnumField); Assert.AreEqual (newed_item.PublicLongEnumProperty, loaded_item.PublicLongEnumProperty); Assert.AreEqual (newed_item.GetPrivateLongEnumField (), loaded_item.GetPrivateLongEnumField ()); Assert.AreEqual (newed_item.GetPrivateLongEnumProperty (), loaded_item.GetPrivateLongEnumProperty ()); } } } #endif
using System; using UnityEngine; namespace InControl { public class InputDevice { public static readonly InputDevice Null = new InputDevice( "None" ); internal int SortOrder = int.MaxValue; public string Name { get; protected set; } public string Meta { get; protected set; } public ulong LastChangeTick { get; protected set; } public InputControl[] Controls { get; protected set; } public OneAxisInputControl LeftStickX { get; protected set; } public OneAxisInputControl LeftStickY { get; protected set; } public TwoAxisInputControl LeftStick { get; protected set; } public OneAxisInputControl RightStickX { get; protected set; } public OneAxisInputControl RightStickY { get; protected set; } public TwoAxisInputControl RightStick { get; protected set; } public OneAxisInputControl DPadX { get; protected set; } public OneAxisInputControl DPadY { get; protected set; } public TwoAxisInputControl DPad { get; protected set; } public InputControl Command { get; protected set; } public bool IsAttached { get; internal set; } public InputDevice( string name ) { Name = name; Meta = ""; LastChangeTick = 0; const int numInputControlTypes = (int) InputControlType.Count + 1; Controls = new InputControl[numInputControlTypes]; LeftStickX = new OneAxisInputControl(); LeftStickY = new OneAxisInputControl(); LeftStick = new TwoAxisInputControl(); RightStickX = new OneAxisInputControl(); RightStickY = new OneAxisInputControl(); RightStick = new TwoAxisInputControl(); DPadX = new OneAxisInputControl(); DPadY = new OneAxisInputControl(); DPad = new TwoAxisInputControl(); Command = AddControl( InputControlType.Command, "Command" ); } public bool HasControl( InputControlType inputControlType ) { return Controls[(int) inputControlType] != null; } public InputControl GetControl( InputControlType inputControlType ) { var control = Controls[(int) inputControlType]; return control ?? InputControl.Null; } // Warning: this is super inefficient. Don't use it unless you have to, m'kay? public static InputControlType GetInputControlTypeByName( string inputControlName ) { return (InputControlType) Enum.Parse( typeof(InputControlType), inputControlName ); } // Warning: this is super inefficient. Don't use it unless you have to, m'kay? public InputControl GetControlByName( string inputControlName ) { var inputControlType = GetInputControlTypeByName( inputControlName ); return GetControl( inputControlType ); } public InputControl AddControl( InputControlType inputControlType, string handle ) { var inputControl = new InputControl( handle, inputControlType ); Controls[(int) inputControlType] = inputControl; return inputControl; } public InputControl AddControl( InputControlType inputControlType, string handle, float lowerDeadZone, float upperDeadZone ) { var inputControl = AddControl( inputControlType, handle ); inputControl.LowerDeadZone = lowerDeadZone; inputControl.UpperDeadZone = upperDeadZone; return inputControl; } internal void UpdateWithState( InputControlType inputControlType, bool state, ulong updateTick, float deltaTime ) { GetControl( inputControlType ).UpdateWithState( state, updateTick, deltaTime ); } internal void UpdateWithValue( InputControlType inputControlType, float value, ulong updateTick, float deltaTime ) { GetControl( inputControlType ).UpdateWithValue( value, updateTick, deltaTime ); } internal void UpdateLeftStickWithValue( Vector2 value, ulong updateTick, float deltaTime ) { LeftStickLeft.UpdateWithValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); LeftStickRight.UpdateWithValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { LeftStickUp.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { LeftStickUp.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void CommitLeftStick() { LeftStickUp.Commit(); LeftStickDown.Commit(); LeftStickLeft.Commit(); LeftStickRight.Commit(); } internal void UpdateRightStickWithValue( Vector2 value, ulong updateTick, float deltaTime ) { RightStickLeft.UpdateWithValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); RightStickRight.UpdateWithValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { RightStickUp.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { RightStickUp.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void CommitRightStick() { RightStickUp.Commit(); RightStickDown.Commit(); RightStickLeft.Commit(); RightStickRight.Commit(); } public virtual void Update( ulong updateTick, float deltaTime ) { // Implemented by subclasses. } bool AnyCommandControlIsPressed() { for (int i = (int) InputControlType.Back; i <= (int) InputControlType.Power; i++) { var control = Controls[i]; if (control != null && control.IsPressed) { return true; } } return false; } internal void ProcessLeftStick( ulong updateTick, float deltaTime ) { var lowerDeadZone = Utility.Max( LeftStickLeft.LowerDeadZone, LeftStickRight.LowerDeadZone, LeftStickUp.LowerDeadZone, LeftStickDown.LowerDeadZone ); var upperDeadZone = Utility.Min( LeftStickLeft.UpperDeadZone, LeftStickRight.UpperDeadZone, LeftStickUp.UpperDeadZone, LeftStickDown.UpperDeadZone ); var x = Utility.ValueFromSides( LeftStickLeft.NextRawValue, LeftStickRight.NextRawValue ); var y = Utility.ValueFromSides( LeftStickDown.NextRawValue, LeftStickUp.NextRawValue, InputManager.InvertYAxis ); var v = Utility.ApplyCircularDeadZone( x, y, lowerDeadZone, upperDeadZone ); LeftStick.Raw = true; LeftStick.UpdateWithAxes( v.x, v.y, updateTick, deltaTime ); LeftStickX.Raw = true; LeftStickX.CommitWithValue( v.x, updateTick, deltaTime ); LeftStickY.Raw = true; LeftStickY.CommitWithValue( v.y, updateTick, deltaTime ); LeftStickLeft.SetValue( LeftStick.Left.Value, updateTick ); LeftStickRight.SetValue( LeftStick.Right.Value, updateTick ); LeftStickUp.SetValue( LeftStick.Up.Value, updateTick ); LeftStickDown.SetValue( LeftStick.Down.Value, updateTick ); } internal void ProcessRightStick( ulong updateTick, float deltaTime ) { var lowerDeadZone = Utility.Max( RightStickLeft.LowerDeadZone, RightStickRight.LowerDeadZone, RightStickUp.LowerDeadZone, RightStickDown.LowerDeadZone ); var upperDeadZone = Utility.Min( RightStickLeft.UpperDeadZone, RightStickRight.UpperDeadZone, RightStickUp.UpperDeadZone, RightStickDown.UpperDeadZone ); var x = Utility.ValueFromSides( RightStickLeft.NextRawValue, RightStickRight.NextRawValue ); var y = Utility.ValueFromSides( RightStickDown.NextRawValue, RightStickUp.NextRawValue, InputManager.InvertYAxis ); var v = Utility.ApplyCircularDeadZone( x, y, lowerDeadZone, upperDeadZone ); RightStick.Raw = true; RightStick.UpdateWithAxes( v.x, v.y, updateTick, deltaTime ); RightStickX.Raw = true; RightStickX.CommitWithValue( v.x, updateTick, deltaTime ); RightStickY.Raw = true; RightStickY.CommitWithValue( v.y, updateTick, deltaTime ); RightStickLeft.SetValue( RightStick.Left.Value, updateTick ); RightStickRight.SetValue( RightStick.Right.Value, updateTick ); RightStickUp.SetValue( RightStick.Up.Value, updateTick ); RightStickDown.SetValue( RightStick.Down.Value, updateTick ); } internal void ProcessDPad( ulong updateTick, float deltaTime ) { var lowerDeadZone = Utility.Max( DPadLeft.LowerDeadZone, DPadRight.LowerDeadZone, DPadUp.LowerDeadZone, DPadDown.LowerDeadZone ); var upperDeadZone = Utility.Min( DPadLeft.UpperDeadZone, DPadRight.UpperDeadZone, DPadUp.UpperDeadZone, DPadDown.UpperDeadZone ); var x = Utility.ValueFromSides( DPadLeft.NextRawValue, DPadRight.NextRawValue ); var y = Utility.ValueFromSides( DPadDown.NextRawValue, DPadUp.NextRawValue, InputManager.InvertYAxis ); var v = Utility.ApplyCircularDeadZone( x, y, lowerDeadZone, upperDeadZone ); DPad.Raw = true; DPad.UpdateWithAxes( v.x, v.y, updateTick, deltaTime ); DPadX.Raw = true; DPadX.CommitWithValue( v.x, updateTick, deltaTime ); DPadY.Raw = true; DPadY.CommitWithValue( v.y, updateTick, deltaTime ); DPadLeft.SetValue( DPad.Left.Value, updateTick ); DPadRight.SetValue( DPad.Right.Value, updateTick ); DPadUp.SetValue( DPad.Up.Value, updateTick ); DPadDown.SetValue( DPad.Down.Value, updateTick ); } public void Commit( ulong updateTick, float deltaTime ) { // We need to do some processing to ensure all the various objects // holding directional values are calculated optimally with circular // deadzones and then set properly everywhere. ProcessLeftStick( updateTick, deltaTime ); ProcessRightStick( updateTick, deltaTime ); ProcessDPad( updateTick, deltaTime ); // Next, commit all control values. int controlCount = Controls.Length; for (int i = 0; i < controlCount; i++) { var control = Controls[i]; if (control != null) { control.Commit(); if (control.HasChanged) { LastChangeTick = updateTick; } } } // Calculate the "Command" control for known controllers and commit it. if (IsKnown) { Command.CommitWithState( AnyCommandControlIsPressed(), updateTick, deltaTime ); } } public bool LastChangedAfter( InputDevice otherDevice ) { return LastChangeTick > otherDevice.LastChangeTick; } internal void RequestActivation() { LastChangeTick = InputManager.CurrentTick; } public virtual void Vibrate( float leftMotor, float rightMotor ) { } public void Vibrate( float intensity ) { Vibrate( intensity, intensity ); } public virtual bool IsSupportedOnThisPlatform { get { return true; } } public virtual bool IsKnown { get { return true; } } public bool IsUnknown { get { return !IsKnown; } } public bool MenuWasPressed { get { return GetControl( InputControlType.Command ).WasPressed; } } public InputControl AnyButton { get { int controlCount = Controls.GetLength( 0 ); for (int i = 0; i < controlCount; i++) { var control = Controls[i]; if (control != null && control.IsButton && control.IsPressed) { return control; } } return InputControl.Null; } } public InputControl LeftStickUp { get { return GetControl( InputControlType.LeftStickUp ); } } public InputControl LeftStickDown { get { return GetControl( InputControlType.LeftStickDown ); } } public InputControl LeftStickLeft { get { return GetControl( InputControlType.LeftStickLeft ); } } public InputControl LeftStickRight { get { return GetControl( InputControlType.LeftStickRight ); } } public InputControl RightStickUp { get { return GetControl( InputControlType.RightStickUp ); } } public InputControl RightStickDown { get { return GetControl( InputControlType.RightStickDown ); } } public InputControl RightStickLeft { get { return GetControl( InputControlType.RightStickLeft ); } } public InputControl RightStickRight { get { return GetControl( InputControlType.RightStickRight ); } } public InputControl DPadUp { get { return GetControl( InputControlType.DPadUp ); } } public InputControl DPadDown { get { return GetControl( InputControlType.DPadDown ); } } public InputControl DPadLeft { get { return GetControl( InputControlType.DPadLeft ); } } public InputControl DPadRight { get { return GetControl( InputControlType.DPadRight ); } } public InputControl Action1 { get { return GetControl( InputControlType.Action1 ); } } public InputControl Action2 { get { return GetControl( InputControlType.Action2 ); } } public InputControl Action3 { get { return GetControl( InputControlType.Action3 ); } } public InputControl Action4 { get { return GetControl( InputControlType.Action4 ); } } public InputControl LeftTrigger { get { return GetControl( InputControlType.LeftTrigger ); } } public InputControl RightTrigger { get { return GetControl( InputControlType.RightTrigger ); } } public InputControl LeftBumper { get { return GetControl( InputControlType.LeftBumper ); } } public InputControl RightBumper { get { return GetControl( InputControlType.RightBumper ); } } public InputControl LeftStickButton { get { return GetControl( InputControlType.LeftStickButton ); } } public InputControl RightStickButton { get { return GetControl( InputControlType.RightStickButton ); } } public TwoAxisInputControl Direction { get { return DPad.UpdateTick > LeftStick.UpdateTick ? DPad : LeftStick; } } public static implicit operator bool( InputDevice device ) { return device != null; } } }
/* * 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.Reflection; using System.Collections.Generic; using log4net; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { /// <summary> /// Circuit data for an agent. Connection information shared between /// regions that accept UDP connections from a client /// </summary> public class AgentCircuitData { // DEBUG ON private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // DEBUG OFF /// <summary> /// Avatar Unique Agent Identifier /// </summary> public UUID AgentID; /// <summary> /// Avatar's Appearance /// </summary> public AvatarAppearance Appearance; /// <summary> /// Agent's root inventory folder /// </summary> public UUID BaseFolder; /// <summary> /// Base Caps path for user /// </summary> public string CapsPath = String.Empty; /// <summary> /// Seed caps for neighbor regions that the user can see into /// </summary> public Dictionary<ulong, string> ChildrenCapSeeds; /// <summary> /// Root agent, or Child agent /// </summary> public bool child; /// <summary> /// Number given to the client when they log-in that they provide /// as credentials to the UDP server /// </summary> public uint circuitcode; /// <summary> /// How this agent got here /// </summary> public uint teleportFlags; /// <summary> /// Agent's account first name /// </summary> public string firstname; public UUID InventoryFolder; /// <summary> /// Agent's account last name /// </summary> public string lastname; /// <summary> /// Agent's full name. /// </summary> public string Name { get { return string.Format("{0} {1}", firstname, lastname); } } /// <summary> /// Random Unique GUID for this session. Client gets this at login and it's /// only supposed to be disclosed over secure channels /// </summary> public UUID SecureSessionID; /// <summary> /// Non secure Session ID /// </summary> public UUID SessionID; /// <summary> /// Hypergrid service token; generated by the user domain, consumed by the receiving grid. /// There is one such unique token for each grid visited. /// </summary> public string ServiceSessionID = string.Empty; /// <summary> /// The client's IP address, as captured by the login service /// </summary> public string IPAddress; /// <summary> /// Viewer's version string as reported by the viewer at login /// </summary> private string m_viewerInternal; /// <summary> /// Viewer's version string /// </summary> public string Viewer { set { m_viewerInternal = value; } // Try to return consistent viewer string taking into account // that viewers have chaagned how version is reported // See http://opensimulator.org/mantis/view.php?id=6851 get { // Old style version string contains viewer name followed by a space followed by a version number if (m_viewerInternal == null || m_viewerInternal.Contains(" ")) { return m_viewerInternal; } else // New style version contains no spaces, just version number { return Channel + " " + m_viewerInternal; } } } /// <summary> /// The channel strinf sent by the viewer at login /// </summary> public string Channel; /// <summary> /// The Mac address as reported by the viewer at login /// </summary> public string Mac; /// <summary> /// The id0 as reported by the viewer at login /// </summary> public string Id0; /// <summary> /// Position the Agent's Avatar starts in the region /// </summary> public Vector3 startpos; public Dictionary<string, object> ServiceURLs; public AgentCircuitData() { } /// <summary> /// Pack AgentCircuitData into an OSDMap for transmission over LLSD XML or LLSD json /// </summary> /// <returns>map of the agent circuit data</returns> public OSDMap PackAgentCircuitData(EntityTransferContext ctx) { OSDMap args = new OSDMap(); args["agent_id"] = OSD.FromUUID(AgentID); args["base_folder"] = OSD.FromUUID(BaseFolder); args["caps_path"] = OSD.FromString(CapsPath); if (ChildrenCapSeeds != null) { OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count); foreach (KeyValuePair<ulong, string> kvp in ChildrenCapSeeds) { OSDMap pair = new OSDMap(); pair["handle"] = OSD.FromString(kvp.Key.ToString()); pair["seed"] = OSD.FromString(kvp.Value); childrenSeeds.Add(pair); } if (ChildrenCapSeeds.Count > 0) args["children_seeds"] = childrenSeeds; } args["child"] = OSD.FromBoolean(child); args["circuit_code"] = OSD.FromString(circuitcode.ToString()); args["first_name"] = OSD.FromString(firstname); args["last_name"] = OSD.FromString(lastname); args["inventory_folder"] = OSD.FromUUID(InventoryFolder); args["secure_session_id"] = OSD.FromUUID(SecureSessionID); args["session_id"] = OSD.FromUUID(SessionID); args["service_session_id"] = OSD.FromString(ServiceSessionID); args["start_pos"] = OSD.FromString(startpos.ToString()); args["client_ip"] = OSD.FromString(IPAddress); args["viewer"] = OSD.FromString(Viewer); args["channel"] = OSD.FromString(Channel); args["mac"] = OSD.FromString(Mac); args["id0"] = OSD.FromString(Id0); if (Appearance != null) { args["appearance_serial"] = OSD.FromInteger(Appearance.Serial); OSDMap appmap = Appearance.Pack(ctx); args["packed_appearance"] = appmap; } // Old, bad way. Keeping it fow now for backwards compatibility // OBSOLETE -- soon to be deleted if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDArray urls = new OSDArray(ServiceURLs.Count * 2); foreach (KeyValuePair<string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls.Add(OSD.FromString(kvp.Key)); urls.Add(OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString())); } args["service_urls"] = urls; } // again, this time the right way if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDMap urls = new OSDMap(); foreach (KeyValuePair<string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls[kvp.Key] = OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString()); } args["serviceurls"] = urls; } return args; } /// <summary> /// Unpack agent circuit data map into an AgentCiruitData object /// </summary> /// <param name="args"></param> public void UnpackAgentCircuitData(OSDMap args) { if (args["agent_id"] != null) AgentID = args["agent_id"].AsUUID(); if (args["base_folder"] != null) BaseFolder = args["base_folder"].AsUUID(); if (args["caps_path"] != null) CapsPath = args["caps_path"].AsString(); if ((args["children_seeds"] != null) && (args["children_seeds"].Type == OSDType.Array)) { OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]); ChildrenCapSeeds = new Dictionary<ulong, string>(); foreach (OSD o in childrenSeeds) { if (o.Type == OSDType.Map) { ulong handle = 0; string seed = ""; OSDMap pair = (OSDMap)o; if (pair["handle"] != null) if (!UInt64.TryParse(pair["handle"].AsString(), out handle)) continue; if (pair["seed"] != null) seed = pair["seed"].AsString(); if (!ChildrenCapSeeds.ContainsKey(handle)) ChildrenCapSeeds.Add(handle, seed); } } } else ChildrenCapSeeds = new Dictionary<ulong, string>(); if (args["child"] != null) child = args["child"].AsBoolean(); if (args["circuit_code"] != null) UInt32.TryParse(args["circuit_code"].AsString(), out circuitcode); if (args["first_name"] != null) firstname = args["first_name"].AsString(); if (args["last_name"] != null) lastname = args["last_name"].AsString(); if (args["inventory_folder"] != null) InventoryFolder = args["inventory_folder"].AsUUID(); if (args["secure_session_id"] != null) SecureSessionID = args["secure_session_id"].AsUUID(); if (args["session_id"] != null) SessionID = args["session_id"].AsUUID(); if (args["service_session_id"] != null) ServiceSessionID = args["service_session_id"].AsString(); if (args["client_ip"] != null) IPAddress = args["client_ip"].AsString(); if (args["viewer"] != null) Viewer = args["viewer"].AsString(); if (args["channel"] != null) Channel = args["channel"].AsString(); if (args["mac"] != null) Mac = args["mac"].AsString(); if (args["id0"] != null) Id0 = args["id0"].AsString(); if (args["teleport_flags"] != null) teleportFlags = args["teleport_flags"].AsUInteger(); if (args["start_pos"] != null) Vector3.TryParse(args["start_pos"].AsString(), out startpos); //m_log.InfoFormat("[AGENTCIRCUITDATA]: agentid={0}, child={1}, startpos={2}", AgentID, child, startpos); try { // Unpack various appearance elements Appearance = new AvatarAppearance(); // Eventually this code should be deprecated, use full appearance // packing in packed_appearance if (args["appearance_serial"] != null) Appearance.Serial = args["appearance_serial"].AsInteger(); if (args.ContainsKey("packed_appearance") && (args["packed_appearance"].Type == OSDType.Map)) { Appearance.Unpack((OSDMap)args["packed_appearance"]); // m_log.InfoFormat("[AGENTCIRCUITDATA] unpacked appearance"); } else { m_log.Warn("[AGENTCIRCUITDATA]: failed to find a valid packed_appearance"); } } catch (Exception e) { m_log.ErrorFormat("[AGENTCIRCUITDATA] failed to unpack appearance; {0}",e.Message); } ServiceURLs = new Dictionary<string, object>(); // Try parse the new way, OSDMap if (args.ContainsKey("serviceurls") && args["serviceurls"] != null && (args["serviceurls"]).Type == OSDType.Map) { OSDMap urls = (OSDMap)(args["serviceurls"]); foreach (KeyValuePair<String, OSD> kvp in urls) { ServiceURLs[kvp.Key] = kvp.Value.AsString(); //System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]); } } // else try the old way, OSDArray // OBSOLETE -- soon to be deleted else if (args.ContainsKey("service_urls") && args["service_urls"] != null && (args["service_urls"]).Type == OSDType.Array) { OSDArray urls = (OSDArray)(args["service_urls"]); for (int i = 0; i < urls.Count / 2; i++) { ServiceURLs[urls[i * 2].AsString()] = urls[(i * 2) + 1].AsString(); //System.Console.WriteLine("XXX " + urls[i * 2].AsString() + "=" + urls[(i * 2) + 1].AsString()); } } } } }
//----------------------------------------------------------------------- // <copyright file="FileSourceSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using Akka.Actor; using Akka.IO; using Akka.Streams.Dsl; using Akka.Streams.Implementation; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.IO { public class FileSourceSpec : AkkaSpec { private readonly string _testText = ""; private readonly ActorMaterializer _materializer; private readonly FileInfo _testFilePath = new FileInfo(Path.Combine(Path.GetTempPath(), "file-source-spec.tmp")); private FileInfo _manyLinesPath; public FileSourceSpec(ITestOutputHelper helper) : base(Utils.UnboundedMailboxConfig, helper) { Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig()); var settings = ActorMaterializerSettings.Create(Sys).WithDispatcher("akka.actor.default-dispatcher"); _materializer = Sys.Materializer(settings); var sb = new StringBuilder(6000); foreach (var character in new[] { "a", "b", "c", "d", "e", "f" }) for (var i = 0; i < 1000; i++) sb.Append(character); _testText = sb.ToString(); } [Fact] public void FileSource_should_read_contents_from_a_file() { this.AssertAllStagesStopped(() => { var chunkSize = 512; var bufferAttributes = Attributes.CreateInputBuffer(1, 2); var p = FileIO.FromFile(TestFile(), chunkSize) .WithAttributes(bufferAttributes) .RunWith(Sink.AsPublisher<ByteString>(false), _materializer); var c = this.CreateManualProbe<ByteString>(); p.Subscribe(c); var sub = c.ExpectSubscription(); var remaining = _testText; var nextChunk = new Func<string>(() => { string chunks; if (remaining.Length <= chunkSize) { chunks = remaining; remaining = string.Empty; } else { chunks = remaining.Substring(0, chunkSize); remaining = remaining.Substring(chunkSize); } return chunks; }); sub.Request(1); c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); sub.Request(1); c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); c.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); sub.Request(200); var expectedChunk = nextChunk(); while (!string.IsNullOrEmpty(expectedChunk)) { var actual = c.ExpectNext().DecodeString(Encoding.UTF8); actual.Should().Be(expectedChunk); expectedChunk = nextChunk(); } sub.Request(1); c.ExpectComplete(); }, _materializer); } [Fact] public void FileSource_should_complete_only_when_all_contents_of_a_file_have_been_signalled() { this.AssertAllStagesStopped(() => { var chunkSize = 512; var bufferAttributes = Attributes.CreateInputBuffer(1, 2); var demandAllButOnechunks = _testText.Length / chunkSize - 1; var p = FileIO.FromFile(TestFile(), chunkSize) .WithAttributes(bufferAttributes) .RunWith(Sink.AsPublisher<ByteString>(false), _materializer); var c = this.CreateManualProbe<ByteString>(); p.Subscribe(c); var sub = c.ExpectSubscription(); var remaining = _testText; var nextChunk = new Func<string>(() => { string chunks; if (remaining.Length <= chunkSize) { chunks = remaining; remaining = string.Empty; } else { chunks = remaining.Substring(0, chunkSize); remaining = remaining.Substring(chunkSize); } return chunks; }); sub.Request(demandAllButOnechunks); for (var i = 0; i < demandAllButOnechunks; i++) c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); c.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); sub.Request(1); c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); c.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); sub.Request(1); c.ExpectNext().DecodeString(Encoding.UTF8).Should().Be(nextChunk()); c.ExpectComplete(); }, _materializer); } [Fact] public void FileSource_should_onError_when_trying_to_read_from_file_which_does_not_exist() { this.AssertAllStagesStopped(() => { var p = FileIO.FromFile(NotExistingFile()).RunWith(Sink.AsPublisher<ByteString>(false), _materializer); var c = this.CreateManualProbe<ByteString>(); p.Subscribe(c); c.ExpectSubscription(); c.ExpectError(); }, _materializer); } [Theory] [InlineData(512, 2)] [InlineData(512, 4)] [InlineData(2048, 2)] [InlineData(2048, 4)] public void FileSource_should_count_lines_in_a_real_file(int chunkSize, int readAhead) { var s = FileIO.FromFile(ManyLines(), chunkSize) .WithAttributes(Attributes.CreateInputBuffer(readAhead, readAhead)); var f = s.RunWith( Sink.Aggregate<ByteString, int>(0, (acc, l) => acc + l.DecodeString(Encoding.UTF8).Count(c => c == '\n')), _materializer); f.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var lineCount = f.Result; lineCount.Should().Be(LinesCount); } [Fact] public void FileSource_should_use_dedicated_blocking_io_dispatcher_by_default() { this.AssertAllStagesStopped(() => { var sys = ActorSystem.Create("dispatcher-testing", Utils.UnboundedMailboxConfig); var materializer = sys.Materializer(); try { var p = FileIO.FromFile(ManyLines()).RunWith(this.SinkProbe<ByteString>(), materializer); (materializer as ActorMaterializerImpl).Supervisor.Tell(StreamSupervisor.GetChildren.Instance, TestActor); var actorRef = ExpectMsg<StreamSupervisor.Children>().Refs.First(r => r.Path.ToString().Contains("fileSource")); try { Utils.AssertDispatcher(actorRef, "akka.stream.default-blocking-io-dispatcher"); } finally { p.Cancel(); } } finally { Shutdown(sys); } }, _materializer); } [Fact(Skip = "overriding dispatcher should be made available with dispatcher alias support in materializer (#17929)")] //FIXME: overriding dispatcher should be made available with dispatcher alias support in materializer (#17929) public void FileSource_should_should_allow_overriding_the_dispather_using_Attributes() { var sys = ActorSystem.Create("dispatcher-testing", Utils.UnboundedMailboxConfig); var materializer = sys.Materializer(); try { var p = FileIO.FromFile(ManyLines()) .WithAttributes(ActorAttributes.CreateDispatcher("akka.actor.default-dispatcher")) .RunWith(this.SinkProbe<ByteString>(), materializer); (materializer as ActorMaterializerImpl).Supervisor.Tell(StreamSupervisor.GetChildren.Instance, TestActor); var actorRef = ExpectMsg<StreamSupervisor.Children>().Refs.First(r => r.Path.ToString().Contains("File")); try { Utils.AssertDispatcher(actorRef, "akka.actor.default-dispatcher"); } finally { p.Cancel(); } } finally { Shutdown(sys); } } private int LinesCount { get; } = 2000 + new Random().Next(300); private FileInfo ManyLines() { _manyLinesPath = new FileInfo(Path.Combine(Path.GetTempPath(), $"file-source-spec-lines_{LinesCount}.tmp")); var line = ""; var lines = new List<string>(); for (var i = 0; i < LinesCount; i++) line += "a"; for (var i = 0; i < LinesCount; i++) lines.Add(line); File.AppendAllLines(_manyLinesPath.FullName, lines); return _manyLinesPath; } private FileInfo TestFile() { File.AppendAllText(_testFilePath.FullName, _testText); return _testFilePath; } private FileInfo NotExistingFile() { var f = new FileInfo(Path.Combine(Path.GetTempPath(), "not-existing-file.tmp")); if (f.Exists) f.Delete(); return f; } protected override void AfterAll() { base.AfterAll(); //give the system enough time to shutdown and release the file handle Thread.Sleep(500); _manyLinesPath?.Delete(); _testFilePath?.Delete(); } } }
#region License /* * Copyright 2002-2010 the original author or 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. */ #endregion using System; using System.Collections; using NUnit.Framework; using Spring.Core; using Spring.Globalization.Formatters; using Spring.Validation; namespace Spring.DataBinding { /// <summary> /// Test cases for the BaseBindingManager. /// </summary> /// <author>Aleksandar Seovic</author> [TestFixture] public class BaseBindingManagerTests { private BaseBindingManager mgr; [OneTimeSetUp] public void SetUp() { mgr = new BaseBindingManager(); mgr.AddBinding("['name']", "Name"); mgr.AddBinding("['dob']", "DOB"); mgr.AddBinding("['dateofgraduation']", "DateOfGraduation"); mgr.AddBinding("['inventions']", "Inventions"); mgr.AddBinding("['cityOfBirth']", "PlaceOfBirth.City"); mgr.AddBinding("['countryOfBirth']", "PlaceOfBirth.Country"); } [Test] public void WithoutTypeConversion() { Hashtable source = new Hashtable(); Inventor target = new Inventor(); source["name"] = "Nikola Tesla"; source["dob"] = new DateTime(1856, 7, 9); // I know this is pupin's graduation year but I need a date here source["dateofgraduation"] = new DateTime(1883,1,1); source["inventions"] = new string[] {"One", "Two"}; mgr.BindSourceToTarget(source, target, null); Assert.IsTrue(mgr.HasBindings); Assert.AreEqual("Nikola Tesla", target.Name); Assert.AreEqual(new DateTime(1856, 7, 9), target.DOB); Assert.AreEqual(new string[] {"One", "Two"}, target.Inventions); Assert.IsNull(target.PlaceOfBirth.City); Assert.IsNull(target.PlaceOfBirth.Country); target.Name = "Tesla, Nikola"; target.DOB = DateTime.Today; target.PlaceOfBirth.City = "Smiljan"; target.PlaceOfBirth.Country = "Lika"; mgr.BindTargetToSource(source, target, null); Assert.AreEqual("Tesla, Nikola", source["name"]); Assert.AreEqual(DateTime.Today, source["dob"]); Assert.AreEqual("One", ((string[]) source["inventions"])[0]); Assert.AreEqual("Smiljan", source["cityOfBirth"]); Assert.AreEqual("Lika", source["countryOfBirth"]); } [Test] public void WithTypeConversion() { Hashtable source = new Hashtable(); Inventor target = new Inventor(); source["name"] = "Nikola Tesla"; source["dob"] = "1856-7-9"; source["inventions"] = "One,Two"; // I know this is pupin's graduation year but I need a date here source["dateofgraduation"] = "1883-1-1"; mgr.BindSourceToTarget(source, target, null); Assert.IsTrue(mgr.HasBindings); Assert.AreEqual("Nikola Tesla", target.Name); Assert.AreEqual(new DateTime(1856, 7, 9), target.DOB); Assert.AreEqual(new string[] {"One", "Two"}, target.Inventions); Assert.IsNull(target.PlaceOfBirth.City); Assert.IsNull(target.PlaceOfBirth.Country); target.Name = "Tesla, Nikola"; target.DOB = DateTime.Today; target.PlaceOfBirth.City = "Smiljan"; target.PlaceOfBirth.Country = "Lika"; mgr.BindTargetToSource(source, target, null); Assert.AreEqual("Tesla, Nikola", source["name"]); Assert.AreEqual(DateTime.Today, source["dob"]); Assert.AreEqual("One", ((string[]) source["inventions"])[0]); Assert.AreEqual("Smiljan", source["cityOfBirth"]); Assert.AreEqual("Lika", source["countryOfBirth"]); } [Test] public void BindNullValues() { Hashtable source; Inventor target; target = new Inventor(); source = new Hashtable(); // this is legal (dog is nullable) BaseBindingManager mgr = new BaseBindingManager(); mgr.AddBinding("['dateofgraduation']", "DateOfGraduation"); source["dateofgraduation"] = null; target.DateOfGraduation = DateTime.Now; mgr.BindSourceToTarget(source, target, null); Assert.IsNull(target.DateOfGraduation); source["dateofgraduation"] = DateTime.Now; mgr.BindTargetToSource(source, target, null); Assert.IsNull(source["dateofgraduation"]); } [Test] public void BindNullValuesWithFormatter() { Hashtable source; Inventor target; target = new Inventor(); source = new Hashtable(); // this is legal (dog is nullable) BaseBindingManager mgr = new BaseBindingManager(); mgr.AddBinding("['dateofgraduation']", "DateOfGraduation", new HasTextFilteringFormatter(null, null)); source["dateofgraduation"] = string.Empty; target.DateOfGraduation = DateTime.Now; mgr.BindSourceToTarget(source, target, null); Assert.IsNull(target.DateOfGraduation); } [Test] public void UnhandledTypeConversionExceptionSourceToTarget() { BaseBindingManager dbm = new BaseBindingManager(); Hashtable source = new Hashtable(); source["boolValue"] = false; Inventor target = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); dbm.AddBinding("['boolValue']", "DOB"); try { dbm.BindSourceToTarget(source, target, null); Assert.Fail("Binding boolean to date should throw an exception."); } catch (TypeMismatchException) {} // binding state is not remembered with ValidationErrors=null! dbm.BindTargetToSource(source, target, null); Assert.AreEqual(target.DOB, source["boolValue"]); } [Test] public void UnhandledTypeConversionExceptionTargetToSource() { BaseBindingManager dbm = new BaseBindingManager(); Inventor st = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); st.Inventions = new string[] {"Invention One", "Invention Two"}; dbm.AddBinding("pob", "DOB"); try { dbm.BindTargetToSource(st, st, null); Assert.Fail("Binding date to custom Place type should throw an exception."); } catch (TypeMismatchException) {} // binding state is not remembered with ValidationErrors=null! try { dbm.BindSourceToTarget(st, st, null); Assert.Fail("Binding custom Place to date type should throw an exception."); } catch (TypeMismatchException) {} } [Test] public void HandledTypeConversionExceptionSourceToTarget() { BaseBindingManager dbm = new BaseBindingManager(); IValidationErrors errors = new ValidationErrors(); Hashtable source = new Hashtable(); source["boolValue"] = false; Inventor target = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); SimpleExpressionBinding binding = new SimpleExpressionBinding("['boolValue']", "DOB"); binding.SetErrorMessage("error", "errors"); dbm.AddBinding(binding); dbm.BindSourceToTarget(source, target, errors); Assert.IsFalse(binding.IsValid(errors)); Assert.IsFalse(errors.IsEmpty); Assert.AreEqual(1, errors.GetErrors("errors").Count); // make sure that the old value doesn't override current invalid value dbm.BindTargetToSource(source, target, errors); Assert.AreEqual(false, source["boolValue"]); } [Test] public void HandledTypeConversionExceptionTargetToSource() { BaseBindingManager dbm = new BaseBindingManager(); IValidationErrors errors = new ValidationErrors(); Inventor st = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); st.Inventions = new string[] {"Invention One", "Invention Two"}; SimpleExpressionBinding binding = new SimpleExpressionBinding("pob", "DOB"); binding.SetErrorMessage("error", "errors"); dbm.AddBinding(binding); dbm.BindTargetToSource(st, st, errors); Assert.IsFalse(binding.IsValid(errors)); Assert.IsFalse(errors.IsEmpty); Assert.AreEqual(1, errors.GetErrors("errors").Count); // make sure that the old value doesn't override current invalid value dbm.BindSourceToTarget(st, st, errors); Assert.AreEqual(new DateTime(1856, 7, 9), st.DOB); } [Test] public void DirectionSourceToTarget() { BaseBindingManager dbm = new BaseBindingManager(); Inventor source = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); Hashtable target = new Hashtable(); dbm.AddBinding("Name", "['name']", BindingDirection.SourceToTarget); dbm.BindSourceToTarget(source, target, null); Assert.AreEqual("Nikola Tesla", target["name"]); target["name"] = "Mihajlo Pupin"; dbm.BindTargetToSource(source, target, null); Assert.AreEqual("Nikola Tesla", source.Name); } [Test] public void DirectionTargetToSource() { BaseBindingManager dbm = new BaseBindingManager(); Inventor source = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); Hashtable target = new Hashtable(); dbm.AddBinding("Name", "['name']", BindingDirection.TargetToSource); dbm.BindSourceToTarget(source, target, null); Assert.IsNull(target["name"]); target["name"] = "Mihajlo Pupin"; dbm.BindTargetToSource(source, target, null); Assert.AreEqual("Mihajlo Pupin", source.Name); } // [Test] // public void ResetBindingStates() // { // BaseBindingManager dbm = new BaseBindingManager(); // Inventor source = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); // Hashtable target = new Hashtable(); // // dbm.AddBinding("Name", "['name']"); // dbm.AddBinding("WrongProperty", "['wrongproperty']"); // // try // { // dbm.BindSourceToTarget(source, target, null); // throw new AssertionException("should throw InvalidPropertyException"); // } catch(Spring.Objects.InvalidPropertyException) {} // ok // // // will ignore previously failed bindings - bindingState is false // dbm.BindSourceToTarget(source, target, null); // // // now reset states // dbm.ResetBindingStates(); // // // now throws again // try // { // dbm.BindSourceToTarget(source, target, null); // throw new AssertionException("should throw InvalidPropertyException"); // } // catch(Spring.Objects.InvalidPropertyException) {} // ok // } } }
//----------------------------------------------------------------------------- // Mictronics CAN<->USB interface driver // $Id$ //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Runtime.InteropServices; //using System.Diagnostics; using System.Linq; using System.IO.Ports; using Microsoft.Win32; namespace T5CANLib.CAN { //----------------------------------------------------------------------------- /** Wrapper for Mictronics CAN<->USB interface (see http://www.mictronics.de). */ public class MctCanDevice : ICANDevice { bool m_deviceIsOpen = false; SerialPort m_serialPort = new SerialPort(); private Thread m_readThread; Object m_synchObject = new Object(); bool m_endThread = false; private const char ESC = '\x1B'; private int m_forcedBaudrate = 115200; //private int m_forcedBaudrate = 921600; // internal state //private Thread read_thread; ///< reader thread //private bool term_requested = false; ///< thread termination flag //private Object term_mutex = new Object(); ///< mutex for termination flag //------------------------------------------------------------------------- /** Default constructor. */ public MctCanDevice() { // create reader thread //this.read_thread = new Thread(this.read_messages); //Debug.Assert(read_thread != null); } //------------------------------------------------------------------------- /** Destructor. */ ~MctCanDevice() { lock (m_synchObject) { m_endThread = true; } close(); } override public void EnableLogging(string path2log) { } override public void DisableLogging() { } public override float GetADCValue(uint channel) { return 0F; } // not supported by lawicel public override float GetThermoValue() { return 0F; } override public int GetNumberOfAdapters() { return 1; } public override void Delete() { } public override void setPortNumber(string portnumber) { //nothing to do } override public void clearTransmitBuffer() { // implement clearTransmitBuffer } override public void clearReceiveBuffer() { // implement clearReceiveBuffer } //------------------------------------------------------------------------- /** Opens a connection to CAN interface. @return result */ public override OpenResult open() { //Automatically find port with Just4Trionic //string port = MineRegistryForJust4TrionicPortName("SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0D28&PID_0204&MI_01"); string port = MineRegistryForJust4TrionicPortName("SYSTEM\\CurrentControlSet\\Enum\\USB"); m_serialPort.BaudRate = m_forcedBaudrate; m_serialPort.Handshake = Handshake.None; //m_serialPort.ReadBufferSize = 0x10000; m_serialPort.ReadTimeout = 100; if (port != null) { // only check this comport Console.WriteLine("Opening com: " + port); if (m_serialPort.IsOpen) m_serialPort.Close(); m_serialPort.PortName = port; try { m_serialPort.Open(); } catch (UnauthorizedAccessException) { return OpenResult.OpenError; } m_deviceIsOpen = true; m_serialPort.BreakState = true; //Reset mbed / Just4trionic m_serialPort.BreakState = false; // Thread.Sleep(1000); m_serialPort.Write("o\r"); // 'open' Just4trionic CAN interface Thread.Sleep(10); m_serialPort.Write("s2\r"); // Set Just4trionic CAN speed to 615,000 bits (T5-SFI) Thread.Sleep(10); this.Flush(); // Flush 'junk' in serial port buffers try { //m_serialPort.ReadLine(); Console.WriteLine("Connected to CAN at 615,000 speed"); //CastInformationEvent("Connected to CAN T5-SFI using " + port); //if (m_readThread != null) //{ // Console.WriteLine(m_readThread.ThreadState.ToString()); //} m_readThread = new Thread(readMessages); m_endThread = false; // reset for next tries :) if (m_readThread.ThreadState == ThreadState.Unstarted) m_readThread.Start(); m_serialPort.Write("f5\r"); // Set Just4trionic filter to allow only Trionic 5 messages Thread.Sleep(10); this.Flush(); // Flush 'junk' in serial port buffers return OpenResult.OK; } catch (Exception) { Console.WriteLine("Unable to connect to the T5 SFI"); } //CastInformationEvent("Oh dear :-( Just4Trionic cannot connect to a CAN bus."); this.close(); return OpenResult.OpenError; } //CastInformationEvent("Oh dear :-( Just4Trionic doesn't seem to be connected to your computer."); this.close(); return OpenResult.OpenError; } /// <summary> /// Recursively enumerates registry subkeys starting with strStartKey looking for /// "Device Parameters" subkey. If key is present, friendly port name is extracted. /// </summary> /// <param name="strStartKey">the start key from which to begin the enumeration</param> private string MineRegistryForJust4TrionicPortName(string strStartKey) { // string strStartKey = "SYSTEM\\CurrentControlSet\\Enum"; string[] oPortNamesToMatch = System.IO.Ports.SerialPort.GetPortNames(); Microsoft.Win32.RegistryKey oCurrentKey = Registry.LocalMachine.OpenSubKey(strStartKey); string[] oSubKeyNames = oCurrentKey.GetSubKeyNames(); object oFriendlyName = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + strStartKey, "FriendlyName", null); string strFriendlyName = (oFriendlyName != null) ? oFriendlyName.ToString() : "N/A"; if (strFriendlyName.StartsWith("mbed Serial Port")) { object oPortNameValue = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + strStartKey + "\\Device Parameters", "PortName", null); return oPortNamesToMatch.Contains(oPortNameValue.ToString()) ? oPortNameValue.ToString() : null; } else { foreach (string strSubKey in oSubKeyNames) if (MineRegistryForJust4TrionicPortName(strStartKey + "\\" + strSubKey) != null) return MineRegistryForJust4TrionicPortName(strStartKey + "\\" + strSubKey); } return null; } private void Flush() //public override void Flush() { if (m_deviceIsOpen) { m_serialPort.DiscardInBuffer(); m_serialPort.DiscardOutBuffer(); } } //------------------------------------------------------------------------- /** Determines if connection to CAN device is open. return open (true/false) */ public override bool isOpen() { return m_deviceIsOpen; } //------------------------------------------------------------------------- /** Closes the connection to CAN interface. return success (true/false) */ public override CloseResult close() { if (m_deviceIsOpen) { m_serialPort.Write("\x1B"); // mbed ESCape CAN interface m_serialPort.BreakState = true; // Reset mbed / Just4trionic m_serialPort.BreakState = false; // } // terminate thread? m_endThread = true; m_serialPort.Close(); m_deviceIsOpen = false; return CloseResult.OK; } //------------------------------------------------------------------------- /** Sends a 11 bit CAN data frame. @param message CAN message @return success (true/false) */ public override bool sendMessage(CANMessage a_message) { string sendString = "t"; sendString += a_message.getID().ToString("X3"); sendString += a_message.getLength().ToString("X1"); for (uint i = 0; i < a_message.getLength(); i++) // leave out the length field, the ELM chip assigns that for us { sendString += a_message.getCanData(i).ToString("X2"); } sendString += "\r"; if (m_serialPort.IsOpen) { //AddToCanTrace("TX: " + a_message.getID().ToString("X3") + " " + a_message.getLength().ToString("X1") + " " + a_message.getData().ToString("X16")); m_serialPort.Write(sendString); //Console.WriteLine("TX: " + sendString); } // bitrate = 38400bps -> 3840 bytes per second // sending each byte will take 0.2 ms approx //Thread.Sleep(a_message.getLength()); // sleep length ms // Thread.Sleep(10); Thread.Sleep(1); return true; // remove after implementation } //------------------------------------------------------------------------- /** Waits for any message to be received. @param timeout timeout @param msg message @return message ID if received, 0 otherwise */ private uint wait_message(uint timeout, out CANMessage msg) { msg = new CANMessage(); //Debug.Assert(msg != null); //int wait_cnt = 0; //uint id; //byte length; //ulong data; //while (wait_cnt < timeout) //{ // if (MctAdapter_ReceiveMessage(out id, out length, out data)) // { // // message received // msg.setID(id); // msg.setLength(length); // msg.setData(data); // return id; // } // // wait a bit // Thread.Sleep(1); // ++wait_cnt; //} //// nothing was received return 0; } //------------------------------------------------------------------------- /** Handles incoming messages. */ private void readMessages() { CANMessage canMessage = new CANMessage(); string rxMessage = string.Empty; Console.WriteLine("readMessages started"); while (true) { lock (m_synchObject) { if (m_endThread) { Console.WriteLine("readMessages ended"); return; } } try { if (m_serialPort.IsOpen) { do { rxMessage = m_serialPort.ReadLine(); rxMessage = rxMessage.Replace("\r", ""); // remove prompt characters... we don't need that stuff rxMessage = rxMessage.Replace("\n", ""); // remove prompt characters... we don't need that stuff } while (rxMessage.StartsWith("w") == false); uint id = Convert.ToUInt32(rxMessage.Substring(1, 3), 16); canMessage.setID(id); canMessage.setLength(8); canMessage.setData(0x0000000000000000); for (uint i = 0; i < 8; i++) canMessage.setCanData(Convert.ToByte(rxMessage.Substring(5 + (2 * (int)i), 2), 16), i); lock (m_listeners) { //AddToCanTrace("RX: " + canMessage.getID().ToString("X3") + " " + canMessage.getLength().ToString("X1") + " " + canMessage.getData().ToString("X16")); //Console.WriteLine("MSG: " + rxMessage); foreach (ICANListener listener in m_listeners) { listener.handleMessage(canMessage); } //CastInformationEvent(canMessage); // <GS-05042011> re-activated this function } // give up CPU for a moment Thread.Sleep(1); } } catch (Exception) { Console.WriteLine("MSG: " + rxMessage); } } } }; } // end namespace //----------------------------------------------------------------------------- // EOF //-----------------------------------------------------------------------------
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 383115 $ * $Date: 2006-10-30 12:09:11 -0700 (Mon, 30 Oct 2006) $ * * iBATIS.NET Data Mapper * Copyright (C) 2005 - Gilles Bayon * * * 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 IBatisNet.DataMapper.Scope; using System.Configuration; using System.Globalization; namespace IBatisNet.DataMapper.Commands { /// <summary> /// Decorate an <see cref="System.Data.IDataReader"></see> /// to auto move to next ResultMap on NextResult call. /// </summary> public class DataReaderDecorator : IDataReader { private IDataReader _innerDataReader = null; private RequestScope _request = null; /// <summary> /// Initializes a new instance of the <see cref="DataReaderDecorator"/> class. /// </summary> /// <param name="dataReader">The data reader.</param> /// <param name="request">The request scope</param> public DataReaderDecorator(IDataReader dataReader, RequestScope request) { _innerDataReader = dataReader; _request = request; } #region IDataReader Members /// <summary> /// Closes the <see cref="System.Data.IDataReader"></see> 0bject. /// </summary> void IDataReader.Close() { _innerDataReader.Close(); } /// <summary> /// Gets a value indicating the depth of nesting for the current row. /// </summary> /// <value></value> /// <returns>The level of nesting.</returns> int IDataReader.Depth { get { return _innerDataReader.Depth; } } /// <summary> /// Returns a <see cref="System.Data.DataTable"></see> that describes the column metadata of the <see cref="System.Data.IDataReader"></see>. /// </summary> /// <returns> /// A <see cref="System.Data.DataTable"></see> that describes the column metadata. /// </returns> /// <exception cref="System.InvalidOperationException">The <see cref="System.Data.IDataReader"></see> is closed. </exception> DataTable IDataReader.GetSchemaTable() { return _innerDataReader.GetSchemaTable(); } /// <summary> /// Gets a value indicating whether the data reader is closed. /// </summary> /// <value></value> /// <returns>true if the data reader is closed; otherwise, false.</returns> bool IDataReader.IsClosed { get { return _innerDataReader.IsClosed; } } /// <summary> /// Advances the data reader to the next result, when reading the results of batch SQL statements. /// </summary> /// <returns> /// true if there are more rows; otherwise, false. /// </returns> bool IDataReader.NextResult() { _request.MoveNextResultMap(); return _innerDataReader.NextResult(); } /// <summary> /// Advances the <see cref="System.Data.IDataReader"></see> to the next record. /// </summary> /// <returns> /// true if there are more rows; otherwise, false. /// </returns> bool IDataReader.Read() { return _innerDataReader.Read(); } int IDataReader.RecordsAffected { get { return _innerDataReader.RecordsAffected; } } #endregion #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { _innerDataReader.Dispose(); } #endregion #region IDataRecord Members /// <summary> /// Gets the number of columns in the current row. /// </summary> /// <value></value> /// <returns>When not positioned in a valid recordset, 0; otherwise the number of columns in the current record. The default is -1.</returns> int IDataRecord.FieldCount { get { return _innerDataReader.FieldCount; } } /// <summary> /// Gets the value of the specified column as a Boolean. /// </summary> /// <param name="i">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> bool IDataRecord.GetBoolean(int i) { return _innerDataReader.GetBoolean(i); } /// <summary> /// Gets the 8-bit unsigned integer value of the specified column. /// </summary> /// <param name="i">The zero-based column ordinal.</param> /// <returns> /// The 8-bit unsigned integer value of the specified column. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> byte IDataRecord.GetByte(int i) { return _innerDataReader.GetByte(i); } /// <summary> /// Reads a stream of bytes from the specified column offset into the buffer as an array, starting at the given buffer offset. /// </summary> /// <param name="i">The zero-based column ordinal.</param> /// <param name="fieldOffset">The index within the field from which to start the read operation.</param> /// <param name="buffer">The buffer into which to read the stream of bytes.</param> /// <param name="bufferoffset">The index for buffer to start the read operation.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>The actual number of bytes read.</returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> long IDataRecord.GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { return _innerDataReader.GetBytes(i, fieldOffset, buffer, bufferoffset, length); } /// <summary> /// Gets the character value of the specified column. /// </summary> /// <param name="i">The zero-based column ordinal.</param> /// <returns> /// The character value of the specified column. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> char IDataRecord.GetChar(int i) { return _innerDataReader.GetChar(i); } /// <summary> /// Reads a stream of characters from the specified column offset into the buffer as an array, starting at the given buffer offset. /// </summary> /// <param name="i">The zero-based column ordinal.</param> /// <param name="fieldoffset">The index within the row from which to start the read operation.</param> /// <param name="buffer">The buffer into which to read the stream of bytes.</param> /// <param name="bufferoffset">The index for buffer to start the read operation.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>The actual number of characters read.</returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> long IDataRecord.GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { return _innerDataReader.GetChars(i, fieldoffset, buffer, bufferoffset, length); } /// <summary> /// Gets an <see cref="System.Data.IDataReader"></see> to be used when the field points to more remote structured data. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// An <see cref="System.Data.IDataReader"></see> to be used when the field points to more remote structured data. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> IDataReader IDataRecord.GetData(int i) { return _innerDataReader.GetData(i); } /// <summary> /// Gets the data type information for the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The data type information for the specified field. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> string IDataRecord.GetDataTypeName(int i) { return _innerDataReader.GetDataTypeName(i); } /// <summary> /// Gets the date and time data value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The date and time data value of the spcified field. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> DateTime IDataRecord.GetDateTime(int i) { string dateTimeFormat = ConfigurationManager.AppSettings["dateTimeFormat"]; if ((!string.IsNullOrWhiteSpace(dateTimeFormat)) && (_innerDataReader.GetFieldType(i)==typeof(string))) { return DateTime.ParseExact(_innerDataReader.GetString(i), dateTimeFormat, CultureInfo.InvariantCulture); } return _innerDataReader.GetDateTime(i); } /// <summary> /// Gets the fixed-position numeric value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The fixed-position numeric value of the specified field. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> decimal IDataRecord.GetDecimal(int i) { return _innerDataReader.GetDecimal(i); } /// <summary> /// Gets the double-precision floating point number of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The double-precision floating point number of the specified field. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> double IDataRecord.GetDouble(int i) { return _innerDataReader.GetDouble(i); } /// <summary> /// Gets the <see cref="System.Type"></see> information corresponding to the type of <see cref="System.Object"></see> that would be returned from <see cref="M:System.Data.IDataRecord.GetValue(System.Int32)"></see>. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The <see cref="System.Type"></see> information corresponding to the type of <see cref="System.Object"></see> that would be returned from <see cref="M:System.Data.IDataRecord.GetValue(System.Int32)"></see>. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> Type IDataRecord.GetFieldType(int i) { return _innerDataReader.GetFieldType(i); } /// <summary> /// Gets the single-precision floating point number of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The single-precision floating point number of the specified field. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> float IDataRecord.GetFloat(int i) { return _innerDataReader.GetFloat(i); } /// <summary> /// Returns the GUID value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns>The GUID value of the specified field.</returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> Guid IDataRecord.GetGuid(int i) { return _innerDataReader.GetGuid(i); } /// <summary> /// Gets the 16-bit signed integer value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The 16-bit signed integer value of the specified field. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> short IDataRecord.GetInt16(int i) { return _innerDataReader.GetInt16(i); } /// <summary> /// Gets the 32-bit signed integer value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The 32-bit signed integer value of the specified field. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> int IDataRecord.GetInt32(int i) { return _innerDataReader.GetInt32(i); } /// <summary> /// Gets the 64-bit signed integer value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The 64-bit signed integer value of the specified field. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> long IDataRecord.GetInt64(int i) { return _innerDataReader.GetInt64(i); } /// <summary> /// Gets the name for the field to find. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The name of the field or the empty string (""), if there is no value to return. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> string IDataRecord.GetName(int i) { return _innerDataReader.GetName(i); } /// <summary> /// Return the index of the named field. /// </summary> /// <param name="name">The name of the field to find.</param> /// <returns>The index of the named field.</returns> int IDataRecord.GetOrdinal(string name) { return _innerDataReader.GetOrdinal(name); } /// <summary> /// Gets the string value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns>The string value of the specified field.</returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> string IDataRecord.GetString(int i) { return _innerDataReader.GetString(i); } /// <summary> /// Return the value of the specified field. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// The <see cref="System.Object"></see> which will contain the field value upon return. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> object IDataRecord.GetValue(int i) { return _innerDataReader.GetValue(i); } int IDataRecord.GetValues(object[] values) { return _innerDataReader.GetValues(values); } /// <summary> /// Return whether the specified field is set to null. /// </summary> /// <param name="i">The index of the field to find.</param> /// <returns> /// true if the specified field is set to null. Otherwise, false. /// </returns> /// <exception cref="System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"></see>. </exception> bool IDataRecord.IsDBNull(int i) { return _innerDataReader.IsDBNull(i); } /// <summary> /// Gets the <see cref="Object"/> with the specified name. /// </summary> /// <value></value> object IDataRecord.this[string name] { get { return _innerDataReader[name]; } } /// <summary> /// Gets the <see cref="Object"/> with the specified i. /// </summary> /// <value></value> object IDataRecord.this[int i] { get { return _innerDataReader[i]; } } #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; using System.Diagnostics; using System.Globalization; using System.Text; using System.Text.RegularExpressions; namespace System.Data.Common { internal class DbConnectionOptions { // instances of this class are intended to be immutable, i.e readonly // used by pooling classes so it is much easier to verify correctness // when not worried about the class being modified during execution #if DEBUG /*private const string ConnectionStringPatternV1 = "[\\s;]*" +"(?<key>([^=\\s]|\\s+[^=\\s]|\\s+==|==)+)" + "\\s*=(?!=)\\s*" +"(?<value>(" + "(" + "\"" + "([^\"]|\"\")*" + "\"" + ")" + "|" + "(" + "'" + "([^']|'')*" + "'" + ")" + "|" + "(" + "(?![\"'])" + "([^\\s;]|\\s+[^\\s;])*" + "(?<![\"'])" + ")" + "))" + "[\\s;]*" ;*/ private const string ConnectionStringPattern = // may not contain embedded null except trailing last value "([\\s;]*" // leading whitespace and extra semicolons + "(?![\\s;])" // key does not start with space or semicolon + "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '==' + "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts + "(?<value>" + "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as "" + "|" + "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as '' + "|" + "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted + "(?<![\"']))" // unquoted value must not stop with " or ' + ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line + ")*" // repeat the key-value pair + "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end ; private static readonly Regex s_connectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled); #endif private const string ConnectionStringValidKeyPattern = "^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$"; // key not allowed to start with semi-colon or space or contain non-visible characters or end with space private const string ConnectionStringValidValuePattern = "^[^\u0000]*$"; // value not allowed to contain embedded null private static readonly Regex s_connectionStringValidKeyRegex = new Regex(ConnectionStringValidKeyPattern, RegexOptions.Compiled); private static readonly Regex s_connectionStringValidValueRegex = new Regex(ConnectionStringValidValuePattern, RegexOptions.Compiled); // connection string common keywords private static class KEY { internal const string Integrated_Security = "integrated security"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; }; // known connection string common synonyms private static class SYNONYM { internal const string Pwd = "pwd"; }; private readonly string _usersConnectionString; private readonly Hashtable _parsetable; internal readonly NameValuePair KeyChain; internal readonly bool HasPasswordKeyword; public DbConnectionOptions(string connectionString, Hashtable synonyms) { _parsetable = new Hashtable(); _usersConnectionString = ((null != connectionString) ? connectionString : ""); // first pass on parsing, initial syntax check if (0 < _usersConnectionString.Length) { KeyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms); HasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd)); } } protected DbConnectionOptions(DbConnectionOptions connectionOptions) { // Clone used by SqlConnectionString _usersConnectionString = connectionOptions._usersConnectionString; HasPasswordKeyword = connectionOptions.HasPasswordKeyword; _parsetable = connectionOptions._parsetable; KeyChain = connectionOptions.KeyChain; } public string UsersConnectionString(bool hidePassword) { return UsersConnectionString(hidePassword, false); } private string UsersConnectionString(bool hidePassword, bool forceHidePassword) { string connectionString = _usersConnectionString; if (HasPasswordKeyword && (forceHidePassword || (hidePassword && !HasPersistablePassword))) { ReplacePasswordPwd(out connectionString, false); } return ((null != connectionString) ? connectionString : ""); } internal bool HasPersistablePassword { get { if (HasPasswordKeyword) { return ConvertValueToBoolean(KEY.Persist_Security_Info, false); } return true; // no password means persistable password so we don't have to munge } } public bool IsEmpty { get { return (null == KeyChain); } } internal Hashtable Parsetable { get { return _parsetable; } } public bool ConvertValueToBoolean(string keyName, bool defaultValue) { object value = _parsetable[keyName]; if (null == value) { return defaultValue; } return ConvertValueToBooleanInternal(keyName, (string)value); } internal static bool ConvertValueToBooleanInternal(string keyName, string stringValue) { if (CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes")) return true; else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no")) return false; else { string tmp = stringValue.Trim(); // Remove leading & trailing white space. if (CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes")) return true; else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no")) return false; else { throw ADP.InvalidConnectionOptionValue(keyName); } } } // same as Boolean, but with SSPI thrown in as valid yes public bool ConvertValueToIntegratedSecurity() { object value = _parsetable[KEY.Integrated_Security]; if (null == value) { return false; } return ConvertValueToIntegratedSecurityInternal((string)value); } internal bool ConvertValueToIntegratedSecurityInternal(string stringValue) { if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes")) return true; else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no")) return false; else { string tmp = stringValue.Trim(); // Remove leading & trailing white space. if (CompareInsensitiveInvariant(tmp, "sspi") || CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes")) return true; else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no")) return false; else { throw ADP.InvalidConnectionOptionValue(KEY.Integrated_Security); } } } public int ConvertValueToInt32(string keyName, int defaultValue) { object value = _parsetable[keyName]; if (null == value) { return defaultValue; } return ConvertToInt32Internal(keyName, (string)value); } internal static int ConvertToInt32Internal(string keyname, string stringValue) { try { return System.Int32.Parse(stringValue, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(keyname, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(keyname, e); } } public string ConvertValueToString(string keyName, string defaultValue) { string value = (string)_parsetable[keyName]; return ((null != value) ? value : defaultValue); } static private bool CompareInsensitiveInvariant(string strvalue, string strconst) { return (0 == StringComparer.OrdinalIgnoreCase.Compare(strvalue, strconst)); } public bool ContainsKey(string keyword) { return _parsetable.ContainsKey(keyword); } #if DEBUG [System.Diagnostics.Conditional("DEBUG")] private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hashtable synonyms) { } #endif static private string GetKeyName(StringBuilder buffer) { int count = buffer.Length; while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1])) { count--; // trailing whitespace } return buffer.ToString(0, count).ToLowerInvariant(); } static private string GetKeyValue(StringBuilder buffer, bool trimWhitespace) { int count = buffer.Length; int index = 0; if (trimWhitespace) { while ((index < count) && Char.IsWhiteSpace(buffer[index])) { index++; // leading whitespace } while ((0 < count) && Char.IsWhiteSpace(buffer[count - 1])) { count--; // trailing whitespace } } return buffer.ToString(index, count - index); } // transition states used for parsing private enum ParserState { NothingYet = 1, //start point Key, KeyEqual, KeyEnd, UnquotedValue, DoubleQuoteValue, DoubleQuoteValueQuote, SingleQuoteValue, SingleQuoteValueQuote, BraceQuoteValue, BraceQuoteValueQuote, QuotedValueEnd, NullTermination, }; static internal int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, out string keyname, out string keyvalue) { int startposition = currentPosition; buffer.Length = 0; keyname = null; keyvalue = null; char currentChar = '\0'; ParserState parserState = ParserState.NothingYet; int length = connectionString.Length; for (; currentPosition < length; ++currentPosition) { currentChar = connectionString[currentPosition]; switch (parserState) { case ParserState.NothingYet: // [\\s;]* if ((';' == currentChar) || Char.IsWhiteSpace(currentChar)) { continue; } if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; } if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); } startposition = currentPosition; if ('=' != currentChar) { parserState = ParserState.Key; break; } else { parserState = ParserState.KeyEqual; continue; } case ParserState.Key: // (?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+) if ('=' == currentChar) { parserState = ParserState.KeyEqual; continue; } if (Char.IsWhiteSpace(currentChar)) { break; } if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.KeyEqual: // \\s*=(?!=)\\s* if ('=' == currentChar) { parserState = ParserState.Key; break; } keyname = GetKeyName(buffer); if (string.IsNullOrEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); } buffer.Length = 0; parserState = ParserState.KeyEnd; goto case ParserState.KeyEnd; case ParserState.KeyEnd: if (Char.IsWhiteSpace(currentChar)) { continue; } { if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; continue; } if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; continue; } } if (';' == currentChar) { goto ParserExit; } if ('\0' == currentChar) { goto ParserExit; } if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); } parserState = ParserState.UnquotedValue; break; case ParserState.UnquotedValue: // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(?<![\"']))" if (Char.IsWhiteSpace(currentChar)) { break; } if (Char.IsControl(currentChar) || ';' == currentChar) { goto ParserExit; } break; case ParserState.DoubleQuoteValue: // "(\"([^\"\u0000]|\"\")*\")" if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValueQuote; continue; } if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.DoubleQuoteValueQuote: if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; break; } keyvalue = GetKeyValue(buffer, false); parserState = ParserState.QuotedValueEnd; goto case ParserState.QuotedValueEnd; case ParserState.SingleQuoteValue: // "('([^'\u0000]|'')*')" if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValueQuote; continue; } if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.SingleQuoteValueQuote: if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; break; } keyvalue = GetKeyValue(buffer, false); parserState = ParserState.QuotedValueEnd; goto case ParserState.QuotedValueEnd; case ParserState.BraceQuoteValue: // "(\\{([^\\}\u0000]|\\}\\})*\\})" if ('}' == currentChar) { parserState = ParserState.BraceQuoteValueQuote; break; } if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.BraceQuoteValueQuote: if ('}' == currentChar) { parserState = ParserState.BraceQuoteValue; break; } keyvalue = GetKeyValue(buffer, false); parserState = ParserState.QuotedValueEnd; goto case ParserState.QuotedValueEnd; case ParserState.QuotedValueEnd: if (Char.IsWhiteSpace(currentChar)) { continue; } if (';' == currentChar) { goto ParserExit; } if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; } throw ADP.ConnectionStringSyntax(startposition); // unbalanced single quote case ParserState.NullTermination: // [\\s;\u0000]* if ('\0' == currentChar) { continue; } if (Char.IsWhiteSpace(currentChar)) { continue; } throw ADP.ConnectionStringSyntax(currentPosition); default: throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState1); } buffer.Append(currentChar); } ParserExit: switch (parserState) { case ParserState.Key: case ParserState.DoubleQuoteValue: case ParserState.SingleQuoteValue: case ParserState.BraceQuoteValue: // keyword not found/unbalanced double/single quote throw ADP.ConnectionStringSyntax(startposition); case ParserState.KeyEqual: // equal sign at end of line keyname = GetKeyName(buffer); if (string.IsNullOrEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); } break; case ParserState.UnquotedValue: // unquoted value at end of line keyvalue = GetKeyValue(buffer, true); char tmpChar = keyvalue[keyvalue.Length - 1]; if (('\'' == tmpChar) || ('"' == tmpChar)) { throw ADP.ConnectionStringSyntax(startposition); // unquoted value must not end in quote, except for odbc } break; case ParserState.DoubleQuoteValueQuote: case ParserState.SingleQuoteValueQuote: case ParserState.BraceQuoteValueQuote: case ParserState.QuotedValueEnd: // quoted value at end of line keyvalue = GetKeyValue(buffer, false); break; case ParserState.NothingYet: case ParserState.KeyEnd: case ParserState.NullTermination: // do nothing break; default: throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState2); } if ((';' == currentChar) && (currentPosition < connectionString.Length)) { currentPosition++; } return currentPosition; } static private bool IsValueValidInternal(string keyvalue) { if (null != keyvalue) { #if DEBUG bool compValue = s_connectionStringValidValueRegex.IsMatch(keyvalue); Debug.Assert((-1 == keyvalue.IndexOf('\u0000')) == compValue, "IsValueValid mismatch with regex"); #endif return (-1 == keyvalue.IndexOf('\u0000')); } return true; } static private bool IsKeyNameValid(string keyname) { if (null != keyname) { #if DEBUG bool compValue = s_connectionStringValidKeyRegex.IsMatch(keyname); Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))) == compValue, "IsValueValid mismatch with regex"); #endif return ((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))); } return false; } #if DEBUG private static Hashtable SplitConnectionString(string connectionString, Hashtable synonyms) { Hashtable parsetable = new Hashtable(); Regex parser = s_connectionStringRegex; const int KeyIndex = 1, ValueIndex = 2; Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index"); Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index"); if (null != connectionString) { Match match = parser.Match(connectionString); if (!match.Success || (match.Length != connectionString.Length)) { throw ADP.ConnectionStringSyntax(match.Length); } int indexValue = 0; CaptureCollection keyvalues = match.Groups[ValueIndex].Captures; foreach (Capture keypair in match.Groups[KeyIndex].Captures) { string keyname = keypair.Value.Replace("==", "=").ToLowerInvariant(); string keyvalue = keyvalues[indexValue++].Value; if (0 < keyvalue.Length) { { switch (keyvalue[0]) { case '\"': keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\""); break; case '\'': keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'"); break; default: break; } } } else { keyvalue = null; } DebugTraceKeyValuePair(keyname, keyvalue, synonyms); string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); if (!IsKeyNameValid(realkeyname)) { throw ADP.KeywordNotSupported(keyname); } { parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) } } } return parsetable; } private static void ParseComparison(Hashtable parsetable, string connectionString, Hashtable synonyms, Exception e) { try { Hashtable parsedvalues = SplitConnectionString(connectionString, synonyms); foreach (DictionaryEntry entry in parsedvalues) { string keyname = (string)entry.Key; string value1 = (string)entry.Value; string value2 = (string)parsetable[keyname]; Debug.Assert(parsetable.Contains(keyname), "ParseInternal code vs. regex mismatch keyname <" + keyname + ">"); Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 + ">"); } } catch (ArgumentException f) { if (null != e) { string msg1 = e.Message; string msg2 = f.Message; const string KeywordNotSupportedMessagePrefix = "Keyword not supported:"; const string WrongFormatMessagePrefix = "Format of the initialization string"; bool isEquivalent = (msg1 == msg2); if (!isEquivalent) { // We also accept cases were Regex parser (debug only) reports "wrong format" and // retail parsing code reports format exception in different location or "keyword not supported" if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) { if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) { isEquivalent = true; } } } Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <" + msg1 + "> <" + msg2 + ">"); } else { Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message); } e = null; } if (null != e) { Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch"); } } #endif private static NameValuePair ParseInternal(Hashtable parsetable, string connectionString, bool buildChain, Hashtable synonyms) { Debug.Assert(null != connectionString, "null connectionstring"); StringBuilder buffer = new StringBuilder(); NameValuePair localKeychain = null, keychain = null; #if DEBUG try { #endif int nextStartPosition = 0; int endPosition = connectionString.Length; while (nextStartPosition < endPosition) { int startPosition = nextStartPosition; string keyname, keyvalue; nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, out keyname, out keyvalue); if (string.IsNullOrEmpty(keyname)) { // if (nextStartPosition != endPosition) { throw; } break; } #if DEBUG DebugTraceKeyValuePair(keyname, keyvalue, synonyms); Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname"); Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue"); #endif string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); if (!IsKeyNameValid(realkeyname)) { throw ADP.KeywordNotSupported(keyname); } { parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) } if (null != localKeychain) { localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); } else if (buildChain) { // first time only - don't contain modified chain from UDL file keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); } } #if DEBUG } catch (ArgumentException e) { ParseComparison(parsetable, connectionString, synonyms, e); throw; } ParseComparison(parsetable, connectionString, synonyms, null); #endif return keychain; } internal NameValuePair ReplacePasswordPwd(out string constr, bool fakePassword) { bool expanded = false; int copyPosition = 0; NameValuePair head = null, tail = null, next = null; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); for (NameValuePair current = KeyChain; null != current; current = current.Next) { if ((KEY.Password != current.Name) && (SYNONYM.Pwd != current.Name)) { builder.Append(_usersConnectionString, copyPosition, current.Length); if (fakePassword) { next = new NameValuePair(current.Name, current.Value, current.Length); } } else if (fakePassword) { // replace user password/pwd value with * const string equalstar = "=*;"; builder.Append(current.Name).Append(equalstar); next = new NameValuePair(current.Name, "*", current.Name.Length + equalstar.Length); expanded = true; } else { // drop the password/pwd completely in returning for user expanded = true; } if (fakePassword) { if (null != tail) { tail = tail.Next = next; } else { tail = head = next; } } copyPosition += current.Length; } Debug.Assert(expanded, "password/pwd was not removed"); constr = builder.ToString(); return head; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Confingo.Services.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* * 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.IO; using System.Linq; using System.Text; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Data.Auxiliary; using QuantConnect.Securities; using QuantConnect.ToolBox; using QuantConnect.Util; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Data.Consolidators; using QuantConnect.Data.Market; namespace QuantConnect.Tests.ToolBox { [TestFixture, Parallelizable(ParallelScope.Fixtures)] public class LeanDataReaderTests { string _dataDirectory = "../../../Data/"; DateTime _fromDate = new DateTime(2013, 10, 7); DateTime _toDate = new DateTime(2013, 10, 11); [Test, Parallelizable(ParallelScope.Self)] public void LoadsEquity_Daily_SingleEntryZip() { var dataPath = LeanData.GenerateZipFilePath(Globals.DataFolder, Symbols.AAPL, DateTime.UtcNow, Resolution.Daily, TickType.Trade); var leanDataReader = new LeanDataReader(dataPath); var data = leanDataReader.Parse().ToList(); Assert.AreEqual(5849, data.Count); Assert.IsTrue(data.All(baseData => baseData.Symbol == Symbols.AAPL && baseData is TradeBar)); } #region futures [Test, Parallelizable(ParallelScope.Self)] public void ReadsEntireZipFileEntries_OpenInterest() { var baseFuture = Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, SecurityIdentifier.DefaultDate); var filePath = LeanData.GenerateZipFilePath(Globals.DataFolder, baseFuture, new DateTime(2013, 10, 06), Resolution.Minute, TickType.OpenInterest); var leanDataReader = new LeanDataReader(filePath); var data = leanDataReader.Parse() .ToList() .GroupBy(baseData => baseData.Symbol) .Select(grp => grp.ToList()) .OrderBy(list => list[0].Symbol) .ToList(); Assert.AreEqual(5, data.Count); Assert.IsTrue(data.All(kvp => kvp.Count == 1)); foreach (var dataForSymbol in data) { Assert.IsTrue(dataForSymbol[0] is OpenInterest); Assert.IsFalse(dataForSymbol[0].Symbol.IsCanonical()); Assert.AreEqual(Futures.Indices.SP500EMini, dataForSymbol[0].Symbol.ID.Symbol); Assert.AreNotEqual(0, dataForSymbol[0]); } } [Test, Parallelizable(ParallelScope.Self)] public void ReadsEntireZipFileEntries_Trade() { var baseFuture = Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, SecurityIdentifier.DefaultDate); var filePath = LeanData.GenerateZipFilePath(Globals.DataFolder, baseFuture, new DateTime(2013, 10, 06), Resolution.Minute, TickType.Trade); var leanDataReader = new LeanDataReader(filePath); var data = leanDataReader.Parse() .ToList() .GroupBy(baseData => baseData.Symbol) .Select(grp => grp.ToList()) .OrderBy(list => list[0].Symbol) .ToList(); Assert.AreEqual(2, data.Count); foreach (var dataForSymbol in data) { Assert.IsTrue(dataForSymbol[0] is TradeBar); Assert.IsFalse(dataForSymbol[0].Symbol.IsCanonical()); Assert.AreEqual(Futures.Indices.SP500EMini, dataForSymbol[0].Symbol.ID.Symbol); } Assert.AreEqual(118, data[0].Count); Assert.AreEqual(10, data[1].Count); } [Test, Parallelizable(ParallelScope.Self)] public void ReadsEntireZipFileEntries_Quote() { var baseFuture = Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, SecurityIdentifier.DefaultDate); var filePath = LeanData.GenerateZipFilePath(Globals.DataFolder, baseFuture, new DateTime(2013, 10, 06), Resolution.Minute, TickType.Quote); var leanDataReader = new LeanDataReader(filePath); var data = leanDataReader.Parse() .ToList() .GroupBy(baseData => baseData.Symbol) .Select(grp => grp.ToList()) .OrderBy(list => list[0].Symbol) .ToList(); Assert.AreEqual(5, data.Count); foreach (var dataForSymbol in data) { Assert.IsTrue(dataForSymbol[0] is QuoteBar); Assert.IsFalse(dataForSymbol[0].Symbol.IsCanonical()); Assert.AreEqual(Futures.Indices.SP500EMini, dataForSymbol[0].Symbol.ID.Symbol); } Assert.AreEqual(10, data[0].Count); Assert.AreEqual(13, data[1].Count); Assert.AreEqual(52, data[2].Count); Assert.AreEqual(155, data[3].Count); Assert.AreEqual(100, data[4].Count); } [Test] public void ReadFutureChainData() { var canonicalFutures = new Dictionary<Symbol, string>() { { Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME), "ES20Z13|ES21H14|ES20M14|ES19U14|ES19Z14" }, {Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX), "GC29V13|GC26X13|GC27Z13|GC26G14|GC28J14|GC26M14|GC27Q14|GC29V14|GC29Z14|GC25G15|GC28J15|GC26M15|GC27Q15|GC29Z15|GC28M16|GC28Z16|GC28M17|GC27Z17|GC27M18|GC27Z18|GC26M19"}, }; var tickTypes = new[] { TickType.Trade, TickType.Quote, TickType.OpenInterest }; var resolutions = new[] { Resolution.Minute }; foreach (var canonical in canonicalFutures) { foreach (var res in resolutions) { foreach (var tickType in tickTypes) { var futures = LoadFutureChain(canonical.Key, _fromDate, tickType, res); string chain = string.Join("|", futures.Select(f => f.Value)); if (tickType == TickType.Quote) //only quotes have the full chain! Assert.AreEqual(canonical.Value, chain); foreach (var future in futures) { string csv = LoadFutureData(future, tickType, res); Assert.IsTrue(!string.IsNullOrEmpty(csv)); } } } } } private List<Symbol> LoadFutureChain(Symbol baseFuture, DateTime date, TickType tickType, Resolution res) { var filePath = LeanData.GenerateZipFilePath(_dataDirectory, baseFuture, date, res, tickType); //load future chain first var config = new SubscriptionDataConfig(typeof(ZipEntryName), baseFuture, res, TimeZones.NewYork, TimeZones.NewYork, false, false, false, false, tickType); using var cacheProvider = new ZipDataCacheProvider(TestGlobals.DataProvider); var factory = new ZipEntryNameSubscriptionDataSourceReader(cacheProvider, config, date, false); var result = factory.Read(new SubscriptionDataSource(filePath, SubscriptionTransportMedium.LocalFile, FileFormat.ZipEntryName)) .Select(s => s.Symbol).ToList(); return result; } private string LoadFutureData(Symbol future, TickType tickType, Resolution res) { var dataType = LeanData.GetDataType(res, tickType); var config = new SubscriptionDataConfig(dataType, future, res, TimeZones.NewYork, TimeZones.NewYork, false, false, false, false, tickType); var date = _fromDate; var sb = new StringBuilder(); while (date <= _toDate) { var leanDataReader = new LeanDataReader(config, future, res, date, _dataDirectory); foreach (var bar in leanDataReader.Parse()) { //write base data type back to string sb.AppendLine(LeanData.GenerateLine(bar, SecurityType.Future, res)); } date = date.AddDays(1); } var csv = sb.ToString(); return csv; } [Test] public void GenerateDailyAndHourlyFutureDataFromMinutes() { var tickTypes = new[] { TickType.Trade, TickType.Quote, TickType.OpenInterest }; var futures = new[] { Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME), Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX)}; var resolutions = new[] { Resolution.Hour, Resolution.Daily }; foreach (var future in futures) foreach (var res in resolutions) foreach (var tickType in tickTypes) ConvertMinuteFuturesData(future, tickType, res); } private void ConvertMinuteFuturesData(Symbol canonical, TickType tickType, Resolution outputResolution, Resolution inputResolution = Resolution.Minute) { var timeSpans = new Dictionary<Resolution, TimeSpan>() { { Resolution.Daily, TimeSpan.FromHours(24)}, { Resolution.Hour, TimeSpan.FromHours(1)}, }; var timeSpan = timeSpans[outputResolution]; var tickTypeConsolidatorMap = new Dictionary<TickType, Func<IDataConsolidator>>() { {TickType.Quote, () => new QuoteBarConsolidator(timeSpan)}, {TickType.OpenInterest, ()=> new OpenInterestConsolidator(timeSpan)}, {TickType.Trade, ()=> new TradeBarConsolidator(timeSpan) } }; var consolidators = new Dictionary<string, IDataConsolidator>(); var configs = new Dictionary<string, SubscriptionDataConfig>(); var outputFiles = new Dictionary<string, StringBuilder>(); var futures = new Dictionary<string, Symbol>(); var date = _fromDate; while (date <= _toDate) { var futureChain = LoadFutureChain(canonical, date, tickType, inputResolution); foreach (var future in futureChain) { if (!futures.ContainsKey(future.Value)) { futures[future.Value] = future; var config = new SubscriptionDataConfig(LeanData.GetDataType(outputResolution, tickType), future, inputResolution, TimeZones.NewYork, TimeZones.NewYork, false, false, false, false, tickType); configs[future.Value] = config; consolidators[future.Value] = tickTypeConsolidatorMap[tickType].Invoke(); var sb = new StringBuilder(); outputFiles[future.Value] = sb; consolidators[future.Value].DataConsolidated += (sender, bar) => { sb.Append(LeanData.GenerateLine(bar, SecurityType.Future, outputResolution) + Environment.NewLine); }; } var leanDataReader = new LeanDataReader(configs[future.Value], future, inputResolution, date, _dataDirectory); var consolidator = consolidators[future.Value]; foreach (var bar in leanDataReader.Parse()) { consolidator.Update(bar); } } date = date.AddDays(1); } //write all results foreach (var consolidator in consolidators.Values) consolidator.Scan(date); var zip = LeanData.GenerateRelativeZipFilePath(canonical, _fromDate, outputResolution, tickType); var zipPath = Path.Combine(_dataDirectory, zip); var fi = new FileInfo(zipPath); if (!fi.Directory.Exists) fi.Directory.Create(); foreach (var future in futures.Values) { var zipEntry = LeanData.GenerateZipEntryName(future, _fromDate, outputResolution, tickType); var sb = outputFiles[future.Value]; //Uncomment to write zip files //QuantConnect.Compression.ZipCreateAppendData(zipPath, zipEntry, sb.ToString()); Assert.IsTrue(sb.Length > 0); } } #endregion [Test, TestCaseSource(nameof(OptionAndFuturesCases))] public void ReadLeanFutureAndOptionDataFromFilePath(string composedFilePath, Symbol symbol, int rowsInfile, double sumValue) { // Act var ldr = new LeanDataReader(composedFilePath); var data = ldr.Parse().ToList(); // Assert Assert.True(symbol.Equals(data.First().Symbol)); Assert.AreEqual(rowsInfile, data.Count); Assert.AreEqual(sumValue, data.Sum(c => c.Value)); } public static object[] OptionAndFuturesCases = { new object[] { "../../../Data/future/cme/minute/es/20131008_quote.zip#20131008_es_minute_quote_201312_20131220.csv", LeanData .ReadSymbolFromZipEntry(Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME), Resolution.Minute, "20131008_es_minute_quote_201312_20131220.csv"), 1411, 2346061.875 }, new object[] { "../../../Data/future/comex/minute/gc/20131010_trade.zip#20131010_gc_minute_trade_201312_20131227.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX), Resolution.Minute, "20131010_gc_minute_trade_201312_20131227.csv"), 1379, 1791800.9 }, new object[] { "../../../Data/future/comex/tick/gc/20131009_quote.zip#20131009_gc_tick_quote_201406_20140626.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX), Resolution.Tick, "20131009_gc_tick_quote_201406_20140626.csv"), 197839, 259245064.8 }, new object[] { "../../../Data/future/comex/tick/gc/20131009_trade.zip#20131009_gc_tick_trade_201312_20131227.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX), Resolution.Tick, "20131009_gc_tick_trade_201312_20131227.csv"), 64712, 84596673.8 }, new object[] { "../../../Data/future/cme/minute/es/20131010_openinterest.zip#20131010_es_minute_openinterest_201312_20131220.csv", LeanData .ReadSymbolFromZipEntry(Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME), Resolution.Minute, "20131010_es_minute_openinterest_201312.csv"), 3, 8119169 }, new object[] { "../../../Data/future/comex/tick/gc/20131009_openinterest.zip#20131009_gc_tick_openinterest_201310_20131029.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX), Resolution.Tick, "20131009_gc_tick_openinterest_201310_20131029.csv"), 4, 1312 }, new object[] { "../../../Data/option/usa/minute/aapl/20140606_quote_american.zip#20140606_aapl_minute_quote_american_put_7500000_20141018.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create("AAPL", SecurityType.Option, Market.USA), Resolution.Minute, "20140606_aapl_minute_quote_american_put_7500000_20141018.csv"), 391, 44210.7 }, new object[] { "../../../Data/option/usa/minute/aapl/20140606_trade_american.zip#20140606_aapl_minute_trade_american_call_6475000_20140606.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create("AAPL", SecurityType.Option, Market.USA), Resolution.Minute, "20140606_aapl_minute_trade_american_call_6475000_20140606.csv"), 374, 745.35 }, new object[] { "../../../Data/option/usa/minute/goog/20151224_openinterest_american.zip#20151224_goog_minute_openinterest_american_call_3000000_20160115.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create("GOOG", SecurityType.Option, Market.USA), Resolution.Minute, "20151224_goog_minute_openinterest_american_call_3000000_20160115.csv"), 1, 38 }, new object[] { "../../../Data/option/usa/daily/aapl_2014_openinterest_american.zip#aapl_openinterest_american_call_1950000_20150117.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create("AAPL", SecurityType.Option, Market.USA), Resolution.Daily, "aapl_openinterest_american_call_1950000_20150117.csv"), 2, 824 }, new object[] { "../../../Data/option/usa/daily/aapl_2014_trade_american.zip#aapl_trade_american_call_5400000_20141018.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create("AAPL", SecurityType.Option, Market.USA), Resolution.Daily, "aapl_trade_american_call_5400000_20141018.csv"), 1, 109.9 }, new object[] { "../../../Data/option/usa/daily/aapl_2014_quote_american.zip#aapl_quote_american_call_307100_20150117.csv", LeanData.ReadSymbolFromZipEntry(Symbol.Create("AAPL", SecurityType.Option, Market.USA), Resolution.Daily, "aapl_quote_american_call_307100_20150117.csv"), 1, 63.3 } }; [Test, TestCaseSource(nameof(SpotMarketCases))] public void ReadLeanSpotMarketsSecuritiesDataFromFilePath(string securityType, string market, string resolution, string ticker, string fileName, int rowsInfile, double sumValue) { // Arrange var filepath = GenerateFilepathForTesting(_dataDirectory, securityType, market, resolution, ticker, fileName); SecurityType securityTypeEnum; Enum.TryParse(securityType, true, out securityTypeEnum); var symbol = Symbol.Create(ticker, securityTypeEnum, market); // Act var ldr = new LeanDataReader(filepath); var data = ldr.Parse().ToList(); // Assert Assert.True(symbol.Equals(data.First().Symbol)); Assert.AreEqual(rowsInfile, data.Count); Assert.AreEqual(sumValue, data.Sum(c => c.Value)); } public static object[] SpotMarketCases = { //TODO: generate Low resolution sample data for equities new object[] {"equity", "usa", "daily", "aig", "aig.zip", 5849, 340770.5801}, new object[] {"equity", "usa", "minute", "aapl", "20140605_trade.zip", 686, 443184.58}, new object[] {"equity", "usa", "minute", "ibm", "20131010_quote.zip", 584, 107061.125}, new object[] {"equity", "usa", "second", "ibm", "20131010_trade.zip", 5060, 929385.34}, new object[] {"equity", "usa", "tick", "bac", "20131011_trade.zip", 112177, 1591680.73}, new object[] {"forex", "oanda", "minute", "eurusd", "20140502_quote.zip", 1222, 1693.578875}, new object[] {"forex", "oanda", "second", "nzdusd", "20140514_quote.zip", 18061, 15638.724575}, new object[] {"forex", "oanda", "tick", "eurusd", "20140507_quote.zip", 41367, 57598.54664}, new object[] {"cfd", "oanda", "hour", "xauusd", "xauusd.zip", 76499, 90453133.772 }, new object[] {"crypto", "gdax", "second", "btcusd", "20161008_trade.zip", 3453, 2137057.57}, new object[] {"crypto", "gdax", "minute", "ethusd", "20170903_trade.zip", 1440, 510470.66}, new object[] {"crypto", "gdax", "daily", "btcusd", "btcusd_trade.zip", 1318, 3725052.03}, }; public static string GenerateFilepathForTesting(string dataDirectory, string securityType, string market, string resolution, string ticker, string fileName) { string filepath; if (resolution == "daily" || resolution == "hour") { filepath = Path.Combine(dataDirectory, securityType, market, resolution, fileName); } else { filepath = Path.Combine(dataDirectory, securityType, market, resolution, ticker, fileName); } return filepath; } } }
using System; using UnityEngine; using System.Collections; #if UNITY_EDITOR using UnityEditor; #endif // TODO faceDir & timeSign are the same ?! namespace UnityPlatformer { /// <summary> /// Rope tile /// </summary> public class Rope : MonoBehaviour, IUpdateEntity { /// <summary> /// Object that can be 'atachhed' to the rope /// This allow to create rope in background, for example. /// </summary> public LayerMask passengers; /// <summary> /// The number of segments.. /// </summary> public int segments; /// <summary> /// The length of the rope.. /// </summary> public float segmentLength; /// <summary> /// The prefab to use for each rope section (i.e. put the mesh or sprite here).. /// </summary> public GameObject sectionPrefab; /// <summary> /// If true only the bottom section of the rope will be grabable and will have a fixed position.. /// </summary> public bool usedFixedPosition; /// <summary> /// The mass of each rope segment (except the last which has mass = ropeMass * 5). /// </summary> public float ropeMass = 1.0f; /// <summary> /// Min rope angle. /// </summary> public float angleLimits = 0; /// <summary> /// rope rotation easing /// </summary> public EasingType easing = EasingType.Sine; /// <summary> /// rope is stopped /// </summary> public bool stop = false; [Range(0, 1)] /// <summary> /// Initial time /// </summary> public float initialTime = 0; /* /// <summary> /// Angluar drag per section. /// </summary> public float angularDrag = 1.0f; */ /// <summary> /// Where the rope movement is facing /// </summary> public float faceDir { get { return Mathf.Sign(lastAngle); } } /// <summary> /// Rotation speed in degrees per second. /// </summary> [Tooltip ("Time to complete a full rotation from -angleLimits to +angleLimits (seconds)")] public float rotationTime = 3.0f; /// <summary> /// If true we move at a constant speed, false we slow down at the apex. /// </summary> [Tooltip ("A value between 0 for no slow down at apex and 1 for lots of slow down at apex")] [Range(0,1)] public float slowDownModifier; /// <summary> /// Rope callback type /// </summary> public delegate void RopeCallback(Rope rope); /// <summary> /// When a side is reached (before change waving) /// </summary> public RopeCallback onSideReached; /// <summary> /// When rope is broken /// </summary> public RopeCallback onBreak; /// <summary> /// GameObjects with RopeSection /// </summary> internal GameObject[] sections; /// <summary> /// /// </summary> int timeSign = 1; /// <summary> /// Current time, goes from 0-1 /// </summary> float time = 0; /// <summary> /// Root RopeSection last angle /// </summary> float lastAngle = 0; /// <summary> /// Health of the Rope, so it can be breakable /// </summary> CharacterHealth health; void Start() { // create the rope from bottom to top // and chain them gameObject.transform.DestroyImmediateChildren(); health = GetComponent<CharacterHealth>(); if (health != null) { health.onDeath += BreakRope; } sections = new GameObject[segments]; GameObject anchor = CreateAnchor(); // Create segments Rigidbody2D nextConnectedBody = anchor.GetComponent<Rigidbody2D>(); for (int i = 0; i < segments; i++) { GameObject section = CreateSection(i, nextConnectedBody); // Update for next loop nextConnectedBody = section.GetComponent<Rigidbody2D>(); } time = initialTime; if (time == 1) { timeSign = -1; } UpdateRotation(); } #if UNITY_EDITOR /// <summary> /// Set layer to Configuration.ropesMask /// </summary> void Reset() { gameObject.layer = Configuration.instance.ropesMask; } #endif /// <summary> /// Conversion factor /// </summary> public float SpeedToSectionOffset(float speed) { return speed / segmentLength; } /// <summary> /// Create Rope anchor /// </summary> GameObject CreateAnchor() { GameObject anchor = new GameObject (); anchor.transform.parent = transform; anchor.transform.localPosition = Vector3.zero; anchor.name = "RopeAnchor"; Rigidbody2D anchorRigidbody = anchor.AddComponent<Rigidbody2D> (); anchorRigidbody.isKinematic = true; return anchor; } /// <summary> /// Create and configure RopeSection /// </summary> GameObject CreateSection(int i, Rigidbody2D connectedBody) { GameObject section; float currentLocalYPos = -segmentLength / 2.0f - segmentLength * i; if (sectionPrefab != null) { section = (GameObject) GameObject.Instantiate(sectionPrefab); } else { section = new GameObject(); } section.name = "RopeSection_" + i; section.layer = gameObject.layer; // Set length and position section.transform.parent = transform; section.transform.localPosition = new Vector3(0, currentLocalYPos, 0); Rigidbody2D rb = section.GetOrAddComponent<Rigidbody2D>(); rb.mass = ropeMass; // NOTE this is mandatory atm. // the rope movement it's a bit basic, because i cannot have a more stable // version rb.isKinematic = true; BoxCollider2D bc2d = section.GetOrAddComponent<BoxCollider2D>(); // Default to a 0.5f wide box collider bc2d.size = new Vector2(0.5f, segmentLength); bc2d.isTrigger = true; // Check Hinge Joint HingeJoint2D hingeJoint = section.GetOrAddComponent<HingeJoint2D>(); hingeJoint.anchor = new Vector2(0, 0.5f); hingeJoint.connectedAnchor = new Vector2(0, i == 0 ? 0.0f : -0.5f); hingeJoint.connectedBody = connectedBody; if (angleLimits > 0) { hingeJoint.useLimits = true; JointAngleLimits2D limits = new JointAngleLimits2D(); limits.min = angleLimits; limits.max = -angleLimits; hingeJoint.limits = limits; } // this will handle the player entering the rope RopeSection rs = section.AddComponent<RopeSection>(); rs.rope = this; rs.index = i; if (health != null) { // NOTE add/get the HitBox so it can be destroyed // if we add a hitbox, it's just useless we need a proper collideWith // configured HitBox hitbox = section.GetOrAddComponent<HitBox>(); hitbox.owner = health; //hitbox.type = HitBoxType.RecieveDamage; //hitbox.collideWith = recieveDamage; } // Special case, for last section if (i == segments - 1) { rb.mass = ropeMass * 5; } sections[i] = section; return section; } /// <summary> /// Gets the rope section above the provided one or null if none. /// </summary> /// <returns>The section below.</returns> virtual public GameObject GetSectionAbove(GameObject section) { int index = Array.IndexOf(sections, section); if (index > 0) return sections[index - 1]; return null; } /// <summary> /// Gets the rope section below the provided one or null if none. /// </summary> /// <returns>The section below.</returns> virtual public GameObject GetSectionBelow(GameObject section) { int index = Array.IndexOf(sections, section); if (index < segments - 1) return sections[index + 1]; return null; } /// <summary> /// notify UpdateManager /// </summary> public virtual void OnEnable() { UpdateManager.Push(this, Configuration.instance.movingPlatformsPriority); } /// <summary> /// notify UpdateManager /// </summary> public virtual void OnDisable() { UpdateManager.Remove(this); } /// <summary> /// Update rope rotation, this is called PlatformerUpdate /// if you need to called it outside, remember that time must be updated before /// </summary> public void UpdateRotation() { // rotate only top section // rope isKinematic atm, not realistic but works perfectly // movement need more work, but rotate the hinge it's a nightmare! GameObject obj = sections[0]; if (time > 1) { time = 1; timeSign = -1; if (onSideReached != null) { onSideReached(this); } } else if (time < 0) { time = 0; timeSign = 1; if (onSideReached != null) { onSideReached(this); } } float factor = Easing.EaseInOut(time, easing); lastAngle = factor * 2 * angleLimits - angleLimits; // reset first transform.rotation = Quaternion.identity; transform.RotateAround( obj.GetComponent<HingeJoint2D>().connectedBody.transform.position, new Vector3(0, 0, -1), lastAngle ); } /// <summary> /// Rope motion! /// </summary> public virtual void PlatformerUpdate(float delta) { if (stop) return; time += delta * timeSign / rotationTime; UpdateRotation(); } /// <summary> /// Do nothing, use PlatformerUpdate instead /// </summary> public virtual void LatePlatformerUpdate(float delta) {} /// <summary> /// Break the rope and stop movement /// TODO break do not destroy sections /// </summary> public void BreakRope() { if (onBreak != null) { onBreak(this); } Debug.Log("BreakRope"); stop = true; gameObject.transform.DestroyChildren(); } #if UNITY_EDITOR /// <summary> /// Draw in Editor /// </summary> [DrawGizmo(GizmoType.InSelectionHierarchy | GizmoType.NotInSelectionHierarchy)] void OnDrawGizmos() { if (Application.isPlaying) return; Gizmos.color = Color.green; float height = segments * segmentLength; var c = Mathf.Cos(angleLimits * Mathf.Deg2Rad); var s = Mathf.Sin(angleLimits * Mathf.Deg2Rad); Gizmos.DrawLine(transform.position, transform.position - new Vector3(0, height)); Gizmos.DrawLine(transform.position, transform.position + new Vector3(s * height, -c * height)); Gizmos.DrawLine(transform.position, transform.position + new Vector3(-s * height, -c * height)); } #endif } }
/* 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; using System.Collections.Generic; using System.Linq; using Adxstudio.Xrm.Services.Query; using Adxstudio.Xrm.Web.UI; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query; namespace Adxstudio.Xrm.Cms { /// <summary> /// Describes a content map column set. /// </summary> public class SolutionColumnSet { public SolutionColumnSet(string solution, params EntityNodeColumn[] columns) { Solution = solution; EntityNodeColumns = columns; } public string Solution { get; private set; } public IEnumerable<string> ColumnSet { get { if (EntityNodeColumns != null && EntityNodeColumns.Any()) { return EntityNodeColumns.Select(column => column.Name); } return null; } } public IEnumerable<EntityNodeColumn> EntityNodeColumns { get; private set; } public SolutionColumnSet GetFilteredColumns(Version solutionVersion) { List<EntityNodeColumn> filteredColumns = new List<EntityNodeColumn>(); if (this.EntityNodeColumns != null) { foreach (var column in this.EntityNodeColumns) { if (column.IntroducedVersion != null) { var columnVersion = column.IntroducedVersion; if (columnVersion.Major <= solutionVersion.Major && columnVersion.Minor <= solutionVersion.Minor) { filteredColumns.Add(column); } } else { filteredColumns.Add(column); } } } return new SolutionColumnSet(this.Solution, filteredColumns.ToArray()); } } /// <summary> /// Describes a content map entity node. /// </summary> public class EntityDefinition { /// <summary> /// Builds and returns an <see cref="EntityDefinition"/> object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="solution"></param> /// <param name="logicalName"></param> /// <param name="primaryIdAttributeName"></param> /// <param name="columnSet"></param> /// <param name="activeStateCode"></param> /// <param name="queryBuilder"></param> /// <param name="version"></param> /// <param name="relationships"></param> /// <returns>New <see cref="EntityDefinition"/> object.</returns> public static EntityDefinition Create<T>( string solution, string logicalName, string primaryIdAttributeName, EntityNodeColumn[] columnSet, int? activeStateCode, QueryBuilder queryBuilder, Version version, params RelationshipDefinition[] relationships) where T : EntityNode { return Create<T>(solution, logicalName, primaryIdAttributeName, columnSet, activeStateCode, queryBuilder, version, false, relationships); } /// <summary> /// Builds and returns an <see cref="EntityDefinition"/> object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="solution"></param> /// <param name="logicalName"></param> /// <param name="primaryIdAttributeName"></param> /// <param name="columnSet"></param> /// <param name="activeStateCode"></param> /// <param name="queryBuilder"></param> /// <param name="version"></param> /// <param name="checkEntityBeforeRefreshing">Whether to check an entity matches on the relationships before refreshing it into the ContentMap. Typically this is not necessary.</param> /// <param name="relationships"></param> /// <returns>New <see cref="EntityDefinition"/> object.</returns> public static EntityDefinition Create<T>( string solution, string logicalName, string primaryIdAttributeName, EntityNodeColumn[] columnSet, int? activeStateCode, QueryBuilder queryBuilder, Version version, bool checkEntityBeforeRefreshing, params RelationshipDefinition[] relationships) where T : EntityNode { return new EntityDefinition( solution, logicalName, primaryIdAttributeName, typeof(T), activeStateCode, new[] { new SolutionColumnSet(solution, columnSet), }, queryBuilder, version, checkEntityBeforeRefreshing, relationships); } /// <summary> /// Builds and returns an <see cref="EntityDefinition"/> object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="solution"></param> /// <param name="logicalName"></param> /// <param name="columnSet"></param> /// <param name="version"></param> /// <param name="relationships"></param> /// <returns>New <see cref="EntityDefinition"/> object.</returns> public static EntityDefinition Extend<T>( string solution, string logicalName, SolutionColumnSet columnSet, Version version, params RelationshipDefinition[] relationships) { var columnSets = columnSet != null ? new[] { columnSet } : null; return new EntityDefinition(solution, logicalName, null, typeof(T), null, columnSets, null, version, false, relationships); } public string LogicalName { get; private set; } public string PrimaryIdAttributeName { get; private set; } public Type EntityNodeType { get; private set; } public string Solution { get; private set; } public int? ActiveStateCode { get; private set; } public IEnumerable<SolutionColumnSet> ColumnSets { get; private set; } public IEnumerable<RelationshipDefinition> Relationships { get; private set; } public QueryBuilder QueryBuilder { get; private set; } /// <summary> /// Introduced version of entity in portals. /// </summary> public Version IntroducedVersion { get; private set; } /// <summary> /// Whether to check an entity matches on the relationships before refreshing it into the ContentMap. Typically this is not necessary. /// When the ContentMap is built, only entities that match on the relationships defined by the solution are included. /// But when the ContentMap is refreshed for a particular entity (or entities), those relationships are not enforced, and so /// an entity could be added to ContentMap even if it doesn't match on any relationships definition. Setting this to true will /// force an extra check to prevent this scenario. /// </summary> public bool CheckEntityBeforeContentMapRefresh { get; private set; } /// <summary> /// <see cref="EntityDefinition"/> constructor. /// </summary> /// <param name="solution"></param> /// <param name="logicalName"></param> /// <param name="primaryIdAttributeName"></param> /// <param name="entityNodeType"></param> /// <param name="activeStateCode"></param> /// <param name="columnSets"></param> /// <param name="queryBuilder"></param> /// <param name="version"></param> /// <param name="checkEntityBeforeRefreshing">Whether to check an entity matches on the relationships before refreshing it into the ContentMap. Typically this is not necessary.</param> /// <param name="relationships"></param> public EntityDefinition( string solution, string logicalName, string primaryIdAttributeName, Type entityNodeType, int? activeStateCode, IEnumerable<SolutionColumnSet> columnSets, QueryBuilder queryBuilder, Version version, bool checkEntityBeforeRefreshing, IEnumerable<RelationshipDefinition> relationships) { Solution = solution; LogicalName = logicalName; PrimaryIdAttributeName = primaryIdAttributeName; EntityNodeType = entityNodeType; ActiveStateCode = activeStateCode; ColumnSets = columnSets; QueryBuilder = queryBuilder; IntroducedVersion = version; CheckEntityBeforeContentMapRefresh = checkEntityBeforeRefreshing; Relationships = relationships; } /// <summary> /// Checks if a given entity should be included in the content map by making sure it matches one of the relationships defined for this entity. /// Note: will only perform the check if 'CheckEntityBeforeContentMapRefresh' is set to True for this entity definition, otherwise will always return true. /// </summary> /// <param name="entity">Entity to check.</param> /// <returns>Whether the given entity should be included in the content map.</returns> public bool ShouldIncludeInContentMap(Entity entity) { if (!this.CheckEntityBeforeContentMapRefresh) { // This entity definition doesn't have 'CheckEntityBeforeContentMapRefresh' enabled, so automatically return true. return true; } if (!this.Relationships.Any()) { // No relationships to check, automatically include. return true; } foreach (var relationship in this.Relationships) { var regardingEntity = entity.GetAttributeValue<EntityReference>(relationship.ForeignIdAttributeName); if (string.Equals(regardingEntity?.LogicalName, relationship.ForeignEntityLogicalname)) { // Found matching relationship, include. return true; } } // If we fell through, then it means the entity didn't match any defined relationship, exclude. return false; } public Fetch CreateFetchExpression() { var fetch = new Fetch { Entity = new FetchEntity(LogicalName) { Attributes = GetFetchAttributes(), Filters = GetStateCodeFilters() } }; return fetch; } private ICollection<FetchAttribute> GetFetchAttributes() { // merge the column sets return ColumnSets.SelectMany(set => set.ColumnSet).Select(set => new FetchAttribute { Name = set }).ToArray(); } private ICollection<Filter> GetStateCodeFilters() { if (ActiveStateCode == null) return null; return new[] { new Filter { Conditions = new[] { new Condition("statecode", ConditionOperator.Equal, ActiveStateCode.Value) } } }; } public Fetch CreateFetch() { var columnSet = ColumnSets.SelectMany(set => set.ColumnSet).ToArray(); var fetch = new Fetch { Entity = new FetchEntity(LogicalName) { Attributes = columnSet.Select(column => new FetchAttribute(column)).ToList() }, SkipCache = true }; if (ActiveStateCode != null) { fetch.AddFilter(new Filter { Conditions = new List<Condition> { new Condition("statecode", ConditionOperator.Equal, ActiveStateCode.Value) } }); } return fetch; } public EntityNode ToNode(Entity entity) { var node = Activator.CreateInstance(EntityNodeType, entity, null) as EntityNode; return node; } /// <summary> /// Filters out columns based on solution version. /// </summary> /// <param name="solutionVersion"></param> /// <returns></returns> public IEnumerable<SolutionColumnSet> GetFilteredColumns(Version solutionVersion) { List<SolutionColumnSet> filteredColumnSet = new List<SolutionColumnSet>(); foreach (var solutionColumnSet in this.ColumnSets) { filteredColumnSet.Add(solutionColumnSet.GetFilteredColumns(solutionVersion)); } return filteredColumnSet; } /// <summary> /// Filters out the relationships based on the solution version. /// </summary> /// <param name="crmSolutions">Dictionary which contains incofrmation of all solutions installed in CRM.</param> /// <returns></returns> public IEnumerable<RelationshipDefinition> GetFilteredRelationships(IDictionary<string, SolutionInfo> crmSolutions) { List<RelationshipDefinition> filteredRelationships = new List<RelationshipDefinition>(); if (this.Relationships != null) { foreach (var relationship in this.Relationships) { // If solution name is missing in Relationship definition or CRM is missing this solution, do the filtering based on MicrosoftCrmPortalBase solution version. var solutionVersion = !string.IsNullOrEmpty(relationship.Solution) && crmSolutions.ContainsKey(relationship.Solution) ? crmSolutions[relationship.Solution].SolutionVersion : crmSolutions["MicrosoftCrmPortalBase"].SolutionVersion; if (relationship.IntroducedVersion != null) { var relationshipVersion = relationship.IntroducedVersion; if (relationshipVersion.Major <= solutionVersion.Major && relationshipVersion.Minor <= solutionVersion.Minor) { filteredRelationships.Add(relationship); } } else { filteredRelationships.Add(relationship); } } } return filteredRelationships; } } }
using System; using System.IO; using System.Collections.Generic; using ATL.Logging; using System.Text; using static ATL.AudioData.AudioDataManager; using Commons; using static ATL.ChannelsArrangements; namespace ATL.AudioData.IO { /// <summary> /// Class for Extended Module files manipulation (extensions : .XM) /// </summary> class XM : MetaDataIO, IAudioDataIO { private const string ZONE_TITLE = "title"; private const String XM_SIGNATURE = "Extended Module: "; // Effects (NB : very close to the MOD effect codes) private const byte EFFECT_POSITION_JUMP = 0xB; private const byte EFFECT_PATTERN_BREAK = 0xD; private const byte EFFECT_SET_SPEED = 0xF; private const byte EFFECT_EXTENDED = 0xE; private const byte EFFECT_EXTENDED_LOOP = 0x6; private const byte EFFECT_NOTE_CUT = 0xC; private const byte EFFECT_NOTE_DELAY = 0xD; private const byte EFFECT_PATTERN_DELAY = 0xE; // Standard fields private IList<byte> FPatternTable; private IList<IList<IList<Event>>> FPatterns; private IList<Instrument> FInstruments; private ushort initialSpeed; // Ticks per line private ushort initialTempo; // BPM private byte nbChannels; private String trackerName; private double bitrate; private double duration; private SizeInfo sizeInfo; private readonly string filePath; // ---------- INFORMATIVE INTERFACE IMPLEMENTATIONS & MANDATORY OVERRIDES // IAudioDataIO public int SampleRate // Sample rate (hz) { get { return 0; } } public bool IsVBR { get { return false; } } public int CodecFamily { get { return AudioDataIOFactory.CF_SEQ_WAV; } } public string FileName { get { return filePath; } } public double BitRate { get { return bitrate; } } public double Duration { get { return duration; } } public ChannelsArrangement ChannelsArrangement { get { return ChannelsArrangements.STEREO; } } public bool IsMetaSupported(int metaDataType) { return (metaDataType == MetaDataIOFactory.TAG_NATIVE); } // IMetaDataIO protected override int getDefaultTagOffset() { return TO_BUILTIN; } protected override int getImplementedTagType() { return MetaDataIOFactory.TAG_NATIVE; } protected override byte getFrameMapping(string zone, string ID, byte tagVersion) { throw new NotImplementedException(); } // === PRIVATE STRUCTURES/SUBCLASSES === private class Instrument { //public byte Type; Useful for S3M but not for XM public String DisplayName; // Other fields not useful for ATL public void Reset() { //Type = 0; DisplayName = ""; } } private class Event { // Commented fields below not useful for ATL public int Channel; //public byte Note; //public byte Instrument; //public byte Volume; public byte Command; public byte Info; public void Reset() { Channel = 0; Command = 0; Info = 0; } } // ---------- CONSTRUCTORS & INITIALIZERS private void resetData() { duration = 0; bitrate = 0; FPatternTable = new List<byte>(); FPatterns = new List<IList<IList<Event>>>(); FInstruments = new List<Instrument>(); trackerName = ""; nbChannels = 0; ResetData(); } public XM(string filePath) { this.filePath = filePath; resetData(); } // === PRIVATE METHODS === private double calculateDuration() { double result = 0; // Jump and break control variables int currentPatternIndex = 0; // Index in the pattern table int currentPattern = 0; // Pattern number per se int currentRow = 0; bool positionJump = false; bool patternBreak = false; // Loop control variables bool isInsideLoop = false; double loopDuration = 0; IList<Event> row; double speed = initialSpeed; double tempo = initialTempo; do // Patterns loop { do // Lines loop { currentPattern = FPatternTable[currentPatternIndex]; while ((currentPattern > FPatterns.Count - 1) && (currentPatternIndex < FPatternTable.Count - 1)) { if (currentPattern.Equals(255)) // End of song / sub-song { // Reset speed & tempo to file default (do not keep remaining values from previous sub-song) speed = initialSpeed; tempo = initialTempo; } currentPattern = FPatternTable[++currentPatternIndex]; } if (currentPattern > FPatterns.Count - 1) return result; row = FPatterns[currentPattern][currentRow]; foreach (Event theEvent in row) // Events loop { if (theEvent.Command.Equals(EFFECT_SET_SPEED)) { if (theEvent.Info > 0) { if (theEvent.Info > 32) // BPM { tempo = theEvent.Info; } else // ticks per line { speed = theEvent.Info; } } } else if (theEvent.Command.Equals(EFFECT_POSITION_JUMP)) { // Processes position jump only if the jump is forward // => Prevents processing "forced" song loops ad infinitum if (theEvent.Info > currentPatternIndex) { currentPatternIndex = Math.Min(theEvent.Info, FPatternTable.Count - 1); currentRow = 0; positionJump = true; } } else if (theEvent.Command.Equals(EFFECT_PATTERN_BREAK)) { currentPatternIndex++; currentRow = Math.Min(theEvent.Info, (byte)63); patternBreak = true; } else if (theEvent.Command.Equals(EFFECT_EXTENDED)) { if ((theEvent.Info >> 4).Equals(EFFECT_EXTENDED_LOOP)) { if ((theEvent.Info & 0xF).Equals(0)) // Beginning of loop { loopDuration = 0; isInsideLoop = true; } else // End of loop + nb. repeat indicator { result += loopDuration * (theEvent.Info & 0xF); isInsideLoop = false; } } } if (positionJump || patternBreak) break; } // end Events loop result += 60 * (speed / (24 * tempo)); if (isInsideLoop) loopDuration += 60 * (speed / (24 * tempo)); if (positionJump || patternBreak) break; currentRow++; } while (currentRow < FPatterns[currentPattern].Count); if (positionJump || patternBreak) { positionJump = false; patternBreak = false; } else { currentPatternIndex++; currentRow = 0; } } while (currentPatternIndex < FPatternTable.Count); // end patterns loop return result; } private void readInstruments(BufferedBinaryReader source, int nbInstruments) { uint instrumentHeaderSize; ushort nbSamples; IList<UInt32> sampleSizes = new List<uint>(); for (int i = 0; i < nbInstruments; i++) { Instrument instrument = new Instrument(); instrumentHeaderSize = source.ReadUInt32(); instrument.DisplayName = Utils.Latin1Encoding.GetString(source.ReadBytes(22)).Trim(); instrument.DisplayName = instrument.DisplayName.Replace("\0", ""); source.Seek(1, SeekOrigin.Current); // Instrument type; useless according to documentation nbSamples = source.ReadUInt16(); source.Seek(instrumentHeaderSize - 29, SeekOrigin.Current); if (nbSamples > 0) { sampleSizes.Clear(); for (int j = 0; j < nbSamples; j++) // Sample headers { sampleSizes.Add(source.ReadUInt32()); source.Seek(36, SeekOrigin.Current); } for (int j = 0; j < nbSamples; j++) // Sample data { source.Seek(sampleSizes[j], SeekOrigin.Current); } } FInstruments.Add(instrument); } } private void readPatterns(BufferedBinaryReader source, int nbPatterns) { byte firstByte; IList<Event> aRow; IList<IList<Event>> aPattern; uint headerLength; ushort nbRows; uint packedDataSize; for (int i=0; i<nbPatterns;i++) { aPattern = new List<IList<Event>>(); headerLength = source.ReadUInt32(); source.Seek(1, SeekOrigin.Current); // Packing type nbRows = source.ReadUInt16(); packedDataSize = source.ReadUInt16(); if (packedDataSize > 0) // The patterns is not empty { for (int j = 0; j < nbRows; j++) { aRow = new List<Event>(); for (int k=0; k<nbChannels;k++) { Event e = new Event(); e.Channel = k+1; firstByte = source.ReadByte(); if ((firstByte & 0x80) > 0) // Most Significant Byte (MSB) is set => packed data layout { if ((firstByte & 0x1) > 0) source.Seek(1,SeekOrigin.Current); // Note if ((firstByte & 0x2) > 0) source.Seek(1,SeekOrigin.Current); // Instrument if ((firstByte & 0x4) > 0) source.Seek(1,SeekOrigin.Current); // Volume if ((firstByte & 0x8) > 0) e.Command = source.ReadByte(); // Effect type if ((firstByte & 0x10) > 0) e.Info = source.ReadByte(); // Effect param } else { // No MSB set => standard data layout // firstByte is the Note source.Seek(1,SeekOrigin.Current); // Instrument source.Seek(1,SeekOrigin.Current); // Volume e.Command = source.ReadByte(); e.Info = source.ReadByte(); } aRow.Add(e); } aPattern.Add(aRow); } } FPatterns.Add(aPattern); } } // === PUBLIC METHODS === public bool Read(BinaryReader source, AudioDataManager.SizeInfo sizeInfo, MetaDataIO.ReadTagParams readTagParams) { this.sizeInfo = sizeInfo; return read(source, readTagParams); } protected override bool read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams) { bool result = true; ushort nbPatterns = 0; ushort nbInstruments = 0; ushort trackerVersion; uint headerSize = 0; uint songLength = 0; StringBuilder comment = new StringBuilder(""); resetData(); BufferedBinaryReader bSource = new BufferedBinaryReader(source.BaseStream); // File format signature if (!XM_SIGNATURE.Equals(Utils.Latin1Encoding.GetString(bSource.ReadBytes(17)))) { result = false; throw new Exception("Invalid XM file (file signature String mismatch)"); } // Title = chars 17 to 37 (length 20) string title = StreamUtils.ReadNullTerminatedStringFixed(bSource, System.Text.Encoding.ASCII, 20); if (readTagParams.PrepareForWriting) { structureHelper.AddZone(17, 20, new byte[20] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, ZONE_TITLE); } tagData.IntegrateValue(TagData.TAG_FIELD_TITLE, title.Trim()); // File format signature if (!0x1a.Equals(bSource.ReadByte())) { result = false; throw new Exception("Invalid XM file (file signature ID mismatch)"); } tagExists = true; trackerName = StreamUtils.ReadNullTerminatedStringFixed(bSource, System.Text.Encoding.ASCII, 20).Trim(); trackerVersion = bSource.ReadUInt16(); // hi-byte major and low-byte minor trackerName += (trackerVersion << 8) + "." + (trackerVersion & 0xFF00); headerSize = bSource.ReadUInt32(); // Calculated FROM THIS OFFSET, not from the beginning of the file songLength = bSource.ReadUInt16(); bSource.Seek(2, SeekOrigin.Current); // Restart position nbChannels = (byte)Math.Min(bSource.ReadUInt16(),(ushort)0xFF); nbPatterns = bSource.ReadUInt16(); nbInstruments = bSource.ReadUInt16(); bSource.Seek(2, SeekOrigin.Current); // Flags for frequency tables; useless for ATL initialSpeed = bSource.ReadUInt16(); initialTempo = bSource.ReadUInt16(); // Pattern table for (int i = 0; i < (headerSize - 20); i++) // 20 being the number of bytes read since the header size marker { if (i < songLength) FPatternTable.Add(bSource.ReadByte()); else bSource.Seek(1, SeekOrigin.Current); } readPatterns(bSource, nbPatterns); readInstruments(bSource, nbInstruments); // == Computing track properties duration = calculateDuration() * 1000.0; foreach (Instrument i in FInstruments) { if (i.DisplayName.Length > 0) comment.Append(i.DisplayName).Append(Settings.InternalValueSeparator); } if (comment.Length > 0) comment.Remove(comment.Length - 1, 1); tagData.IntegrateValue(TagData.TAG_FIELD_COMMENT, comment.ToString()); bitrate = sizeInfo.FileSize / duration; return result; } protected override int write(TagData tag, BinaryWriter w, string zone) { int result = 0; if (ZONE_TITLE.Equals(zone)) { string title = tag.Title; if (title.Length > 20) title = title.Substring(0, 20); else if (title.Length < 20) title = Utils.BuildStrictLengthString(title, 20, '\0'); w.Write(Utils.Latin1Encoding.GetBytes(title)); result = 1; } return result; } } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // Bessel function (besj) was adapted for use in AGG library by Andy Wilk // Contact: castor.vulgaris@gmail.com //---------------------------------------------------------------------------- using System; namespace MatterHackers.Agg { public static class agg_math { //------------------------------------------------------vertex_dist_epsilon // Coinciding points maximal distance (Epsilon) public const double vertex_dist_epsilon = 1e-14; //-----------------------------------------------------intersection_epsilon // See calc_intersection public const double intersection_epsilon = 1.0e-30; //------------------------------------------------------------cross_product public static double cross_product(double x1, double y1, double x2, double y2, double x, double y) { return (x - x2) * (y2 - y1) - (y - y2) * (x2 - x1); } //--------------------------------------------------------point_in_triangle public static bool point_in_triangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { bool cp1 = cross_product(x1, y1, x2, y2, x, y) < 0.0; bool cp2 = cross_product(x2, y2, x3, y3, x, y) < 0.0; bool cp3 = cross_product(x3, y3, x1, y1, x, y) < 0.0; return cp1 == cp2 && cp2 == cp3 && cp3 == cp1; } //-----------------------------------------------------------calc_distance public static double calc_distance(double x1, double y1, double x2, double y2) { double dx = x2 - x1; double dy = y2 - y1; return Math.Sqrt(dx * dx + dy * dy); } //--------------------------------------------------------calc_sq_distance public static double calc_sq_distance(double x1, double y1, double x2, double y2) { double dx = x2 - x1; double dy = y2 - y1; return dx * dx + dy * dy; } //------------------------------------------------calc_line_point_distance public static double calc_line_point_distance(double x1, double y1, double x2, double y2, double x, double y) { double dx = x2 - x1; double dy = y2 - y1; double d = Math.Sqrt(dx * dx + dy * dy); if (d < vertex_dist_epsilon) { return calc_distance(x1, y1, x, y); } return ((x - x2) * dy - (y - y2) * dx) / d; } //-------------------------------------------------------calc_line_point_u public static double calc_segment_point_u(double x1, double y1, double x2, double y2, double x, double y) { double dx = x2 - x1; double dy = y2 - y1; if (dx == 0 && dy == 0) { return 0; } double pdx = x - x1; double pdy = y - y1; return (pdx * dx + pdy * dy) / (dx * dx + dy * dy); } //---------------------------------------------calc_line_point_sq_distance public static double calc_segment_point_sq_distance(double x1, double y1, double x2, double y2, double x, double y, double u) { if (u <= 0) { return calc_sq_distance(x, y, x1, y1); } else if (u >= 1) { return calc_sq_distance(x, y, x2, y2); } return calc_sq_distance(x, y, x1 + u * (x2 - x1), y1 + u * (y2 - y1)); } //---------------------------------------------calc_line_point_sq_distance public static double calc_segment_point_sq_distance(double x1, double y1, double x2, double y2, double x, double y) { return calc_segment_point_sq_distance( x1, y1, x2, y2, x, y, calc_segment_point_u(x1, y1, x2, y2, x, y)); } //-------------------------------------------------------calc_intersection public static bool calc_intersection(double aX1, double aY1, double aX2, double aY2, double bX1, double bY1, double bX2, double bY2, out double x, out double y) { double num = (aY1 - bY1) * (bX2 - bX1) - (aX1 - bX1) * (bY2 - bY1); double den = (aX2 - aX1) * (bY2 - bY1) - (aY2 - aY1) * (bX2 - bX1); if (Math.Abs(den) < intersection_epsilon) { x = 0; y = 0; return false; } double r = num / den; x = aX1 + r * (aX2 - aX1); y = aY1 + r * (aY2 - aY1); return true; } //-----------------------------------------------------intersection_exists public static bool intersection_exists(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { // It's less expensive but you can't control the // boundary conditions: Less or LessEqual double dx1 = x2 - x1; double dy1 = y2 - y1; double dx2 = x4 - x3; double dy2 = y4 - y3; return ((x3 - x2) * dy1 - (y3 - y2) * dx1 < 0.0) != ((x4 - x2) * dy1 - (y4 - y2) * dx1 < 0.0) && ((x1 - x4) * dy2 - (y1 - y4) * dx2 < 0.0) != ((x2 - x4) * dy2 - (y2 - y4) * dx2 < 0.0); // It's is more expensive but more flexible // in terms of boundary conditions. //-------------------- //double den = (x2-x1) * (y4-y3) - (y2-y1) * (x4-x3); //if(Math.Abs(den) < intersection_epsilon) return false; //double nom1 = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3); //double nom2 = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3); //double ua = nom1 / den; //double ub = nom2 / den; //return ua >= 0.0 && ua <= 1.0 && ub >= 0.0 && ub <= 1.0; } //--------------------------------------------------------calc_orthogonal public static void calc_orthogonal(double thickness, double x1, double y1, double x2, double y2, out double x, out double y) { double dx = x2 - x1; double dy = y2 - y1; double d = Math.Sqrt(dx * dx + dy * dy); x = thickness * dy / d; y = -thickness * dx / d; } //--------------------------------------------------------dilate_triangle public static void dilate_triangle(double x1, double y1, double x2, double y2, double x3, double y3, double[] x, double[] y, double d) { double dx1 = 0.0; double dy1 = 0.0; double dx2 = 0.0; double dy2 = 0.0; double dx3 = 0.0; double dy3 = 0.0; double loc = cross_product(x1, y1, x2, y2, x3, y3); if (Math.Abs(loc) > intersection_epsilon) { if (cross_product(x1, y1, x2, y2, x3, y3) > 0.0) { d = -d; } calc_orthogonal(d, x1, y1, x2, y2, out dx1, out dy1); calc_orthogonal(d, x2, y2, x3, y3, out dx2, out dy2); calc_orthogonal(d, x3, y3, x1, y1, out dx3, out dy3); } x[0] = x1 + dx1; y[0] = y1 + dy1; x[1] = x2 + dx1; y[1] = y2 + dy1; x[2] = x2 + dx2; y[2] = y2 + dy2; x[3] = x3 + dx2; y[3] = y3 + dy2; x[4] = x3 + dx3; y[4] = y3 + dy3; x[5] = x1 + dx3; y[5] = y1 + dy3; } //------------------------------------------------------calc_triangle_area public static double calc_triangle_area(double x1, double y1, double x2, double y2, double x3, double y3) { return (x1 * y2 - x2 * y1 + x2 * y3 - x3 * y2 + x3 * y1 - x1 * y3) * 0.5; } //-------------------------------------------------------calc_polygon_area public static double calc_polygon_area(VertexSequence st) { int i; double sum = 0.0; double x = st[0].x; double y = st[0].y; double xs = x; double ys = y; for (i = 1; i < st.size(); i++) { VertexDistance v = st[i]; sum += x * v.y - y * v.x; x = v.x; y = v.y; } return (sum + x * ys - y * xs) * 0.5; } //------------------------------------------------------------------------ // Tables for fast sqrt public static ushort[] g_sqrt_table = //----------g_sqrt_table { 0, 2048,2896,3547,4096,4579,5017,5418,5793,6144,6476,6792,7094,7384,7663,7932,8192,8444, 8689,8927,9159,9385,9606,9822,10033,10240,10443,10642,10837,11029,11217,11403,11585, 11765,11942,12116,12288,12457,12625,12790,12953,13114,13273,13430,13585,13738,13890, 14040,14189,14336,14482,14626,14768,14910,15050,15188,15326,15462,15597,15731,15864, 15995,16126,16255,16384,16512,16638,16764,16888,17012,17135,17257,17378,17498,17618, 17736,17854,17971,18087,18203,18318,18432,18545,18658,18770,18882,18992,19102,19212, 19321,19429,19537,19644,19750,19856,19961,20066,20170,20274,20377,20480,20582,20684, 20785,20886,20986,21085,21185,21283,21382,21480,21577,21674,21771,21867,21962,22058, 22153,22247,22341,22435,22528,22621,22713,22806,22897,22989,23080,23170,23261,23351, 23440,23530,23619,23707,23796,23884,23971,24059,24146,24232,24319,24405,24491,24576, 24661,24746,24831,24915,24999,25083,25166,25249,25332,25415,25497,25580,25661,25743, 25824,25905,25986,26067,26147,26227,26307,26387,26466,26545,26624,26703,26781,26859, 26937,27015,27092,27170,27247,27324,27400,27477,27553,27629,27705,27780,27856,27931, 28006,28081,28155,28230,28304,28378,28452,28525,28599,28672,28745,28818,28891,28963, 29035,29108,29180,29251,29323,29394,29466,29537,29608,29678,29749,29819,29890,29960, 30030,30099,30169,30238,30308,30377,30446,30515,30583,30652,30720,30788,30856,30924, 30992,31059,31127,31194,31261,31328,31395,31462,31529,31595,31661,31727,31794,31859, 31925,31991,32056,32122,32187,32252,32317,32382,32446,32511,32575,32640,32704,32768, 32832,32896,32959,33023,33086,33150,33213,33276,33339,33402,33465,33527,33590,33652, 33714,33776,33839,33900,33962,34024,34086,34147,34208,34270,34331,34392,34453,34514, 34574,34635,34695,34756,34816,34876,34936,34996,35056,35116,35176,35235,35295,35354, 35413,35472,35531,35590,35649,35708,35767,35825,35884,35942,36001,36059,36117,36175, 36233,36291,36348,36406,36464,36521,36578,36636,36693,36750,36807,36864,36921,36978, 37034,37091,37147,37204,37260,37316,37372,37429,37485,37540,37596,37652,37708,37763, 37819,37874,37929,37985,38040,38095,38150,38205,38260,38315,38369,38424,38478,38533, 38587,38642,38696,38750,38804,38858,38912,38966,39020,39073,39127,39181,39234,39287, 39341,39394,39447,39500,39553,39606,39659,39712,39765,39818,39870,39923,39975,40028, 40080,40132,40185,40237,40289,40341,40393,40445,40497,40548,40600,40652,40703,40755, 40806,40857,40909,40960,41011,41062,41113,41164,41215,41266,41317,41368,41418,41469, 41519,41570,41620,41671,41721,41771,41821,41871,41922,41972,42021,42071,42121,42171, 42221,42270,42320,42369,42419,42468,42518,42567,42616,42665,42714,42763,42813,42861, 42910,42959,43008,43057,43105,43154,43203,43251,43300,43348,43396,43445,43493,43541, 43589,43637,43685,43733,43781,43829,43877,43925,43972,44020,44068,44115,44163,44210, 44258,44305,44352,44400,44447,44494,44541,44588,44635,44682,44729,44776,44823,44869, 44916,44963,45009,45056,45103,45149,45195,45242,45288,45334,45381,45427,45473,45519, 45565,45611,45657,45703,45749,45795,45840,45886,45932,45977,46023,46069,46114,46160, 46205,46250,46296,46341,46386,46431,46477,46522,46567,46612,46657,46702,46746,46791, 46836,46881,46926,46970,47015,47059,47104,47149,47193,47237,47282,47326,47370,47415, 47459,47503,47547,47591,47635,47679,47723,47767,47811,47855,47899,47942,47986,48030, 48074,48117,48161,48204,48248,48291,48335,48378,48421,48465,48508,48551,48594,48637, 48680,48723,48766,48809,48852,48895,48938,48981,49024,49067,49109,49152,49195,49237, 49280,49322,49365,49407,49450,49492,49535,49577,49619,49661,49704,49746,49788,49830, 49872,49914,49956,49998,50040,50082,50124,50166,50207,50249,50291,50332,50374,50416, 50457,50499,50540,50582,50623,50665,50706,50747,50789,50830,50871,50912,50954,50995, 51036,51077,51118,51159,51200,51241,51282,51323,51364,51404,51445,51486,51527,51567, 51608,51649,51689,51730,51770,51811,51851,51892,51932,51972,52013,52053,52093,52134, 52174,52214,52254,52294,52334,52374,52414,52454,52494,52534,52574,52614,52654,52694, 52734,52773,52813,52853,52892,52932,52972,53011,53051,53090,53130,53169,53209,53248, 53287,53327,53366,53405,53445,53484,53523,53562,53601,53640,53679,53719,53758,53797, 53836,53874,53913,53952,53991,54030,54069,54108,54146,54185,54224,54262,54301,54340, 54378,54417,54455,54494,54532,54571,54609,54647,54686,54724,54762,54801,54839,54877, 54915,54954,54992,55030,55068,55106,55144,55182,55220,55258,55296,55334,55372,55410, 55447,55485,55523,55561,55599,55636,55674,55712,55749,55787,55824,55862,55900,55937, 55975,56012,56049,56087,56124,56162,56199,56236,56273,56311,56348,56385,56422,56459, 56497,56534,56571,56608,56645,56682,56719,56756,56793,56830,56867,56903,56940,56977, 57014,57051,57087,57124,57161,57198,57234,57271,57307,57344,57381,57417,57454,57490, 57527,57563,57599,57636,57672,57709,57745,57781,57817,57854,57890,57926,57962,57999, 58035,58071,58107,58143,58179,58215,58251,58287,58323,58359,58395,58431,58467,58503, 58538,58574,58610,58646,58682,58717,58753,58789,58824,58860,58896,58931,58967,59002, 59038,59073,59109,59144,59180,59215,59251,59286,59321,59357,59392,59427,59463,59498, 59533,59568,59603,59639,59674,59709,59744,59779,59814,59849,59884,59919,59954,59989, 60024,60059,60094,60129,60164,60199,60233,60268,60303,60338,60373,60407,60442,60477, 60511,60546,60581,60615,60650,60684,60719,60753,60788,60822,60857,60891,60926,60960, 60995,61029,61063,61098,61132,61166,61201,61235,61269,61303,61338,61372,61406,61440, 61474,61508,61542,61576,61610,61644,61678,61712,61746,61780,61814,61848,61882,61916, 61950,61984,62018,62051,62085,62119,62153,62186,62220,62254,62287,62321,62355,62388, 62422,62456,62489,62523,62556,62590,62623,62657,62690,62724,62757,62790,62824,62857, 62891,62924,62957,62991,63024,63057,63090,63124,63157,63190,63223,63256,63289,63323, 63356,63389,63422,63455,63488,63521,63554,63587,63620,63653,63686,63719,63752,63785, 63817,63850,63883,63916,63949,63982,64014,64047,64080,64113,64145,64178,64211,64243, 64276,64309,64341,64374,64406,64439,64471,64504,64536,64569,64601,64634,64666,64699, 64731,64763,64796,64828,64861,64893,64925,64957,64990,65022,65054,65086,65119,65151, 65183,65215,65247,65279,65312,65344,65376,65408,65440,65472,65504 }; public static byte[] g_elder_bit_table = //---------g_elder_bit_table { 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 }; //---------------------------------------------------------------fast_sqrt //Fast integer Sqrt - really fast: no cycles, divisions or multiplications public static int fast_sqrt(int val) { //This code is actually pure C and portable to most //architectures including 64bit ones. int t = val; int bit = 0; int shift = 11; //The following piece of code is just an emulation of the //Ix86 assembler command "bsr" (see above). However on old //Intels (like Intel MMX 233MHz) this code is about twice //as fast as just one "bsr". On PIII and PIV the //bsr is optimized quite well. bit = (int)t >> 24; if (bit != 0) { bit = g_elder_bit_table[bit] + 24; } else { bit = ((int)t >> 16) & 0xFF; if (bit != 0) { bit = g_elder_bit_table[bit] + 16; } else { bit = ((int)t >> 8) & 0xFF; if (bit != 0) { bit = g_elder_bit_table[bit] + 8; } else { bit = g_elder_bit_table[t]; } } } //This code calculates the sqrt. bit -= 9; if (bit > 0) { bit = (bit >> 1) + (bit & 1); shift -= (int)bit; val >>= (bit << 1); } return (int)((int)g_sqrt_table[val] >> (int)shift); } //--------------------------------------------------------------------besj // Function BESJ calculates Bessel function of first kind of order n // Arguments: // n - an integer (>=0), the order // x - value at which the Bessel function is required //-------------------- // C++ Mathematical Library // Converted from equivalent FORTRAN library // Converted by Gareth Walker for use by course 392 computational project // All functions tested and yield the same results as the corresponding // FORTRAN versions. // // If you have any problems using these functions please report them to // M.Muldoon@UMIST.ac.uk // // Documentation available on the web // http://www.ma.umist.ac.uk/mrm/Teaching/392/libs/392.html // Version 1.0 8/98 // 29 October, 1999 //-------------------- // Adapted for use in AGG library by Andy Wilk (castor.vulgaris@gmail.com) //------------------------------------------------------------------------ public static double besj(double x, int n) { if (n < 0) { return 0; } double d = 1E-6; double b = 0; if (Math.Abs(x) <= d) { if (n != 0) return 0; return 1; } double b1 = 0; // b1 is the value from the previous iteration // Set up a starting order for recurrence int m1 = (int)Math.Abs(x) + 6; if (Math.Abs(x) > 5) { m1 = (int)(Math.Abs(1.4 * x + 60 / x)); } int m2 = (int)(n + 2 + Math.Abs(x) / 4); if (m1 > m2) { m2 = m1; } // Apply recurrence down from current max order for (; ; ) { double c3 = 0; double c2 = 1E-30; double c4 = 0; int m8 = 1; if (m2 / 2 * 2 == m2) { m8 = -1; } int imax = m2 - 2; for (int i = 1; i <= imax; i++) { double c6t = 2 * (m2 - i) * c2 / x - c3; c3 = c2; c2 = c6t; if (m2 - i - 1 == n) { b = c6t; } m8 = -1 * m8; if (m8 > 0) { c4 = c4 + 2 * c6t; } } double c6 = 2 * c2 / x - c3; if (n == 0) { b = c6; } c4 += c6; b /= c4; if (Math.Abs(b - b1) < d) { return b; } b1 = b; m2 += 3; } } } }
// 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: Your favorite String class. Native methods ** are implemented in StringNative.cpp ** ===========================================================*/ using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; namespace System { // The String class represents a static string of characters. Many of // the String methods perform some type of transformation on the current // instance and return the result as a new String. All comparison methods are // implemented as a part of String. As with arrays, character positions // (indices) are zero-based. // STRING LAYOUT // ------------- // Strings are null-terminated for easy interop with native, but the value returned by String.Length // does NOT include this null character in its count. As a result, there's some trickiness here in the // layout and allocation of strings that needs explanation... // // String is allocated like any other array, using the RhNewArray API. It is essentially a very special // char[] object. In order to be an array, the String EEType must have an 'array element size' of 2, // which is setup by a special case in the binder. Strings must also have a typical array instance // layout, which means that the first field after the m_pEEType field is the 'number of array elements' // field. However, here, it is called _stringLength because it contains the number of characters in the // string (NOT including the terminating null element) and, thus, directly represents both the array // length and String.Length. // // As with all arrays, the GC calculates the size of an object using the following formula: // // obj_size = align(base_size + (num_elements * element_size), sizeof(void*)) // // The values 'base_size' and 'element_size' are both stored in the EEType for String and 'num_elements' // is _stringLength. // // Our base_size is the size of the fixed portion of the string defined below. It, therefore, contains // the size of the _firstChar field in it. This means that, since our string data actually starts // inside the fixed 'base_size' area, and our num_elements is equal to String.Length, we end up with one // extra character at the end. This is how we get our extra null terminator which allows us to pass a // pinned string out to native code as a null-terminated string. This is also why we don't increment the // requested string length by one before passing it to RhNewArray. There is no need to allocate an extra // array element, it is already allocated here in the fixed layout of the String. // // Typically, the base_size of an array type is aligned up to the nearest pointer size multiple (so that // array elements start out aligned in case they need alignment themselves), but we don't want to do that // with String because we are allocating String.Length components with RhNewArray and the overall object // size will then need another alignment, resulting in wasted space. So the binder specially shrinks the // base_size of String, leaving it unaligned in order to allow the use of that otherwise wasted space. // // One more note on base_size -- on 64-bit, the base_size ends up being 22 bytes, which is less than the // min_obj_size of (3 * sizeof(void*)). This is OK because our array allocator will still align up the // overall object size, so a 0-length string will end up with an object size of 24 bytes, which meets the // min_obj_size requirement. // // NOTE: This class is marked EagerStaticClassConstruction because McgCurrentModule class being eagerly // constructed itself depends on this class also being eagerly constructed. Plus, it's nice to have this // eagerly constructed to avoid the cost of defered ctors. I can't imagine any app that doesn't use string // [StructLayout(LayoutKind.Sequential)] [System.Runtime.CompilerServices.EagerStaticClassConstructionAttribute] public sealed partial class String : IComparable, IEnumerable, IEnumerable<char>, IComparable<String>, IEquatable<String>, IConvertible, ICloneable { #if BIT64 private const int POINTER_SIZE = 8; #else private const int POINTER_SIZE = 4; #endif // m_pEEType + _stringLength internal const int FIRST_CHAR_OFFSET = POINTER_SIZE + sizeof(int); // CS0169: The private field '{blah}' is never used // CS0649: Field '{blah}' is never assigned to, and will always have its default value #pragma warning disable 169, 649 #if !CORERT [Bound] #endif // WARNING: We allow diagnostic tools to directly inspect these two members (_stringLength, _firstChar) // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. private int _stringLength; private char _firstChar; #pragma warning restore // String constructors // These are special. the implementation methods for these have a different signature from the // declared constructors. [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String(char[] value); [System.Runtime.CompilerServices.DependencyReductionRoot] private static String Ctor(char[] value) { if (value != null && value.Length != 0) { String result = FastAllocateString(value.Length); unsafe { fixed (char* dest = &result._firstChar, source = value) { wstrcpy(dest, source, value.Length); } } return result; } else return String.Empty; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String(char[] value, int startIndex, int length); [System.Runtime.CompilerServices.DependencyReductionRoot] private static String Ctor(char[] value, int startIndex, int length) { if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); if (startIndex > value.Length - length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); if (length > 0) { String result = FastAllocateString(length); unsafe { fixed (char* dest = &result._firstChar, source = value) { wstrcpy(dest, source + startIndex, length); } } return result; } else return String.Empty; } [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe public extern String(char* value); [System.Runtime.CompilerServices.DependencyReductionRoot] private static unsafe String Ctor(char* ptr) { if (ptr == null) return String.Empty; #if !PLATFORM_UNIX if (ptr < (char*)64000) throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom); #endif // PLATFORM_UNIX try { int count = wcslen(ptr); if (count == 0) return String.Empty; String result = FastAllocateString(count); fixed (char* dest = &result._firstChar) wstrcpy(dest, ptr, count); return result; } catch (NullReferenceException) { throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR); } } [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe public extern String(char* value, int startIndex, int length); [System.Runtime.CompilerServices.DependencyReductionRoot] private static unsafe String Ctor(char* ptr, int startIndex, int length) { if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); } if (startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); } Contract.EndContractBlock(); char* pFrom = ptr + startIndex; if (pFrom < ptr) { // This means that the pointer operation has had an overflow throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR); } if (length == 0) return String.Empty; String result = FastAllocateString(length); try { fixed (char* dest = &result._firstChar) wstrcpy(dest, pFrom, length); return result; } catch (NullReferenceException) { throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String(char c, int count); [System.Runtime.CompilerServices.DependencyReductionRoot] private static String Ctor(char c, int count) { if (count > 0) { String result = FastAllocateString(count); if (c == '\0') return result; // Fast path null char string unsafe { fixed (char* dest = &result._firstChar) { uint cc = (uint)((c << 16) | c); uint* dmem = (uint*)dest; if (count >= 4) { count -= 4; do { dmem[0] = cc; dmem[1] = cc; dmem += 2; count -= 4; } while (count >= 0); } if ((count & 2) != 0) { *dmem = cc; dmem++; } if ((count & 1) != 0) ((char*)dmem)[0] = c; } } return result; } else if (count == 0) return String.Empty; else throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount); } public object Clone() { return this; } public static readonly String Empty = ""; // Gets the character at a specified position. // // Spec#: Apply the precondition here using a contract assembly. Potential perf issue. [System.Runtime.CompilerServices.IndexerName("Chars")] public unsafe char this[int index] { [NonVersionable] #if CORERT [Intrinsic] get { if ((uint)index >= _stringLength) throw new IndexOutOfRangeException(); return Unsafe.Add(ref _firstChar, index); } #else [BoundsChecking] get { return Unsafe.Add(ref _firstChar, index); } #endif } // Converts a substring of this string to an array of characters. Copies the // characters of this string beginning at position sourceIndex and ending at // sourceIndex + count - 1 to the character array buffer, beginning // at destinationIndex. // unsafe public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException(nameof(destination)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount); if (sourceIndex < 0) throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index); if (count > Length - sourceIndex) throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexCount); if (destinationIndex > destination.Length - count || destinationIndex < 0) throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount); // Note: fixed does not like empty arrays if (count > 0) { fixed (char* src = &_firstChar) fixed (char* dest = destination) wstrcpy(dest + destinationIndex, src + sourceIndex, count); } } // Returns the entire string as an array of characters. unsafe public char[] ToCharArray() { // Huge performance improvement for short strings by doing this. int length = Length; if (length > 0) { char[] chars = new char[length]; fixed (char* src = &_firstChar) fixed (char* dest = &chars[0]) { wstrcpy(dest, src, length); } return chars; } return Array.Empty<char>(); } // Returns a substring of this string as an array of characters. // unsafe public char[] ToCharArray(int startIndex, int length) { // Range check everything. if (startIndex < 0 || startIndex > Length || startIndex > Length - length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); if (length > 0) { char[] chars = new char[length]; fixed (char* src = &_firstChar) fixed (char* dest = &chars[0]) { wstrcpy(dest, src + startIndex, length); } return chars; } return Array.Empty<char>(); } public static bool IsNullOrEmpty(String value) { return (value == null || value.Length == 0); } public static bool IsNullOrWhiteSpace(String value) { if (value == null) return true; for (int i = 0; i < value.Length; i++) { if (!Char.IsWhiteSpace(value[i])) return false; } return true; } // Gets the length of this string // /// This is a EE implemented function so that the JIT can recognise is specially /// and eliminate checks on character fetchs in a loop like: /// for(int i = 0; i < str.Length; i++) str[i] /// The actually code generated for this will be one instruction and will be inlined. // // Spec#: Add postcondition in a contract assembly. Potential perf problem. public int Length { get { return _stringLength; } } // Helper for encodings so they can talk to our buffer directly // stringLength must be the exact size we'll expect unsafe internal static String CreateStringFromEncoding( byte* bytes, int byteLength, Encoding encoding) { Debug.Assert(bytes != null); Debug.Assert(byteLength >= 0); // Get our string length int stringLength = encoding.GetCharCount(bytes, byteLength, null); Debug.Assert(stringLength >= 0, "stringLength >= 0"); // They gave us an empty string if they needed one // 0 bytelength might be possible if there's something in an encoder if (stringLength == 0) return String.Empty; String s = FastAllocateString(stringLength); fixed (char* pTempChars = &s._firstChar) { int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null); Debug.Assert(stringLength == doubleCheck, "Expected encoding.GetChars to return same length as encoding.GetCharCount"); } return s; } // This is only intended to be used by char.ToString. // It is necessary to put the code in this class instead of Char, since _firstChar is a private member. // Making _firstChar internal would be dangerous since it would make it much easier to break String's immutability. internal static string CreateFromChar(char c) { string result = FastAllocateString(1); result._firstChar = c; return result; } internal static String FastAllocateString(int length) { try { // We allocate one extra char as an interop convenience so that our strings are null- // terminated, however, we don't pass the extra +1 to the array allocation because the base // size of this object includes the _firstChar field. string newStr = RuntimeImports.RhNewArrayAsString(EETypePtr.EETypePtrOf<string>(), length); Debug.Assert(newStr._stringLength == length); return newStr; } catch (OverflowException) { throw new OutOfMemoryException(); } } internal static unsafe void wstrcpy(char* dmem, char* smem, int charCount) { Buffer.Memmove((byte*)dmem, (byte*)smem, ((uint)charCount) * 2); } // Returns this string. public override String ToString() { return this; } // Returns this string. String IConvertible.ToString(IFormatProvider provider) { return this; } IEnumerator<char> IEnumerable<char>.GetEnumerator() { return new CharEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new CharEnumerator(this); } internal static unsafe int wcslen(char* ptr) { char* end = ptr; // First make sure our pointer is aligned on a word boundary int alignment = IntPtr.Size - 1; // If ptr is at an odd address (e.g. 0x5), this loop will simply iterate all the way while (((uint)end & (uint)alignment) != 0) { if (*end == 0) goto FoundZero; end++; } #if !BIT64 // The loop condition below works because if "end[0] & end[1]" is non-zero, that means // neither operand can have been zero. If is zero, we have to look at the operands individually, // but we hope this going to fairly rare. // In general, it would be incorrect to access end[1] if we haven't made sure // end[0] is non-zero. However, we know the ptr has been aligned by the loop above // so end[0] and end[1] must be in the same word (and therefore page), so they're either both accessible, or both not. while ((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0)) { end += 2; } Debug.Assert(end[0] == 0 || end[1] == 0); if (end[0] != 0) end++; #else // !BIT64 // Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord // 64-bit implementation: process 1 ulong (word) at a time // What we do here is add 0x7fff from each of the // 4 individual chars within the ulong, using MagicMask. // If the char > 0 and < 0x8001, it will have its high bit set. // We then OR with MagicMask, to set all the other bits. // This will result in all bits set (ulong.MaxValue) for any // char that fits the above criteria, and something else otherwise. // Note that for any char > 0x8000, this will be a false // positive and we will fallback to the slow path and // check each char individually. This is OK though, since // we optimize for the common case (ASCII chars, which are < 0x80). // NOTE: We can access a ulong a time since the ptr is aligned, // and therefore we're only accessing the same word/page. (See notes // for the 32-bit version above.) const ulong MagicMask = 0x7fff7fff7fff7fff; while (true) { ulong word = *(ulong*)end; word += MagicMask; // cause high bit to be set if not zero, and <= 0x8000 word |= MagicMask; // set everything besides the high bits if (word == ulong.MaxValue) // 0xffff... { // all of the chars have their bits set (and therefore none can be 0) end += 4; continue; } // at least one of them didn't have their high bit set! // go through each char and check for 0. if (end[0] == 0) goto EndAt0; if (end[1] == 0) goto EndAt1; if (end[2] == 0) goto EndAt2; if (end[3] == 0) goto EndAt3; // if we reached here, it was a false positive-- just continue end += 4; } EndAt3: end++; EndAt2: end++; EndAt1: end++; EndAt0: #endif // !BIT64 FoundZero: Debug.Assert(*end == 0); int count = (int)(end - ptr); return count; } // // IConvertible implementation // TypeCode IConvertible.GetTypeCode() { return TypeCode.String; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this, provider); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this, provider); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this, provider); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this, provider); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this, provider); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this, provider); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this, provider); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this, provider); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this, provider); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this, provider); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this, provider); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this, provider); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this, provider); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { return Convert.ToDateTime(this, provider); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } // Normalization Methods // These just wrap calls to Normalization class public bool IsNormalized() { // Default to Form IDNA return IsNormalized((NormalizationForm)ExtendedNormalizationForms.FormIdna); } public bool IsNormalized(NormalizationForm normalizationForm) { return Normalization.IsNormalized(this, normalizationForm); } public String Normalize() { // Default to Form IDNA return Normalize((NormalizationForm)ExtendedNormalizationForms.FormIdna); } public String Normalize(NormalizationForm normalizationForm) { return Normalization.Normalize(this, normalizationForm); } } }
/* * NameObjectCollectionBase.cs - Implementation of * "System.Collections.Specialized.NameObjectCollectionBase". * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Collections.Specialized { using System; using System.Globalization; using System.Collections; using System.Runtime.Serialization; #if !ECMA_COMPAT public #else internal #endif abstract class NameObjectCollectionBase : ICollection, IEnumerable #if CONFIG_SERIALIZATION , ISerializable, IDeserializationCallback #endif { // Internal state. We implement our own hash table rather than // use the Hashtable class, because we have to handle multiple // values per key, which Hashtable cannot do. Working around // Hashtable's foibles can give unreliable behaviour as entries // are added and removed. private Entry[] table; private IHashCodeProvider hcp; private IComparer cmp; private ArrayList entries; private bool readOnly; private const int HashTableSize = 61; #if CONFIG_SERIALIZATION private SerializationInfo info; #endif // Constructors. protected NameObjectCollectionBase() : this(0, null, null) {} protected NameObjectCollectionBase(int capacity) : this(capacity, null, null) {} protected NameObjectCollectionBase(IHashCodeProvider hashProvider, IComparer comparer) : this(0, hashProvider, comparer) {} protected NameObjectCollectionBase(int capacity, IHashCodeProvider hashProvider, IComparer comparer) { if(capacity < 0) { throw new ArgumentOutOfRangeException ("capacity", S._("ArgRange_NonNegative")); } if(hashProvider == null) { hashProvider = CaseInsensitiveHashCodeProvider.Default; } if(comparer == null) { comparer = CaseInsensitiveComparer.Default; } table = new Entry [HashTableSize]; hcp = hashProvider; cmp = comparer; entries = new ArrayList(capacity); readOnly = false; } #if CONFIG_SERIALIZATION protected NameObjectCollectionBase(SerializationInfo info, StreamingContext context) : this(0, null, null) { this.info = info; } #endif // Properties. public virtual KeysCollection Keys { get { return new KeysCollection(this); } } protected bool IsReadOnly { get { return readOnly; } set { readOnly = value; } } // Implement the ICollection interface. public virtual int Count { get { return entries.Count; } } void ICollection.CopyTo(Array array, int index) { foreach(Object obj in this) { array.SetValue(obj, index); ++index; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return this; } } // Implement the IEnumerator interface. public IEnumerator GetEnumerator() { return new KeysEnumerator(this); } #if CONFIG_SERIALIZATION // Implement the ISerializable interface. public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // Validate the parameters. if(info == null) { throw new ArgumentNullException("info"); } // Add general information. info.AddValue("ReadOnly", readOnly); info.AddValue("HashProvider", hcp, typeof(IHashCodeProvider)); info.AddValue("Comparer", cmp, typeof(IComparer)); info.AddValue("Count", entries.Count); // Build arrays for the keys and values and serialize them. String[] keys = new String [entries.Count]; Object[] values = new Object [entries.Count]; int posn; Entry entry; for(posn = 0; posn < entries.Count; ++posn) { entry = (Entry)(entries[posn]); keys[posn] = entry.key; values[posn] = entry.value; } info.AddValue("Keys", keys, typeof(String[])); info.AddValue("Values", values, typeof(Object[])); } // Implement the IDeserializationCallback interface. public virtual void OnDeserialization(Object sender) { // Bail out if we've already been deserialized. if(hcp != null) { return; } // Validate the deserialization state. if(info == null) { throw new SerializationException (S._("Serialize_StateMissing")); } // De-serialize the hash provider and comparer. hcp = (IHashCodeProvider)(info.GetValue ("HashProvider", typeof(IHashCodeProvider))); cmp = (IComparer)(info.GetValue ("Comparer", typeof(IComparer))); if(hcp == null || cmp == null) { throw new SerializationException (S._("Serialize_StateMissing")); } // De-serialize the key/value arrays. String[] keys = (String[])(info.GetValue ("Keys", typeof(String[]))); Object[] values = (String[])(info.GetValue ("Values", typeof(Object[]))); if(keys == null || values == null) { throw new SerializationException (S._("Serialize_StateMissing")); } int count = info.GetInt32("Count"); int posn; for(posn = 0; posn < count; ++posn) { BaseAdd(keys[posn], values[posn]); } // De-serialize the read-only flag last. readOnly = info.GetBoolean("ReadOnly"); // De-serialization is complete. info = null; } #endif // CONFIG_SERIALIZATION // Get the hash value for a string, restricted to the table size. private int GetHash(String name) { int hash = (name != null ? hcp.GetHashCode(name) : 0); return (int)(((uint)hash) % (uint)HashTableSize); } // Compare two keys for equality. private bool Compare(String key1, String key2) { if(key1 == null || key2 == null) { return (key1 == key2); } else { return (cmp.Compare(key1, key2) == 0); } } // Add a name/value pair to this collection. protected void BaseAdd(String name, Object value) { if(readOnly) { throw new NotSupportedException(S._("NotSupp_ReadOnly")); } Entry entry = new Entry(name, value); int hash = GetHash(name); Entry last = table[hash]; if(last == null) { table[hash] = entry; } else { while(last.next != null) { last = last.next; } last.next = entry; } entries.Add(entry); } // Clear this collection. protected void BaseClear() { if(readOnly) { throw new NotSupportedException(S._("NotSupp_ReadOnly")); } ((IList)table).Clear(); entries.Clear(); } // Get the item at a specific index within this collection. protected Object BaseGet(int index) { return ((Entry)(entries[index])).value; } // Get the item associated with a specific name within this collection. protected Object BaseGet(String name) { Entry entry = table[GetHash(name)]; while(entry != null) { if(Compare(entry.key, name)) { return entry.value; } entry = entry.next; } return null; } // Get a list of all keys in the collection. protected String[] BaseGetAllKeys() { String[] keys = new String [entries.Count]; int index = 0; foreach(Entry entry in entries) { keys[index++] = (String)(entry.key); } return keys; } // Get a list of all values in the collection. protected Object[] BaseGetAllValues() { Object[] values = new String [entries.Count]; int index = 0; foreach(Entry entry in entries) { values[index++] = entry.value; } return values; } // Get an array of a specific type of all values in the collection. protected Object[] BaseGetAllValues(Type type) { if(type == null) { throw new ArgumentNullException("type"); } Object[] values = (Object[]) Array.CreateInstance(type, entries.Count); int index = 0; foreach(Entry entry in entries) { values[index++] = entry.value; } return values; } // Get the key at a specific index. protected String BaseGetKey(int index) { return ((Entry)(entries[index])).key; } // Determine if there a non-null keys in the collection. protected bool BaseHasKeys() { Entry entry = table[GetHash(null)]; while(entry != null) { if(entry.key != null) { return true; } entry = entry.next; } return false; } // Remove all entries with a specific key. protected void BaseRemove(String name) { if(readOnly) { throw new NotSupportedException(S._("NotSupp_ReadOnly")); } int hash = GetHash(name); Entry entry = table[hash]; Entry prev = null; while(entry != null) { if(Compare(entry.key, name)) { if(prev != null) { prev.next = entry.next; } else { table[hash] = entry.next; } entry = entry.next; } else { prev = entry; entry = entry.next; } } int count = entries.Count; int posn = 0; while(posn < count) { if(Compare(((Entry)(entries[posn])).key, name)) { entries.RemoveAt(posn); --count; } else { ++posn; } } } // Remove a specific entry by index. protected void BaseRemoveAt(int index) { if(readOnly) { throw new NotSupportedException(S._("NotSupp_ReadOnly")); } Entry entry = (Entry)(entries[index]); entries.RemoveAt(index); int hash = GetHash(entry.key); Entry find = table[hash]; Entry prev = null; while(find != null) { if(find == entry) { if(prev != null) { prev.next = find.next; } else { table[hash] = find.next; } return; } else { prev = find; find = find.next; } } } // Set the value of an entry at a particular index. protected void BaseSet(int index, Object value) { if(readOnly) { throw new NotSupportedException(S._("NotSupp_ReadOnly")); } ((Entry)(entries[index])).value = value; } // Set the value of the first entry with a particular name. protected void BaseSet(String name, Object value) { if(readOnly) { throw new NotSupportedException(S._("NotSupp_ReadOnly")); } int hash = GetHash(name); Entry entry = table[hash]; while(entry != null) { if(Compare(entry.key, name)) { entry.value = value; return; } entry = entry.next; } entry = new Entry(name, value); entry.next = table[hash]; table[hash] = entry; entries.Add(entry); } // Structure of an entry in the collection. private class Entry { public String key; public Object value; public Entry next; // Constructor. public Entry(String key, Object value) { this.key = key; this.value = value; this.next = null; } }; // class Entry // Alternate interface to the keys in a name object collection. public class KeysCollection : ICollection, IEnumerable { // Internal state. private NameObjectCollectionBase c; // Constructor. internal KeysCollection(NameObjectCollectionBase c) { this.c = c; } // Implement the ICollection interface. public int Count { get { return c.Count; } } void ICollection.CopyTo(Array array, int index) { foreach(Object obj in this) { array.SetValue(obj, index); ++index; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return c; } } // Implement the IEnumerable interface. public IEnumerator GetEnumerator() { return new KeysEnumerator(c); } // Get the key at a specific index. public String Get(int index) { return c.BaseGetKey(index); } public String this[int index] { get { return Get(index); } } }; // class KeysCollection // Enumerator for the keys in a name object collection. private class KeysEnumerator : IEnumerator { // Internal state. private IEnumerator e; // Constructor. public KeysEnumerator(NameObjectCollectionBase c) { e = c.entries.GetEnumerator(); } // Implement the IEnumerator interface. bool IEnumerator.MoveNext() { return e.MoveNext(); } void IEnumerator.Reset() { e.Reset(); } Object IEnumerator.Current { get { return ((Entry)(e.Current)).key; } } }; // class KeysEnumerator #if ECMA_COMPAT // Local copy of "System.Collections.CaseInsenstiveHashCodeProvider" // for use in ECMA-compatbile systems. private class CaseInsensitiveHashCodeProvider : IHashCodeProvider { private static readonly CaseInsensitiveHashCodeProvider defaultProvider = new CaseInsensitiveHashCodeProvider(); // Internal state. private TextInfo info; // Get the default comparer instance. public static CaseInsensitiveHashCodeProvider Default { get { return defaultProvider; } } // Constructors. public CaseInsensitiveHashCodeProvider() { info = CultureInfo.CurrentCulture.TextInfo; } public CaseInsensitiveHashCodeProvider(CultureInfo culture) { if(culture == null) { throw new ArgumentNullException("culture"); } info = culture.TextInfo; } // Implement the IHashCodeProvider interface. public int GetHashCode(Object obj) { String str = (obj as String); if(str != null) { return info.ToLower(str).GetHashCode(); } else if(obj != null) { return obj.GetHashCode(); } else { throw new ArgumentNullException("obj"); } } }; // class CaseInsensitiveHashCodeProvider // Local copy of "System.Collections.CaseInsenstiveComparer" // for use in ECMA-compatbile systems. private class CaseInsensitiveComparer : IComparer { // The default case insensitive comparer instance. private static readonly CaseInsensitiveComparer defaultComparer = new CaseInsensitiveComparer(); // Internal state. private CompareInfo compare; // Get the default comparer instance. public static CaseInsensitiveComparer Default { get { return defaultComparer; } } // Constructors. public CaseInsensitiveComparer() { compare = CultureInfo.CurrentCulture.CompareInfo; } public CaseInsensitiveComparer(CultureInfo culture) { if(culture == null) { throw new ArgumentNullException("culture"); } compare = culture.CompareInfo; } // Implement the IComparer interface. public int Compare(Object a, Object b) { String stra = (a as String); String strb = (b as String); if(stra != null && strb != null) { return compare.Compare (stra, strb, CompareOptions.IgnoreCase); } else { return Comparer.Default.Compare(a, b); } } }; // class CaseInsensitiveComparer #endif // ECMA_COMPAT }; // class NameObjectCollectionBase }; // namespace System.Collections.Specialized
using System; using System.Threading.Tasks; using OrchardCore.ContentManagement.Display.Models; using OrchardCore.ContentManagement.Metadata.Models; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Views; namespace OrchardCore.ContentManagement.Display.ContentDisplay { public abstract class ContentFieldDisplayDriver<TField> : DisplayDriverBase, IContentFieldDisplayDriver where TField : ContentField, new() { private const string DisplayToken = "_Display"; private const string DisplaySeparator = "_Display__"; private ContentTypePartDefinition _typePartDefinition; private ContentPartFieldDefinition _partFieldDefinition; public override ShapeResult Factory(string shapeType, Func<IBuildShapeContext, ValueTask<IShape>> shapeBuilder, Func<IShape, Task> initializeAsync) { // e.g., HtmlBodyPart.Summary, HtmlBodyPart-BlogPost, BagPart-LandingPage-Services // context.Shape is the ContentItem shape, we need to alter the part shape var result = base.Factory(shapeType, shapeBuilder, initializeAsync).Prefix(Prefix); if (_typePartDefinition != null && _partFieldDefinition != null) { var partType = _typePartDefinition.PartDefinition.Name; var partName = _typePartDefinition.Name; var fieldType = _partFieldDefinition.FieldDefinition.Name; var fieldName = _partFieldDefinition.Name; var contentType = _typePartDefinition.ContentTypeDefinition.Name; var displayMode = _partFieldDefinition.DisplayMode(); var hasDisplayMode = !String.IsNullOrEmpty(displayMode); if (GetEditorShapeType(_partFieldDefinition) == shapeType) { // HtmlBodyPart-Description, Services-Description result.Differentiator($"{partName}-{fieldName}"); // We do not need to add alternates on edit as they are handled with field editor types so return before adding alternates return result; } // If the shape type and the field type only differ by the display mode if (hasDisplayMode && shapeType == fieldType + DisplaySeparator + displayMode) { // Preserve the shape name regardless its differentiator result.Name($"{partName}-{fieldName}"); } if (fieldType == shapeType) { // HtmlBodyPart-Description, Services-Description result.Differentiator($"{partName}-{fieldName}"); } else { // HtmlBodyPart-Description-TextField, Services-Description-TextField result.Differentiator($"{partName}-{fieldName}-{shapeType}"); } result.Displaying(ctx => { var displayTypes = new[] { "", "_" + ctx.Shape.Metadata.DisplayType }; // [ShapeType]_[DisplayType], e.g. TextField.Summary ctx.Shape.Metadata.Alternates.Add($"{shapeType}_{ctx.Shape.Metadata.DisplayType}"); // When the shape type is the same as the field, we can ignore one of them in the alternate name // For instance TextField returns a unique TextField shape type. if (shapeType == fieldType) { foreach (var displayType in displayTypes) { // [PartType]__[FieldName], e.g. HtmlBodyPart-Description ctx.Shape.Metadata.Alternates.Add($"{partType}{displayType}__{fieldName}"); // [ContentType]__[FieldType], e.g. Blog-TextField, LandingPage-TextField ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{fieldType}"); // [ContentType]__[PartName]__[FieldName], e.g. Blog-HtmlBodyPart-Description, LandingPage-Services-Description ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partType}__{fieldName}"); } } else { if (hasDisplayMode) { // [FieldType]_[DisplayType]__[DisplayMode]_Display, e.g. TextField-Header.Display.Summary ctx.Shape.Metadata.Alternates.Add($"{fieldType}_{ctx.Shape.Metadata.DisplayType}__{displayMode}{DisplayToken}"); } for (var i = 0; i < displayTypes.Length; i++) { var displayType = displayTypes[i]; if (hasDisplayMode) { shapeType = $"{fieldType}__{displayMode}"; if (displayType == "") { displayType = DisplayToken; } else { shapeType += DisplayToken; } } // [FieldType]__[ShapeType], e.g. TextField-TextFieldSummary ctx.Shape.Metadata.Alternates.Add($"{fieldType}{displayType}__{shapeType}"); // [PartType]__[FieldName]__[ShapeType], e.g. HtmlBodyPart-Description-TextFieldSummary ctx.Shape.Metadata.Alternates.Add($"{partType}{displayType}__{fieldName}__{shapeType}"); // [ContentType]__[FieldType]__[ShapeType], e.g. Blog-TextField-TextFieldSummary, LandingPage-TextField-TextFieldSummary ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{fieldType}__{shapeType}"); // [ContentType]__[PartName]__[FieldName]__[ShapeType], e.g. Blog-HtmlBodyPart-Description-TextFieldSummary, LandingPage-Services-Description-TextFieldSummary ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partName}__{fieldName}__{shapeType}"); } } }); } return result; } Task<IDisplayResult> IContentFieldDisplayDriver.BuildDisplayAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, BuildDisplayContext context) { if (!String.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !String.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return Task.FromResult(default(IDisplayResult)); } var field = contentPart.Get<TField>(partFieldDefinition.Name); if (field != null) { BuildPrefix(typePartDefinition, partFieldDefinition, context.HtmlFieldPrefix); var fieldDisplayContext = new BuildFieldDisplayContext(contentPart, typePartDefinition, partFieldDefinition, context); _typePartDefinition = typePartDefinition; _partFieldDefinition = partFieldDefinition; var result = DisplayAsync(field, fieldDisplayContext); _typePartDefinition = null; _partFieldDefinition = null; return result; } return Task.FromResult(default(IDisplayResult)); } Task<IDisplayResult> IContentFieldDisplayDriver.BuildEditorAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, BuildEditorContext context) { if (!String.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !String.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return Task.FromResult(default(IDisplayResult)); } var field = contentPart.GetOrCreate<TField>(partFieldDefinition.Name); if (field != null) { BuildPrefix(typePartDefinition, partFieldDefinition, context.HtmlFieldPrefix); var fieldEditorContext = new BuildFieldEditorContext(contentPart, typePartDefinition, partFieldDefinition, context); _typePartDefinition = typePartDefinition; _partFieldDefinition = partFieldDefinition; var result = EditAsync(field, fieldEditorContext); _typePartDefinition = null; _partFieldDefinition = null; return result; } return Task.FromResult(default(IDisplayResult)); } async Task<IDisplayResult> IContentFieldDisplayDriver.UpdateEditorAsync(ContentPart contentPart, ContentPartFieldDefinition partFieldDefinition, ContentTypePartDefinition typePartDefinition, UpdateEditorContext context) { if (!String.Equals(typeof(TField).Name, partFieldDefinition.FieldDefinition.Name) && !String.Equals(nameof(ContentField), partFieldDefinition.FieldDefinition.Name)) { return null; } var field = contentPart.GetOrCreate<TField>(partFieldDefinition.Name); BuildPrefix(typePartDefinition, partFieldDefinition, context.HtmlFieldPrefix); var updateFieldEditorContext = new UpdateFieldEditorContext(contentPart, typePartDefinition, partFieldDefinition, context); _typePartDefinition = typePartDefinition; _partFieldDefinition = partFieldDefinition; var result = await UpdateAsync(field, context.Updater, updateFieldEditorContext); _typePartDefinition = null; _partFieldDefinition = null; if (result == null) { return null; } contentPart.Apply(partFieldDefinition.Name, field); return result; } public virtual Task<IDisplayResult> DisplayAsync(TField field, BuildFieldDisplayContext fieldDisplayContext) { return Task.FromResult(Display(field, fieldDisplayContext)); } public virtual Task<IDisplayResult> EditAsync(TField field, BuildFieldEditorContext context) { return Task.FromResult(Edit(field, context)); } public virtual Task<IDisplayResult> UpdateAsync(TField field, IUpdateModel updater, UpdateFieldEditorContext context) { return Task.FromResult(Update(field, updater, context)); } public virtual IDisplayResult Display(TField field, BuildFieldDisplayContext fieldDisplayContext) { return null; } public virtual IDisplayResult Edit(TField field, BuildFieldEditorContext context) { return null; } public virtual IDisplayResult Update(TField field, IUpdateModel updater, UpdateFieldEditorContext context) { return null; } protected string GetEditorShapeType(string shapeType, ContentPartFieldDefinition partFieldDefinition) { var editor = partFieldDefinition.Editor(); return !String.IsNullOrEmpty(editor) ? shapeType + "__" + editor : shapeType; } protected string GetEditorShapeType(string shapeType, BuildFieldEditorContext context) { return GetEditorShapeType(shapeType, context.PartFieldDefinition); } protected string GetEditorShapeType(ContentPartFieldDefinition partFieldDefinition) { return GetEditorShapeType(typeof(TField).Name + "_Edit", partFieldDefinition); } protected string GetEditorShapeType(BuildFieldEditorContext context) { return GetEditorShapeType(context.PartFieldDefinition); } protected string GetDisplayShapeType(string shapeType, BuildFieldDisplayContext context) { var displayMode = context.PartFieldDefinition.DisplayMode(); return !String.IsNullOrEmpty(displayMode) ? shapeType + DisplaySeparator + displayMode : shapeType; } protected string GetDisplayShapeType(BuildFieldDisplayContext context) { return GetDisplayShapeType(typeof(TField).Name, context); } private void BuildPrefix(ContentTypePartDefinition typePartDefinition, ContentPartFieldDefinition partFieldDefinition, string htmlFieldPrefix) { Prefix = typePartDefinition.Name + "." + partFieldDefinition.Name; if (!String.IsNullOrEmpty(htmlFieldPrefix)) { Prefix = htmlFieldPrefix + "." + Prefix; } } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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 MindTouch.Tasking; using NUnit.Framework; namespace MindTouch.Dream.Test { using Yield = IEnumerator<IYield>; [TestFixture] public class CoroutineTests { //--- Types --- public class BubbledException : Exception { } public class IntentionalException : Exception { } //--- Class Fields --- private static readonly log4net.ILog _log = LogUtils.CreateLog(); //--- Class Methods --- #region Coroutines private static Yield Ret(int p, Result<int> result) { result.Return(p); yield break; } private static Yield Yield_Ret(int p, Result<int> result) { yield return AsyncUtil.Sleep(TimeSpan.FromMilliseconds(10), new Result(TimeSpan.MaxValue)); result.Return(p); } private static Yield Throw(int p, Result<int> result) { throw new IntentionalException(); } private static Yield Yield_Throw(int p, Result<int> result) { yield return AsyncUtil.Sleep(TimeSpan.FromMilliseconds(10), new Result(TimeSpan.MaxValue)); throw new IntentionalException(); } private static Yield Ret_Throw(int p, Result<int> result) { result.Return(p); throw new IntentionalException(); } private static Yield Yield_Ret_Throw(int p, Result<int> result) { yield return AsyncUtil.Sleep(TimeSpan.FromMilliseconds(10), new Result(TimeSpan.MaxValue)); result.Return(p); throw new IntentionalException(); } private static Yield Ret_Yield_Throw(int p, Result<int> result) { yield return AsyncUtil.Sleep(TimeSpan.FromMilliseconds(10), new Result(TimeSpan.MaxValue)); result.Return(p); throw new IntentionalException(); } private static Yield Call(CoroutineHandler<int, Result<int>> coroutine, int p, Result<int> result) { Result<int> inner; yield return inner = Coroutine.Invoke(coroutine, p, new Result<int>()); result.Return(inner); } private Yield Call_Set(CoroutineHandler<int, Result<int>> coroutine, int value, Result<int> result) { int? receive = null; var res = Coroutine.Invoke(coroutine, value, new Result<int>()); yield return res.Set(v => receive = v); result.Return(receive.Value); } private Yield Call_Set_Fail(CoroutineHandler<int, Result<int>> coroutine, int value, Result<int> result) { int? receive = null; yield return Coroutine.Invoke(coroutine, value, new Result<int>()).Set(_ => Assert.Fail()); result.Return(receive.Value); } private Yield Call_CatchAndLog(CoroutineHandler<int, Result<int>> coroutine, int value, Result<int> result) { Result<int> inner; yield return (inner = Coroutine.Invoke(coroutine, value, new Result<int>())).CatchAndLog(_log); result.Return(inner); } #endregion //--- Methods --- #region Direct invocation tests [Test] public void Direct_invoke_with_return_in_startup() { var result = Coroutine.Invoke(Ret, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Direct_invoke_with_return_in_continuation() { var result = Coroutine.Invoke(Yield_Ret, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Direct_invoke_with_exception_in_startup() { var result = Coroutine.Invoke(Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasException); Assert.IsInstanceOf<IntentionalException>(result.Exception, "wrong exception type"); } [Test] public void Direct_invoke_with_exception_in_continuation() { var result = Coroutine.Invoke(Yield_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasException); Assert.IsInstanceOf<IntentionalException>(result.Exception, "wrong exception type"); } [Test] public void Direct_invoke_with_exception_after_return_in_startup() { var result = Coroutine.Invoke(Ret_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Direct_invoke_with_exception_after_return_in_continuation1() { var result = Coroutine.Invoke(Yield_Ret_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Direct_invoke_with_exception_after_return_in_continuation2() { var result = Coroutine.Invoke(Ret_Yield_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } #endregion #region Nested invocation tests public void Nested_invoke_with_return_in_startup() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call, Ret, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Nested_invoke_with_return_in_continuation() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call, Yield_Ret, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Nested_invoke_with_exception_in_startup() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call, Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasException); Assert.IsInstanceOf<IntentionalException>(result.Exception, "wrong exception type"); } [Test] public void Nested_invoke_with_exception_in_continuation() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call, Yield_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasException); Assert.IsInstanceOf<IntentionalException>(result.Exception, "wrong exception type"); } [Test] public void Nested_invoke_with_exception_after_return_in_startup() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call, Ret_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Nested_invoke_with_exception_after_return_in_continuation1() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call, Yield_Ret_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Nested_invoke_with_exception_after_return_in_continuation2() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call, Ret_Yield_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } #endregion #region Set tests [Test] public void Direct_SetValue_with_return_in_startup() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call_Set, Ret, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Direct_SetValue_with_return_in_continuation() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call_Set, Yield_Ret, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Direct_SetValue_with_exception_in_startup() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call_Set_Fail, Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasException); Assert.IsInstanceOf<IntentionalException>(result.Exception); } [Test] public void Direct_SetValue_with_exception_in_continuation() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call_Set_Fail, Yield_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasException); Assert.IsInstanceOf<IntentionalException>(result.Exception); } #endregion #region CatchAndLog tests [Test] public void Direct_CatchAndLog_with_return_in_startup() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call_CatchAndLog, Ret, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Direct_CatchAndLog_with_return_in_continuation() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call_CatchAndLog, Yield_Ret, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasValue, "result value missing"); Assert.AreEqual(11, result.Value, "wrong result value"); } [Test] public void Direct_CatchAndLog_with_exception_in_startup() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call_CatchAndLog, Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasException); Assert.IsInstanceOf<IntentionalException>(result.Exception); } [Test] public void Direct_CatchAndLog_with_exception_in_continuation() { var result = Coroutine.Invoke<CoroutineHandler<int, Result<int>>, int, Result<int>>(Call_CatchAndLog, Yield_Throw, 11, new Result<int>()).Block(); Assert.IsTrue(result.HasException); Assert.IsInstanceOf<IntentionalException>(result.Exception); } #endregion #region Misc tests [Test] public void Nested_Catches_bubble_up_exception_from_innermost_coroutine() { _log.Debug("invoking coroutine"); Result r = Coroutine.Invoke(BubbleCoroutine, 5, new Result()); r.Block(); Assert.IsTrue(r.HasException); _log.Debug("exception", r.Exception); Assert.AreEqual(typeof(BubbledException), r.Exception.GetType()); } private Yield BubbleCoroutine(int depth, Result result) { _log.DebugFormat("{0} levels remaining", depth); yield return AsyncUtil.Sleep(TimeSpan.FromMilliseconds(10), new Result(TimeSpan.MaxValue)); if(depth > 0) { _log.Debug("invoking BubbleCoroutine again"); yield return Coroutine.Invoke(BubbleCoroutine, depth - 1, new Result()); result.Return(); yield break; } _log.Debug("throwing"); throw new BubbledException(); } #endregion } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using DrawingEx.ColorManagement.ColorModels; namespace DrawingEx.IconEncoder { public sealed class Quantizer { #region variables private int _maxcolors; private Octree _octree=null; #endregion /// <summary> /// constructs a new quantizer object for the /// specified bitdepth /// </summary> public Quantizer(PixelFormat format) { _maxcolors=LengthOfPalette(format); } /// <summary> /// constructs a new quantizer object for the /// specified bitdepth /// </summary> public Quantizer(int bitsperpixel) { _maxcolors=LengthOfPalette(bitsperpixel); } #region public members /// <summary> /// evaluates the colors in a palette of the specified bitdepth /// </summary> public static int LengthOfPalette(int bitsperpixel) { switch(bitsperpixel) { case 1: return 2; case 4: return 16; case 8: return 256; default: throw new ArgumentOutOfRangeException("bitsperpixel"); } } /// <summary> /// evaluates the colors in a palette of the specified format /// </summary> public static int LengthOfPalette(PixelFormat format) { switch(format) { case PixelFormat.Format1bppIndexed: return 2; case PixelFormat.Format4bppIndexed: return 16; case PixelFormat.Format8bppIndexed: return 256; default: throw new ArgumentOutOfRangeException("format"); } } /// <summary> /// makes a copy of the image with a 32bpp argb format. /// the original image is not altered /// </summary> public static Bitmap CopyImage(Bitmap bmp) { if (bmp==null || bmp.Width<1 || bmp.Height<1) return null; //copy the input argument Bitmap copy=new Bitmap(bmp.Width,bmp.Height,PixelFormat.Format32bppArgb); using (Graphics gr=Graphics.FromImage(copy)) { gr.DrawImage(bmp,0,0,bmp.Width,bmp.Height); } return copy; } /// <summary> /// quantizes the specified image with the internal palette. /// to alter the palette, use MakePalette() /// </summary> public unsafe void QuantizeImage(Bitmap bmp,DitheringType dithering) { if (bmp==null || bmp.PixelFormat!=PixelFormat.Format32bppArgb) return; if (_octree==null) throw new Exception("table not initialized. add some colors to the table"); //lock bitmap BitmapData bdata=bmp.LockBits( new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); switch(dithering) { case DitheringType.Uniform: QuantizeUniform( (ColorBgra*)bdata.Scan0, bmp.Width, bmp.Height); break; case DitheringType.RandomError: QuantizeRandom( (ColorBgra*)bdata.Scan0, bmp.Width, bmp.Height); break; case DitheringType.FloydSteinberg: QuantizeFloydSteinberg( (ColorBgra*)bdata.Scan0, bmp.Width, bmp.Height); break; } bmp.UnlockBits(bdata); } #region makepalette /// <summary> /// creates an adaptive palette based on the data in the /// specified bitmap /// </summary> /// <param name="bmp">a bitmap containing the colors. use only 32bppArgb images</param> public void MakePalette(Bitmap bmp) { _octree=Octree.FromBitmap(bmp,_maxcolors); } /// <summary> /// creates an exact palette based on the colors in the array /// </summary> public void MakePalette(ColorBgra[] value) { if(value==null || value.Length!=_maxcolors) throw new ArgumentException("invalid","value"); _octree=Octree.FromColorArray(value); } #endregion #endregion #region properties /// <summary> /// gets the internal octree /// be careful: if you haven't initialized a palette, /// this is NULL /// </summary> public ColorBgra[] Palette { get { if(_octree==null) return null; else return _octree.Table; } } /// <summary> /// gets the maximum number of colors /// </summary> public int MaxColors { get{return _maxcolors;} } #endregion #region quantization algorithms #region constants //matrix containing the error dispersion //coefficients for floyd-steinberg algorithm private int[][] floydsteinbergmatrix= new int[][]{ new int[]{0,0,7}, new int[]{3,5,1} }; private int floydsteinbergsum=16; #endregion /// <summary> /// quantizes the specified image using a floyd-steinberg error diffusion dithering /// </summary> private unsafe void QuantizeFloydSteinberg(ColorBgra* pixels, int width, int height) { if(_octree==null) return; int index=0; ColorBgra col; for (int y=0; y<height; y++) { for (int x=0; x<width; x++, index++) { col=_octree.Table[_octree.GetOctreeIndex(pixels[index])]; int er=(int)pixels[index].R-(int)col.R, eg=(int)pixels[index].G-(int)col.G, eb=(int)pixels[index].B-(int)col.B; #region error matrix for (int i=0; i<2; i++) { int iy=i+y; if (iy>=0 && iy<height) { for (int j=-1; j<2; j++) { int jx=j+x; if (jx>=0 && jx<width) { //load error dispersion from matrix int w=floydsteinbergmatrix[i][j+1]; if (w!=0) { int k=jx+iy*width; pixels[k].Red+=(er*w)/floydsteinbergsum; pixels[k].Green+=(eg*w)/floydsteinbergsum; pixels[k].Blue+=(eb*w)/floydsteinbergsum; } } } } #endregion } pixels[index]=col; } } } /// <summary> /// quantizes the specified image using a random error diffusion /// </summary> private unsafe void QuantizeRandom(ColorBgra* pixels, int width, int height) { if(_octree==null) return; Random rnd=new Random(); int count=width*height; for (int i=0; i<count; i++) pixels[i]=_octree.Table[ _octree.GetOctreeIndex( Math.Min(255,Math.Max(0,pixels[i].Red+rnd.Next(-12,12))), Math.Min(255,Math.Max(0,pixels[i].Green+rnd.Next(-12,12))), Math.Min(255,Math.Max(0,pixels[i].Blue+rnd.Next(-12,12))))]; } /// <summary> /// quantizes the specified image without using any dithering /// </summary> private unsafe void QuantizeUniform(ColorBgra* pixels, int width, int height) { if(_octree==null) return; int count=width*height; for (int i=0; i<count; i++) pixels[i]=_octree.Table[_octree.GetOctreeIndex(pixels[i])]; } #endregion } /// <summary> /// encapsulates an octree for quick lookup of colors /// </summary> public class Octree:IDisposable { #region types /// <summary> /// encapsulates a single octree node /// </summary> private class OctreeNode { #region variables public OctreeNode[] Children=new OctreeNode[8]; public bool IsLeaf=false; public OctreeNode Next=null; public int RedSum=0, GreenSum=0, BlueSum=0, PixelCount=0; public int Index; #endregion /// <summary> /// ctor /// </summary> public OctreeNode(bool isleaf, ref OctreeNode reducible) { this.IsLeaf=isleaf; if (!isleaf) { this.Next=reducible; reducible=this; } } #region public members /// <summary> /// adds the specified color to the node and /// increases the counter by one /// </summary> public void AddPixel(int red, int green, int blue) { this.RedSum+=red; this.GreenSum+=green; this.BlueSum+=blue; this.PixelCount++; } /// <summary> /// returns a value representing the color of the node. /// if this is not a leaf, ColorBgra.Transparent is returned /// </summary> public ColorBgra ToColor() { if (PixelCount<1) return ColorBgra.Transparent; return new ColorBgra( (byte)(RedSum/PixelCount), (byte)(GreenSum/PixelCount), (byte)(BlueSum/PixelCount)); } /// <summary> /// adds the element recursively to the specified table /// </summary> public void AddToTable(ColorBgra[] table, ref int index) { //failure, index out of range if (index>=table.Length) return; if (this.IsLeaf) { //add to table and remember index table[index]=this.ToColor(); this.Index=index; index++; } else { //recursively add children to table for (int i=0; i<8; i++) { if (Children[i]==null) continue; Children[i].AddToTable(table, ref index); } } } /// <summary> /// deletes all children of the node, /// including the next pointer /// </summary> public void DeleteChildren() { for (int i=0; i<8; i++) { if (Children[i]==null) continue; Children[i].DeleteChildren(); Children[i]=null; } Next=null; } #endregion } #endregion #region variables private int MAXDEPTH=5; private OctreeNode _root; private OctreeNode[] _reduciblenodes; private int _colors, _maxcolors=0; private ColorBgra[] _table; #endregion #region constructors private Octree(int maxdepth, int maxcolors) { //different maxdepths are needet for exactness MAXDEPTH=maxdepth; //init nodes _reduciblenodes=new OctreeNode[MAXDEPTH+1]; _root=new OctreeNode(false,ref _reduciblenodes[0]); _colors=0; } /// <summary> /// parses an array of colors into the octree for /// making possible a quick lookup /// </summary> public static Octree FromColorArray(ColorBgra[] value) { if(value==null) throw new ArgumentNullException("value"); if(value.Length<2 || value.Length>256) throw new ArgumentException("length of colors not equal to maxcolors","value"); //exact mapping of colors Octree ret=new Octree(8,value.Length); //loop through colors for(int i=0; i<value.Length; i++) { OctreeNode node=ret.FindOrCreateNode(value[i]); if(node==null)continue; node.Index=i; } //no reduction needed this time, create table ret._table=new ColorBgra[value.Length]; value.CopyTo(ret._table,0); //return octree return ret; } /// <summary> /// creates a palette of colors from a bitmap /// </summary> public unsafe static Octree FromBitmap(Bitmap bmp, int maxcolors) { if (bmp==null || bmp.PixelFormat!=PixelFormat.Format32bppArgb) throw new ArgumentException("bmp not valid. use copyimage()"); if(maxcolors<2 || maxcolors>256) throw new ArgumentException("length of colors not valid","value"); //no exact mapping of colors Octree ret=new Octree(5,maxcolors); #region adding bitmap //lock bitmap BitmapData bdata=bmp.LockBits( new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int count=bmp.Width*bmp.Height; ColorBgra* pixels=(ColorBgra*)bdata.Scan0; //loop through pixels for (int i=0; i<count; i++) { ret.AddColor(pixels[i]); while(ret._colors>ret._maxcolors) { ret.ReduceTree(); } } bmp.UnlockBits(bdata); #endregion //make palette ret._table=new ColorBgra[maxcolors]; int index=0; ret._root.AddToTable(ret._table,ref index); //return octree return ret; } #endregion public void Dispose() { //erase reducible pointers _reduciblenodes=null; //delete recursively _root.DeleteChildren(); //delete table _table=null; } #region algorithms /// <summary> /// adds the specified color to the octree /// </summary> private void AddColor(ColorBgra value) { OctreeNode node=FindOrCreateNode(value); if(node!=null) node.AddPixel(value.Red,value.Green,value.Blue); } /// <summary> /// finds or creates a node for the given color /// </summary> private OctreeNode FindOrCreateNode(ColorBgra value) { return FindOrCreateNode(value.Red,value.Green,value.Blue); } /// <summary> /// finds or creates a node for the given color /// </summary> private OctreeNode FindOrCreateNode(int r, int g, int b) { int mask=0x80, index; OctreeNode node=_root, child; //root is the only color if (node.IsLeaf) return node; //loop through children for (int depth=1; depth<=MAXDEPTH; depth++, mask>>=1) { index=0; //index selecting if((r&mask)!=0) index+=4; if((g&mask)!=0) index+=2; if((b&mask)!=0) index+=1; //look for child node, no matter if NULL child=node.Children[index]; //create new node and add to reducibles if not leaf if (child==null) { node.Children[index]=child=new OctreeNode( depth==MAXDEPTH, ref _reduciblenodes[depth]); if (child.IsLeaf) _colors++; } //child represents the color if (child.IsLeaf) return child; node=child; } return null; } /// <summary> /// gets the index of the octree node closest to the specified color /// </summary> private OctreeNode FindNode(int r, int g, int b) { int mask=0x80, index; OctreeNode node=_root, child; //root is the only color if (node.IsLeaf) return node; //loop through children for (int depth=1; depth<=MAXDEPTH; depth++, mask>>=1) { //index selecting index=0; if((r&mask)!=0) index+=4; if((g&mask)!=0) index+=2; if((b&mask)!=0) index+=1; //look for child node child=node.Children[index]; //color not in octree if (child==null) { //search for first child for (int i=0; i<8; i++) if (node.Children[i]!=null) { child=node.Children[i]; break; } //fatal failure if (child==null) return null; } //child represents color if (child.IsLeaf) return child; node=child; } return null; } /// <summary> /// reduces the last node in the deepest level /// </summary> private void ReduceTree() { OctreeNode node; int depth; //find deepest level for (depth=MAXDEPTH; depth>0 && _reduciblenodes[depth]==null; depth--); //swap values node=_reduciblenodes[depth]; _reduciblenodes[depth]=node.Next; //reduce all children for (int i=0; i<8; i++) { if (node.Children[i]==null) continue; //eat child node.RedSum+=node.Children[i].RedSum; node.GreenSum+=node.Children[i].GreenSum; node.BlueSum+=node.Children[i].BlueSum; node.PixelCount+=node.Children[i].PixelCount; node.Children[i]=null; //reduce global color counter _colors--; } //parent node is now a color _colors++; node.IsLeaf=true; } #endregion #region public members /// <summary> /// gets the index of the octree node closest to the specified color /// </summary> public int GetOctreeIndex(Color color) { return GetOctreeIndex(color.R,color.G,color.B); } /// <summary> /// gets the index of the octree node closest to the specified color /// </summary> public int GetOctreeIndex(ColorBgra color) { return GetOctreeIndex(color.Red,color.Green,color.Blue); } /// <summary> /// gets the index of the octree node closest to the specified color /// </summary> public int GetOctreeIndex(int r, int g, int b) { OctreeNode node=FindNode(r,g,b); if(node==null) return 0;//fatal error else return node.Index; } #endregion #region properties /// <summary> /// gets the palette this octree refers to /// </summary> public ColorBgra[] Table { get{return _table;} } #endregion } /// <summary> /// enumeration of possible dithering strategies /// </summary> public enum DitheringType { Uniform=0, FloydSteinberg=1, RandomError=2 } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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.Text; using OpenMetaverse; using OpenSim.Framework.Statistics.Interfaces; using OpenMetaverse.StructuredData; using System.Threading; namespace OpenSim.Framework.Statistics { /// <summary> /// Collects sim statistics which aren't already being collected for the linden viewer's statistics pane /// </summary> public class SimExtraStatsCollector : BaseStatsCollector { private long abnormalClientThreadTerminations; private long assetsInCache; private long texturesInCache; private long assetCacheMemoryUsage; private long textureCacheMemoryUsage; private TimeSpan assetRequestTimeAfterCacheMiss; private long blockedMissingTextureRequests; private long assetServiceRequestFailures; private long inventoryServiceRetrievalFailures; private volatile float timeDilation; private volatile float simFps; private volatile float physicsFps; private volatile float agentUpdates; private volatile float rootAgents; private volatile float childAgents; private volatile float totalPrims; private volatile float activePrims; private volatile float totalFrameTime; private volatile float netFrameTime; private volatile float physicsFrameTime; private volatile float otherFrameTime; private volatile float imageFrameTime; private volatile float inPacketsPerSecond; private volatile float outPacketsPerSecond; private volatile float unackedBytes; private volatile float agentFrameTime; private volatile float pendingDownloads; private volatile float pendingUploads; private volatile float activeScripts; private volatile float scriptLinesPerSecond; /// <summary> /// Number of times that a client thread terminated because of an exception /// </summary> public long AbnormalClientThreadTerminations { get { return abnormalClientThreadTerminations; } } /// <summary> /// These statistics are being collected by push rather than pull. Pull would be simpler, but I had the /// notion of providing some flow statistics (which pull wouldn't give us). Though admittedly these /// haven't yet been implemented... /// </summary> public long AssetsInCache { get { return assetsInCache; } } /// <value> /// Currently unused /// </value> public long TexturesInCache { get { return texturesInCache; } } /// <value> /// Currently misleading since we can't currently subtract removed asset memory usage without a performance hit /// </value> public long AssetCacheMemoryUsage { get { return assetCacheMemoryUsage; } } /// <value> /// Currently unused /// </value> public long TextureCacheMemoryUsage { get { return textureCacheMemoryUsage; } } public float TimeDilation { get { return timeDilation; } } public float SimFps { get { return simFps; } } public float PhysicsFps { get { return physicsFps; } } public float AgentUpdates { get { return agentUpdates; } } public float RootAgents { get { return rootAgents; } } public float ChildAgents { get { return childAgents; } } public float TotalPrims { get { return totalPrims; } } public float ActivePrims { get { return activePrims; } } public float TotalFrameTime { get { return totalFrameTime; } } public float NetFrameTime { get { return netFrameTime; } } public float PhysicsFrameTime { get { return physicsFrameTime; } } public float OtherFrameTime { get { return otherFrameTime; } } public float ImageFrameTime { get { return imageFrameTime; } } public float InPacketsPerSecond { get { return inPacketsPerSecond; } } public float OutPacketsPerSecond { get { return outPacketsPerSecond; } } public float UnackedBytes { get { return unackedBytes; } } public float AgentFrameTime { get { return agentFrameTime; } } public float PendingDownloads { get { return pendingDownloads; } } public float PendingUploads { get { return pendingUploads; } } public float ActiveScripts { get { return activeScripts; } } public float ScriptLinesPerSecond { get { return scriptLinesPerSecond; } } /// <summary> /// This is the time it took for the last asset request made in response to a cache miss. /// </summary> public TimeSpan AssetRequestTimeAfterCacheMiss { get { return assetRequestTimeAfterCacheMiss; } } /// <summary> /// Number of persistent requests for missing textures we have started blocking from clients. To some extent /// this is just a temporary statistic to keep this problem in view - the root cause of this lies either /// in a mishandling of the reply protocol, related to avatar appearance or may even originate in graphics /// driver bugs on clients (though this seems less likely). /// </summary> public long BlockedMissingTextureRequests { get { return blockedMissingTextureRequests; } } /// <summary> /// Record the number of times that an asset request has failed. Failures are effectively exceptions, such as /// request timeouts. If an asset service replies that a particular asset cannot be found, this is not counted /// as a failure /// </summary> public long AssetServiceRequestFailures { get { return assetServiceRequestFailures; } } /// <summary> /// Number of known failures to retrieve avatar inventory from the inventory service. This does not /// cover situations where the inventory service accepts the request but never returns any data, since /// we do not yet timeout this situation. /// </summary> public long InventoryServiceRetrievalFailures { get { return inventoryServiceRetrievalFailures; } } /// <summary> /// Retrieve the total frame time (in ms) of the last frame /// </summary> //public float TotalFrameTime { get { return totalFrameTime; } } /// <summary> /// Retrieve the physics update component (in ms) of the last frame /// </summary> //public float PhysicsFrameTime { get { return physicsFrameTime; } } /// <summary> /// Retain a dictionary of all packet queues stats reporters /// </summary> private IDictionary<UUID, PacketQueueStatsCollector> packetQueueStatsCollectors = new Dictionary<UUID, PacketQueueStatsCollector>(); public void AddAbnormalClientThreadTermination() { abnormalClientThreadTerminations++; } public void AddAsset(AssetBase asset) { assetsInCache++; //assetCacheMemoryUsage += asset.Data.Length; } public void RemoveAsset(UUID uuid) { assetsInCache--; } public void AddTexture(AssetBase image) { if (image.Data != null) { texturesInCache++; // This could have been a pull stat, though there was originally a nebulous idea to measure flow rates textureCacheMemoryUsage += image.Data.Length; } } /// <summary> /// Signal that the asset cache has been cleared. /// </summary> public void ClearAssetCacheStatistics() { assetsInCache = 0; assetCacheMemoryUsage = 0; texturesInCache = 0; textureCacheMemoryUsage = 0; } public void AddAssetRequestTimeAfterCacheMiss(TimeSpan ts) { assetRequestTimeAfterCacheMiss = ts; } public void AddBlockedMissingTextureRequest() { blockedMissingTextureRequests++; } public void AddAssetServiceRequestFailure() { assetServiceRequestFailures++; } public void AddInventoryServiceRetrievalFailure() { inventoryServiceRetrievalFailures++; } /// <summary> /// Register as a packet queue stats provider /// </summary> /// <param name="uuid">An agent UUID</param> /// <param name="provider"></param> public void RegisterPacketQueueStatsProvider(UUID uuid, IPullStatsProvider provider) { lock (packetQueueStatsCollectors) { // FIXME: If the region service is providing more than one region, then the child and root agent // queues are wrongly replacing each other here. packetQueueStatsCollectors[uuid] = new PacketQueueStatsCollector(provider); } } /// <summary> /// Deregister a packet queue stats provider /// </summary> /// <param name="uuid">An agent UUID</param> public void DeregisterPacketQueueStatsProvider(UUID uuid) { lock (packetQueueStatsCollectors) { packetQueueStatsCollectors.Remove(uuid); } } /// <summary> /// This is the method on which the classic sim stats reporter (which collects stats for /// client purposes) sends information to listeners. /// </summary> /// <param name="pack"></param> public void ReceiveClassicSimStatsPacket(SimStats stats) { // FIXME: SimStats shouldn't allow an arbitrary stat packing order (which is inherited from the original // SimStatsPacket that was being used). timeDilation = stats.StatsBlock[0].StatValue; simFps = stats.StatsBlock[1].StatValue; physicsFps = stats.StatsBlock[2].StatValue; agentUpdates = stats.StatsBlock[3].StatValue; rootAgents = stats.StatsBlock[4].StatValue; childAgents = stats.StatsBlock[5].StatValue; totalPrims = stats.StatsBlock[6].StatValue; activePrims = stats.StatsBlock[7].StatValue; totalFrameTime = stats.StatsBlock[8].StatValue; netFrameTime = stats.StatsBlock[9].StatValue; physicsFrameTime = stats.StatsBlock[10].StatValue; otherFrameTime = stats.StatsBlock[11].StatValue; imageFrameTime = stats.StatsBlock[12].StatValue; inPacketsPerSecond = stats.StatsBlock[13].StatValue; outPacketsPerSecond = stats.StatsBlock[14].StatValue; unackedBytes = stats.StatsBlock[15].StatValue; agentFrameTime = stats.StatsBlock[16].StatValue; pendingDownloads = stats.StatsBlock[17].StatValue; pendingUploads = stats.StatsBlock[18].StatValue; activeScripts = stats.StatsBlock[19].StatValue; scriptLinesPerSecond = stats.StatsBlock[20].StatValue; } /// <summary> /// Report back collected statistical information. /// </summary> /// <returns></returns> public override string Report() { StringBuilder sb = new StringBuilder(Environment.NewLine); sb.Append("ASSET STATISTICS"); sb.Append(Environment.NewLine); //do calcs on asset data int numAssetReads = _currentNumRequests; int numAssetWrites = _currentNumWrites; long assetReadAvg = numAssetReads > 0 ? _currentRequestTimeTotal / numAssetReads : 0; long assetWriteAvg = numAssetWrites > 0 ? _currentWriteTimeTotal / numAssetWrites : 0; sb.Append( string.Format( @"Average Asset Read Request Latency: {0} ms Average Asset Write Request Latency: {1} ms "+ Environment.NewLine, assetReadAvg, assetWriteAvg)); sb.Append(Environment.NewLine); sb.Append("CONNECTION STATISTICS"); sb.Append(Environment.NewLine); sb.Append( string.Format( "Abnormal client thread terminations: {0}" + Environment.NewLine, abnormalClientThreadTerminations)); sb.Append(Environment.NewLine); sb.Append("INVENTORY STATISTICS"); sb.Append(Environment.NewLine); sb.Append( string.Format( "Initial inventory caching failures: {0}" + Environment.NewLine, InventoryServiceRetrievalFailures)); sb.Append(Environment.NewLine); sb.Append("FRAME STATISTICS"); sb.Append(Environment.NewLine); sb.Append("Dilatn SimFPS PhyFPS AgntUp RootAg ChldAg Prims AtvPrm AtvScr ScrLPS"); sb.Append(Environment.NewLine); sb.Append( string.Format( "{0,6:0.00} {1,6:0} {2,6:0.0} {3,6:0.0} {4,6:0} {5,6:0} {6,6:0} {7,6:0} {8,6:0} {9,6:0}", timeDilation, simFps, physicsFps, agentUpdates, rootAgents, childAgents, totalPrims, activePrims, activeScripts, scriptLinesPerSecond)); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); // There is no script frame time currently because we don't yet collect it sb.Append("PktsIn PktOut PendDl PendUl UnackB TotlFt NetFt PhysFt OthrFt AgntFt ImgsFt"); sb.Append(Environment.NewLine); sb.Append( string.Format( "{0,6:0} {1,6:0} {2,6:0} {3,6:0} {4,6:0} {5,6:0.0} {6,6:0.0} {7,6:0.0} {8,6:0.0} {9,6:0.0} {10,6:0.0}", inPacketsPerSecond, outPacketsPerSecond, pendingDownloads, pendingUploads, unackedBytes, totalFrameTime, netFrameTime, physicsFrameTime, otherFrameTime, agentFrameTime, imageFrameTime)); sb.Append(Environment.NewLine); /* sb.Append(Environment.NewLine); sb.Append("PACKET QUEUE STATISTICS"); sb.Append(Environment.NewLine); sb.Append("Agent UUID "); sb.Append( string.Format( " {0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}", "Send", "In", "Out", "Resend", "Land", "Wind", "Cloud", "Task", "Texture", "Asset")); sb.Append(Environment.NewLine); foreach (UUID key in packetQueueStatsCollectors.Keys) { sb.Append(string.Format("{0}: ", key)); sb.Append(packetQueueStatsCollectors[key].Report()); sb.Append(Environment.NewLine); } */ sb.Append(base.Report()); return sb.ToString(); } /// <summary> /// Report back collected statistical information as json serialization. /// </summary> /// <returns></returns> public override string XReport(string uptime, string version) { OSDMap args = new OSDMap(30); args["AssetsInCache"] = OSD.FromReal(AssetsInCache); args["TimeAfterCacheMiss"] = OSD.FromReal(assetRequestTimeAfterCacheMiss.Milliseconds / 1000.0); args["BlockedMissingTextureRequests"] = OSD.FromReal(BlockedMissingTextureRequests); args["AssetServiceRequestFailures"] = OSD.FromReal(AssetServiceRequestFailures); args["abnormalClientThreadTerminations"] = OSD.FromReal(abnormalClientThreadTerminations); args["InventoryServiceRetrievalFailures"] = OSD.FromReal(InventoryServiceRetrievalFailures); args["Dilatn"] = OSD.FromReal(timeDilation); args["SimFPS"] = OSD.FromReal(simFps); args["PhyFPS"] = OSD.FromReal(physicsFps); args["AgntUp"] = OSD.FromReal(agentUpdates); args["RootAg"] = OSD.FromReal(rootAgents); args["ChldAg"] = OSD.FromReal(childAgents); args["Prims"] = OSD.FromReal(totalPrims); args["AtvPrm"] = OSD.FromReal(activePrims); args["AtvScr"] = OSD.FromReal(activeScripts); args["ScrLPS"] = OSD.FromReal(scriptLinesPerSecond); args["PktsIn"] = OSD.FromReal(inPacketsPerSecond); args["PktOut"] = OSD.FromReal(outPacketsPerSecond); args["PendDl"] = OSD.FromReal(pendingDownloads); args["PendUl"] = OSD.FromReal(pendingUploads); args["UnackB"] = OSD.FromReal(unackedBytes); args["TotlFt"] = OSD.FromReal(totalFrameTime); args["NetFt"] = OSD.FromReal(netFrameTime); args["PhysFt"] = OSD.FromReal(physicsFrameTime); args["OthrFt"] = OSD.FromReal(otherFrameTime); args["AgntFt"] = OSD.FromReal(agentFrameTime); args["ImgsFt"] = OSD.FromReal(imageFrameTime); args["Memory"] = OSD.FromString(base.XReport(uptime, version)); args["Uptime"] = OSD.FromString(uptime); args["Version"] = OSD.FromString(version); string strBuffer = ""; strBuffer = OSDParser.SerializeJsonString(args); return strBuffer; } private const int NUM_VALUES_FOR_ASSET_AVG = 100; private long _currentRequestTimeTotal; private int _currentNumRequests; private long _currentWriteTimeTotal; private int _currentNumWrites; public void AddAssetRequestTime(long p) { Interlocked.Add(ref _currentRequestTimeTotal, p); if (Interlocked.Increment(ref _currentNumRequests) > NUM_VALUES_FOR_ASSET_AVG) { Interlocked.Exchange(ref _currentRequestTimeTotal, 0); Interlocked.Exchange(ref _currentNumRequests, 0); } } public void AddAssetWriteTime(long p) { Interlocked.Add(ref _currentRequestTimeTotal, p); if (Interlocked.Increment(ref _currentNumWrites) > NUM_VALUES_FOR_ASSET_AVG) { Interlocked.Exchange(ref _currentWriteTimeTotal, 0); Interlocked.Exchange(ref _currentNumWrites, 0); } } } /// <summary> /// Pull packet queue stats from packet queues and report /// </summary> public class PacketQueueStatsCollector : IStatsCollector { private IPullStatsProvider m_statsProvider; public PacketQueueStatsCollector(IPullStatsProvider provider) { m_statsProvider = provider; } /// <summary> /// Report back collected statistical information. /// </summary> /// <returns></returns> public string Report() { return m_statsProvider.GetStats(); } public string XReport(string uptime, string version) { return ""; } } }
namespace AutoMapper { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Impl; using Internal; using Mappers; using QueryableExtensions; using QueryableExtensions.Impl; public class MappingEngine : IMappingEngine, IMappingEngineRunner { private static readonly IDictionaryFactory DictionaryFactory = PlatformAdapter.Resolve<IDictionaryFactory>(); private static readonly IProxyGeneratorFactory ProxyGeneratorFactory = PlatformAdapter.Resolve<IProxyGeneratorFactory>(); private static readonly IExpressionResultConverter[] ExpressionResultConverters = { new MemberGetterExpressionResultConverter(), new MemberResolverExpressionResultConverter(), new NullSubstitutionExpressionResultConverter() }; private static readonly IExpressionBinder[] Binders = { new NullableExpressionBinder(), new AssignableExpressionBinder(), new EnumerableExpressionBinder(), new MappedTypeExpressionBinder(), new CustomProjectionExpressionBinder(), new StringExpressionBinder() }; private bool _disposed; private readonly IObjectMapper[] _mappers; private readonly Internal.IDictionary<TypePair, IObjectMapper> _objectMapperCache; private readonly Internal.IDictionary<ExpressionRequest, LambdaExpression> _expressionCache; private readonly Func<Type, object> _serviceCtor; public MappingEngine(IConfigurationProvider configurationProvider) : this( configurationProvider, DictionaryFactory.CreateDictionary<TypePair, IObjectMapper>(), DictionaryFactory.CreateDictionary<ExpressionRequest, LambdaExpression>(), configurationProvider.ServiceCtor) { } public MappingEngine(IConfigurationProvider configurationProvider, Internal.IDictionary<TypePair, IObjectMapper> objectMapperCache, Internal.IDictionary<ExpressionRequest, LambdaExpression> expressionCache, Func<Type, object> serviceCtor) { ConfigurationProvider = configurationProvider; _objectMapperCache = objectMapperCache; _expressionCache = expressionCache; _serviceCtor = serviceCtor; _mappers = configurationProvider.GetMappers(); ConfigurationProvider.TypeMapCreated += ClearTypeMap; } public IConfigurationProvider ConfigurationProvider { get; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { if (ConfigurationProvider != null) ConfigurationProvider.TypeMapCreated -= ClearTypeMap; } _disposed = true; } } public TDestination Map<TDestination>(object source) { return Map<TDestination>(source, DefaultMappingOptions); } public TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts) { var mappedObject = default(TDestination); if (source != null) { var sourceType = source.GetType(); var destinationType = typeof (TDestination); mappedObject = (TDestination) Map(source, sourceType, destinationType, opts); } return mappedObject; } public TDestination Map<TSource, TDestination>(TSource source) { Type modelType = typeof (TSource); Type destinationType = typeof (TDestination); return (TDestination) Map(source, modelType, destinationType, DefaultMappingOptions); } public TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts) { Type modelType = typeof (TSource); Type destinationType = typeof (TDestination); var options = new MappingOperationOptions<TSource, TDestination>(); opts(options); return (TDestination) MapCore(source, modelType, destinationType, options); } public TDestination Map<TSource, TDestination>(TSource source, TDestination destination) { return Map(source, destination, DefaultMappingOptions); } public TDestination Map<TSource, TDestination>(TSource source, TDestination destination, Action<IMappingOperationOptions<TSource, TDestination>> opts) { Type modelType = typeof (TSource); Type destinationType = typeof (TDestination); var options = new MappingOperationOptions<TSource, TDestination>(); opts(options); return (TDestination) MapCore(source, destination, modelType, destinationType, options); } public object Map(object source, Type sourceType, Type destinationType) { return Map(source, sourceType, destinationType, DefaultMappingOptions); } public object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) { var options = new MappingOperationOptions(); opts(options); return MapCore(source, sourceType, destinationType, options); } private object MapCore(object source, Type sourceType, Type destinationType, MappingOperationOptions options) { TypeMap typeMap = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType); var context = new ResolutionContext(typeMap, source, sourceType, destinationType, options, this); return ((IMappingEngineRunner) this).Map(context); } public object Map(object source, object destination, Type sourceType, Type destinationType) { return Map(source, destination, sourceType, destinationType, DefaultMappingOptions); } public object Map(object source, object destination, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts) { var options = new MappingOperationOptions(); opts(options); return MapCore(source, destination, sourceType, destinationType, options); } private object MapCore(object source, object destination, Type sourceType, Type destinationType, MappingOperationOptions options) { TypeMap typeMap = ConfigurationProvider.ResolveTypeMap(source, destination, sourceType, destinationType); var context = new ResolutionContext(typeMap, source, destination, sourceType, destinationType, options, this); return ((IMappingEngineRunner) this).Map(context); } public TDestination DynamicMap<TSource, TDestination>(TSource source) { Type modelType = typeof (TSource); Type destinationType = typeof (TDestination); return (TDestination) DynamicMap(source, modelType, destinationType); } public void DynamicMap<TSource, TDestination>(TSource source, TDestination destination) { Type modelType = typeof (TSource); Type destinationType = typeof (TDestination); DynamicMap(source, destination, modelType, destinationType); } public TDestination DynamicMap<TDestination>(object source) { Type modelType = source?.GetType() ?? typeof (object); Type destinationType = typeof (TDestination); return (TDestination) DynamicMap(source, modelType, destinationType); } public object DynamicMap(object source, Type sourceType, Type destinationType) { var typeMap = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType); var context = new ResolutionContext(typeMap, source, sourceType, destinationType, new MappingOperationOptions { CreateMissingTypeMaps = true }, this); return ((IMappingEngineRunner) this).Map(context); } public void DynamicMap(object source, object destination, Type sourceType, Type destinationType) { var typeMap = ConfigurationProvider.ResolveTypeMap(source, destination, sourceType, destinationType); var context = new ResolutionContext(typeMap, source, destination, sourceType, destinationType, new MappingOperationOptions { CreateMissingTypeMaps = true }, this); ((IMappingEngineRunner) this).Map(context); } public TDestination Map<TSource, TDestination>(ResolutionContext parentContext, TSource source) { Type destinationType = typeof (TDestination); Type sourceType = typeof (TSource); TypeMap typeMap = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType); var context = parentContext.CreateTypeContext(typeMap, source, null, sourceType, destinationType); return (TDestination) ((IMappingEngineRunner) this).Map(context); } public Expression CreateMapExpression(Type sourceType, Type destinationType, System.Collections.Generic.IDictionary<string, object> parameters = null, params MemberInfo[] membersToExpand) { parameters = parameters ?? new Dictionary<string, object>(); var cachedExpression = _expressionCache.GetOrAdd(new ExpressionRequest(sourceType, destinationType, membersToExpand), tp => CreateMapExpression(tp, DictionaryFactory.CreateDictionary<ExpressionRequest, int>())); if (!parameters.Any()) return cachedExpression; var visitor = new ConstantExpressionReplacementVisitor(parameters); return visitor.Visit(cachedExpression); } public LambdaExpression CreateMapExpression(ExpressionRequest request, Internal.IDictionary<ExpressionRequest, int> typePairCount) { // this is the input parameter of this expression with name <variableName> var instanceParameter = Expression.Parameter(request.SourceType, "dto"); var total = CreateMapExpression(request, instanceParameter, typePairCount); var delegateType = typeof(Func<,>).MakeGenericType(request.SourceType, request.DestinationType); return Expression.Lambda(delegateType, total, instanceParameter); } public Expression CreateMapExpression(ExpressionRequest request, Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount) { var typeMap = ConfigurationProvider.ResolveTypeMap(request.SourceType, request.DestinationType); if (typeMap == null) { const string MessageFormat = "Missing map from {0} to {1}. Create using Mapper.CreateMap<{0}, {1}>."; var message = string.Format(MessageFormat, request.SourceType.Name, request.DestinationType.Name); throw new InvalidOperationException(message); } var bindings = CreateMemberBindings(request, typeMap, instanceParameter, typePairCount); var parameterReplacer = new ParameterReplacementVisitor(instanceParameter); var visitor = new NewFinderVisitor(); var constructorExpression = typeMap.DestinationConstructorExpression(instanceParameter); visitor.Visit(parameterReplacer.Visit(constructorExpression)); var expression = Expression.MemberInit( visitor.NewExpression, bindings.ToArray() ); return expression; } private class NewFinderVisitor : ExpressionVisitor { public NewExpression NewExpression { get; private set; } protected override Expression VisitNew(NewExpression node) { NewExpression = node; return base.VisitNew(node); } } private List<MemberBinding> CreateMemberBindings(ExpressionRequest request, TypeMap typeMap, Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount) { var bindings = new List<MemberBinding>(); var visitCount = typePairCount.AddOrUpdate(request, 0, (tp, i) => i + 1); if (visitCount >= typeMap.MaxDepth) return bindings; foreach (var propertyMap in typeMap.GetPropertyMaps().Where(pm => pm.CanResolveValue())) { var result = ResolveExpression(propertyMap, request.SourceType, instanceParameter); if (propertyMap.ExplicitExpansion && !request.MembersToExpand.Contains(propertyMap.DestinationProperty.MemberInfo)) continue; var propertyTypeMap = ConfigurationProvider.ResolveTypeMap(result.Type, propertyMap.DestinationPropertyType); var propertyRequest = new ExpressionRequest(result.Type, propertyMap.DestinationPropertyType, request.MembersToExpand); var binder = Binders.FirstOrDefault(b => b.IsMatch(propertyMap, propertyTypeMap, result)); if (binder == null) { var message = $"Unable to create a map expression from {propertyMap.SourceMember?.DeclaringType?.Name}.{propertyMap.SourceMember?.Name} ({result.Type}) to {propertyMap.DestinationProperty.MemberInfo.DeclaringType?.Name}.{propertyMap.DestinationProperty.Name} ({propertyMap.DestinationPropertyType})"; throw new AutoMapperMappingException(message); } var bindExpression = binder.Build(this, propertyMap, propertyTypeMap, propertyRequest, result, typePairCount); bindings.Add(bindExpression); } return bindings; } private static ExpressionResolutionResult ResolveExpression(PropertyMap propertyMap, Type currentType, Expression instanceParameter) { var result = new ExpressionResolutionResult(instanceParameter, currentType); foreach (var resolver in propertyMap.GetSourceValueResolvers()) { var matchingExpressionConverter = ExpressionResultConverters.FirstOrDefault(c => c.CanGetExpressionResolutionResult(result, resolver)); if (matchingExpressionConverter == null) throw new Exception("Can't resolve this to Queryable Expression"); result = matchingExpressionConverter.GetExpressionResolutionResult(result, propertyMap, resolver); } return result; } private class ConstantExpressionReplacementVisitor : ExpressionVisitor { private readonly System.Collections.Generic.IDictionary<string, object> _paramValues; public ConstantExpressionReplacementVisitor( System.Collections.Generic.IDictionary<string, object> paramValues) { _paramValues = paramValues; } protected override Expression VisitMember(MemberExpression node) { if (!node.Member.DeclaringType.Name.Contains("<>")) return base.VisitMember(node); if (!_paramValues.ContainsKey(node.Member.Name)) return base.VisitMember(node); return Expression.Convert( Expression.Constant(_paramValues[node.Member.Name]), node.Member.GetMemberType()); } } object IMappingEngineRunner.Map(ResolutionContext context) { try { var contextTypePair = new TypePair(context.SourceType, context.DestinationType); Func<TypePair, IObjectMapper> missFunc = tp => _mappers.FirstOrDefault(mapper => mapper.IsMatch(context)); IObjectMapper mapperToUse = _objectMapperCache.GetOrAdd(contextTypePair, missFunc); if (mapperToUse == null || (context.Options.CreateMissingTypeMaps && !mapperToUse.IsMatch(context))) { if (context.Options.CreateMissingTypeMaps) { var typeMap = ConfigurationProvider.CreateTypeMap(context.SourceType, context.DestinationType); context = context.CreateTypeContext(typeMap, context.SourceValue, context.DestinationValue, context.SourceType, context.DestinationType); mapperToUse = missFunc(contextTypePair); if(mapperToUse == null) { throw new AutoMapperMappingException(context, "Unsupported mapping."); } _objectMapperCache.AddOrUpdate(contextTypePair, mapperToUse, (tp, mapper) => mapperToUse); } else { if(context.SourceValue != null) { throw new AutoMapperMappingException(context, "Missing type map configuration or unsupported mapping."); } return ObjectCreator.CreateDefaultValue(context.DestinationType); } } return mapperToUse.Map(context, this); } catch (AutoMapperMappingException) { throw; } catch (Exception ex) { throw new AutoMapperMappingException(context, ex); } } object IMappingEngineRunner.CreateObject(ResolutionContext context) { var typeMap = context.TypeMap; var destinationType = context.DestinationType; if (typeMap != null) if (typeMap.DestinationCtor != null) return typeMap.DestinationCtor(context); else if (typeMap.ConstructDestinationUsingServiceLocator) return context.Options.ServiceCtor(destinationType); else if (typeMap.ConstructorMap != null && typeMap.ConstructorMap.CtorParams.All(p => p.CanResolve)) return typeMap.ConstructorMap.ResolveValue(context, this); if (context.DestinationValue != null) return context.DestinationValue; if (destinationType.IsInterface()) destinationType = ProxyGeneratorFactory.Create().GetProxyType(destinationType); return !ConfigurationProvider.MapNullSourceValuesAsNull ? ObjectCreator.CreateNonNullValue(destinationType) : ObjectCreator.CreateObject(destinationType); } bool IMappingEngineRunner.ShouldMapSourceValueAsNull(ResolutionContext context) { if (context.DestinationType.IsValueType() && !context.DestinationType.IsNullableType()) return false; var typeMap = context.GetContextTypeMap(); if (typeMap != null) return ConfigurationProvider.GetProfileConfiguration(typeMap.Profile).MapNullSourceValuesAsNull; return ConfigurationProvider.MapNullSourceValuesAsNull; } bool IMappingEngineRunner.ShouldMapSourceCollectionAsNull(ResolutionContext context) { var typeMap = context.GetContextTypeMap(); if (typeMap != null) return ConfigurationProvider.GetProfileConfiguration(typeMap.Profile).MapNullSourceCollectionsAsNull; return ConfigurationProvider.MapNullSourceCollectionsAsNull; } private void ClearTypeMap(object sender, TypeMapCreatedEventArgs e) { IObjectMapper existing; _objectMapperCache.TryRemove(new TypePair(e.TypeMap.SourceType, e.TypeMap.DestinationType), out existing); } private void DefaultMappingOptions(IMappingOperationOptions opts) { opts.ConstructServicesUsing(_serviceCtor); } } }
// 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.Linq; using System.Linq.Expressions; using System.Reflection; using Moq.Expressions.Visitors; using E = System.Linq.Expressions.Expression; namespace Moq { /// <summary> /// Describes the "shape" of an invocation against which concrete <see cref="Invocation"/>s can be matched. /// <para> /// This shape is described by <see cref="InvocationShape.Expression"/> which has the general form /// `mock => mock.Method(...arguments)`. Because the method and arguments are frequently needed, /// they are cached in <see cref="InvocationShape.Method"/> and <see cref="InvocationShape.Arguments"/> /// for faster access. /// </para> /// </summary> internal sealed class InvocationShape : IEquatable<InvocationShape> { public static InvocationShape CreateFrom(Invocation invocation) { var method = invocation.Method; Expression[] arguments; { var parameterTypes = method.GetParameterTypes(); var n = parameterTypes.Count; arguments = new Expression[n]; for (int i = 0; i < n; ++i) { arguments[i] = E.Constant(invocation.Arguments[i], parameterTypes[i]); } } LambdaExpression expression; { var mock = E.Parameter(method.DeclaringType, "mock"); expression = E.Lambda(E.Call(mock, method, arguments).Apply(UpgradePropertyAccessorMethods.Rewriter), mock); } if (expression.IsProperty()) { var property = expression.ToPropertyInfo(); Guard.CanRead(property); Debug.Assert(property.CanRead(out var getter) && method == getter); } return new InvocationShape(expression, method, arguments, exactGenericTypeArguments: true); } private static readonly Expression[] noArguments = new Expression[0]; private static readonly IMatcher[] noArgumentMatchers = new IMatcher[0]; public readonly LambdaExpression Expression; public readonly MethodInfo Method; public readonly IReadOnlyList<Expression> Arguments; private readonly IMatcher[] argumentMatchers; private MethodInfo methodImplementation; private Expression[] partiallyEvaluatedArguments; #if DEBUG private Type proxyType; #endif private readonly bool exactGenericTypeArguments; public InvocationShape(LambdaExpression expression, MethodInfo method, IReadOnlyList<Expression> arguments = null, bool exactGenericTypeArguments = false, bool skipMatcherInitialization = false) { Debug.Assert(expression != null); Debug.Assert(method != null); Guard.IsOverridable(method, expression); Guard.IsVisibleToProxyFactory(method); this.Expression = expression; this.Method = method; if (arguments != null && !skipMatcherInitialization) { (this.argumentMatchers, this.Arguments) = MatcherFactory.CreateMatchers(arguments, method.GetParameters()); } else { this.argumentMatchers = noArgumentMatchers; this.Arguments = arguments ?? noArguments; } this.exactGenericTypeArguments = exactGenericTypeArguments; } public void Deconstruct(out LambdaExpression expression, out MethodInfo method, out IReadOnlyList<Expression> arguments) { expression = this.Expression; method = this.Method; arguments = this.Arguments; } public bool IsMatch(Invocation invocation) { if (invocation.Method != this.Method && !this.IsOverride(invocation)) { return false; } var arguments = invocation.Arguments; var parameterTypes = invocation.Method.GetParameterTypes(); for (int i = 0, n = this.argumentMatchers.Length; i < n; ++i) { if (this.argumentMatchers[i].Matches(arguments[i], parameterTypes[i]) == false) { return false; } } return true; } public void SetupEvaluatedSuccessfully(Invocation invocation) { var arguments = invocation.Arguments; var parameterTypes = invocation.Method.GetParameterTypes(); for (int i = 0, n = this.argumentMatchers.Length; i < n; ++i) { this.argumentMatchers[i].SetupEvaluatedSuccessfully(arguments[i], parameterTypes[i]); } } private bool IsOverride(Invocation invocation) { Debug.Assert(invocation.Method != this.Method); var method = this.Method; var invocationMethod = invocation.Method; var proxyType = invocation.ProxyType; #if DEBUG // The following `if` block is a sanity check to ensure this `InvocationShape` always // runs against the same proxy type. This is important because we're caching the result // of mapping methods into that particular proxy type. We have no cache invalidation // logic in place; instead, we simply assume that the cached results will stay valid. // If the below assertion fails, that assumption was wrong. if (this.proxyType == null) { this.proxyType = proxyType; } else { Debug.Assert(this.proxyType == proxyType); } #endif // If not already in the cache, map this `InvocationShape`'s method into the proxy type: if (this.methodImplementation == null) { this.methodImplementation = method.GetImplementingMethod(proxyType); } if (invocation.MethodImplementation != this.methodImplementation) { return false; } if (method.IsGenericMethod || invocationMethod.IsGenericMethod) { if (!method.GetGenericArguments().CompareTo(invocationMethod.GetGenericArguments(), exact: this.exactGenericTypeArguments, considerTypeMatchers: true)) { return false; } } return true; } public bool Equals(InvocationShape other) { if (this.Method != other.Method) { return false; } if (this.Arguments.Count != other.Arguments.Count) { return false; } if (this.partiallyEvaluatedArguments == null) { this.partiallyEvaluatedArguments = PartiallyEvaluateArguments(this.Arguments); } if (other.partiallyEvaluatedArguments == null) { other.partiallyEvaluatedArguments = PartiallyEvaluateArguments(other.Arguments); } var lastParameter = this.Method.GetParameters().LastOrDefault(); var lastParameterIsParamArray = lastParameter != null && lastParameter.ParameterType.IsArray && lastParameter.IsDefined(typeof(ParamArrayAttribute)); for (int i = 0, li = this.partiallyEvaluatedArguments.Length - 1; i <= li; ++i) { // Special case for final `params` parameters, which need to be compared by structural equality, // not array reference equality: if (i == li && lastParameterIsParamArray) { // In the following, if we retrieved the `params` arrays via `partiallyEvaluatedArguments`, // we might see them either as `NewArrayExpression`s or reduced to `ConstantExpression`s. // By retrieving them via `Arguments` we always see them as non-reduced `NewArrayExpression`s, // so we don't have to distinguish between two cases. (However, the expressions inside those // have already been partially evaluated by `MatcherFactory` earlier on!) if (this.Arguments[li] is NewArrayExpression e1 && other.Arguments[li] is NewArrayExpression e2 && e1.Expressions.Count == e2.Expressions.Count) { for (int j = 0, nj = e1.Expressions.Count; j < nj; ++j) { if (!ExpressionComparer.Default.Equals(e1.Expressions[j], e2.Expressions[j])) { return false; } } continue; } } if (!ExpressionComparer.Default.Equals(this.partiallyEvaluatedArguments[i], other.partiallyEvaluatedArguments[i])) { return false; } } return true; } private static Expression[] PartiallyEvaluateArguments(IReadOnlyList<Expression> arguments) { Debug.Assert(arguments != null); if (arguments.Count == 0) { return noArguments; } var partiallyEvaluatedArguments = new Expression[arguments.Count]; for (int i = 0, n = arguments.Count; i < n; ++i) { partiallyEvaluatedArguments[i] = arguments[i].PartialMatcherAwareEval(); } return partiallyEvaluatedArguments; } public override bool Equals(object obj) { return obj is InvocationShape other && this.Equals(other); } public override int GetHashCode() { return this.Method.GetHashCode(); } public override string ToString() { return this.Expression.ToStringFixed(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Net.Http.Headers { [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is not a collection")] public sealed class HttpRequestHeaders : HttpHeaders { private static readonly Dictionary<string, HttpHeaderParser> s_parserStore = CreateParserStore(); private static readonly HashSet<string> s_invalidHeaders = CreateInvalidHeaders(); private HttpGeneralHeaders _generalHeaders; private HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> _accept; private HttpHeaderValueCollection<NameValueWithParametersHeaderValue> _expect; private bool _expectContinueSet; private HttpHeaderValueCollection<EntityTagHeaderValue> _ifMatch; private HttpHeaderValueCollection<EntityTagHeaderValue> _ifNoneMatch; private HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue> _te; private HttpHeaderValueCollection<ProductInfoHeaderValue> _userAgent; private HttpHeaderValueCollection<StringWithQualityHeaderValue> _acceptCharset; private HttpHeaderValueCollection<StringWithQualityHeaderValue> _acceptEncoding; private HttpHeaderValueCollection<StringWithQualityHeaderValue> _acceptLanguage; #region Request Headers public HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> Accept { get { if (_accept == null) { _accept = new HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue>( HttpKnownHeaderNames.Accept, this); } return _accept; } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Charset", Justification = "The HTTP header name is 'Accept-Charset'.")] public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptCharset { get { if (_acceptCharset == null) { _acceptCharset = new HttpHeaderValueCollection<StringWithQualityHeaderValue>( HttpKnownHeaderNames.AcceptCharset, this); } return _acceptCharset; } } public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptEncoding { get { if (_acceptEncoding == null) { _acceptEncoding = new HttpHeaderValueCollection<StringWithQualityHeaderValue>( HttpKnownHeaderNames.AcceptEncoding, this); } return _acceptEncoding; } } public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptLanguage { get { if (_acceptLanguage == null) { _acceptLanguage = new HttpHeaderValueCollection<StringWithQualityHeaderValue>( HttpKnownHeaderNames.AcceptLanguage, this); } return _acceptLanguage; } } public AuthenticationHeaderValue Authorization { get { return (AuthenticationHeaderValue)GetParsedValues(HttpKnownHeaderNames.Authorization); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Authorization, value); } } public HttpHeaderValueCollection<NameValueWithParametersHeaderValue> Expect { get { return ExpectCore; } } public bool? ExpectContinue { get { if (ExpectCore.IsSpecialValueSet) { return true; } if (_expectContinueSet) { return false; } return null; } set { if (value == true) { _expectContinueSet = true; ExpectCore.SetSpecialValue(); } else { _expectContinueSet = value != null; ExpectCore.RemoveSpecialValue(); } } } public string From { get { return (string)GetParsedValues(HttpKnownHeaderNames.From); } set { // Null and empty string are equivalent. In this case it means, remove the From header value (if any). if (value == string.Empty) { value = null; } if ((value != null) && !HeaderUtilities.IsValidEmailAddress(value)) { throw new FormatException(SR.net_http_headers_invalid_from_header); } SetOrRemoveParsedValue(HttpKnownHeaderNames.From, value); } } public string Host { get { return (string)GetParsedValues(HttpKnownHeaderNames.Host); } set { // Null and empty string are equivalent. In this case it means, remove the Host header value (if any). if (value == string.Empty) { value = null; } string host = null; if ((value != null) && (HttpRuleParser.GetHostLength(value, 0, false, out host) != value.Length)) { throw new FormatException(SR.net_http_headers_invalid_host_header); } SetOrRemoveParsedValue(HttpKnownHeaderNames.Host, value); } } public HttpHeaderValueCollection<EntityTagHeaderValue> IfMatch { get { if (_ifMatch == null) { _ifMatch = new HttpHeaderValueCollection<EntityTagHeaderValue>( HttpKnownHeaderNames.IfMatch, this); } return _ifMatch; } } public DateTimeOffset? IfModifiedSince { get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.IfModifiedSince, this); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.IfModifiedSince, value); } } public HttpHeaderValueCollection<EntityTagHeaderValue> IfNoneMatch { get { if (_ifNoneMatch == null) { _ifNoneMatch = new HttpHeaderValueCollection<EntityTagHeaderValue>( HttpKnownHeaderNames.IfNoneMatch, this); } return _ifNoneMatch; } } public RangeConditionHeaderValue IfRange { get { return (RangeConditionHeaderValue)GetParsedValues(HttpKnownHeaderNames.IfRange); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.IfRange, value); } } public DateTimeOffset? IfUnmodifiedSince { get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.IfUnmodifiedSince, this); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.IfUnmodifiedSince, value); } } public int? MaxForwards { get { object storedValue = GetParsedValues(HttpKnownHeaderNames.MaxForwards); if (storedValue != null) { return (int)storedValue; } return null; } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.MaxForwards, value); } } public AuthenticationHeaderValue ProxyAuthorization { get { return (AuthenticationHeaderValue)GetParsedValues(HttpKnownHeaderNames.ProxyAuthorization); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.ProxyAuthorization, value); } } public RangeHeaderValue Range { get { return (RangeHeaderValue)GetParsedValues(HttpKnownHeaderNames.Range); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Range, value); } } public Uri Referrer { get { return (Uri)GetParsedValues(HttpKnownHeaderNames.Referer); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Referer, value); } } public HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue> TE { get { if (_te == null) { _te = new HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue>( HttpKnownHeaderNames.TE, this); } return _te; } } public HttpHeaderValueCollection<ProductInfoHeaderValue> UserAgent { get { if (_userAgent == null) { _userAgent = new HttpHeaderValueCollection<ProductInfoHeaderValue>(HttpKnownHeaderNames.UserAgent, this); } return _userAgent; } } private HttpHeaderValueCollection<NameValueWithParametersHeaderValue> ExpectCore { get { if (_expect == null) { _expect = new HttpHeaderValueCollection<NameValueWithParametersHeaderValue>( HttpKnownHeaderNames.Expect, this, HeaderUtilities.ExpectContinue); } return _expect; } } #endregion #region General Headers public CacheControlHeaderValue CacheControl { get { return _generalHeaders.CacheControl; } set { _generalHeaders.CacheControl = value; } } public HttpHeaderValueCollection<string> Connection { get { return _generalHeaders.Connection; } } public bool? ConnectionClose { get { return _generalHeaders.ConnectionClose; } set { _generalHeaders.ConnectionClose = value; } } public DateTimeOffset? Date { get { return _generalHeaders.Date; } set { _generalHeaders.Date = value; } } public HttpHeaderValueCollection<NameValueHeaderValue> Pragma { get { return _generalHeaders.Pragma; } } public HttpHeaderValueCollection<string> Trailer { get { return _generalHeaders.Trailer; } } public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding { get { return _generalHeaders.TransferEncoding; } } public bool? TransferEncodingChunked { get { return _generalHeaders.TransferEncodingChunked; } set { _generalHeaders.TransferEncodingChunked = value; } } public HttpHeaderValueCollection<ProductHeaderValue> Upgrade { get { return _generalHeaders.Upgrade; } } public HttpHeaderValueCollection<ViaHeaderValue> Via { get { return _generalHeaders.Via; } } public HttpHeaderValueCollection<WarningHeaderValue> Warning { get { return _generalHeaders.Warning; } } #endregion internal HttpRequestHeaders() { _generalHeaders = new HttpGeneralHeaders(this); base.SetConfiguration(s_parserStore, s_invalidHeaders); } private static Dictionary<string, HttpHeaderParser> CreateParserStore() { var parserStore = new Dictionary<string, HttpHeaderParser>(StringComparer.OrdinalIgnoreCase); parserStore.Add(HttpKnownHeaderNames.Accept, MediaTypeHeaderParser.MultipleValuesParser); parserStore.Add(HttpKnownHeaderNames.AcceptCharset, GenericHeaderParser.MultipleValueStringWithQualityParser); parserStore.Add(HttpKnownHeaderNames.AcceptEncoding, GenericHeaderParser.MultipleValueStringWithQualityParser); parserStore.Add(HttpKnownHeaderNames.AcceptLanguage, GenericHeaderParser.MultipleValueStringWithQualityParser); parserStore.Add(HttpKnownHeaderNames.Authorization, GenericHeaderParser.SingleValueAuthenticationParser); parserStore.Add(HttpKnownHeaderNames.Expect, GenericHeaderParser.MultipleValueNameValueWithParametersParser); parserStore.Add(HttpKnownHeaderNames.From, GenericHeaderParser.MailAddressParser); parserStore.Add(HttpKnownHeaderNames.Host, GenericHeaderParser.HostParser); parserStore.Add(HttpKnownHeaderNames.IfMatch, GenericHeaderParser.MultipleValueEntityTagParser); parserStore.Add(HttpKnownHeaderNames.IfModifiedSince, DateHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.IfNoneMatch, GenericHeaderParser.MultipleValueEntityTagParser); parserStore.Add(HttpKnownHeaderNames.IfRange, GenericHeaderParser.RangeConditionParser); parserStore.Add(HttpKnownHeaderNames.IfUnmodifiedSince, DateHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.MaxForwards, Int32NumberHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.ProxyAuthorization, GenericHeaderParser.SingleValueAuthenticationParser); parserStore.Add(HttpKnownHeaderNames.Range, GenericHeaderParser.RangeParser); parserStore.Add(HttpKnownHeaderNames.Referer, UriHeaderParser.RelativeOrAbsoluteUriParser); parserStore.Add(HttpKnownHeaderNames.TE, TransferCodingHeaderParser.MultipleValueWithQualityParser); parserStore.Add(HttpKnownHeaderNames.UserAgent, ProductInfoHeaderParser.MultipleValueParser); HttpGeneralHeaders.AddParsers(parserStore); return parserStore; } private static HashSet<string> CreateInvalidHeaders() { var invalidHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase); HttpContentHeaders.AddKnownHeaders(invalidHeaders); return invalidHeaders; // Note: Reserved response header names are allowed as custom request header names. Reserved response // headers have no defined meaning or format when used on a request. This enables a server to accept // any headers sent from the client as either content headers or request headers. } internal static void AddKnownHeaders(HashSet<string> headerSet) { Contract.Requires(headerSet != null); headerSet.Add(HttpKnownHeaderNames.Accept); headerSet.Add(HttpKnownHeaderNames.AcceptCharset); headerSet.Add(HttpKnownHeaderNames.AcceptEncoding); headerSet.Add(HttpKnownHeaderNames.AcceptLanguage); headerSet.Add(HttpKnownHeaderNames.Authorization); headerSet.Add(HttpKnownHeaderNames.Expect); headerSet.Add(HttpKnownHeaderNames.From); headerSet.Add(HttpKnownHeaderNames.Host); headerSet.Add(HttpKnownHeaderNames.IfMatch); headerSet.Add(HttpKnownHeaderNames.IfModifiedSince); headerSet.Add(HttpKnownHeaderNames.IfNoneMatch); headerSet.Add(HttpKnownHeaderNames.IfRange); headerSet.Add(HttpKnownHeaderNames.IfUnmodifiedSince); headerSet.Add(HttpKnownHeaderNames.MaxForwards); headerSet.Add(HttpKnownHeaderNames.ProxyAuthorization); headerSet.Add(HttpKnownHeaderNames.Range); headerSet.Add(HttpKnownHeaderNames.Referer); headerSet.Add(HttpKnownHeaderNames.TE); headerSet.Add(HttpKnownHeaderNames.UserAgent); } internal override void AddHeaders(HttpHeaders sourceHeaders) { base.AddHeaders(sourceHeaders); HttpRequestHeaders sourceRequestHeaders = sourceHeaders as HttpRequestHeaders; Debug.Assert(sourceRequestHeaders != null); // Copy special values but do not overwrite. _generalHeaders.AddSpecialsFrom(sourceRequestHeaders._generalHeaders); bool? expectContinue = ExpectContinue; if (!expectContinue.HasValue) { ExpectContinue = sourceRequestHeaders.ExpectContinue; } } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Testing.Algo File: HistoryMessageAdapter.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Testing { using System; using System.Collections.Generic; using System.Linq; using Ecng.Common; using MoreLinq; using StockSharp.Algo.Storages; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// The adapter, receiving messages form the storage <see cref="IStorageRegistry"/>. /// </summary> public class HistoryMessageAdapter : MessageAdapter { private bool _isSuspended; private bool _isStarted; /// <summary> /// The number of loaded events. /// </summary> public int LoadedMessageCount { get; private set; } /// <summary> /// The number of the event <see cref="IConnector.MarketTimeChanged"/> calls after end of trading. By default it is equal to 2. /// </summary> /// <remarks> /// It is required for activation of post-trade rules (rules, basing on events, occurring after end of trading). /// </remarks> public int PostTradeMarketTimeChangedCount { get { return BasketStorage.PostTradeMarketTimeChangedCount; } set { BasketStorage.PostTradeMarketTimeChangedCount = value; } } private IStorageRegistry _storageRegistry; /// <summary> /// Market data storage. /// </summary> public IStorageRegistry StorageRegistry { get { return _storageRegistry; } set { _storageRegistry = value; if (value != null) Drive = value.DefaultDrive; } } private IMarketDataDrive _drive; /// <summary> /// The storage which is used by default. By default, <see cref="IStorageRegistry.DefaultDrive"/> is used. /// </summary> public IMarketDataDrive Drive { get { return _drive; } set { if (value == null && StorageRegistry != null) throw new ArgumentNullException(); _drive = value; } } /// <summary> /// The format of market data. <see cref="StorageFormats.Binary"/> is used by default. /// </summary> public StorageFormats StorageFormat { get; set; } /// <summary> /// The aggregator-storage. /// </summary> public CachedBasketMarketDataStorage<Message> BasketStorage { get; } /// <summary> /// The provider of information about instruments. /// </summary> public ISecurityProvider SecurityProvider { get; } /// <summary> /// The interval of message <see cref="TimeMessage"/> generation. By default, it is equal to 1 sec. /// </summary> [CategoryLoc(LocalizedStrings.Str186Key)] [DisplayNameLoc(LocalizedStrings.TimeIntervalKey)] [DescriptionLoc(LocalizedStrings.Str195Key)] public virtual TimeSpan MarketTimeChangedInterval { get { return BasketStorage.MarketTimeChangedInterval; } set { BasketStorage.MarketTimeChangedInterval = value; } } /// <summary> /// Default value of <see cref="MaxMessageCount"/>. /// </summary> public const int DefaultMaxMessageCount = 1000000; /// <summary> /// The maximal size of the message queue, up to which history data are read. By default, it is equal to <see cref="DefaultMaxMessageCount"/>. /// </summary> public int MaxMessageCount { get { return BasketStorage.MaxMessageCount; } set { BasketStorage.MaxMessageCount = value; } } /// <summary> /// Initializes a new instance of the <see cref="HistoryMessageAdapter"/>. /// </summary> /// <param name="transactionIdGenerator">Transaction id generator.</param> public HistoryMessageAdapter(IdGenerator transactionIdGenerator) : base(transactionIdGenerator) { BasketStorage = new CachedBasketMarketDataStorage<Message> { Boards = Enumerable.Empty<ExchangeBoard>() }; MaxMessageCount = DefaultMaxMessageCount; StartDate = DateTimeOffset.MinValue; StopDate = DateTimeOffset.MaxValue; } /// <summary> /// Initializes a new instance of the <see cref="HistoryMessageAdapter"/>. /// </summary> /// <param name="transactionIdGenerator">Transaction id generator.</param> /// <param name="securityProvider">The provider of information about instruments.</param> public HistoryMessageAdapter(IdGenerator transactionIdGenerator, ISecurityProvider securityProvider) : this(transactionIdGenerator) { SecurityProvider = securityProvider; BasketStorage.Boards = SecurityProvider .LookupAll() .Select(s => s.Board) .Distinct(); this.AddMarketDataSupport(); this.AddSupportedMessage(ExtendedMessageTypes.EmulationState); this.AddSupportedMessage(ExtendedMessageTypes.HistorySource); } /// <summary> /// Date in history for starting the paper trading. /// </summary> public DateTimeOffset StartDate { get { return BasketStorage.StartDate; } set { BasketStorage.StartDate = value; } } /// <summary> /// Date in history to stop the paper trading (date is included). /// </summary> public DateTimeOffset StopDate { get { return BasketStorage.StopDate; } set { BasketStorage.StopDate = value; } } /// <summary> /// Order book builders. /// </summary> public IDictionary<SecurityId, IOrderLogMarketDepthBuilder> OrderLogMarketDepthBuilders { get; } = new Dictionary<SecurityId, IOrderLogMarketDepthBuilder>(); /// <summary> /// Create market depth builder. /// </summary> /// <param name="securityId">Security ID.</param> /// <returns>Order log to market depth builder.</returns> public override IOrderLogMarketDepthBuilder CreateOrderLogMarketDepthBuilder(SecurityId securityId) { return OrderLogMarketDepthBuilders[securityId]; } private DateTimeOffset _currentTime; /// <summary> /// The current time. /// </summary> public override DateTimeOffset CurrentTime => _currentTime; /// <summary> /// Release resources. /// </summary> protected override void DisposeManaged() { BasketStorage.Dispose(); base.DisposeManaged(); } /// <summary> /// <see cref="SecurityLookupMessage"/> required to get securities. /// </summary> public override bool SecurityLookupRequired => true; /// <summary> /// Send message. /// </summary> /// <param name="message">Message.</param> protected override void OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { _isSuspended = false; _currentTime = default(DateTimeOffset); BasketStorage.Reset(); LoadedMessageCount = 0; if (!_isStarted) SendOutMessage(new ResetMessage()); break; } case MessageTypes.Connect: { if (_isStarted) throw new InvalidOperationException(LocalizedStrings.Str1116); SendOutMessage(new ConnectMessage { LocalTime = StartDate }); return; } case MessageTypes.Disconnect: { _isSuspended = false; if(_isStarted) SendOutMessage(new LastMessage { LocalTime = StopDate }); SendOutMessage(new DisconnectMessage { LocalTime = StopDate }); //SendOutMessage(new ResetMessage()); BasketStorage.Reset(); _isStarted = false; return; } case MessageTypes.SecurityLookup: { var lookupMsg = (SecurityLookupMessage)message; var securities = lookupMsg.SecurityId.IsDefault() ? SecurityProvider.LookupAll() : SecurityProvider.Lookup(lookupMsg.ToSecurity()); securities.ForEach(security => { SendOutMessage(security.Board.ToMessage()); var secMsg = security.ToMessage(); secMsg.OriginalTransactionId = lookupMsg.TransactionId; SendOutMessage(secMsg); //SendOutMessage(new Level1ChangeMessage { SecurityId = security.ToSecurityId() } // .Add(Level1Fields.StepPrice, security.StepPrice) // .Add(Level1Fields.MinPrice, security.MinPrice) // .Add(Level1Fields.MaxPrice, security.MaxPrice) // .Add(Level1Fields.MarginBuy, security.MarginBuy) // .Add(Level1Fields.MarginSell, security.MarginSell)); }); SendOutMessage(new SecurityLookupResultMessage { OriginalTransactionId = lookupMsg.TransactionId }); return; } case MessageTypes.MarketData: case ExtendedMessageTypes.HistorySource: ProcessMarketDataMessage((MarketDataMessage)message); return; case ExtendedMessageTypes.EmulationState: var stateMsg = (EmulationStateMessage)message; var isSuspended = false; switch (stateMsg.State) { case EmulationStates.Starting: { if (_isStarted) _isSuspended = false; else _isStarted = true; break; } case EmulationStates.Suspending: { _isSuspended = true; isSuspended = true; break; } case EmulationStates.Stopping: { _isSuspended = false; break; } } SendOutMessage(message); if (isSuspended) SendOutMessage(new EmulationStateMessage { State = EmulationStates.Suspended }); return; } //SendOutMessage(message); } private void ProcessMarketDataMessage(MarketDataMessage message) { var securityId = message.SecurityId; var security = SecurityProvider.LookupById(securityId.ToStringId()); if (security == null) { RaiseMarketDataMessage(message, new InvalidOperationException(LocalizedStrings.Str704Params.Put(securityId))); return; } if (StorageRegistry == null) { RaiseMarketDataMessage(message, new InvalidOperationException(LocalizedStrings.Str1117Params.Put(message.DataType, securityId))); return; } var history = message as HistorySourceMessage; Exception error = null; switch (message.DataType) { case MarketDataTypes.Level1: { if (message.IsSubscribe) { if (history == null) { BasketStorage.AddStorage(StorageRegistry.GetLevel1MessageStorage(security, Drive, StorageFormat)); BasketStorage.AddStorage(new InMemoryMarketDataStorage<ClearingMessage>(security, null, date => new[] { new ClearingMessage { LocalTime = date.Date + security.Board.ExpiryTime, SecurityId = securityId, ClearMarketDepth = true } })); } else { BasketStorage.AddStorage(new InMemoryMarketDataStorage<Level1ChangeMessage>(security, null, history.GetMessages)); } } else { BasketStorage.RemoveStorage<IMarketDataStorage<Level1ChangeMessage>>(security, MessageTypes.Level1Change, null); BasketStorage.RemoveStorage<InMemoryMarketDataStorage<ClearingMessage>>(security, ExtendedMessageTypes.Clearing, null); } break; } case MarketDataTypes.MarketDepth: { if (message.IsSubscribe) { BasketStorage.AddStorage(history == null ? StorageRegistry.GetQuoteMessageStorage(security, Drive, StorageFormat) : new InMemoryMarketDataStorage<QuoteChangeMessage>(security, null, history.GetMessages)); } else BasketStorage.RemoveStorage<IMarketDataStorage<QuoteChangeMessage>>(security, MessageTypes.QuoteChange, null); break; } case MarketDataTypes.Trades: { if (message.IsSubscribe) { BasketStorage.AddStorage(history == null ? StorageRegistry.GetTickMessageStorage(security, Drive, StorageFormat) : new InMemoryMarketDataStorage<ExecutionMessage>(security, null, history.GetMessages)); } else BasketStorage.RemoveStorage<IMarketDataStorage<ExecutionMessage>>(security, MessageTypes.Execution, ExecutionTypes.Tick); break; } case MarketDataTypes.OrderLog: { if (message.IsSubscribe) { BasketStorage.AddStorage(history == null ? StorageRegistry.GetOrderLogMessageStorage(security, Drive, StorageFormat) : new InMemoryMarketDataStorage<ExecutionMessage>(security, null, history.GetMessages)); } else BasketStorage.RemoveStorage<IMarketDataStorage<ExecutionMessage>>(security, MessageTypes.Execution, ExecutionTypes.OrderLog); break; } case MarketDataTypes.CandleTimeFrame: case MarketDataTypes.CandleTick: case MarketDataTypes.CandleVolume: case MarketDataTypes.CandleRange: case MarketDataTypes.CandlePnF: case MarketDataTypes.CandleRenko: { var msgType = message.DataType.ToCandleMessageType(); if (message.IsSubscribe) { var candleType = message.DataType.ToCandleMessage(); BasketStorage.AddStorage(history == null ? StorageRegistry.GetCandleMessageStorage(candleType, security, message.Arg, Drive, StorageFormat) : new InMemoryMarketDataStorage<CandleMessage>(security, message.Arg, history.GetMessages, candleType)); } else BasketStorage.RemoveStorage<IMarketDataStorage<CandleMessage>>(security, msgType, message.Arg); break; } default: error = new InvalidOperationException(LocalizedStrings.Str1118Params.Put(message.DataType)); break; } RaiseMarketDataMessage(message, error); } private void RaiseMarketDataMessage(MarketDataMessage message, Exception error) { var reply = (MarketDataMessage)message.Clone(); reply.OriginalTransactionId = message.TransactionId; reply.Error = error; SendOutMessage(reply); } /// <summary> /// Send next outgoing message. /// </summary> /// <returns><see langword="true" />, if message was sent, otherwise, <see langword="false" />.</returns> public bool SendOutMessage() { if (!_isStarted || _isSuspended) return false; if (!BasketStorage.MoveNext()) return false; var msg = BasketStorage.Current; SendOutMessage(msg); return true; } /// <summary> /// Send outgoing message and raise <see cref="MessageAdapter.NewOutMessage"/> event. /// </summary> /// <param name="message">Message.</param> public override void SendOutMessage(Message message) { LoadedMessageCount++; var serverTime = message.GetServerTime(); if (serverTime != null) _currentTime = serverTime.Value; base.SendOutMessage(message); } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return LocalizedStrings.Str1127Params.Put(StartDate, StopDate); } } }
//------------------------------------------------------------------------------ // <copyright file="XmlDiffDocument.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.IO; using System.Xml; using System.Diagnostics; using System.Collections; namespace Microsoft.XmlDiffPatch { ////////////////////////////////////////////////////////////////// // XmlDiffDocument // internal class XmlDiffDocument : XmlDiffParentNode { // Fields protected XmlDiff _XmlDiff; bool _bLoaded; // Used at loading only XmlDiffNode _curLastChild; XmlHash _xmlHash; // Constructor internal XmlDiffDocument( XmlDiff xmlDiff ) : base( 0 ) { _bLoaded = false; _XmlDiff = xmlDiff; } // Properties internal override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Document; } } internal bool IsFragment { get { XmlDiffNode node = _firstChildNode; while ( node != null && node.NodeType != XmlDiffNodeType.Element ) { node = node._nextSibling; } if ( node == null ) { return true; } node = node._nextSibling; while ( node != null && node.NodeType != XmlDiffNodeType.Element ) { node = node._nextSibling; } return ( node != null ); } } // Methods // computes the hash value of the node and saves it into the _hashValue field internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( _hashValue == 0 ); _hashValue = xmlHash.ComputeHashXmlDiffDocument( this ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { if ( changedNode.NodeType != XmlDiffNodeType.Document ) return XmlDiffOperation.Undefined; else return XmlDiffOperation.Match; } // Loads the document from XmlReader internal virtual void Load( XmlReader reader, XmlHash xmlHash ) { if ( _bLoaded ) throw new InvalidOperationException( "The document already contains data and should not be used again." ); try { _curLastChild = null; _xmlHash = xmlHash; LoadChildNodes( this, reader, false ); ComputeHashValue( _xmlHash ); _bLoaded = true; #if DEBUG if ( XmlDiff.T_LoadedDoc.Enabled ) { Trace.Write( "\nLoaded document " + reader.BaseURI + ": \n" ); Dump(); } #endif } finally { _xmlHash = null; } } // Loads child nodes of the 'parent' node internal void LoadChildNodes ( XmlDiffParentNode parent, XmlReader reader, bool bEmptyElement ) { XmlDiffNode savedLastChild = _curLastChild; _curLastChild = null; // load attributes & namespace nodes while ( reader.MoveToNextAttribute() ) { if ( reader.Prefix == "xmlns" ) { if ( !_XmlDiff.IgnoreNamespaces ) { XmlDiffNamespace nsNode = new XmlDiffNamespace( reader.LocalName, reader.Value ); nsNode.ComputeHashValue( _xmlHash ); InsertAttributeOrNamespace( (XmlDiffElement)parent, nsNode ); } } else if ( reader.Prefix == string.Empty && reader.LocalName == "xmlns" ) { if ( !_XmlDiff.IgnoreNamespaces ) { XmlDiffNamespace nsNode = new XmlDiffNamespace( string.Empty, reader.Value ); nsNode.ComputeHashValue( _xmlHash ); InsertAttributeOrNamespace( (XmlDiffElement)parent, nsNode ); } } else { string attrValue = _XmlDiff.IgnoreWhitespace ? XmlDiff.NormalizeText( reader.Value ) : reader.Value; XmlDiffAttribute attr = new XmlDiffAttribute( reader.LocalName, reader.Prefix, reader.NamespaceURI, attrValue ); attr.ComputeHashValue( _xmlHash ); InsertAttributeOrNamespace( (XmlDiffElement)parent, attr ); } } // empty element -> return, do not load chilren if ( bEmptyElement ) goto End; int childPosition = 0; // load children if ( !reader.Read()) goto End; do { // ignore whitespaces between nodes if ( reader.NodeType == XmlNodeType.Whitespace ) continue; switch ( reader.NodeType ) { case XmlNodeType.Element: { bool bEmptyEl = reader.IsEmptyElement; XmlDiffElement elem = new XmlDiffElement( ++childPosition, reader.LocalName, reader.Prefix, reader.NamespaceURI ); LoadChildNodes( elem, reader, bEmptyEl ); elem.ComputeHashValue( _xmlHash ); InsertChild( parent, elem ); break; } case XmlNodeType.Attribute: { Debug.Assert( false, "We should never get to this point, attributes should be read at the beginning of thid method." ); break; } case XmlNodeType.Text: { string textValue = ( _XmlDiff.IgnoreWhitespace ) ? XmlDiff.NormalizeText( reader.Value ) : reader.Value; XmlDiffCharData charDataNode = new XmlDiffCharData( ++childPosition, textValue, XmlDiffNodeType.Text ); charDataNode.ComputeHashValue( _xmlHash ); InsertChild( parent, charDataNode ); break; } case XmlNodeType.CDATA: { XmlDiffCharData charDataNode = new XmlDiffCharData( ++childPosition, reader.Value, XmlDiffNodeType.CDATA ); charDataNode.ComputeHashValue( _xmlHash ); InsertChild( parent, charDataNode ); break; } case XmlNodeType.EntityReference: { XmlDiffER er = new XmlDiffER( ++childPosition, reader.Name ); er.ComputeHashValue( _xmlHash ); InsertChild( parent, er ); break; } case XmlNodeType.Comment: { ++childPosition; if ( !_XmlDiff.IgnoreComments ) { XmlDiffCharData charDataNode = new XmlDiffCharData( childPosition, reader.Value, XmlDiffNodeType.Comment ); charDataNode.ComputeHashValue( _xmlHash ); InsertChild( parent, charDataNode ); } break; } case XmlNodeType.ProcessingInstruction: { ++childPosition; if ( !_XmlDiff.IgnorePI ) { XmlDiffPI pi = new XmlDiffPI( childPosition, reader.Name, reader.Value ); pi.ComputeHashValue( _xmlHash ); InsertChild( parent, pi ); } break; } case XmlNodeType.SignificantWhitespace: { if( reader.XmlSpace == XmlSpace.Preserve ) { ++childPosition; if (!_XmlDiff.IgnoreWhitespace ) { XmlDiffCharData charDataNode = new XmlDiffCharData( childPosition, reader.Value, XmlDiffNodeType.SignificantWhitespace ); charDataNode.ComputeHashValue( _xmlHash ); InsertChild( parent, charDataNode ); } } break; } case XmlNodeType.XmlDeclaration: { ++childPosition; if ( !_XmlDiff.IgnoreXmlDecl ) { XmlDiffXmlDeclaration xmlDecl = new XmlDiffXmlDeclaration( childPosition, XmlDiff.NormalizeXmlDeclaration( reader.Value ) ); xmlDecl.ComputeHashValue( _xmlHash ); InsertChild( parent, xmlDecl ); } break; } case XmlNodeType.EndElement: goto End; case XmlNodeType.DocumentType: childPosition++; if ( !_XmlDiff.IgnoreDtd ) { XmlDiffDocumentType docType = new XmlDiffDocumentType( childPosition, reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value ); docType.ComputeHashValue( _xmlHash ); InsertChild( parent, docType ); } break; default: Debug.Assert( false ); break; } } while ( reader.Read() ); End: _curLastChild = savedLastChild; } // Loads the document from XmlNode internal virtual void Load( XmlNode node, XmlHash xmlHash ) { if ( _bLoaded ) throw new InvalidOperationException( "The document already contains data and should not be used again." ); if ( node.NodeType == XmlNodeType.Attribute || node.NodeType == XmlNodeType.Entity || node.NodeType == XmlNodeType.Notation || node.NodeType == XmlNodeType.Whitespace ) { throw new ArgumentException( "Invalid node type." ); } try { _curLastChild = null; _xmlHash = xmlHash; if ( node.NodeType == XmlNodeType.Document || node.NodeType == XmlNodeType.DocumentFragment ) { LoadChildNodes( this, node ); ComputeHashValue( _xmlHash ); } else { int childPos = 0; XmlDiffNode rootNode = LoadNode( node, ref childPos ); if ( rootNode != null ) { InsertChildNodeAfter( null, rootNode ); _hashValue = rootNode.HashValue; } } _bLoaded = true; #if DEBUG if ( XmlDiff.T_LoadedDoc.Enabled ) { Trace.Write( "\nLoaded document " + node.BaseURI + ": \n" ); Dump(); } #endif } finally { _xmlHash = null; } } internal XmlDiffNode LoadNode( XmlNode node, ref int childPosition ) { switch ( node.NodeType ) { case XmlNodeType.Element: XmlDiffElement elem = new XmlDiffElement( ++childPosition, node.LocalName, node.Prefix, node.NamespaceURI ); LoadChildNodes( elem, node ); elem.ComputeHashValue( _xmlHash ); return elem; case XmlNodeType.Attribute: Debug.Assert( false, "Attributes cannot be loaded by this method." ); return null; case XmlNodeType.Text: string textValue = ( _XmlDiff.IgnoreWhitespace ) ? XmlDiff.NormalizeText( node.Value ) : node.Value; XmlDiffCharData text = new XmlDiffCharData( ++childPosition, textValue, XmlDiffNodeType.Text ); text.ComputeHashValue( _xmlHash ); return text; case XmlNodeType.CDATA: XmlDiffCharData cdata = new XmlDiffCharData( ++childPosition, node.Value, XmlDiffNodeType.CDATA ); cdata.ComputeHashValue( _xmlHash ); return cdata; case XmlNodeType.EntityReference: XmlDiffER er = new XmlDiffER( ++childPosition, node.Name ); er.ComputeHashValue( _xmlHash ); return er; case XmlNodeType.Comment: ++childPosition; if ( _XmlDiff.IgnoreComments ) return null; XmlDiffCharData comment = new XmlDiffCharData( childPosition, node.Value, XmlDiffNodeType.Comment ); comment.ComputeHashValue( _xmlHash ); return comment; case XmlNodeType.ProcessingInstruction: ++childPosition; if ( _XmlDiff.IgnorePI ) return null; XmlDiffPI pi = new XmlDiffPI( childPosition, node.Name, node.Value ); pi.ComputeHashValue( _xmlHash ); return pi; case XmlNodeType.SignificantWhitespace: ++childPosition; if ( _XmlDiff.IgnoreWhitespace ) return null; XmlDiffCharData ws = new XmlDiffCharData( childPosition, node.Value, XmlDiffNodeType.SignificantWhitespace ); ws.ComputeHashValue( _xmlHash ); return ws; case XmlNodeType.XmlDeclaration: ++childPosition; if ( _XmlDiff.IgnoreXmlDecl ) return null; XmlDiffXmlDeclaration xmlDecl = new XmlDiffXmlDeclaration( childPosition, XmlDiff.NormalizeXmlDeclaration( node.Value ) ); xmlDecl.ComputeHashValue( _xmlHash ); return xmlDecl; case XmlNodeType.EndElement: return null; case XmlNodeType.DocumentType: childPosition++; if ( _XmlDiff.IgnoreDtd ) return null; XmlDocumentType docType = (XmlDocumentType)node; XmlDiffDocumentType diffDocType = new XmlDiffDocumentType( childPosition, docType.Name, docType.PublicId, docType.SystemId, docType.InternalSubset ); diffDocType.ComputeHashValue( _xmlHash ); return diffDocType; default: Debug.Assert( false ); return null; } } // Loads child nodes of the 'parent' node internal void LoadChildNodes( XmlDiffParentNode parent, XmlNode parentDomNode ) { XmlDiffNode savedLastChild = _curLastChild; _curLastChild = null; // load attributes & namespace nodes XmlNamedNodeMap attribs = parentDomNode.Attributes; if ( attribs != null && attribs.Count > 0 ) { IEnumerator attrEnum = attribs.GetEnumerator(); while ( attrEnum.MoveNext() ) { XmlAttribute attr = (XmlAttribute)attrEnum.Current; if ( attr.Prefix == "xmlns" ) { if ( !_XmlDiff.IgnoreNamespaces ) { XmlDiffNamespace nsNode = new XmlDiffNamespace( attr.LocalName, attr.Value ); nsNode.ComputeHashValue( _xmlHash ); InsertAttributeOrNamespace( (XmlDiffElement)parent, nsNode ); } } else if ( attr.Prefix == string.Empty && attr.LocalName == "xmlns" ) { if ( !_XmlDiff.IgnoreNamespaces ) { XmlDiffNamespace nsNode = new XmlDiffNamespace( string.Empty, attr.Value ); nsNode.ComputeHashValue( _xmlHash ); InsertAttributeOrNamespace( (XmlDiffElement)parent, nsNode ); } } else { string attrValue = _XmlDiff.IgnoreWhitespace ? XmlDiff.NormalizeText( attr.Value ) : attr.Value; XmlDiffAttribute newAttr = new XmlDiffAttribute( attr.LocalName, attr.Prefix, attr.NamespaceURI, attrValue ); newAttr.ComputeHashValue( _xmlHash ); InsertAttributeOrNamespace( (XmlDiffElement)parent, newAttr ); } } } // load children XmlNodeList children = parentDomNode.ChildNodes; if ( children.Count == 0 ) goto End; int childPosition = 0; IEnumerator childEnum = children.GetEnumerator(); while ( childEnum.MoveNext() ) { XmlNode node = (XmlNode)childEnum.Current; // ignore whitespaces between nodes if ( node.NodeType == XmlNodeType.Whitespace ) continue; XmlDiffNode newDiffNode = LoadNode( (XmlNode)childEnum.Current, ref childPosition ); if ( newDiffNode != null ) InsertChild( parent, newDiffNode ); } End: _curLastChild = savedLastChild; } // Inserts the 'newChild' node. If child order is significant, the new child is // inserted at the end of all child nodes. If the child order is not signoficant, // the new node is sorted into the other child nodes. private void InsertChild( XmlDiffParentNode parent, XmlDiffNode newChild ) { if ( _XmlDiff.IgnoreChildOrder ) { XmlDiffNode curChild = parent.FirstChildNode; XmlDiffNode prevChild = null; while ( curChild != null && ( OrderChildren( curChild, newChild ) <= 0 ) ) { prevChild = curChild; curChild = curChild._nextSibling; } parent.InsertChildNodeAfter( prevChild, newChild ); } else { parent.InsertChildNodeAfter( _curLastChild, newChild ); _curLastChild = newChild; } } // Inserts an attribute or namespace node. The new node is sorted into the other attributes/namespace nodes. private void InsertAttributeOrNamespace( XmlDiffElement element, XmlDiffAttributeOrNamespace newAttrOrNs ) { element.InsertAttributeOrNamespace( newAttrOrNs ); } // Compares the two nodes. Used for sorting of the child nodes when the child order is not significant. static internal int OrderChildren( XmlDiffNode node1, XmlDiffNode node2 ) { Debug.Assert( node1 != null && node2 != null ); int nt1 = (int) node1.NodeType; int nt2 = (int) node2.NodeType; if ( nt1 < nt2) return -1; if ( nt2 < nt1 ) return 1; // now nt1 == nt2 switch ( nt1 ) { case (int) XmlDiffNodeType.Element: return OrderElements( node1 as XmlDiffElement, node2 as XmlDiffElement ); case (int) XmlDiffNodeType.Attribute: case (int) XmlDiffNodeType.Namespace: Debug.Assert( false, "We should never get to this point" ); return 0; case (int) XmlDiffNodeType.EntityReference: return OrderERs( node1 as XmlDiffER, node2 as XmlDiffER ); case (int) XmlDiffNodeType.ProcessingInstruction: return OrderPIs( node1 as XmlDiffPI, node2 as XmlDiffPI ); case (int) XmlDiffNodeType.ShrankNode: if ( ((XmlDiffShrankNode)node1).MatchingShrankNode == ((XmlDiffShrankNode)node2).MatchingShrankNode ) { return 0; } else { return ( ((XmlDiffShrankNode)node1).HashValue < ((XmlDiffShrankNode)node2).HashValue ) ? -1 : 1; } default: Debug.Assert ( node1 is XmlDiffCharData ); return OrderCharacterData( node1 as XmlDiffCharData, node2 as XmlDiffCharData ); } } static internal int OrderElements( XmlDiffElement elem1, XmlDiffElement elem2 ) { Debug.Assert( elem1 != null && elem2 != null ); int nCompare; if ( ( nCompare = OrderStrings( elem1.LocalName, elem2.LocalName ) ) == 0 && ( nCompare = OrderStrings( elem1.NamespaceURI, elem2.NamespaceURI ) ) == 0 ) { return OrderSubTrees( elem1, elem2 ); } return nCompare; } static internal int OrderAttributesOrNamespaces( XmlDiffAttributeOrNamespace node1, XmlDiffAttributeOrNamespace node2 ) { Debug.Assert( node1 != null && node2 != null ); if ( node1.NodeType != node2.NodeType ) { if ( node1.NodeType == XmlDiffNodeType.Namespace ) return -1; else return 1; } int nCompare; if ( ( nCompare = OrderStrings( node1.LocalName, node2.LocalName ) ) == 0 && ( nCompare = OrderStrings( node1.Prefix, node2.Prefix ) ) == 0 && ( nCompare = OrderStrings( node1.NamespaceURI, node2.NamespaceURI ) ) == 0 && ( nCompare = OrderStrings( node1.Value, node2.Value ) ) == 0 ) { return 0; } return nCompare; } static internal int OrderERs( XmlDiffER er1, XmlDiffER er2 ) { Debug.Assert( er1 != null && er2 != null ); return OrderStrings( er1.Name, er2.Name ); } static internal int OrderPIs( XmlDiffPI pi1, XmlDiffPI pi2 ) { Debug.Assert( pi1 != null && pi2 != null ); int nCompare = 0; if ( ( nCompare = OrderStrings( pi1.Name, pi2.Name ) ) == 0 && ( nCompare = OrderStrings( pi1.Value, pi2.Value ) ) == 0 ) { return 0; } return nCompare; } static internal int OrderCharacterData( XmlDiffCharData t1, XmlDiffCharData t2 ) { Debug.Assert( t1 != null && t2 != null ); return OrderStrings( t1.Value, t2.Value ); } // returns 0 if the same string; 1 if s1 > s2 and -1 if s1 < s2 static internal int OrderStrings( string s1, string s2 ) { int len = ( s1.Length < s2.Length ) ? s1.Length : s2.Length; int i = 0; while ( i < len && s1[i] == s2[i] ) i++; if ( i < len ) return ( s1[i] < s2[i]) ? -1 : 1; else if ( s1.Length == s2.Length ) return 0; else return ( s2.Length > s1.Length) ? -1 : 1; } static internal int OrderSubTrees( XmlDiffElement elem1, XmlDiffElement elem2 ) { Debug.Assert( elem1 != null && elem2 != null ); int nCompare = 0; // attributes - ignore namespace nodes XmlDiffAttributeOrNamespace curAttr1 = elem1._attributes; XmlDiffAttributeOrNamespace curAttr2 = elem2._attributes; while ( curAttr1 != null && curAttr1.NodeType == XmlDiffNodeType.Namespace ) curAttr1 = (XmlDiffAttributeOrNamespace)curAttr1._nextSibling; while ( curAttr2 != null && curAttr2.NodeType == XmlDiffNodeType.Namespace ) curAttr2 = (XmlDiffAttributeOrNamespace)curAttr2._nextSibling; while ( curAttr1 != null && curAttr2 != null ) { if ( ( nCompare = OrderAttributesOrNamespaces( curAttr1, curAttr2 ) ) != 0 ) return nCompare; curAttr1 = (XmlDiffAttributeOrNamespace)curAttr1._nextSibling; curAttr2 = (XmlDiffAttributeOrNamespace)curAttr2._nextSibling; } // children if ( curAttr1 == curAttr2 ) { XmlDiffNode curChild1 = elem1.FirstChildNode; XmlDiffNode curChild2 = elem2.FirstChildNode; while ( curChild1 != null && curChild2 != null ) { if ( ( nCompare = OrderChildren( curChild1, curChild2 ) ) != 0 ) return nCompare; curChild1 = curChild1._nextSibling; curChild2 = curChild2._nextSibling; } if ( curChild1 == curChild2 ) return 0; else if ( curChild1 == null ) return 1; //elem2 > elem1; else return -1; //elem1 > elem1; } else if ( curAttr1 == null ) return 1; //elem2 > elem1; else { return -1; //elem1 > elem1; } } internal override void WriteTo( XmlWriter w ) { WriteContentTo( w ); } internal override void WriteContentTo( XmlWriter w ) { XmlDiffNode child = FirstChildNode; while ( child != null ) { child.WriteTo( w ); child = child._nextSibling; } } #if DEBUG private void Dump( ) { Dump( "- " ); } internal override void Dump( string indent ) { DumpChildren( indent ); } #endif } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using Eto.Drawing; namespace Eto.Forms { /// <summary> /// Layout for controls in a table /// </summary> /// <remarks> /// This is similar to an html table, though each control will fill its entire cell. /// </remarks> [ContentProperty("Rows")] [Handler(typeof(TableLayout.IHandler))] public class TableLayout : Layout { new IHandler Handler { get { return (IHandler)base.Handler; } } static object rowsKey = new object(); Size dimensions; bool created; /// <summary> /// Gets an enumeration of controls that are directly contained by this container /// </summary> /// <value>The contained controls.</value> public override IEnumerable<Control> Controls { get { return Rows.SelectMany(r => r.Cells).Select(r => r.Control).Where(r => r != null); } } /// <summary> /// Gets the collection of rows in the table /// </summary> /// <value>The rows.</value> public Collection<TableRow> Rows { get { return Properties.Create<TableRowCollection>(rowsKey); } private set { Properties[rowsKey] = value; } } /// <summary> /// Gets the dimensions of the table in cells. /// </summary> /// <value>The dimensions of the table.</value> public Size Dimensions { get { return dimensions; } } /// <summary> /// Creates a table layout with an auto sized control. /// </summary> /// <remarks> /// Since controls fill an entire cell, you can use this method to create a layout that will ensure that the /// specified <paramref name="control"/> gets its preferred size instead of stretching to fill the container. /// /// By default, extra space will be added to the right and bottom, unless <paramref name="centered"/> is <c>true</c>, /// which will add equal space to the top/bottom, and left/right. /// </remarks> /// <returns>The table layout with the auto sized control.</returns> /// <param name="control">Control to auto size.</param> /// <param name="padding">Padding around the control</param> /// <param name="centered">If set to <c>true</c> center the control, otherwise control is upper left of the container.</param> public static TableLayout AutoSized(Control control, Padding? padding = null, bool centered = false) { if (centered) { var layout = new TableLayout(3, 3); layout.Padding = padding ?? Padding.Empty; layout.Spacing = Size.Empty; layout.SetColumnScale(0); layout.SetColumnScale(2); layout.SetRowScale(0); layout.SetRowScale(2); layout.Add(control, 1, 1); return layout; } else { var layout = new TableLayout(2, 2); layout.Padding = padding ?? Padding.Empty; layout.Spacing = Size.Empty; layout.Add(control, 0, 0); return layout; } } /// <summary> /// Creates a horizontal table layout with the specified cells. /// </summary> /// <remarks> /// Since table layouts are by default vertical by defining the rows and the cells for each row, /// it is verbose to create nested tables when you want a horizontal table. E.g. <code>new TableLayout(new TableRow(...))</code>. /// /// This method is used to easily create a single row table layout with a horizontal set of cells. E.g. /// <code>TableLayout.Horizontal(...)</code> /// </remarks> /// <param name="cells">Cells for the row</param> /// <returns>A new single row table layout with the specified cells</returns> public static TableLayout Horizontal(params TableCell[] cells) { return new TableLayout(new TableRow(cells)); } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.TableLayout"/> class. /// </summary> public TableLayout() { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.TableLayout"/> class with the specified number of columns and rows. /// </summary> /// <param name="columns">Number of columns in the table.</param> /// <param name="rows">Number of rows in the table.</param> public TableLayout(int columns, int rows) : this(new Size(columns, rows)) { } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.TableLayout"/> class with the specified dimensions. /// </summary> /// <param name="dimensions">Dimensions of the table.</param> public TableLayout(Size dimensions) { SetCellSize(dimensions, true); Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.TableLayout"/> class with the specified rows. /// </summary> /// <param name="rows">Rows to populate the table.</param> public TableLayout(params TableRow[] rows) { Rows = new TableRowCollection(rows); Create(); Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.TableLayout"/> class with the specified rows. /// </summary> /// <param name="rows">Rows to populate the table.</param> public TableLayout(IEnumerable<TableRow> rows) { Rows = new TableRowCollection(rows); Create(); Initialize(); } static readonly object DataContextChangedKey = new object(); /// <summary> /// Raises the <see cref="BindableWidget.DataContextChanged"/> event /// </summary> /// <remarks> /// Implementors may override this to fire this event on child widgets in a heirarchy. /// This allows a control to be bound to its own <see cref="BindableWidget.DataContext"/>, which would be set /// on one of the parent control(s). /// </remarks> /// <param name="e">Event arguments</param> protected override void OnDataContextChanged(EventArgs e) { if (created) base.OnDataContextChanged(e); else Properties[DataContextChangedKey] = true; } void Create() { var rows = Rows; var columnCount = rows.DefaultIfEmpty().Max(r => r != null ? r.Cells.Count : 0); SetCellSize(new Size(columnCount, rows.Count), false); if (columnCount > 0) { for (int y = 0; y < rows.Count; y++) { var row = rows[y]; while (row.Cells.Count < columnCount) row.Cells.Add(new TableCell()); for (int x = 0; x < columnCount; x++) { var cell = row.Cells[x]; Add(cell.Control, x, y); if (cell.ScaleWidth) SetColumnScale(x); } while (row.Cells.Count < columnCount) row.Cells.Add(new TableCell()); if (row.ScaleHeight) SetRowScale(y); } } created = true; if (Properties.Get<bool>(DataContextChangedKey)) { OnDataContextChanged(EventArgs.Empty); Properties[DataContextChangedKey] = null; } } void SetCellSize(Size value, bool createRows) { if (created) throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Can only set the cell size of a table once")); dimensions = value; Handler.CreateControl(dimensions.Width, dimensions.Height); if (!dimensions.IsEmpty) { if (createRows) { var rows = Enumerable.Range(0, value.Height).Select(r => new TableRow(Enumerable.Range(0, value.Width).Select(c => new TableCell()))); Rows = new TableRowCollection(rows); created = true; } } } /// <summary> /// Sets the scale for the specified column. /// </summary> /// <param name="column">Column to set the scale for.</param> /// <param name="scale">If set to <c>true</c> scale, otherwise size to preferred size of controls in the column.</param> public void SetColumnScale(int column, bool scale = true) { Handler.SetColumnScale(column, scale); } /// <summary> /// Gets the scale for the specified column. /// </summary> /// <returns><c>true</c>, if column is scaled, <c>false</c> otherwise.</returns> /// <param name="column">Column to retrieve the scale.</param> public bool GetColumnScale(int column) { return Handler.GetColumnScale(column); } /// <summary> /// Sets the scale for the specified row. /// </summary> /// <param name="row">Row to set the scale for.</param> /// <param name="scale">If set to <c>true</c> scale, otherwise size to preferred size of controls in the row.</param> public void SetRowScale(int row, bool scale = true) { Handler.SetRowScale(row, scale); } /// <summary> /// Gets the scale for the specified row. /// </summary> /// <returns><c>true</c>, if row is scaled, <c>false</c> otherwise.</returns> /// <param name="row">Row to retrieve the scale.</param> public bool GetRowScale(int row) { return Handler.GetRowScale(row); } /// <summary> /// Adds a control to the specified x &amp; y coordinates. /// </summary> /// <remarks> /// If a control already exists in the location, it is replaced. Only one control can exist in a cell. /// </remarks> /// <param name="control">Control to add.</param> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> public void Add(Control control, int x, int y) { InnerAdd(control, x, y); } void InnerAdd(Control control, int x, int y) { if (dimensions.IsEmpty) throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "You must set the size of the TableLayout before adding controls")); var cell = Rows[y].Cells[x]; SetParent(control, () => { cell.Control = control; Handler.Add(control, x, y); }, cell.Control); } /// <summary> /// Adds a control to the specified x &amp; y coordinates. /// </summary> /// <remarks> /// If a control already exists in the location, it is replaced. Only one control can exist in a cell. /// The <paramref name="xscale"/> and <paramref name="yscale"/> parameters are to easily set the scaling /// for the current row/column while adding the control. /// </remarks> /// <param name="control">Control to add.</param> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <param name="xscale">If set to <c>true</c> xscale.</param> /// <param name="yscale">If set to <c>true</c> yscale.</param> public void Add(Control control, int x, int y, bool xscale, bool yscale) { SetColumnScale(x, xscale); SetRowScale(y, yscale); Add(control, x, y); } /// <summary> /// Adds a control to the specified location. /// </summary> /// <remarks> /// If a control already exists in the location, it is replaced. Only one control can exist in a cell. /// </remarks> /// <param name="control">Control to add.</param> /// <param name="location">The location of the control.</param> public void Add(Control control, Point location) { Add(control, location.X, location.Y); } /// <summary> /// Moves the specified control to the new x and y coordinates. /// </summary> /// <remarks> /// If a control already exists in the new location, it will be replaced. Only one control can exist in a cell. /// The old location of the control will have an empty space. /// </remarks> /// <param name="control">Control to move.</param> /// <param name="x">The new x coordinate.</param> /// <param name="y">The new y coordinate.</param> public void Move(Control control, int x, int y) { var cell = Rows.SelectMany(r => r.Cells).FirstOrDefault(r => r.Control == control); if (cell != null) cell.Control = null; cell = Rows[y].Cells[x]; var old = cell.Control; if (old != null) RemoveParent(old); cell.Control = control; Handler.Move(control, x, y); } /// <summary> /// Move the specified control to a new location. /// </summary> /// <remarks> /// If a control already exists in the new location, it will be replaced. Only one control can exist in a cell. /// The old location of the control will have an empty space. /// </remarks> /// <param name="control">Control to move.</param> /// <param name="location">New location of the control.</param> public void Move(Control control, Point location) { Move(control, location.X, location.Y); } /// <summary> /// Remove the specified child control. /// </summary> /// <param name="child">Child control to remove.</param> public override void Remove(Control child) { var cell = Rows.SelectMany(r => r.Cells).FirstOrDefault(r => r.Control == child); if (cell != null) { cell.SetControl(null); Handler.Remove(child); RemoveParent(child); } } /// <summary> /// Gets or sets the horizontal and vertical spacing between each of the cells of the table. /// </summary> /// <value>The spacing between the cells.</value> public Size Spacing { get { return Handler.Spacing; } set { Handler.Spacing = value; } } /// <summary> /// Gets or sets the padding bordering the table. /// </summary> /// <value>The padding bordering the table.</value> public Padding Padding { get { return Handler.Padding; } set { Handler.Padding = value; } } [OnDeserialized] void OnDeserialized(StreamingContext context) { OnDeserialized(false); } /// <summary> /// Ends the initialization when loading from xaml or other code generated scenarios /// </summary> public override void EndInit() { base.EndInit(); OnDeserialized(Parent != null); // mono calls EndInit BEFORE setting to parent } /// <summary> /// Raises the <see cref="Control.PreLoad"/> event, and recurses to this container's children /// </summary> /// <param name="e">Event arguments</param> protected override void OnPreLoad(EventArgs e) { OnDeserialized(true); base.OnPreLoad(e); } /// <summary> /// Raises the <see cref="Control.Load"/> event, and recursed to this container's children /// </summary> /// <param name="e">Event arguments</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); // ensure we've been deserialized, in case something was done in load or pre-load event OnDeserialized(false); } void OnDeserialized(bool direct) { if (Loaded || direct) { if (!created) { var rows = Properties.Get<Collection<TableRow>>(rowsKey); if (rows != null) { Create(); } } } } /// <summary> /// Handler interface for <see cref="TableLayout"/> /// </summary> /// <remarks> /// Currently, TableLayout handlers only need to set its size while created and cannot be resized. /// </remarks> [AutoInitialize(false)] public new interface IHandler : Layout.IHandler, IPositionalLayoutHandler { /// <summary> /// Creates the control with the specified dimensions. /// </summary> /// <param name="columns">Number of columns for the table.</param> /// <param name="rows">Number of rows for the table.</param> void CreateControl(int columns, int rows); /// <summary> /// Gets the scale for the specified column. /// </summary> /// <returns><c>true</c>, if column is scaled, <c>false</c> otherwise.</returns> /// <param name="column">Column to retrieve the scale.</param> bool GetColumnScale(int column); /// <summary> /// Sets the scale for the specified column. /// </summary> /// <param name="column">Column to set the scale for.</param> /// <param name="scale">If set to <c>true</c> scale, otherwise size to preferred size of controls in the column.</param> void SetColumnScale(int column, bool scale); /// <summary> /// Gets the scale for the specified row. /// </summary> /// <returns><c>true</c>, if row is scaled, <c>false</c> otherwise.</returns> /// <param name="row">Row to retrieve the scale.</param> bool GetRowScale(int row); /// <summary> /// Sets the scale for the specified row. /// </summary> /// <param name="row">Row to set the scale for.</param> /// <param name="scale">If set to <c>true</c> scale, otherwise size to preferred size of controls in the row.</param> void SetRowScale(int row, bool scale); /// <summary> /// Gets or sets the horizontal and vertical spacing between each of the cells of the table. /// </summary> /// <value>The spacing between the cells.</value> Size Spacing { get; set; } /// <summary> /// Gets or sets the padding bordering the table. /// </summary> /// <value>The padding bordering the table.</value> Padding Padding { get; set; } } /// <summary> /// Implicitly converts an array of rows to a vertical TableLayout /// </summary> /// <param name="rows">Rows to convert.</param> public static implicit operator TableLayout(TableRow[] rows) { return new TableLayout(rows); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using UnityEngine; namespace HUX.Spatial { [RequireComponent(typeof(SolverHandler))] /// <summary> /// SurfaceMagnetism casts rays to Surfaces in the world align the object to the surface. /// </summary> public class SolverSurfaceMagnetism : Solver { #region public enums public enum RaycastDirectionEnum { HeadFacing, ToObject, ToLinkedPosition } public enum RaycastModeEnum { Simple, Box, Sphere } public enum OrientModeEnum { None, Vertical, Full, Blended } #endregion #region public members [Tooltip("Max distance to check for surfaces")] public float MaxDistance = 3f; [Tooltip("Closest distance to bring object")] public float CloseDistance = 0.5f; [Tooltip("Offset from surface along surface normal")] public float SurfaceNormalOffset = 0.5f; [Tooltip("Offset from surface along ray cast direction")] public float SurfaceRayOffset = 0; [Tooltip("Surface raycast mode. Simple = single raycast, Complex = bbox corners")] public RaycastModeEnum raycastMode = RaycastModeEnum.Simple; [Tooltip("Number of rays per edge, should be odd. Total casts is n^2")] public int BoxRaysPerEdge = 3; [Tooltip("If true, use orthographic casting for box lines instead of perspective")] public bool OrthoBoxCast = false; [Tooltip("Align to ray cast direction if box cast hits many normals facing in varying directions")] public float MaximumNormalVariance = 0.5f; [Tooltip("Radius to use for sphere cast")] public float SphereSize = 1f; [Tooltip("When doing volume casts, use size override if non-zero instead of object's current scale")] public float VolumeCastSizeOverride = 0; [Tooltip("When doing volume casts, use linked AltScale instead of object's current scale")] public bool UseLinkedAltScaleOverride = false; // This is broken [Tooltip("Instead of using mesh normal, extract normal from tex coord (SR is reported to put smoothed normals in there)")] bool UseTexCoordNormals = false; [Tooltip("Raycast direction. Can cast from head in facing dir, or cast from head to object position")] public RaycastDirectionEnum raycastDirection = RaycastDirectionEnum.ToLinkedPosition; [Tooltip("Orientation mode. None = no orienting, Vertical = Face head, but always oriented up/down, Full = Aligned to surface normal completely")] public OrientModeEnum orientationMode = OrientModeEnum.Vertical; [Tooltip("Orientation Blend Value 0.0 = All head 1.0 = All surface")] public float OrientBlend = 0.65f; [HideInInspector] public bool OnSurface; #endregion #region private members private Transform m_head; private BoxCollider m_BoxCollider; #endregion protected void Start() { m_head = Veil.Instance.HeadTransform; if (raycastMode == RaycastModeEnum.Box) { m_BoxCollider = GetComponent<BoxCollider>(); if (m_BoxCollider == null) { Debug.LogError("Box raycast mode requires a BoxCollider, but none was found! Defaulting to Simple raycast mode"); raycastMode = RaycastModeEnum.Simple; } if (Application.isEditor) { HUX.Utility.Raycast.DebugEnabled = true; } } if (Application.isEditor && UseTexCoordNormals) { Debug.LogWarning("Disabling tex coord normals while in editor mode"); UseTexCoordNormals = false; } } /// <summary> /// Wraps the raycast call in one spot. Should add a tunable layer parameter and implement here. /// </summary> /// <param name="origin"></param> /// <param name="direction"></param> /// <param name="distance"></param> /// <param name="result"></param> /// <returns>bool, true if a surface was hit</returns> private static bool DefaultRaycast(Vector3 origin, Vector3 direction, float distance, out HUX.Utility.RaycastResult result) { return HUX.Utility.Raycast.First(origin, direction, distance, HUX.Layers.ToMask(HUX.Layers.Surface), out result); } private static bool DefaultSpherecast(Vector3 origin, Vector3 direction, float radius, float distance, out HUX.Utility.RaycastResult result) { return HUX.Utility.Raycast.SphereFirst(origin, direction, radius, distance, HUX.Layers.ToMask(HUX.Layers.Surface), out result); } /// <summary> /// Where should rays originate from? /// </summary> /// <returns>Vector3</returns> Vector3 GetRaycastOrigin() { if(m_head == null) m_head = Veil.Instance.HeadTransform; return m_head.transform.position;//Veil.Instance.HeadPositionFiltered; } /// <summary> /// Which point should the ray cast toward? Not really the 'end' of the ray. The ray may be cast along /// the head facing direction, from the eye to the object, or to the solver's linked position (working from /// the previous solvers) /// </summary> /// <returns>Vector3, a point on the ray besides the origin</returns> Vector3 GetRaycastEndPoint() { Vector3 ret = Vector3.forward; if (raycastDirection == RaycastDirectionEnum.HeadFacing) { ret = m_head.transform.position/*Veil.Instance.HeadPositionFiltered*/ + m_head.forward; } else if (raycastDirection == RaycastDirectionEnum.ToObject) { ret = transform.position; } else if (raycastDirection == RaycastDirectionEnum.ToLinkedPosition) { ret = solverHandler.GoalPosition; } return ret; } /// <summary> /// Calculate the raycast direction based on the two ray points /// </summary> /// <returns>Vector3, the direction of the raycast</returns> Vector3 GetRaycastDirection() { Vector3 ret = Vector3.forward; if (raycastDirection == RaycastDirectionEnum.HeadFacing) { // This is a very minor optimization ret = m_head.forward; } else { ret = (GetRaycastEndPoint() - GetRaycastOrigin()).normalized; } return ret; } /// <summary> /// Calculates how the object should orient to the surface. May be none to pass shared orientation through, /// oriented to the surface but fully vertical, fully oriented to the surface normal, or a slerped blend /// of the vertial orientation and the pass-through rotation. /// </summary> /// <param name="rayDir"></param> /// <param name="surfaceNormal"></param> /// <returns>Quaternion, the orientation to use for the object</returns> Quaternion CalculateMagnetismOrientation(Vector3 rayDir, Vector3 surfaceNormal) { // Calculate the surface rotation Vector3 newDir = -surfaceNormal; if (IsNormalVertical(newDir)) newDir = rayDir; newDir.y = 0; Quaternion surfaceRot = Quaternion.LookRotation(newDir, Vector3.up); if (orientationMode == OrientModeEnum.None) { return solverHandler.GoalRotation; } else if (orientationMode == OrientModeEnum.Vertical) { return surfaceRot; } else if (orientationMode == OrientModeEnum.Full) { return Quaternion.LookRotation(-surfaceNormal, Vector3.up); } else if (orientationMode == OrientModeEnum.Blended) { return Quaternion.Slerp(solverHandler.GoalRotation, surfaceRot, OrientBlend); } return Quaternion.identity; } /// <summary> /// Checks if a normal is nearly vertical /// </summary> /// <param name="normal"></param> /// <returns>bool</returns> bool IsNormalVertical(Vector3 normal) { return 1f - Mathf.Abs(normal.y) < 0.01f; } /// <summary> /// A constant scale override may be specified for volumetric raycasts, oherwise uses the current value of the solver link's alt scale /// </summary> /// <returns>float</returns> float GetScaleOverride() { if (UseLinkedAltScaleOverride) { return solverHandler.AltScale.Current.magnitude; } return VolumeCastSizeOverride; } public override void SolverUpdate() { // Pass-through by default this.GoalPosition = WorkingPos; this.GoalRotation = WorkingRot; // Determine raycast params Ray ray = new Ray(GetRaycastOrigin(), GetRaycastDirection()); // Skip if there's no valid direction if (ray.direction == Vector3.zero) { return; } if (raycastMode == RaycastModeEnum.Simple) { // Do the cast! HUX.Utility.RaycastResult result; bool bHit = DefaultRaycast(ray.origin, ray.direction, MaxDistance, out result); OnSurface = bHit; if (UseTexCoordNormals) { result.OverrideNormalFromTextureCoord(); } // Enforce CloseDistance Vector3 hitDelta = result.Point - ray.origin; float len = hitDelta.magnitude; if (len < CloseDistance) { result.OverridePoint(ray.origin + ray.direction * CloseDistance); } // Apply results if (bHit) { this.GoalPosition = result.Point + SurfaceNormalOffset * result.Normal + SurfaceRayOffset * ray.direction; this.GoalRotation = CalculateMagnetismOrientation(ray.direction, result.Normal); } } else if (raycastMode == RaycastModeEnum.Box) { float ScaleOverride = GetScaleOverride(); Vector3 scale = transform.lossyScale; if (ScaleOverride > 0) { scale = scale.normalized * ScaleOverride; } Quaternion orientation = orientationMode == OrientModeEnum.None ? Quaternion.LookRotation(ray.direction, Vector3.up) : CalculateMagnetismOrientation(ray.direction, Vector3.up); Matrix4x4 targetMatrix = Matrix4x4.TRS(Vector3.zero, orientation, scale); if (m_BoxCollider == null) m_BoxCollider = this.GetComponent<BoxCollider>(); Vector3 extents = m_BoxCollider.size; Vector3[] positions; Vector3[] normals; bool[] hits; if (HUX.Utility.Raycast.CastBoxExtents(extents, transform.position, targetMatrix, ray, MaxDistance, DefaultRaycast, BoxRaysPerEdge, OrthoBoxCast, out positions, out normals, out hits)) { Plane plane; float distance; // place an unconstrained plane down the ray. Never use vertical constrain. FindPlacementPlane(ray.origin, ray.direction, positions, normals, hits, m_BoxCollider.size.x, MaximumNormalVariance, false, orientationMode == OrientModeEnum.None, out plane, out distance); // If placing on a horzizontal surface, need to adjust the calculated distance by half the app height float verticalCorrectionOffset = 0; if (IsNormalVertical(plane.normal) && !Mathf.Approximately(ray.direction.y, 0)) { float boxSurfaceOffsetVert = targetMatrix.MultiplyVector(new Vector3(0, extents.y / 2f, 0)).magnitude; Vector3 correctionVec = boxSurfaceOffsetVert * (ray.direction / ray.direction.y); verticalCorrectionOffset = -correctionVec.magnitude; } float boxSurfaceOffset = targetMatrix.MultiplyVector(new Vector3(0, 0, extents.z / 2f)).magnitude; // Apply boxSurfaceOffset to rayDir and not surfaceNormalDir to reduce sliding this.GoalPosition = ray.origin + ray.direction * Mathf.Max(CloseDistance, distance + SurfaceRayOffset + boxSurfaceOffset + verticalCorrectionOffset) + plane.normal * (0 * boxSurfaceOffset + SurfaceNormalOffset); this.GoalRotation = CalculateMagnetismOrientation(ray.direction, plane.normal); OnSurface = true; } else { OnSurface = false; } } else if (raycastMode == RaycastModeEnum.Sphere) { // WIP! float ScaleOverride = GetScaleOverride(); // Do the cast! HUX.Utility.RaycastResult result; float size = ScaleOverride > 0 ? ScaleOverride : transform.lossyScale.x * SphereSize; bool bHit = DefaultSpherecast(ray.origin, ray.direction, size, MaxDistance, out result); OnSurface = bHit; // Enforce CloseDistance Vector3 hitDelta = result.Point - ray.origin; float len = hitDelta.magnitude; if (len < CloseDistance) { result.OverridePoint(ray.origin + ray.direction * CloseDistance); } // Apply results if (bHit) { this.GoalPosition = result.Point + SurfaceNormalOffset * result.Normal + SurfaceRayOffset * ray.direction; this.GoalRotation = CalculateMagnetismOrientation(ray.direction, result.Normal); } } // Do frame to frame updates of transform, smoothly toward the goal, if desired //UpdateWorkingToGoal(); UpdateWorkingPosToGoal(); UpdateWorkingRotToGoal(); } /// <summary> /// Calculates a plane from all raycast hit locations upon which the object may align /// </summary> /// <param name="origin"></param> /// <param name="direction"></param> /// <param name="positions"></param> /// <param name="normals"></param> /// <param name="hits"></param> /// <param name="assetWidth"></param> /// <param name="maxNormalVariance"></param> /// <param name="constrainVertical"></param> /// <param name="bUseClosestDistance"></param> /// <param name="plane"></param> /// <param name="closestDistance"></param> private static void FindPlacementPlane(Vector3 origin, Vector3 direction, Vector3[] positions, Vector3[] normals, bool[] hits, float assetWidth, float maxNormalVariance, bool constrainVertical, bool bUseClosestDistance, out Plane plane, out float closestDistance) { bool debugEnabled = HUX.Utility.Raycast.DebugEnabled; int numRays = positions.Length; Vector3 originalDirection = direction; if (constrainVertical) { direction.y = 0.0f; direction = direction.normalized; } // go through all the points and find the closest distance int closestPoint = -1; closestDistance = float.PositiveInfinity; float farthestDistance = 0f; int numHits = 0; Vector3 averageNormal = Vector3.zero; for (int i = 0; i < numRays; i++) { if (hits[i] != false) { float dist = Vector3.Dot(direction, positions[i] - origin); if (dist < closestDistance) { closestPoint = i; closestDistance = dist; } if (dist > farthestDistance) { farthestDistance = dist; } averageNormal += normals[i]; ++numHits; } } averageNormal /= numHits; // WIP: Shoot me if I don't just grab the first surface normal I find dammit // Calculate variance of all normals float variance = 0; for (int i = 0; i < numRays; ++i) { if (hits[i] != false) { variance += (normals[i] - averageNormal).magnitude; } } variance /= numHits; // If variance is too high, I really don't want to deal with this surface // And if we don't even have enough rays, I'm not confident about this at all if (variance > maxNormalVariance || numHits < numRays / 4) { plane = new Plane(-direction, positions[closestPoint]); return; } // go through all the points and find the most orthagonal plane float lowAngle = float.PositiveInfinity; int lowIndex = -1; float highAngle = float.NegativeInfinity; int highIndex = -1; float maxDot = 0.97f; for (int i = 0; i < numRays; i++) { if (hits[i] == false || i == closestPoint) { continue; } Vector3 diff = (positions[i] - positions[closestPoint]); if (constrainVertical) { diff.y = 0.0f; diff.Normalize(); if (diff == Vector3.zero) { continue; } } else { diff.Normalize(); } float angle = Vector3.Dot(direction, diff); if (angle < lowAngle) { lowAngle = angle; lowIndex = i; } } if (!constrainVertical && lowIndex != -1) { for (int i = 0; i < numRays; i++) { if (hits[i] == false || i == closestPoint || i == lowIndex) { continue; } float dot = Mathf.Abs(Vector3.Dot((positions[i] - positions[closestPoint]).normalized, (positions[lowIndex] - positions[closestPoint]).normalized)); if (dot > maxDot) { continue; } Vector3 normal = Vector3.Cross(positions[lowIndex] - positions[closestPoint], positions[i] - positions[closestPoint]).normalized; float nextAngle = Mathf.Abs(Vector3.Dot(direction, normal)); if (nextAngle > highAngle) { highAngle = nextAngle; highIndex = i; } } } Vector3 placementNormal; if (lowIndex != -1) { if (debugEnabled) { Debug.DrawLine(positions[closestPoint], positions[lowIndex], Color.red); } if (highIndex != -1) { if (debugEnabled) { Debug.DrawLine(positions[closestPoint], positions[highIndex], Color.green); } placementNormal = Vector3.Cross(positions[lowIndex] - positions[closestPoint], positions[highIndex] - positions[closestPoint]).normalized; } else { Vector3 planeUp = Vector3.Cross(positions[lowIndex] - positions[closestPoint], direction); placementNormal = Vector3.Cross(positions[lowIndex] - positions[closestPoint], constrainVertical ? Vector3.up : planeUp).normalized; } if (debugEnabled) { Debug.DrawLine(positions[closestPoint], positions[closestPoint] + placementNormal, Color.blue); } } else { placementNormal = direction * -1.0f; } if (Vector3.Dot(placementNormal, direction) > 0.0f) { placementNormal *= -1.0f; } plane = new Plane(placementNormal, positions[closestPoint]); if (debugEnabled) { Debug.DrawRay(positions[closestPoint], placementNormal, Color.cyan); } // Figure out how far the plane should be. if (!bUseClosestDistance && closestPoint >= 0) { float centerPlaneDistance; Ray centerPlaneRay = new Ray(origin, originalDirection); if (plane.Raycast(centerPlaneRay, out centerPlaneDistance) || centerPlaneDistance != 0) { // When the plane is nearly parallel to the user, we need to clamp the distance to where the raycasts hit. closestDistance = Mathf.Clamp(centerPlaneDistance, closestDistance, farthestDistance + assetWidth * 0.5f); } else { Debug.LogError("FindPlacementPlane: Not expected to have the center point not intersect the plane."); } } } } }
using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; using System.Collections.Generic; using System.Linq; namespace SWTableViewCell { public enum SWCellState { Center, Left, Right } public class ScrollingEventArgs:EventArgs { public SWCellState CellState{ get; set; } public NSIndexPath IndexPath { get; set; } } public class CellUtilityButtonClickedEventArgs:EventArgs { public int UtilityButtonIndex { get; set; } public NSIndexPath IndexPath { get; set; } } public partial class SWTableViewCell : UITableViewCell { public const float UtilityButtonsWidthMax = 260; public const float UtilityButtonWidthDefault = 90; public const float SectionIndexWidth = 15; UITableView containingTableView; UIButton[] rightUtilityButtons; UIView scrollViewLeft; SWCellState cellState; // The state of the cell within the scroll view, can be left, right or middle float additionalRightPadding; // Scroll view to be added to UITableViewCell UIScrollView cellScrollView; // The cell's height float height; // Views that live in the scroll view UIView scrollViewContentView; SWUtilityButtonView scrollViewButtonViewRight; UIScrollViewDelegate scrollViewDelegate; float ScrollLeftViewWidth { get{return this.scrollViewLeft.Frame.Width;} } float RightUtilityButtonsWidth { get{return this.scrollViewButtonViewRight.UtilityButtonsWidth + additionalRightPadding;} } float UtilityButtonsPadding { get{return ScrollLeftViewWidth + RightUtilityButtonsWidth;} } PointF ScrollViewContentOffset { get{return new PointF(ScrollLeftViewWidth, 0);} } public SWTableViewCell (UITableViewCellStyle style, string reuseIdentifier, UITableView containingTable, IEnumerable<UIButton> rightUtilityButtons, UIView leftView):base(style, reuseIdentifier) { this.scrollViewLeft = leftView; this.rightUtilityButtons = rightUtilityButtons.ToArray(); this.scrollViewButtonViewRight = new SWUtilityButtonView (this.rightUtilityButtons, this); this.containingTableView = containingTable; this.height = containingTableView.RowHeight; this.scrollViewDelegate = new SWScrollViewDelegate (this); // Check if the UITableView will display Indices on the right. If that's the case, add a padding if(containingTableView.RespondsToSelector(new MonoTouch.ObjCRuntime.Selector("sectionIndexTitlesForTableView:"))) { var indices = containingTableView.Source.SectionIndexTitles (containingTableView); additionalRightPadding = indices == null || indices.Length == 0 ? 0 : SectionIndexWidth; } // Set up scroll view that will host our cell content this.cellScrollView = new UIScrollView (new RectangleF (0, 0, Bounds.Width, height)); //TODO:frames this.cellScrollView.ContentSize = new SizeF (Bounds.Width + this.UtilityButtonsPadding, height);//TODO:frames this.cellScrollView.ContentOffset = ScrollViewContentOffset; this.cellScrollView.Delegate = this.scrollViewDelegate; this.cellScrollView.ShowsHorizontalScrollIndicator = false; this.cellScrollView.ScrollsToTop = false; UITapGestureRecognizer tapGestureRecognizer = new UITapGestureRecognizer(OnScrollViewPressed); this.cellScrollView.AddGestureRecognizer (tapGestureRecognizer); // Set up the views that will hold the utility buttons this.scrollViewLeft.Frame = new RectangleF (ScrollLeftViewWidth, 0, ScrollLeftViewWidth, height);//TODO:frame this.cellScrollView.AddSubview (scrollViewLeft); this.scrollViewButtonViewRight.Frame = new RectangleF (Bounds.Width, 0, RightUtilityButtonsWidth, height); //TODO:frame this.cellScrollView.AddSubview (scrollViewButtonViewRight); // Populate the button views with utility buttons this.scrollViewButtonViewRight.PopulateUtilityButtons (); // Create the content view that will live in our scroll view this.scrollViewContentView = new UIView(new RectangleF(ScrollLeftViewWidth, 0, Bounds.Width, height)); this.scrollViewContentView.BackgroundColor = UIColor.White; this.cellScrollView.AddSubview (this.scrollViewContentView); UIView contentViewParent; //deals with an internal change introduced in iOS 8 if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)){ contentViewParent = this; } else { // Add the cell scroll view to the cell contentViewParent = Subviews[0]; } foreach (var subView in contentViewParent.Subviews) { this.scrollViewContentView.AddSubview (subView); } AddSubview (this.cellScrollView); HideSwipedContent (false); } public SWCellState State { get{ return cellState; } } void OnScrollViewPressed(UITapGestureRecognizer tap) { if (cellState == SWCellState.Center) { if (containingTableView.Source != null) { var indexPath = this.containingTableView.IndexPathForCell (this); this.containingTableView.Source.RowSelected (containingTableView, indexPath); } } else { // Scroll back to center this.HideSwipedContent (true); } } public void HideSwipedContent(bool animated) { cellScrollView.SetContentOffset (new PointF (ScrollLeftViewWidth, 0), animated); cellState = SWCellState.Center; OnScrolling (); } public override UIColor BackgroundColor { get { return base.BackgroundColor; } set { base.BackgroundColor = value; this.scrollViewContentView.BackgroundColor = value; } } protected internal void OnLeftUtilityButtonPressed(UIButton sender) { int tag = sender.Tag; var handler = this.UtilityButtonPressed; if (handler != null) { var indexPath = this.containingTableView.IndexPathForCell (this); handler(sender, new CellUtilityButtonClickedEventArgs{IndexPath = indexPath, UtilityButtonIndex = tag}); } } void OnScrolling() { var handler = Scrolling; if (handler != null) { var indexPath = this.containingTableView.IndexPathForCell (this); handler (this, new ScrollingEventArgs { CellState = cellState, IndexPath = indexPath }); } } public event EventHandler<ScrollingEventArgs> Scrolling; public event EventHandler<CellUtilityButtonClickedEventArgs> UtilityButtonPressed; public override void LayoutSubviews () { base.LayoutSubviews (); this.cellScrollView.Frame = new RectangleF (0, 0, Bounds.Width, height); this.cellScrollView.ContentSize = new SizeF (Bounds.Width + UtilityButtonsPadding, height); this.cellScrollView.ContentOffset = new PointF (ScrollLeftViewWidth, 0); this.scrollViewLeft.Frame = new RectangleF (ScrollLeftViewWidth , 0, ScrollLeftViewWidth , height); this.scrollViewButtonViewRight.Frame = new RectangleF (Bounds.Width, 0, RightUtilityButtonsWidth , height); this.scrollViewContentView.Frame = new RectangleF (ScrollLeftViewWidth , 0, Bounds.Width, height); } class SWScrollViewDelegate:UIScrollViewDelegate { SWTableViewCell cell; public SWScrollViewDelegate (SWTableViewCell cell) { this.cell = cell; } public override void WillEndDragging (UIScrollView scrollView, PointF velocity, ref PointF targetContentOffset) { switch (cell.cellState) { case SWCellState.Center: if (velocity.X >= 0.5f) { this.ScrollToRight(ref targetContentOffset); } else if (velocity.X <= -0.5f) { this.ScrollToLeft(ref targetContentOffset); } else { float rightThreshold = cell.UtilityButtonsPadding - (cell.UtilityButtonsPadding / 2); float leftThreshold = cell.ScrollLeftViewWidth / 2; if (targetContentOffset.X > rightThreshold) this.ScrollToRight(ref targetContentOffset); else if (targetContentOffset.X < leftThreshold) this.ScrollToLeft(ref targetContentOffset); else this.ScrollToCenter(ref targetContentOffset); } break; case SWCellState.Left: if (velocity.X >= 0.5f) { this.ScrollToCenter(ref targetContentOffset); } else if (velocity.X <= -0.5f) { // No-op } else { if (targetContentOffset.X >= (cell.UtilityButtonsPadding - cell.RightUtilityButtonsWidth / 2)) this.ScrollToRight(ref targetContentOffset); else if (targetContentOffset.X > cell.ScrollLeftViewWidth / 2) this.ScrollToCenter(ref targetContentOffset); else this.ScrollToLeft(ref targetContentOffset); } break; case SWCellState.Right: if (velocity.X >= 0.5f) { // No-op } else if (velocity.X <= -0.5f) { this.ScrollToCenter(ref targetContentOffset); } else { if (targetContentOffset.X <= this.cell.ScrollLeftViewWidth / 2) this.ScrollToLeft(ref targetContentOffset); else if (targetContentOffset.X < (cell.UtilityButtonsPadding- (cell.RightUtilityButtonsWidth / 2))) this.ScrollToCenter(ref targetContentOffset); else this.ScrollToRight(ref targetContentOffset); } break; default: break; } } void ScrollToCenter (ref PointF targetContentOffset) { targetContentOffset.X = cell.ScrollLeftViewWidth; cell.cellState = SWCellState.Center; cell.OnScrolling (); } void ScrollToLeft (ref PointF targetContentOffset) { targetContentOffset.X = 0; cell.cellState = SWCellState.Left; cell.OnScrolling (); } void ScrollToRight (ref PointF targetContentOffset) { targetContentOffset.X = cell.UtilityButtonsPadding; cell.cellState = SWCellState.Right; cell.OnScrolling (); } public override void Scrolled (UIScrollView scrollView) { if (scrollView.ContentOffset.X > this.cell.ScrollLeftViewWidth) { //expose the right view this.cell.scrollViewButtonViewRight.Frame = new RectangleF (scrollView.ContentOffset.X + cell.Bounds.Width - cell.RightUtilityButtonsWidth, 0, cell.RightUtilityButtonsWidth, cell.height); } else { this.cell.scrollViewLeft.Frame = new RectangleF (scrollView.ContentOffset.X, 0, cell.ScrollLeftViewWidth, cell.height); } } } } class SWUtilityButtonView:UIView { SWTableViewCell parentCell; UIButton[] utilityButtons; float utilityButtonWidth; public SWUtilityButtonView (UIButton[] buttons, SWTableViewCell parentCell) { this.utilityButtons = buttons; this.parentCell = parentCell; this.utilityButtonWidth = this.CalculateUtilityButtonWidth (); this.AddSubviews (buttons); } public float UtilityButtonsWidth { get { return utilityButtonWidth * utilityButtons.Length; } } float CalculateUtilityButtonWidth () { float buttonWidth = SWTableViewCell.UtilityButtonWidthDefault; if (buttonWidth * utilityButtons.Length > SWTableViewCell.UtilityButtonsWidthMax) { float buffer = buttonWidth * utilityButtons.Length - SWTableViewCell.UtilityButtonsWidthMax; buttonWidth -= buffer / utilityButtons.Length; } return buttonWidth; } public void PopulateUtilityButtons () { for (int i = 0; i < utilityButtons.Length; i++) { var button = utilityButtons[i]; float x = 0; if (i >= 1) x = utilityButtonWidth * i; button.Frame = new RectangleF (x, 0, utilityButtonWidth, Bounds.Height);//TODO: frame button.Tag = i; button.TouchDown += (object sender, EventArgs e) => this.parentCell.OnLeftUtilityButtonPressed((UIButton)sender); } } } public static class SWButtonCellExtensions { public static void AddUtilityButton(this List<UIButton> list, string title, UIColor color) { var button = new UIButton (UIButtonType.Custom); button.BackgroundColor = color; button.SetTitle (title, UIControlState.Normal); button.SetTitleColor (UIColor.White, UIControlState.Normal); list.Add (button); } } }
using System; using System.Diagnostics; using Org.BouncyCastle.Bcpg; using Org.BouncyCastle.Utilities; using Random = Org.BouncyCastle.Bcpg.Random; namespace Org.BouncyCastle.Math.EC { public class FPFieldElement : ECFieldElement { private readonly IBigInteger _q, _x; /// <summary> /// Initializes a new instance of the <see cref="FPFieldElement"/> class. /// </summary> /// <param name="q">The q.</param> /// <param name="x">The x.</param> /// <exception cref="System.ArgumentException">x value too large in field element</exception> public FPFieldElement(IBigInteger q, IBigInteger x) { if (x.CompareTo(q) >= 0) throw new ArgumentException("x value too large in field element"); _q = q; _x = x; } public override IBigInteger ToBigInteger() { return _x; } /// <summary> /// Gets the name of the field. /// </summary> /// <value> /// The name of the field. /// </value> public override string FieldName { get { return "Fp"; } } /// <summary> /// Gets the size of the field. /// </summary> /// <value> /// The size of the field. /// </value> public override int FieldSize { get { return _q.BitLength; } } /// <summary> /// Gets the Q. /// </summary> /// <value> /// The Q. /// </value> public IBigInteger Q { get { return _q; } } public override ECFieldElement Add(ECFieldElement b) { return new FPFieldElement(_q, _x.Add(b.ToBigInteger()).Mod(_q)); } public override ECFieldElement Subtract(ECFieldElement b) { return new FPFieldElement(_q, _x.Subtract(b.ToBigInteger()).Mod(_q)); } public override ECFieldElement Multiply(ECFieldElement b) { return new FPFieldElement(_q, _x.Multiply(b.ToBigInteger()).Mod(_q)); } public override ECFieldElement Divide(ECFieldElement b) { return new FPFieldElement(_q, _x.Multiply(b.ToBigInteger().ModInverse(_q)).Mod(_q)); } public override ECFieldElement Negate() { return new FPFieldElement(_q, _x.Negate().Mod(_q)); } public override ECFieldElement Square() { return new FPFieldElement(_q, _x.Multiply(_x).Mod(_q)); } public override ECFieldElement Invert() { return new FPFieldElement(_q, _x.ModInverse(_q)); } /// <summary> /// D.1.4 91 /// return a sqrt root - the routine verifies that the calculation /// returns the right value - if none exists it returns null. /// </summary> /// <returns></returns> public override ECFieldElement Sqrt() { if (!_q.TestBit(0)) throw Platform.CreateNotImplementedException("even value of q"); // p mod 4 == 3 if (_q.TestBit(1)) { // TODO Can this be optimised (inline the Square?) // z = g^(u+1) + p, p = 4u + 3 var z = new FPFieldElement(_q, _x.ModPow(_q.ShiftRight(2).Add(BigInteger.One), _q)); return z.Square().Equals(this) ? z : null; } // p mod 4 == 1 var qMinusOne = _q.Subtract(BigInteger.One); var legendreExponent = qMinusOne.ShiftRight(1); if (!(_x.ModPow(legendreExponent, _q).Equals(BigInteger.One))) return null; var u = qMinusOne.ShiftRight(2); var k = u.ShiftLeft(1).Add(BigInteger.One); var Q = _x; var fourQ = Q.ShiftLeft(2).Mod(_q); IBigInteger U; IBigInteger V; do { IRandom rand = new Random(); IBigInteger P; do { P = new BigInteger(_q.BitLength, rand); } while (P.CompareTo(_q) >= 0 || !(P.Multiply(P).Subtract(fourQ).ModPow(legendreExponent, _q).Equals(qMinusOne))); var result = FastLucasSequence(_q, P, Q, k); U = result[0]; V = result[1]; if (!V.Multiply(V).Mod(_q).Equals(fourQ)) continue; // Integer division by 2, mod q if (V.TestBit(0)) { V = V.Add(_q); } V = V.ShiftRight(1); Debug.Assert(V.Multiply(V).Mod(_q).Equals(_x)); return new FPFieldElement(_q, V); } while (U.Equals(BigInteger.One) || U.Equals(qMinusOne)); return null; } private static IBigInteger[] FastLucasSequence(IBigInteger p, IBigInteger P, IBigInteger Q, IBigInteger k) { // TODO Research and apply "common-multiplicand multiplication here" var n = k.BitLength; var s = k.GetLowestSetBit(); Debug.Assert(k.TestBit(s)); var uh = BigInteger.One; var vl = BigInteger.Two; var vh = P; var ql = BigInteger.One; var qh = BigInteger.One; for (var j = n - 1; j >= s + 1; --j) { ql = ql.Multiply(qh).Mod(p); if (k.TestBit(j)) { qh = ql.Multiply(Q).Mod(p); uh = uh.Multiply(vh).Mod(p); vl = vh.Multiply(vl).Subtract(P.Multiply(ql)).Mod(p); vh = vh.Multiply(vh).Subtract(qh.ShiftLeft(1)).Mod(p); } else { qh = ql; uh = uh.Multiply(vl).Subtract(ql).Mod(p); vh = vh.Multiply(vl).Subtract(P.Multiply(ql)).Mod(p); vl = vl.Multiply(vl).Subtract(ql.ShiftLeft(1)).Mod(p); } } ql = ql.Multiply(qh).Mod(p); qh = ql.Multiply(Q).Mod(p); uh = uh.Multiply(vl).Subtract(ql).Mod(p); vl = vh.Multiply(vl).Subtract(P.Multiply(ql)).Mod(p); ql = ql.Multiply(qh).Mod(p); for (var j = 1; j <= s; ++j) { uh = uh.Multiply(vl).Mod(p); vl = vl.Multiply(vl).Subtract(ql.ShiftLeft(1)).Mod(p); ql = ql.Multiply(ql).Mod(p); } return new[] { uh, vl }; } // private static BigInteger[] verifyLucasSequence( // BigInteger p, // BigInteger P, // BigInteger Q, // BigInteger k) // { // BigInteger[] actual = fastLucasSequence(p, P, Q, k); // BigInteger[] plus1 = fastLucasSequence(p, P, Q, k.Add(BigInteger.One)); // BigInteger[] plus2 = fastLucasSequence(p, P, Q, k.Add(BigInteger.Two)); // // BigInteger[] check = stepLucasSequence(p, P, Q, actual, plus1); // // Debug.Assert(check[0].Equals(plus2[0])); // Debug.Assert(check[1].Equals(plus2[1])); // // return actual; // } // // private static BigInteger[] stepLucasSequence( // BigInteger p, // BigInteger P, // BigInteger Q, // BigInteger[] backTwo, // BigInteger[] backOne) // { // return new BigInteger[] // { // P.Multiply(backOne[0]).Subtract(Q.Multiply(backTwo[0])).Mod(p), // P.Multiply(backOne[1]).Subtract(Q.Multiply(backTwo[1])).Mod(p) // }; // } public override bool Equals(object obj) { if (obj == this) return true; var other = obj as FPFieldElement; return other != null && Equals(other); } protected bool Equals(FPFieldElement other) { return _q.Equals(other._q) && base.Equals(other); } public override int GetHashCode() { return _q.GetHashCode() ^ base.GetHashCode(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Threading.Tasks; using System.Xml; namespace System.ServiceModel.Channels { public abstract class Message : IDisposable { private MessageState _state; internal const int InitialBufferSize = 1024; public abstract MessageHeaders Headers { get; } // must never return null protected bool IsDisposed { get { return _state == MessageState.Closed; } } public virtual bool IsFault { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return false; } } public virtual bool IsEmpty { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return false; } } public abstract MessageProperties Properties { get; } public abstract MessageVersion Version { get; } // must never return null internal virtual RecycledMessageState RecycledMessageState { get { return null; } } public MessageState State { get { return _state; } } internal void BodyToString(XmlDictionaryWriter writer) { OnBodyToString(writer); } public void Close() { if (_state != MessageState.Closed) { _state = MessageState.Closed; OnClose(); } else { } } public MessageBuffer CreateBufferedCopy(int maxBufferSize) { if (maxBufferSize < 0) throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxBufferSize", maxBufferSize, SR.ValueMustBeNonNegative), this); switch (_state) { case MessageState.Created: _state = MessageState.Copied; break; case MessageState.Closed: throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); case MessageState.Copied: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenCopied), this); case MessageState.Read: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenRead), this); case MessageState.Written: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenWritten), this); default: Fx.Assert(SR.InvalidMessageState); throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.InvalidMessageState), this); } return OnCreateBufferedCopy(maxBufferSize); } private static Type GetObjectType(object value) { return (value == null) ? typeof(object) : value.GetType(); } static public Message CreateMessage(MessageVersion version, string action, object body) { return CreateMessage(version, action, body, DataContractSerializerDefaults.CreateSerializer(GetObjectType(body), int.MaxValue/*maxItems*/)); } static public Message CreateMessage(MessageVersion version, string action, object body, XmlObjectSerializer serializer) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); return new BodyWriterMessage(version, action, new XmlObjectSerializerBodyWriter(body, serializer)); } static public Message CreateMessage(MessageVersion version, string action, XmlReader body) { return CreateMessage(version, action, XmlDictionaryReader.CreateDictionaryReader(body)); } static public Message CreateMessage(MessageVersion version, string action, XmlDictionaryReader body) { if (body == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("body"); if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version"); return CreateMessage(version, action, new XmlReaderBodyWriter(body, version.Envelope)); } static public Message CreateMessage(MessageVersion version, string action, BodyWriter body) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (body == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("body")); return new BodyWriterMessage(version, action, body); } static internal Message CreateMessage(MessageVersion version, ActionHeader actionHeader, BodyWriter body) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (body == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("body")); return new BodyWriterMessage(version, actionHeader, body); } static public Message CreateMessage(MessageVersion version, string action) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); return new BodyWriterMessage(version, action, EmptyBodyWriter.Value); } static internal Message CreateMessage(MessageVersion version, ActionHeader actionHeader) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); return new BodyWriterMessage(version, actionHeader, EmptyBodyWriter.Value); } static public Message CreateMessage(XmlReader envelopeReader, int maxSizeOfHeaders, MessageVersion version) { return CreateMessage(XmlDictionaryReader.CreateDictionaryReader(envelopeReader), maxSizeOfHeaders, version); } static public Message CreateMessage(XmlDictionaryReader envelopeReader, int maxSizeOfHeaders, MessageVersion version) { if (envelopeReader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("envelopeReader")); if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); Message message = new StreamedMessage(envelopeReader, maxSizeOfHeaders, version); return message; } static public Message CreateMessage(MessageVersion version, FaultCode faultCode, string reason, string action) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (faultCode == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faultCode")); if (reason == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reason")); return CreateMessage(version, MessageFault.CreateFault(faultCode, reason), action); } static public Message CreateMessage(MessageVersion version, FaultCode faultCode, string reason, object detail, string action) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (faultCode == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faultCode")); if (reason == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reason")); return CreateMessage(version, MessageFault.CreateFault(faultCode, new FaultReason(reason), detail), action); } static public Message CreateMessage(MessageVersion version, MessageFault fault, string action) { if (fault == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("fault")); if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); return new BodyWriterMessage(version, action, new FaultBodyWriter(fault, version.Envelope)); } internal Exception CreateMessageDisposedException() { return new ObjectDisposedException("", SR.MessageClosed); } void IDisposable.Dispose() { Close(); } public T GetBody<T>() { XmlDictionaryReader reader = GetReaderAtBodyContents(); // This call will change the message state to Read. return OnGetBody<T>(reader); } protected virtual T OnGetBody<T>(XmlDictionaryReader reader) { return this.GetBodyCore<T>(reader, DataContractSerializerDefaults.CreateSerializer(typeof(T), int.MaxValue/*maxItems*/)); } public T GetBody<T>(XmlObjectSerializer serializer) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); return this.GetBodyCore<T>(GetReaderAtBodyContents(), serializer); } private T GetBodyCore<T>(XmlDictionaryReader reader, XmlObjectSerializer serializer) { T value; using (reader) { value = (T)serializer.ReadObject(reader); this.ReadFromBodyContentsToEnd(reader); } return value; } internal virtual XmlDictionaryReader GetReaderAtHeader() { XmlBuffer buffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); WriteStartEnvelope(writer); MessageHeaders headers = this.Headers; for (int i = 0; i < headers.Count; i++) headers.WriteHeader(i, writer); writer.WriteEndElement(); writer.WriteEndElement(); buffer.CloseSection(); buffer.Close(); XmlDictionaryReader reader = buffer.GetReader(0); reader.ReadStartElement(); reader.MoveToStartElement(); return reader; } public XmlDictionaryReader GetReaderAtBodyContents() { EnsureReadMessageState(); if (IsEmpty) throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageIsEmpty), this); return OnGetReaderAtBodyContents(); } internal void EnsureReadMessageState() { switch (_state) { case MessageState.Created: _state = MessageState.Read; break; case MessageState.Copied: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenCopied), this); case MessageState.Read: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenRead), this); case MessageState.Written: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenWritten), this); case MessageState.Closed: throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); default: Fx.Assert(SR.InvalidMessageState); throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.InvalidMessageState), this); } } internal void InitializeReply(Message request) { UniqueId requestMessageID = request.Headers.MessageId; if (requestMessageID == null) throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.RequestMessageDoesNotHaveAMessageID), request); Headers.RelatesTo = requestMessageID; } static internal bool IsFaultStartElement(XmlDictionaryReader reader, EnvelopeVersion version) { return reader.IsStartElement(XD.MessageDictionary.Fault, version.DictionaryNamespace); } protected virtual void OnBodyToString(XmlDictionaryWriter writer) { writer.WriteString(SR.MessageBodyIsUnknown); } protected virtual MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { return OnCreateBufferedCopy(maxBufferSize, XmlDictionaryReaderQuotas.Max); } internal MessageBuffer OnCreateBufferedCopy(int maxBufferSize, XmlDictionaryReaderQuotas quotas) { XmlBuffer msgBuffer = new XmlBuffer(maxBufferSize); XmlDictionaryWriter writer = msgBuffer.OpenSection(quotas); OnWriteMessage(writer); msgBuffer.CloseSection(); msgBuffer.Close(); return new DefaultMessageBuffer(this, msgBuffer); } protected virtual void OnClose() { } protected virtual XmlDictionaryReader OnGetReaderAtBodyContents() { XmlBuffer bodyBuffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = bodyBuffer.OpenSection(XmlDictionaryReaderQuotas.Max); if (this.Version.Envelope != EnvelopeVersion.None) { OnWriteStartEnvelope(writer); OnWriteStartBody(writer); } OnWriteBodyContents(writer); if (this.Version.Envelope != EnvelopeVersion.None) { writer.WriteEndElement(); writer.WriteEndElement(); } bodyBuffer.CloseSection(); bodyBuffer.Close(); XmlDictionaryReader reader = bodyBuffer.GetReader(0); if (this.Version.Envelope != EnvelopeVersion.None) { reader.ReadStartElement(); reader.ReadStartElement(); } reader.MoveToContent(); return reader; } protected virtual void OnWriteStartBody(XmlDictionaryWriter writer) { MessageDictionary messageDictionary = XD.MessageDictionary; writer.WriteStartElement(messageDictionary.Prefix.Value, messageDictionary.Body, Version.Envelope.DictionaryNamespace); } public void WriteBodyContents(XmlDictionaryWriter writer) { EnsureWriteMessageState(writer); OnWriteBodyContents(writer); } public Task WriteBodyContentsAsync(XmlDictionaryWriter writer) { this.WriteBodyContents(writer); return TaskHelpers.CompletedTask(); } public IAsyncResult BeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { EnsureWriteMessageState(writer); return this.OnBeginWriteBodyContents(writer, callback, state); } public void EndWriteBodyContents(IAsyncResult result) { this.OnEndWriteBodyContents(result); } protected abstract void OnWriteBodyContents(XmlDictionaryWriter writer); protected virtual Task OnWriteBodyContentsAsync(XmlDictionaryWriter writer) { this.OnWriteBodyContents(writer); return TaskHelpers.CompletedTask(); } protected virtual IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return OnWriteBodyContentsAsync(writer).ToApm(callback, state); } protected virtual void OnEndWriteBodyContents(IAsyncResult result) { result.ToApmEnd(); } public void WriteStartEnvelope(XmlDictionaryWriter writer) { if (writer == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("writer"), this); OnWriteStartEnvelope(writer); } protected virtual void OnWriteStartEnvelope(XmlDictionaryWriter writer) { EnvelopeVersion envelopeVersion = Version.Envelope; if (envelopeVersion != EnvelopeVersion.None) { MessageDictionary messageDictionary = XD.MessageDictionary; writer.WriteStartElement(messageDictionary.Prefix.Value, messageDictionary.Envelope, envelopeVersion.DictionaryNamespace); WriteSharedHeaderPrefixes(writer); } } protected virtual void OnWriteStartHeaders(XmlDictionaryWriter writer) { EnvelopeVersion envelopeVersion = Version.Envelope; if (envelopeVersion != EnvelopeVersion.None) { MessageDictionary messageDictionary = XD.MessageDictionary; writer.WriteStartElement(messageDictionary.Prefix.Value, messageDictionary.Header, envelopeVersion.DictionaryNamespace); } } public override string ToString() { if (IsDisposed) { return base.ToString(); } XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { using (XmlWriter textWriter = XmlWriter.Create(stringWriter, settings)) { using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(textWriter)) { try { ToString(writer); writer.Flush(); return stringWriter.ToString(); } catch (XmlException e) { return SR.Format(SR.MessageBodyToStringError, e.GetType().ToString(), e.Message); } } } } } internal void ToString(XmlDictionaryWriter writer) { if (IsDisposed) { throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); } if (this.Version.Envelope != EnvelopeVersion.None) { WriteStartEnvelope(writer); WriteStartHeaders(writer); MessageHeaders headers = this.Headers; for (int i = 0; i < headers.Count; i++) { headers.WriteHeader(i, writer); } writer.WriteEndElement(); MessageDictionary messageDictionary = XD.MessageDictionary; WriteStartBody(writer); } BodyToString(writer); if (this.Version.Envelope != EnvelopeVersion.None) { writer.WriteEndElement(); writer.WriteEndElement(); } } public string GetBodyAttribute(string localName, string ns) { if (localName == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("localName"), this); if (ns == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("ns"), this); switch (_state) { case MessageState.Created: break; case MessageState.Copied: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenCopied), this); case MessageState.Read: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenRead), this); case MessageState.Written: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenWritten), this); case MessageState.Closed: throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); default: Fx.Assert(SR.InvalidMessageState); throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.InvalidMessageState), this); } return OnGetBodyAttribute(localName, ns); } protected virtual string OnGetBodyAttribute(string localName, string ns) { return null; } internal void ReadFromBodyContentsToEnd(XmlDictionaryReader reader) { Message.ReadFromBodyContentsToEnd(reader, this.Version.Envelope); } private static void ReadFromBodyContentsToEnd(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion) { if (envelopeVersion != EnvelopeVersion.None) { reader.ReadEndElement(); // </Body> reader.ReadEndElement(); // </Envelope> } reader.MoveToContent(); } internal static bool ReadStartBody(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion, out bool isFault, out bool isEmpty) { if (reader.IsEmptyElement) { reader.Read(); isEmpty = true; isFault = false; reader.ReadEndElement(); return false; } else { reader.Read(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); if (reader.NodeType == XmlNodeType.Element) { isFault = IsFaultStartElement(reader, envelopeVersion); isEmpty = false; } else if (reader.NodeType == XmlNodeType.EndElement) { isEmpty = true; isFault = false; Message.ReadFromBodyContentsToEnd(reader, envelopeVersion); return false; } else { isEmpty = false; isFault = false; } return true; } } public void WriteBody(XmlWriter writer) { WriteBody(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteBody(XmlDictionaryWriter writer) { WriteStartBody(writer); WriteBodyContents(writer); writer.WriteEndElement(); } public void WriteStartBody(XmlWriter writer) { WriteStartBody(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteStartBody(XmlDictionaryWriter writer) { if (writer == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("writer"), this); OnWriteStartBody(writer); } internal void WriteStartHeaders(XmlDictionaryWriter writer) { OnWriteStartHeaders(writer); } public void WriteMessage(XmlWriter writer) { WriteMessage(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteMessage(XmlDictionaryWriter writer) { EnsureWriteMessageState(writer); OnWriteMessage(writer); } public virtual Task WriteMessageAsync(XmlWriter writer) { this.WriteMessage(writer); return TaskHelpers.CompletedTask(); } public virtual async Task WriteMessageAsync(XmlDictionaryWriter writer) { EnsureWriteMessageState(writer); await this.OnWriteMessageAsync(writer); } public virtual async Task OnWriteMessageAsync(XmlDictionaryWriter writer) { this.WriteMessagePreamble(writer); // We should call OnWriteBodyContentsAsync instead of WriteBodyContentsAsync here, // otherwise EnsureWriteMessageState would get called twice. Also see OnWriteMessage() // for the example. await this.OnWriteBodyContentsAsync(writer); this.WriteMessagePostamble(writer); } private void EnsureWriteMessageState(XmlDictionaryWriter writer) { if (writer == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("writer"), this); switch (_state) { case MessageState.Created: _state = MessageState.Written; break; case MessageState.Copied: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenCopied), this); case MessageState.Read: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenRead), this); case MessageState.Written: throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.MessageHasBeenWritten), this); case MessageState.Closed: throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); default: Fx.Assert(SR.InvalidMessageState); throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.InvalidMessageState), this); } } // WriteMessageAsync public IAsyncResult BeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state) { EnsureWriteMessageState(writer); return OnBeginWriteMessage(writer, callback, state); } public void EndWriteMessage(IAsyncResult result) { OnEndWriteMessage(result); } // OnWriteMessageAsync protected virtual void OnWriteMessage(XmlDictionaryWriter writer) { WriteMessagePreamble(writer); OnWriteBodyContents(writer); WriteMessagePostamble(writer); } internal void WriteMessagePreamble(XmlDictionaryWriter writer) { if (this.Version.Envelope != EnvelopeVersion.None) { OnWriteStartEnvelope(writer); MessageHeaders headers = this.Headers; int headersCount = headers.Count; if (headersCount > 0) { OnWriteStartHeaders(writer); for (int i = 0; i < headersCount; i++) { headers.WriteHeader(i, writer); } writer.WriteEndElement(); } OnWriteStartBody(writer); } } internal void WriteMessagePostamble(XmlDictionaryWriter writer) { if (this.Version.Envelope != EnvelopeVersion.None) { writer.WriteEndElement(); writer.WriteEndElement(); } } protected virtual IAsyncResult OnBeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return new OnWriteMessageAsyncResult(writer, this, callback, state); } protected virtual void OnEndWriteMessage(IAsyncResult result) { OnWriteMessageAsyncResult.End(result); } private void WriteSharedHeaderPrefixes(XmlDictionaryWriter writer) { MessageHeaders headers = Headers; int count = headers.Count; int prefixesWritten = 0; for (int i = 0; i < count; i++) { if (this.Version.Addressing == AddressingVersion.None && headers[i].Namespace == AddressingVersion.None.Namespace) { continue; } IMessageHeaderWithSharedNamespace headerWithSharedNamespace = headers[i] as IMessageHeaderWithSharedNamespace; if (headerWithSharedNamespace != null) { XmlDictionaryString prefix = headerWithSharedNamespace.SharedPrefix; string prefixString = prefix.Value; if (!((prefixString.Length == 1))) { Fx.Assert("Message.WriteSharedHeaderPrefixes: (prefixString.Length == 1) -- IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix."); throw TraceUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix.")), this); } int prefixIndex = prefixString[0] - 'a'; if (!((prefixIndex >= 0 && prefixIndex < 26))) { Fx.Assert("Message.WriteSharedHeaderPrefixes: (prefixIndex >= 0 && prefixIndex < 26) -- IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix."); throw TraceUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "IMessageHeaderWithSharedNamespace must use a single lowercase letter prefix.")), this); } int prefixBit = 1 << prefixIndex; if ((prefixesWritten & prefixBit) == 0) { writer.WriteXmlnsAttribute(prefixString, headerWithSharedNamespace.SharedNamespace); prefixesWritten |= prefixBit; } } } } private class OnWriteMessageAsyncResult : ScheduleActionItemAsyncResult { private Message _message; private XmlDictionaryWriter _writer; public OnWriteMessageAsyncResult(XmlDictionaryWriter writer, Message message, AsyncCallback callback, object state) : base(callback, state) { Fx.Assert(message != null, "message should never be null"); _message = message; _writer = writer; Schedule(); } protected override void OnDoWork() { _message.OnWriteMessage(_writer); } } } internal class EmptyBodyWriter : BodyWriter { private static EmptyBodyWriter s_value; private EmptyBodyWriter() : base(true) { } public static EmptyBodyWriter Value { get { if (s_value == null) s_value = new EmptyBodyWriter(); return s_value; } } internal override bool IsEmpty { get { return true; } } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { } } internal class FaultBodyWriter : BodyWriter { private MessageFault _fault; private EnvelopeVersion _version; public FaultBodyWriter(MessageFault fault, EnvelopeVersion version) : base(true) { _fault = fault; _version = version; } internal override bool IsFault { get { return true; } } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { _fault.WriteTo(writer, _version); } } internal class XmlObjectSerializerBodyWriter : BodyWriter { private object _body; private XmlObjectSerializer _serializer; public XmlObjectSerializerBodyWriter(object body, XmlObjectSerializer serializer) : base(true) { _body = body; _serializer = serializer; } private object ThisLock { get { return this; } } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { lock (ThisLock) { _serializer.WriteObject(writer, _body); } } } internal class XmlReaderBodyWriter : BodyWriter { private XmlDictionaryReader _reader; private bool _isFault; public XmlReaderBodyWriter(XmlDictionaryReader reader, EnvelopeVersion version) : base(false) { _reader = reader; if (reader.MoveToContent() != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidReaderPositionOnCreateMessage, "reader")); _isFault = Message.IsFaultStartElement(reader, version); } internal override bool IsFault { get { return _isFault; } } protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { return OnCreateBufferedCopy(maxBufferSize, _reader.Quotas); } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { using (_reader) { XmlNodeType type = _reader.MoveToContent(); while (!_reader.EOF && type != XmlNodeType.EndElement) { if (type != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidReaderPositionOnCreateMessage, "reader")); writer.WriteNode(_reader, false); type = _reader.MoveToContent(); } } } } internal class BodyWriterMessage : Message { private MessageProperties _properties; private MessageHeaders _headers; private BodyWriter _bodyWriter; private BodyWriterMessage(BodyWriter bodyWriter) { _bodyWriter = bodyWriter; } public BodyWriterMessage(MessageVersion version, string action, BodyWriter bodyWriter) : this(bodyWriter) { _headers = new MessageHeaders(version); _headers.Action = action; } public BodyWriterMessage(MessageVersion version, ActionHeader actionHeader, BodyWriter bodyWriter) : this(bodyWriter) { _headers = new MessageHeaders(version); _headers.SetActionHeader(actionHeader); } public BodyWriterMessage(MessageHeaders headers, KeyValuePair<string, object>[] properties, BodyWriter bodyWriter) : this(bodyWriter) { _headers = new MessageHeaders(headers); _properties = new MessageProperties(properties); } public override bool IsFault { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _bodyWriter.IsFault; } } public override bool IsEmpty { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _bodyWriter.IsEmpty; } } public override MessageHeaders Headers { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _headers; } } public override MessageProperties Properties { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); if (_properties == null) _properties = new MessageProperties(); return _properties; } } public override MessageVersion Version { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _headers.MessageVersion; } } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { BodyWriter bufferedBodyWriter; if (_bodyWriter.IsBuffered) { bufferedBodyWriter = _bodyWriter; } else { bufferedBodyWriter = _bodyWriter.CreateBufferedCopy(maxBufferSize); } KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[Properties.Count]; ((ICollection<KeyValuePair<string, object>>)Properties).CopyTo(properties, 0); return new BodyWriterMessageBuffer(_headers, properties, bufferedBodyWriter); } protected override void OnClose() { Exception ex = null; try { base.OnClose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; ex = e; } try { if (_properties != null) _properties.Dispose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } if (ex != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex); _bodyWriter = null; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { _bodyWriter.WriteBodyContents(writer); } protected override Task OnWriteBodyContentsAsync(XmlDictionaryWriter writer) { return _bodyWriter.WriteBodyContentsAsync(writer); } protected override IAsyncResult OnBeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return null; //WriteMessagePreamble(writer); //return new OnWriteMessageAsyncResult(writer, this, callback, state); } protected override void OnEndWriteMessage(IAsyncResult result) { //OnWriteMessageAsyncResult.End(result); } protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return _bodyWriter.BeginWriteBodyContents(writer, callback, state); } protected override void OnEndWriteBodyContents(IAsyncResult result) { _bodyWriter.EndWriteBodyContents(result); } protected override void OnBodyToString(XmlDictionaryWriter writer) { if (_bodyWriter.IsBuffered) { _bodyWriter.WriteBodyContents(writer); } else { writer.WriteString(SR.MessageBodyIsStream); } } protected internal BodyWriter BodyWriter { get { return _bodyWriter; } } private class OnWriteMessageAsyncResult : AsyncResult { private BodyWriterMessage _message; private XmlDictionaryWriter _writer; public OnWriteMessageAsyncResult(XmlDictionaryWriter writer, BodyWriterMessage message, AsyncCallback callback, object state) : base(callback, state) { _message = message; _writer = writer; if (HandleWriteBodyContents(null)) { this.Complete(true); } } private bool HandleWriteBodyContents(IAsyncResult result) { if (result == null) { result = _message.OnBeginWriteBodyContents(_writer, PrepareAsyncCompletion(HandleWriteBodyContents), this); if (!result.CompletedSynchronously) { return false; } } _message.OnEndWriteBodyContents(result); _message.WriteMessagePostamble(_writer); return true; } public static void End(IAsyncResult result) { AsyncResult.End<OnWriteMessageAsyncResult>(result); } } } internal abstract class ReceivedMessage : Message { private bool _isFault; private bool _isEmpty; public override bool IsEmpty { get { return _isEmpty; } } public override bool IsFault { get { return _isFault; } } protected static bool HasHeaderElement(XmlDictionaryReader reader, EnvelopeVersion envelopeVersion) { return reader.IsStartElement(XD.MessageDictionary.Header, envelopeVersion.DictionaryNamespace); } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { if (!_isEmpty) { using (XmlDictionaryReader bodyReader = OnGetReaderAtBodyContents()) { if (bodyReader.ReadState == ReadState.Error || bodyReader.ReadState == ReadState.Closed) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.MessageBodyReaderInvalidReadState, bodyReader.ReadState.ToString()))); while (bodyReader.NodeType != XmlNodeType.EndElement && !bodyReader.EOF) { writer.WriteNode(bodyReader, false); } this.ReadFromBodyContentsToEnd(bodyReader); } } } protected bool ReadStartBody(XmlDictionaryReader reader) { return Message.ReadStartBody(reader, this.Version.Envelope, out _isFault, out _isEmpty); } protected static EnvelopeVersion ReadStartEnvelope(XmlDictionaryReader reader) { EnvelopeVersion envelopeVersion; if (reader.IsStartElement(XD.MessageDictionary.Envelope, XD.Message12Dictionary.Namespace)) envelopeVersion = EnvelopeVersion.Soap12; else if (reader.IsStartElement(XD.MessageDictionary.Envelope, XD.Message11Dictionary.Namespace)) envelopeVersion = EnvelopeVersion.Soap11; else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.MessageVersionUnknown)); if (reader.IsEmptyElement) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.MessageBodyMissing)); reader.Read(); return envelopeVersion; } protected static void VerifyStartBody(XmlDictionaryReader reader, EnvelopeVersion version) { if (!reader.IsStartElement(XD.MessageDictionary.Body, version.DictionaryNamespace)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.MessageBodyMissing)); } } internal sealed class StreamedMessage : ReceivedMessage { private MessageHeaders _headers; private XmlAttributeHolder[] _envelopeAttributes; private XmlAttributeHolder[] _headerAttributes; private XmlAttributeHolder[] _bodyAttributes; private string _envelopePrefix; private string _headerPrefix; private string _bodyPrefix; private MessageProperties _properties; private XmlDictionaryReader _reader; private XmlDictionaryReaderQuotas _quotas; public StreamedMessage(XmlDictionaryReader reader, int maxSizeOfHeaders, MessageVersion desiredVersion) { _properties = new MessageProperties(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); if (desiredVersion.Envelope == EnvelopeVersion.None) { _reader = reader; _headerAttributes = XmlAttributeHolder.emptyArray; _headers = new MessageHeaders(desiredVersion); } else { _envelopeAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfHeaders); _envelopePrefix = reader.Prefix; EnvelopeVersion envelopeVersion = ReadStartEnvelope(reader); if (desiredVersion.Envelope != envelopeVersion) { Exception versionMismatchException = new ArgumentException(SR.Format(SR.EncoderEnvelopeVersionMismatch, envelopeVersion, desiredVersion.Envelope), "reader"); throw TraceUtility.ThrowHelperError( new CommunicationException(versionMismatchException.Message, versionMismatchException), this); } if (HasHeaderElement(reader, envelopeVersion)) { _headerPrefix = reader.Prefix; _headerAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfHeaders); _headers = new MessageHeaders(desiredVersion, reader, _envelopeAttributes, _headerAttributes, ref maxSizeOfHeaders); } else { _headerAttributes = XmlAttributeHolder.emptyArray; _headers = new MessageHeaders(desiredVersion); } if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); _bodyPrefix = reader.Prefix; VerifyStartBody(reader, envelopeVersion); _bodyAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfHeaders); if (ReadStartBody(reader)) { _reader = reader; } else { _quotas = new XmlDictionaryReaderQuotas(); reader.Quotas.CopyTo(_quotas); reader.Dispose(); } } } public override MessageHeaders Headers { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _headers; } } public override MessageVersion Version { get { return _headers.MessageVersion; } } public override MessageProperties Properties { get { return _properties; } } protected override void OnBodyToString(XmlDictionaryWriter writer) { writer.WriteString(SR.MessageBodyIsStream); } protected override void OnClose() { Exception ex = null; try { base.OnClose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; ex = e; } try { _properties.Dispose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } try { if (_reader != null) { _reader.Dispose(); } } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } if (ex != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex); } protected override XmlDictionaryReader OnGetReaderAtBodyContents() { XmlDictionaryReader reader = _reader; _reader = null; return reader; } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { if (_reader != null) return OnCreateBufferedCopy(maxBufferSize, _reader.Quotas); return OnCreateBufferedCopy(maxBufferSize, _quotas); } protected override void OnWriteStartBody(XmlDictionaryWriter writer) { writer.WriteStartElement(_bodyPrefix, MessageStrings.Body, Version.Envelope.Namespace); XmlAttributeHolder.WriteAttributes(_bodyAttributes, writer); } protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer) { EnvelopeVersion envelopeVersion = Version.Envelope; writer.WriteStartElement(_envelopePrefix, MessageStrings.Envelope, envelopeVersion.Namespace); XmlAttributeHolder.WriteAttributes(_envelopeAttributes, writer); } protected override void OnWriteStartHeaders(XmlDictionaryWriter writer) { EnvelopeVersion envelopeVersion = Version.Envelope; writer.WriteStartElement(_headerPrefix, MessageStrings.Header, envelopeVersion.Namespace); XmlAttributeHolder.WriteAttributes(_headerAttributes, writer); } protected override string OnGetBodyAttribute(string localName, string ns) { return XmlAttributeHolder.GetAttribute(_bodyAttributes, localName, ns); } } internal interface IBufferedMessageData { MessageEncoder MessageEncoder { get; } ArraySegment<byte> Buffer { get; } XmlDictionaryReaderQuotas Quotas { get; } void Close(); void EnableMultipleUsers(); XmlDictionaryReader GetMessageReader(); void Open(); void ReturnMessageState(RecycledMessageState messageState); RecycledMessageState TakeMessageState(); } internal sealed class BufferedMessage : ReceivedMessage { private MessageHeaders _headers; private MessageProperties _properties; private IBufferedMessageData _messageData; private RecycledMessageState _recycledMessageState; private XmlDictionaryReader _reader; private XmlAttributeHolder[] _bodyAttributes; public BufferedMessage(IBufferedMessageData messageData, RecycledMessageState recycledMessageState) : this(messageData, recycledMessageState, null, false) { } public BufferedMessage(IBufferedMessageData messageData, RecycledMessageState recycledMessageState, bool[] understoodHeaders, bool understoodHeadersModified) { bool throwing = true; try { _recycledMessageState = recycledMessageState; _messageData = messageData; _properties = recycledMessageState.TakeProperties(); if (_properties == null) _properties = new MessageProperties(); XmlDictionaryReader reader = messageData.GetMessageReader(); MessageVersion desiredVersion = messageData.MessageEncoder.MessageVersion; if (desiredVersion.Envelope == EnvelopeVersion.None) { _reader = reader; _headers = new MessageHeaders(desiredVersion); } else { EnvelopeVersion envelopeVersion = ReadStartEnvelope(reader); if (desiredVersion.Envelope != envelopeVersion) { Exception versionMismatchException = new ArgumentException(SR.Format(SR.EncoderEnvelopeVersionMismatch, envelopeVersion, desiredVersion.Envelope), "reader"); throw TraceUtility.ThrowHelperError( new CommunicationException(versionMismatchException.Message, versionMismatchException), this); } if (HasHeaderElement(reader, envelopeVersion)) { _headers = recycledMessageState.TakeHeaders(); if (_headers == null) { _headers = new MessageHeaders(desiredVersion, reader, messageData, recycledMessageState, understoodHeaders, understoodHeadersModified); } else { _headers.Init(desiredVersion, reader, messageData, recycledMessageState, understoodHeaders, understoodHeadersModified); } } else { _headers = new MessageHeaders(desiredVersion); } VerifyStartBody(reader, envelopeVersion); int maxSizeOfAttributes = int.MaxValue; _bodyAttributes = XmlAttributeHolder.ReadAttributes(reader, ref maxSizeOfAttributes); if (maxSizeOfAttributes < int.MaxValue - 4096) _bodyAttributes = null; if (ReadStartBody(reader)) { _reader = reader; } else { reader.Dispose(); } } throwing = false; } finally { if (throwing && MessageLogger.LoggingEnabled) { MessageLogger.LogMessage(messageData.Buffer, MessageLoggingSource.Malformed); } } } public override MessageHeaders Headers { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _headers; } } internal IBufferedMessageData MessageData { get { return _messageData; } } public override MessageProperties Properties { get { if (IsDisposed) throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); return _properties; } } internal override RecycledMessageState RecycledMessageState { get { return _recycledMessageState; } } public override MessageVersion Version { get { return _headers.MessageVersion; } } protected override XmlDictionaryReader OnGetReaderAtBodyContents() { XmlDictionaryReader reader = _reader; _reader = null; return reader; } internal override XmlDictionaryReader GetReaderAtHeader() { if (!_headers.ContainsOnlyBufferedMessageHeaders) return base.GetReaderAtHeader(); XmlDictionaryReader reader = _messageData.GetMessageReader(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); reader.Read(); if (HasHeaderElement(reader, _headers.MessageVersion.Envelope)) return reader; return base.GetReaderAtHeader(); } public XmlDictionaryReader GetBufferedReaderAtBody() { XmlDictionaryReader reader = _messageData.GetMessageReader(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); if (this.Version.Envelope != EnvelopeVersion.None) { reader.Read(); if (HasHeaderElement(reader, _headers.MessageVersion.Envelope)) reader.Skip(); if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); } return reader; } public XmlDictionaryReader GetMessageReader() { return _messageData.GetMessageReader(); } protected override void OnBodyToString(XmlDictionaryWriter writer) { using (XmlDictionaryReader reader = GetBufferedReaderAtBody()) { if (this.Version == MessageVersion.None) { writer.WriteNode(reader, false); } else { if (!reader.IsEmptyElement) { reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) writer.WriteNode(reader, false); } } } } protected override void OnClose() { Exception ex = null; try { base.OnClose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; ex = e; } try { _properties.Dispose(); } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } try { if (_reader != null) { _reader.Dispose(); } } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } try { _recycledMessageState.ReturnHeaders(_headers); _recycledMessageState.ReturnProperties(_properties); _messageData.ReturnMessageState(_recycledMessageState); _recycledMessageState = null; _messageData.Close(); _messageData = null; } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (ex == null) ex = e; } if (ex != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex); } protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer) { using (XmlDictionaryReader reader = GetMessageReader()) { reader.MoveToContent(); EnvelopeVersion envelopeVersion = Version.Envelope; writer.WriteStartElement(reader.Prefix, MessageStrings.Envelope, envelopeVersion.Namespace); writer.WriteAttributes(reader, false); } } protected override void OnWriteStartHeaders(XmlDictionaryWriter writer) { using (XmlDictionaryReader reader = GetMessageReader()) { reader.MoveToContent(); EnvelopeVersion envelopeVersion = Version.Envelope; reader.Read(); if (HasHeaderElement(reader, envelopeVersion)) { writer.WriteStartElement(reader.Prefix, MessageStrings.Header, envelopeVersion.Namespace); writer.WriteAttributes(reader, false); } else { writer.WriteStartElement(MessageStrings.Prefix, MessageStrings.Header, envelopeVersion.Namespace); } } } protected override void OnWriteStartBody(XmlDictionaryWriter writer) { using (XmlDictionaryReader reader = GetBufferedReaderAtBody()) { writer.WriteStartElement(reader.Prefix, MessageStrings.Body, Version.Envelope.Namespace); writer.WriteAttributes(reader, false); } } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { if (_headers.ContainsOnlyBufferedMessageHeaders) { KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[Properties.Count]; ((ICollection<KeyValuePair<string, object>>)Properties).CopyTo(properties, 0); _messageData.EnableMultipleUsers(); bool[] understoodHeaders = null; if (_headers.HasMustUnderstandBeenModified) { understoodHeaders = new bool[_headers.Count]; for (int i = 0; i < _headers.Count; i++) { understoodHeaders[i] = _headers.IsUnderstood(i); } } return new BufferedMessageBuffer(_messageData, properties, understoodHeaders, _headers.HasMustUnderstandBeenModified); } else { if (_reader != null) return OnCreateBufferedCopy(maxBufferSize, _reader.Quotas); return OnCreateBufferedCopy(maxBufferSize, XmlDictionaryReaderQuotas.Max); } } protected override string OnGetBodyAttribute(string localName, string ns) { if (_bodyAttributes != null) return XmlAttributeHolder.GetAttribute(_bodyAttributes, localName, ns); using (XmlDictionaryReader reader = GetBufferedReaderAtBody()) { return reader.GetAttribute(localName, ns); } } } internal struct XmlAttributeHolder { private string _prefix; private string _ns; private string _localName; private string _value; public static XmlAttributeHolder[] emptyArray = new XmlAttributeHolder[0]; public XmlAttributeHolder(string prefix, string localName, string ns, string value) { _prefix = prefix; _localName = localName; _ns = ns; _value = value; } public string Prefix { get { return _prefix; } } public string NamespaceUri { get { return _ns; } } public string LocalName { get { return _localName; } } public string Value { get { return _value; } } public void WriteTo(XmlWriter writer) { writer.WriteStartAttribute(_prefix, _localName, _ns); writer.WriteString(_value); writer.WriteEndAttribute(); } public static void WriteAttributes(XmlAttributeHolder[] attributes, XmlWriter writer) { for (int i = 0; i < attributes.Length; i++) attributes[i].WriteTo(writer); } public static XmlAttributeHolder[] ReadAttributes(XmlDictionaryReader reader) { int maxSizeOfHeaders = int.MaxValue; return ReadAttributes(reader, ref maxSizeOfHeaders); } public static XmlAttributeHolder[] ReadAttributes(XmlDictionaryReader reader, ref int maxSizeOfHeaders) { if (reader.AttributeCount == 0) return emptyArray; XmlAttributeHolder[] attributes = new XmlAttributeHolder[reader.AttributeCount]; reader.MoveToFirstAttribute(); for (int i = 0; i < attributes.Length; i++) { string ns = reader.NamespaceURI; string localName = reader.LocalName; string prefix = reader.Prefix; string value = string.Empty; while (reader.ReadAttributeValue()) { if (value.Length == 0) value = reader.Value; else value += reader.Value; } Deduct(prefix, ref maxSizeOfHeaders); Deduct(localName, ref maxSizeOfHeaders); Deduct(ns, ref maxSizeOfHeaders); Deduct(value, ref maxSizeOfHeaders); attributes[i] = new XmlAttributeHolder(prefix, localName, ns, value); reader.MoveToNextAttribute(); } reader.MoveToElement(); return attributes; } private static void Deduct(string s, ref int maxSizeOfHeaders) { int byteCount = s.Length * sizeof(char); if (byteCount > maxSizeOfHeaders) { string message = SR.XmlBufferQuotaExceeded; Exception inner = new QuotaExceededException(message); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(message, inner)); } maxSizeOfHeaders -= byteCount; } public static string GetAttribute(XmlAttributeHolder[] attributes, string localName, string ns) { for (int i = 0; i < attributes.Length; i++) if (attributes[i].LocalName == localName && attributes[i].NamespaceUri == ns) return attributes[i].Value; return null; } } internal class RecycledMessageState { private MessageHeaders _recycledHeaders; private MessageProperties _recycledProperties; private UriCache _uriCache; private HeaderInfoCache _headerInfoCache; public HeaderInfoCache HeaderInfoCache { get { if (_headerInfoCache == null) { _headerInfoCache = new HeaderInfoCache(); } return _headerInfoCache; } } public UriCache UriCache { get { if (_uriCache == null) _uriCache = new UriCache(); return _uriCache; } } public MessageProperties TakeProperties() { MessageProperties taken = _recycledProperties; _recycledProperties = null; return taken; } public void ReturnProperties(MessageProperties properties) { if (properties.CanRecycle) { properties.Recycle(); _recycledProperties = properties; } } public MessageHeaders TakeHeaders() { MessageHeaders taken = _recycledHeaders; _recycledHeaders = null; return taken; } public void ReturnHeaders(MessageHeaders headers) { if (headers.CanRecycle) { headers.Recycle(this.HeaderInfoCache); _recycledHeaders = headers; } } } internal class HeaderInfoCache { private const int maxHeaderInfos = 4; private HeaderInfo[] _headerInfos; private int _index; public MessageHeaderInfo TakeHeaderInfo(XmlDictionaryReader reader, string actor, bool mustUnderstand, bool relay, bool isRefParam) { if (_headerInfos != null) { int i = _index; for (;;) { HeaderInfo headerInfo = _headerInfos[i]; if (headerInfo != null) { if (headerInfo.Matches(reader, actor, mustUnderstand, relay, isRefParam)) { _headerInfos[i] = null; _index = (i + 1) % maxHeaderInfos; return headerInfo; } } i = (i + 1) % maxHeaderInfos; if (i == _index) { break; } } } return new HeaderInfo(reader, actor, mustUnderstand, relay, isRefParam); } public void ReturnHeaderInfo(MessageHeaderInfo headerInfo) { HeaderInfo headerInfoToReturn = headerInfo as HeaderInfo; if (headerInfoToReturn != null) { if (_headerInfos == null) { _headerInfos = new HeaderInfo[maxHeaderInfos]; } int i = _index; for (;;) { if (_headerInfos[i] == null) { break; } i = (i + 1) % maxHeaderInfos; if (i == _index) { break; } } _headerInfos[i] = headerInfoToReturn; _index = (i + 1) % maxHeaderInfos; } } internal class HeaderInfo : MessageHeaderInfo { private string _name; private string _ns; private string _actor; private bool _isReferenceParameter; private bool _mustUnderstand; private bool _relay; public HeaderInfo(XmlDictionaryReader reader, string actor, bool mustUnderstand, bool relay, bool isReferenceParameter) { _actor = actor; _mustUnderstand = mustUnderstand; _relay = relay; _isReferenceParameter = isReferenceParameter; _name = reader.LocalName; _ns = reader.NamespaceURI; } public override string Name { get { return _name; } } public override string Namespace { get { return _ns; } } public override bool IsReferenceParameter { get { return _isReferenceParameter; } } public override string Actor { get { return _actor; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } public bool Matches(XmlDictionaryReader reader, string actor, bool mustUnderstand, bool relay, bool isRefParam) { return reader.IsStartElement(_name, _ns) && _actor == actor && _mustUnderstand == mustUnderstand && _relay == relay && _isReferenceParameter == isRefParam; } } } internal class UriCache { private const int MaxKeyLength = 128; private const int MaxEntries = 8; private Entry[] _entries; private int _count; public UriCache() { _entries = new Entry[MaxEntries]; } public Uri CreateUri(string uriString) { Uri uri = Get(uriString); if (uri == null) { uri = new Uri(uriString); Set(uriString, uri); } return uri; } private Uri Get(string key) { if (key.Length > MaxKeyLength) return null; for (int i = _count - 1; i >= 0; i--) if (_entries[i].Key == key) return _entries[i].Value; return null; } private void Set(string key, Uri value) { if (key.Length > MaxKeyLength) return; if (_count < _entries.Length) { _entries[_count++] = new Entry(key, value); } else { Array.Copy(_entries, 1, _entries, 0, _entries.Length - 1); _entries[_count - 1] = new Entry(key, value); } } internal struct Entry { private string _key; private Uri _value; public Entry(string key, Uri value) { _key = key; _value = value; } public string Key { get { return _key; } } public Uri Value { get { return _value; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Management.Automation.Internal; namespace System.Management.Automation.Runspaces { internal sealed class Help_Format_Ps1Xml { internal static IEnumerable<ExtendedTypeDefinition> GetFormatData() { var TextPropertyControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Text") .EndEntry() .EndControl(); var MamlShortDescriptionControl = CustomControl.Create() .StartEntry(entrySelectedByType: new[] { "MamlParaTextItem" }) .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() .StartEntry() .AddText(" ") .EndEntry() .EndControl(); var MamlDescriptionControl = CustomControl.Create() .StartEntry(entrySelectedByType: new[] { "MamlParaTextItem" }) .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() .StartEntry(entrySelectedByType: new[] { "MamlOrderedListTextItem" }) .StartFrame(firstLineHanging: 4) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndFrame() .EndEntry() .StartEntry(entrySelectedByType: new[] { "MamlUnorderedListTextItem" }) .StartFrame(firstLineHanging: 2) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndFrame() .EndEntry() .StartEntry(entrySelectedByType: new[] { "MamlDefinitionTextItem" }) .AddPropertyExpressionBinding(@"Term") .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Definition") .AddNewline() .EndFrame() .EndEntry() .StartEntry() .AddText(" ") .EndEntry() .EndControl(); var MamlParameterControl = CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding( @"$optional = $_.required -ne 'true' $positional = (($_.position -ne $()) -and ($_.position -ne '') -and ($_.position -notmatch 'named') -and ([int]$_.position -ne $())) $parameterValue = if ($null -ne $_.psobject.Members['ParameterValueGroup']) { "" {$($_.ParameterValueGroup.ParameterValue -join ' | ')}"" } elseif ($null -ne $_.psobject.Members['ParameterValue']) { "" <$($_.ParameterValue)>"" } else { '' } $(if ($optional -and $positional) { '[[-{0}]{1}] ' } elseif ($optional) { '[-{0}{1}] ' } elseif ($positional) { '[-{0}]{1} ' } else { '-{0}{1} ' }) -f $_.Name, $parameterValue") .EndEntry() .EndControl(); var MamlParameterValueControl = CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding(@"if ($_.required -ne 'true') { "" [<$_>]"" } else { "" <$_>"" }") .EndEntry() .EndControl(); var MamlTextItem = CustomControl.Create() .StartEntry(entrySelectedByType: new[] { "MamlParaTextItem" }) .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() .StartEntry(entrySelectedByType: new[] { "MamlOrderedListTextItem" }) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() .StartEntry(entrySelectedByType: new[] { "MamlUnorderedListTextItem" }) .AddPropertyExpressionBinding(@"Tag") .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() .StartEntry(entrySelectedByType: new[] { "MamlDefinitionTextItem" }) .AddPropertyExpressionBinding(@"Term") .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Definition") .EndFrame() .AddNewline() .EndEntry() .StartEntry(entrySelectedByType: new[] { "MamlPreformattedTextItem" }) .AddPropertyExpressionBinding(@"Text") .EndEntry() .StartEntry() .AddText(" ") .EndEntry() .EndControl(); var MamlAlertControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Text") .AddNewline() .EndEntry() .EndControl(); var control4 = CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.FalseShort) .EndEntry() .EndControl(); var control3 = CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.TrueShort) .EndEntry() .EndControl(); var MamlTrueFalseShortControl = CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding(@";", selectedByScript: @"$_.Equals('true', [System.StringComparison]::OrdinalIgnoreCase)", customControl: control3) .AddScriptBlockExpressionBinding(@";", selectedByScript: @"$_.Equals('false', [System.StringComparison]::OrdinalIgnoreCase)", customControl: control4) .EndEntry() .EndControl(); var RelatedLinksHelpInfoControl = CustomControl.Create() .StartEntry() .StartFrame(leftIndent: 4) .AddScriptBlockExpressionBinding(StringUtil.Format(@"Set-StrictMode -Off if (($_.relatedLinks -ne $()) -and ($_.relatedLinks.navigationLink -ne $()) -and ($_.relatedLinks.navigationLink.Length -ne 0)) {{ "" {0}`""get-help $($_.Details.Name) -online`"""" }}", HelpDisplayStrings.RelatedLinksHelpInfo)) .EndFrame() .EndEntry() .EndControl(); var control6 = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"linkText") .AddScriptBlockExpressionBinding("' '", selectedByScript: "$_.linkText.Length -ne 0") .AddPropertyExpressionBinding(@"uri") .AddNewline() .EndEntry() .EndControl(); var MamlRelatedLinksControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"navigationLink", enumerateCollection: true, customControl: control6) .EndEntry() .EndControl(); var MamlDetailsControl = CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.Name) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Name") .AddNewline() .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.Synopsis) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Description", enumerateCollection: true, customControl: MamlShortDescriptionControl) .AddNewline() .AddNewline() .EndFrame() .EndEntry() .EndControl(); var MamlExampleControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Title") .AddNewline() .AddNewline() .AddPropertyExpressionBinding(@"Introduction", enumerateCollection: true, customControl: TextPropertyControl) .AddPropertyExpressionBinding(@"Code", enumerateCollection: true) .AddNewline() .AddPropertyExpressionBinding(@"results") .AddNewline() .AddPropertyExpressionBinding(@"remarks", enumerateCollection: true, customControl: MamlShortDescriptionControl) .EndEntry() .EndControl(); var control1 = CustomControl.Create() .StartEntry() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"description", enumerateCollection: true, customControl: MamlShortDescriptionControl) .EndFrame() .EndEntry() .EndControl(); var control0 = CustomControl.Create() .StartEntry() .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"uri") .AddNewline() .EndFrame() .EndEntry() .EndControl(); var MamlTypeControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"name", enumerateCollection: true) .AddCustomControlExpressionBinding(control0, selectedByScript: "$_.uri") .AddCustomControlExpressionBinding(control1, selectedByScript: "$_.description") .EndEntry() .EndControl(); var control2 = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Value") .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Description", enumerateCollection: true, customControl: MamlShortDescriptionControl) .EndFrame() .AddNewline() .EndEntry() .EndControl(); var MamlPossibleValueControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"possibleValue", enumerateCollection: true, customControl: control2) .EndEntry() .EndControl(); var MamlIndentedDescriptionControl = CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.DetailedDescription) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"description", enumerateCollection: true, customControl: MamlDescriptionControl) .AddNewline() .EndFrame() .AddNewline() .EndEntry() .EndControl(); var control5 = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"name") .AddText(" ") .AddPropertyExpressionBinding(@"Parameter", enumerateCollection: true, customControl: MamlParameterControl) .AddText("[" + HelpDisplayStrings.CommonParameters + "]") .AddNewline(2) .EndEntry() .EndControl(); var MamlSyntaxControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"SyntaxItem", enumerateCollection: true, customControl: control5) .EndEntry() .EndControl(); var ExamplesControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Example", enumerateCollection: true, customControl: MamlExampleControl) .EndEntry() .EndControl(); var MamlTypeWithDescriptionControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"type", customControl: MamlTypeControl) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"description", enumerateCollection: true, customControl: MamlShortDescriptionControl) .EndFrame() .AddNewline() .EndEntry() .EndControl(); var ErrorControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"errorId") .AddText(HelpDisplayStrings.Category) .AddPropertyExpressionBinding(@"category") .AddText(")") .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"description", enumerateCollection: true, customControl: MamlShortDescriptionControl) .EndFrame() .AddNewline() .AddText(HelpDisplayStrings.TypeColon) .AddPropertyExpressionBinding(@"type", customControl: MamlTypeControl) .AddNewline() .AddText(HelpDisplayStrings.TargetObjectTypeColon) .AddPropertyExpressionBinding(@"targetObjectType", customControl: MamlTypeControl) .AddNewline() .AddText(HelpDisplayStrings.SuggestedActionColon) .AddPropertyExpressionBinding(@"recommendedAction", enumerateCollection: true, customControl: MamlShortDescriptionControl) .AddNewline() .AddNewline() .EndEntry() .EndControl(); var MamlPossibleValuesControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"possibleValues", customControl: MamlPossibleValueControl) .EndEntry() .EndControl(); var MamlIndentedSyntaxControl = CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.Syntax) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Syntax", customControl: MamlSyntaxControl) .AddNewline() .EndFrame() .EndEntry() .EndControl(); var control7 = CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.NamedParameter) .EndEntry() .EndControl(); var MamlFullParameterControl = CustomControl.Create() .StartEntry() .AddText("-") .AddPropertyExpressionBinding(@"name") .AddPropertyExpressionBinding(@"ParameterValue", customControl: MamlParameterValueControl) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Description", enumerateCollection: true, customControl: MamlDescriptionControl) .AddNewline() .AddCustomControlExpressionBinding(MamlPossibleValuesControl, selectedByScript: "$_.possibleValues -ne $()") .AddText(HelpDisplayStrings.ParameterRequired) .AddPropertyExpressionBinding(@"required", customControl: MamlTrueFalseShortControl) .AddNewline() .AddText(HelpDisplayStrings.ParameterPosition) .AddScriptBlockExpressionBinding(@" ", selectedByScript: @"($_.position -eq $()) -or ($_.position -eq '')", customControl: control7) .AddScriptBlockExpressionBinding(@"$_.position", selectedByScript: "$_.position -ne $()") .AddNewline() .AddText(HelpDisplayStrings.ParameterDefaultValue) .AddPropertyExpressionBinding(@"defaultValue") .AddNewline() .AddText(HelpDisplayStrings.AcceptsPipelineInput) .AddPropertyExpressionBinding(@"pipelineInput") .AddNewline() .AddText(HelpDisplayStrings.AcceptsWildCardCharacters) .AddPropertyExpressionBinding(@"globbing", customControl: MamlTrueFalseShortControl) .AddNewline() .AddNewline() .EndFrame() .EndEntry() .EndControl(); var control8 = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Parameter", enumerateCollection: true, customControl: MamlFullParameterControl) .EndEntry() .EndControl(); var zzz = CustomControl.Create() .StartEntry() .AddCustomControlExpressionBinding(control8) .AddText(HelpDisplayStrings.CommonParameters) .AddNewline() .StartFrame(leftIndent: 4) .AddText(HelpDisplayStrings.BaseCmdletInformation) .EndFrame() .AddNewline() .AddNewline() .EndEntry() .EndControl(); var sharedControls = new CustomControl[] { TextPropertyControl, MamlShortDescriptionControl, MamlDetailsControl, MamlIndentedDescriptionControl, MamlDescriptionControl, MamlParameterControl, MamlParameterValueControl, ExamplesControl, MamlExampleControl, MamlTypeControl, MamlTextItem, MamlAlertControl, MamlPossibleValuesControl, MamlPossibleValueControl, MamlTrueFalseShortControl, MamlIndentedSyntaxControl, MamlSyntaxControl, MamlTypeWithDescriptionControl, RelatedLinksHelpInfoControl, MamlRelatedLinksControl, ErrorControl, MamlFullParameterControl, zzz }; yield return new ExtendedTypeDefinition( "HelpInfoShort", ViewsOf_HelpInfoShort()); yield return new ExtendedTypeDefinition( "CmdletHelpInfo", ViewsOf_CmdletHelpInfo()); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo", ViewsOf_MamlCommandHelpInfo(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#DetailedView", ViewsOf_MamlCommandHelpInfo_DetailedView(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#ExamplesView", ViewsOf_MamlCommandHelpInfo_ExamplesView(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#FullView", ViewsOf_MamlCommandHelpInfo_FullView(sharedControls)); yield return new ExtendedTypeDefinition( "ProviderHelpInfo", ViewsOf_ProviderHelpInfo(sharedControls)); yield return new ExtendedTypeDefinition( "FaqHelpInfo", ViewsOf_FaqHelpInfo(sharedControls)); yield return new ExtendedTypeDefinition( "GeneralHelpInfo", ViewsOf_GeneralHelpInfo(sharedControls)); yield return new ExtendedTypeDefinition( "GlossaryHelpInfo", ViewsOf_GlossaryHelpInfo(sharedControls)); yield return new ExtendedTypeDefinition( "ScriptHelpInfo", ViewsOf_ScriptHelpInfo(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#Examples", ViewsOf_MamlCommandHelpInfo_Examples(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#Example", ViewsOf_MamlCommandHelpInfo_Example(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#commandDetails", ViewsOf_MamlCommandHelpInfo_commandDetails(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#Parameters", ViewsOf_MamlCommandHelpInfo_Parameters(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#Parameter", ViewsOf_MamlCommandHelpInfo_Parameter(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#Syntax", ViewsOf_MamlCommandHelpInfo_Syntax(sharedControls)); var td18 = new ExtendedTypeDefinition( "MamlDefinitionTextItem", ViewsOf_MamlDefinitionTextItem_MamlOrderedListTextItem_MamlParaTextItem_MamlUnorderedListTextItem(sharedControls)); td18.TypeNames.Add("MamlOrderedListTextItem"); td18.TypeNames.Add("MamlParaTextItem"); td18.TypeNames.Add("MamlUnorderedListTextItem"); yield return td18; yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#inputTypes", ViewsOf_MamlCommandHelpInfo_inputTypes(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#nonTerminatingErrors", ViewsOf_MamlCommandHelpInfo_nonTerminatingErrors(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#terminatingErrors", ViewsOf_MamlCommandHelpInfo_terminatingErrors(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#relatedLinks", ViewsOf_MamlCommandHelpInfo_relatedLinks(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#returnValues", ViewsOf_MamlCommandHelpInfo_returnValues(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#alertSet", ViewsOf_MamlCommandHelpInfo_alertSet(sharedControls)); yield return new ExtendedTypeDefinition( "MamlCommandHelpInfo#details", ViewsOf_MamlCommandHelpInfo_details(sharedControls)); } private static IEnumerable<FormatViewDefinition> ViewsOf_HelpInfoShort() { yield return new FormatViewDefinition("help", TableControl.Create() .AddHeader(Alignment.Left, label: "Name", width: 33) .AddHeader(Alignment.Left, label: "Category", width: 9) .AddHeader(Alignment.Left, label: "Module", width: 25) .AddHeader() .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("Category") .AddScriptBlockColumn("if ($null -ne $_.ModuleName) { $_.ModuleName } else {$_.PSSnapIn}") .AddPropertyColumn("Synopsis") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_CmdletHelpInfo() { yield return new FormatViewDefinition("CmdletHelp", CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.Name) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Name") .AddNewline() .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.Syntax) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Syntax") .AddNewline() .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo(CustomControl[] sharedControls) { yield return new FormatViewDefinition("DefaultCommandHelp", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Details", customControl: sharedControls[2]) .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[15]) .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[3]) .AddText(HelpDisplayStrings.RelatedLinks) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"relatedLinks", customControl: sharedControls[19]) .EndFrame() .AddNewline() .AddText(HelpDisplayStrings.RemarksSection) .AddNewline() .StartFrame(leftIndent: 4) .AddText(HelpDisplayStrings.ExampleHelpInfo + "\"") .AddScriptBlockExpressionBinding(@"""get-help "" + $_.Details.Name + "" -examples""") .AddText("\".") .AddNewline() .AddText(HelpDisplayStrings.VerboseHelpInfo + "\"") .AddScriptBlockExpressionBinding(@"""get-help "" + $_.Details.Name + "" -detailed""") .AddText("\".") .AddNewline() .AddText(HelpDisplayStrings.FullHelpInfo) .AddText(@"""") .AddScriptBlockExpressionBinding(@"""get-help "" + $_.Details.Name + "" -full""") .AddText(@""".") .AddNewline() .AddCustomControlExpressionBinding(sharedControls[18]) .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_DetailedView(CustomControl[] sharedControls) { var control10 = CustomControl.Create() .StartEntry() .AddText("-") .AddPropertyExpressionBinding(@"name") .AddPropertyExpressionBinding(@"ParameterValue", customControl: sharedControls[6]) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Description", enumerateCollection: true, customControl: sharedControls[4]) .AddNewline() .EndFrame() .EndEntry() .EndControl(); var control9 = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Parameter", enumerateCollection: true, customControl: control10) .EndEntry() .EndControl(); yield return new FormatViewDefinition("VerboseCommandHelp", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Details", customControl: sharedControls[2]) .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[15]) .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[3]) .AddText(HelpDisplayStrings.Parameters) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Parameters", customControl: control9) .AddText(HelpDisplayStrings.CommonParameters) .AddNewline() .StartFrame(leftIndent: 4) .AddText(HelpDisplayStrings.BaseCmdletInformation) .EndFrame() .AddNewline() .AddNewline() .EndFrame() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Examples", customControl: sharedControls[7]) .EndFrame() .AddText(HelpDisplayStrings.RemarksSection) .AddNewline() .StartFrame(leftIndent: 4) .AddText(HelpDisplayStrings.ExampleHelpInfo) .AddText(@"""") .AddScriptBlockExpressionBinding(@"""get-help "" + $_.Details.Name + "" -examples""") .AddText(@""".") .AddNewline() .AddText(HelpDisplayStrings.VerboseHelpInfo) .AddText(@"""") .AddScriptBlockExpressionBinding(@"""get-help "" + $_.Details.Name + "" -detailed""") .AddText(@""".") .AddNewline() .AddText(HelpDisplayStrings.FullHelpInfo) .AddText(@"""") .AddScriptBlockExpressionBinding(@"""get-help "" + $_.Details.Name + "" -full""") .AddText(@""".") .AddNewline() .AddCustomControlExpressionBinding(sharedControls[18]) .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_ExamplesView(CustomControl[] sharedControls) { yield return new FormatViewDefinition("ExampleCommandHelp", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Details", customControl: sharedControls[2]) .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Examples", customControl: sharedControls[7]) .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_FullView(CustomControl[] sharedControls) { var control16 = CustomControl.Create() .StartEntry() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"title") .AddNewline() .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"alert", enumerateCollection: true, customControl: sharedControls[11]) .EndFrame() .AddNewline() .EndFrame() .EndEntry() .EndControl(); var control15 = CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.Notes) .AddNewline() .EndEntry() .EndControl(); var control14 = CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.NonHyphenTerminatingErrors) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"nonTerminatingError", enumerateCollection: true, customControl: sharedControls[20]) .EndFrame() .EndEntry() .EndControl(); var control13 = CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.TerminatingErrors) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"terminatingError", enumerateCollection: true, customControl: sharedControls[20]) .EndFrame() .EndEntry() .EndControl(); var control12 = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"ReturnValue", enumerateCollection: true, customControl: sharedControls[17]) .EndEntry() .EndControl(); var control11 = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"InputType", enumerateCollection: true, customControl: sharedControls[17]) .EndEntry() .EndControl(); yield return new FormatViewDefinition("FullCommandHelp", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Details", customControl: sharedControls[2]) .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[15]) .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[3]) .AddText(HelpDisplayStrings.Parameters) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Parameters", customControl: sharedControls[22]) .EndFrame() .AddText(HelpDisplayStrings.InputType) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"InputTypes", customControl: control11) .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.ReturnType) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"ReturnValues", customControl: control12) .AddNewline() .EndFrame() .AddPropertyExpressionBinding(@"terminatingErrors", selectedByScript: @" (($null -ne $_.terminatingErrors) -and ($null -ne $_.terminatingErrors.terminatingError)) ", customControl: control13) .AddPropertyExpressionBinding(@"nonTerminatingErrors", selectedByScript: @" (($null -ne $_.nonTerminatingErrors) -and ($null -ne $_.nonTerminatingErrors.nonTerminatingError)) ", customControl: control14) .AddPropertyExpressionBinding(@"alertSet", selectedByScript: "$null -ne $_.alertSet", customControl: control15) .AddPropertyExpressionBinding(@"alertSet", enumerateCollection: true, selectedByScript: "$null -ne $_.alertSet", customControl: control16) .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Examples", customControl: sharedControls[7]) .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.RelatedLinks) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"relatedLinks", customControl: sharedControls[19]) .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_ProviderHelpInfo(CustomControl[] sharedControls) { var TaskExampleControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Title") .AddNewline() .AddNewline() .AddPropertyExpressionBinding(@"Introduction", enumerateCollection: true, customControl: sharedControls[0]) .AddNewline() .AddNewline() .AddPropertyExpressionBinding(@"Code", enumerateCollection: true) .AddNewline() .AddPropertyExpressionBinding(@"results") .AddNewline() .AddNewline() .AddPropertyExpressionBinding(@"remarks", enumerateCollection: true, customControl: sharedControls[10]) .EndEntry() .EndControl(); var DynamicPossibleValues = CustomControl.Create() .StartEntry() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Value") .AddNewline() .EndFrame() .StartFrame(leftIndent: 8) .AddPropertyExpressionBinding(@"Description", enumerateCollection: true, customControl: sharedControls[10]) .AddNewline() .EndFrame() .EndEntry() .EndControl(); var TaskExamplesControl = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Example", enumerateCollection: true, customControl: TaskExampleControl) .EndEntry() .EndControl(); var control18 = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"PossibleValue", enumerateCollection: true, customControl: DynamicPossibleValues) .EndEntry() .EndControl(); var control17 = CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding(@"""<"" + $_.Name + "">""") .EndEntry() .EndControl(); var DynamicParameterControl = CustomControl.Create() .StartEntry() .StartFrame() .AddText("-") .AddPropertyExpressionBinding(@"Name") .AddText(" ") .AddPropertyExpressionBinding(@"Type", customControl: control17) .AddNewline() .EndFrame() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Description") .AddNewline() .AddNewline() .AddPropertyExpressionBinding(@"PossibleValues", customControl: control18) .AddNewline() .AddText(HelpDisplayStrings.CmdletsSupported) .AddPropertyExpressionBinding(@"CmdletSupported") .AddNewline() .AddNewline() .EndFrame() .EndEntry() .EndControl(); var Task = CustomControl.Create() .StartEntry() .StartFrame() .AddText(HelpDisplayStrings.Task) .AddPropertyExpressionBinding(@"Title") .AddNewline() .AddNewline() .EndFrame() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Description", enumerateCollection: true, customControl: sharedControls[10]) .AddNewline() .AddNewline() .AddPropertyExpressionBinding(@"Examples", enumerateCollection: true, customControl: TaskExamplesControl) .AddNewline() .AddNewline() .EndFrame() .EndEntry() .EndControl(); var ProviderTasks = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Task", enumerateCollection: true, customControl: Task) .AddNewline() .EndEntry() .EndControl(); var control19 = CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"DynamicParameter", enumerateCollection: true, customControl: DynamicParameterControl) .EndEntry() .EndControl(); yield return new FormatViewDefinition("ProviderHelpInfo", CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.ProviderName) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Name") .AddNewline() .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.Drives) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Drives", enumerateCollection: true, customControl: sharedControls[10]) .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.Synopsis) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Synopsis", enumerateCollection: true) .AddNewline() .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.DetailedDescription) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"DetailedDescription", enumerateCollection: true, customControl: sharedControls[10]) .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.Capabilities) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Capabilities", enumerateCollection: true, customControl: sharedControls[10]) .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.Tasks) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Tasks", enumerateCollection: true, customControl: ProviderTasks) .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.DynamicParameters) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"DynamicParameters", customControl: control19) .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.Notes) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Notes") .AddNewline() .EndFrame() .AddNewline() .AddText(HelpDisplayStrings.RelatedLinks) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"relatedLinks", customControl: sharedControls[19]) .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_FaqHelpInfo(CustomControl[] sharedControls) { yield return new FormatViewDefinition("FaqHelpInfo", CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.TitleColon) .AddPropertyExpressionBinding(@"Title") .AddNewline() .AddText(HelpDisplayStrings.QuestionColon) .AddPropertyExpressionBinding(@"Question") .AddNewline() .AddText(HelpDisplayStrings.Answer) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Answer", enumerateCollection: true, customControl: sharedControls[10]) .AddNewline() .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_GeneralHelpInfo(CustomControl[] sharedControls) { yield return new FormatViewDefinition("GeneralHelpInfo", CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.TitleColon) .AddPropertyExpressionBinding(@"Title") .AddNewline() .AddNewline() .AddText(HelpDisplayStrings.DetailedDescription) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Content", enumerateCollection: true, customControl: sharedControls[10]) .AddNewline() .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_GlossaryHelpInfo(CustomControl[] sharedControls) { yield return new FormatViewDefinition("GlossaryHelpInfo", CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.TermColon) .AddPropertyExpressionBinding(@"Name") .AddNewline() .AddText(HelpDisplayStrings.DefinitionColon) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Definition", enumerateCollection: true, customControl: sharedControls[10]) .AddNewline() .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_ScriptHelpInfo(CustomControl[] sharedControls) { yield return new FormatViewDefinition("ScriptHelpInfo", CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.TitleColon) .AddPropertyExpressionBinding(@"Title") .AddNewline() .AddText(HelpDisplayStrings.ContentColon) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Content", enumerateCollection: true, customControl: sharedControls[10]) .AddNewline() .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_Examples(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlCommandExamples", CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[7]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_Example(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlCommandExample", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"Title") .AddNewline() .AddNewline() .AddPropertyExpressionBinding(@"Introduction", enumerateCollection: true, customControl: sharedControls[0]) .AddPropertyExpressionBinding(@"Code", enumerateCollection: true) .AddNewline() .AddNewline() .AddPropertyExpressionBinding(@"results") .AddNewline() .AddNewline() .AddPropertyExpressionBinding(@"remarks", enumerateCollection: true, customControl: sharedControls[1]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_commandDetails(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlCommandDetails", CustomControl.Create() .StartEntry() .AddText(HelpDisplayStrings.Name) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"Name") .AddNewline() .AddNewline() .EndFrame() .AddText(HelpDisplayStrings.Synopsis) .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"commandDescription", enumerateCollection: true, customControl: sharedControls[1]) .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_Parameters(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlCommandParameters", CustomControl.Create() .StartEntry() .StartFrame(leftIndent: 4) .AddCustomControlExpressionBinding(sharedControls[22]) .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_Parameter(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlCommandParameterView", CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[21]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_Syntax(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlCommandSyntax", CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[16]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlDefinitionTextItem_MamlOrderedListTextItem_MamlParaTextItem_MamlUnorderedListTextItem(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlText", CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[4]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_inputTypes(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlInputTypes", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"InputType", enumerateCollection: true, customControl: sharedControls[17]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_nonTerminatingErrors(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlNonTerminatingErrors", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"nonTerminatingError", enumerateCollection: true, customControl: sharedControls[20]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_terminatingErrors(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlTerminatingErrors", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"terminatingError", enumerateCollection: true, customControl: sharedControls[20]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_relatedLinks(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlRelatedLinks", CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[19]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_returnValues(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlReturnTypes", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"ReturnValue", enumerateCollection: true, customControl: sharedControls[17]) .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_alertSet(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlAlertSet", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"title") .AddNewline() .AddNewline() .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"alert", enumerateCollection: true, customControl: sharedControls[11]) .EndFrame() .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_MamlCommandHelpInfo_details(CustomControl[] sharedControls) { yield return new FormatViewDefinition("MamlDetails", CustomControl.Create() .StartEntry() .AddScriptBlockExpressionBinding(@"$_", customControl: sharedControls[2]) .EndEntry() .EndControl()); } } }
#region License /* * Copyright 2002-2009 the original author or 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. */ #endregion using System; using System.Diagnostics; using Common.Logging.Factory; using Microsoft.Practices.EnterpriseLibrary.Logging; namespace Common.Logging.EntLib { /// <summary> /// Concrete implementation of <see cref="ILog"/> interface specific to Enterprise Logging 4.1. /// </summary> /// <remarks> /// Instances are created by the <see cref="EntLibLoggerFactoryAdapter"/>. <see cref="EntLibLoggerFactoryAdapter.DefaultPriority"/> /// is used for logging a <see cref="LogEntry"/> to <see cref="Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.Write"/>. /// The category name used is the name passed into <see cref="LogManager.GetLogger(string)" />. For configuring logging, see <see cref="EntLibLoggerFactoryAdapter"/>. /// </remarks> /// <seealso cref="ILog"/> /// <seealso cref="EntLibLoggerFactoryAdapter"/> /// <author>Mark Pollack</author> /// <author>Erich Eichinger</author> public class EntLibLogger : AbstractLogger { private class TraceLevelLogEntry : LogEntry { public TraceLevelLogEntry(string category, TraceEventType severity) { Categories.Add(category); Severity = severity; } } private readonly LogEntry VerboseLogEntry; private readonly LogEntry InformationLogEntry; private readonly LogEntry WarningLogEntry; private readonly LogEntry ErrorLogEntry; private readonly LogEntry CriticalLogEntry; private readonly string category; private readonly EntLibLoggerSettings settings; private readonly LogWriter logWriter; /// <summary> /// The category of this logger /// </summary> public string Category { get { return category; } } /// <summary> /// The settings used by this logger /// </summary> public EntLibLoggerSettings Settings { get { return settings; } } /// <summary> /// The <see cref="LogWriter"/> used by this logger. /// </summary> public LogWriter LogWriter { get { return logWriter; } } /// <summary> /// Initializes a new instance of the <see cref="EntLibLogger"/> class. /// </summary> /// <param name="category">The category.</param> /// <param name="logWriter">the <see cref="LogWriter"/> to write log events to.</param> /// <param name="settings">the logger settings</param> public EntLibLogger(string category, LogWriter logWriter, EntLibLoggerSettings settings) { this.category = category; this.logWriter = logWriter; this.settings = settings; VerboseLogEntry = new TraceLevelLogEntry(category, TraceEventType.Verbose); InformationLogEntry = new TraceLevelLogEntry(category, TraceEventType.Information); WarningLogEntry = new TraceLevelLogEntry(category, TraceEventType.Warning); ErrorLogEntry = new TraceLevelLogEntry(category, TraceEventType.Error); CriticalLogEntry = new TraceLevelLogEntry(category, TraceEventType.Critical); } #region IsXXXXEnabled /// <summary> /// Gets a value indicating whether this instance is trace enabled. /// </summary> public override bool IsTraceEnabled { get { return ShouldLog(VerboseLogEntry); } } /// <summary> /// Gets a value indicating whether this instance is debug enabled. /// </summary> public override bool IsDebugEnabled { get { return ShouldLog(VerboseLogEntry); } } /// <summary> /// Gets a value indicating whether this instance is info enabled. /// </summary> public override bool IsInfoEnabled { get { return ShouldLog(InformationLogEntry); } } /// <summary> /// Gets a value indicating whether this instance is warn enabled. /// </summary> public override bool IsWarnEnabled { get { return ShouldLog(WarningLogEntry); } } /// <summary> /// Gets a value indicating whether this instance is error enabled. /// </summary> public override bool IsErrorEnabled { get { return ShouldLog(ErrorLogEntry); } } /// <summary> /// Gets a value indicating whether this instance is fatal enabled. /// </summary> public override bool IsFatalEnabled { get { return ShouldLog(CriticalLogEntry); } } #endregion /// <summary> /// Actually sends the message to the EnterpriseLogging log system. /// </summary> /// <param name="logLevel">the level of this log event.</param> /// <param name="message">the message to log</param> /// <param name="exception">the exception to log (may be null)</param> protected override void WriteInternal(LogLevel logLevel, object message, Exception exception) { LogEntry log = CreateLogEntry(GetTraceEventType(logLevel)); if (ShouldLog(log)) { PopulateLogEntry(log, message, exception); WriteLog(log); } } /// <summary> /// May be overridden for custom filter logic /// </summary> /// <param name="log"></param> /// <returns></returns> protected virtual bool ShouldLog(LogEntry log) { return logWriter.ShouldLog(log); } /// <summary> /// Write the fully populated event to the log. /// </summary> protected virtual void WriteLog(LogEntry log) { logWriter.Write(log); } /// <summary> /// Translates a <see cref="LogLevel"/> to a <see cref="TraceEventType"/>. /// </summary> protected virtual TraceEventType GetTraceEventType(LogLevel logLevel) { switch (logLevel) { case LogLevel.All: return TraceEventType.Verbose; case LogLevel.Trace: return TraceEventType.Verbose; case LogLevel.Debug: return TraceEventType.Verbose; case LogLevel.Info: return TraceEventType.Information; case LogLevel.Warn: return TraceEventType.Warning; case LogLevel.Error: return TraceEventType.Error; case LogLevel.Fatal: return TraceEventType.Critical; case LogLevel.Off: return 0; default: throw new ArgumentOutOfRangeException("logLevel", logLevel, "unknown log level"); } } /// <summary> /// Creates a minimal log entry instance that will be passed into <see cref="Logger.ShouldLog"/> /// to asap decide, whether this event should be logged. /// </summary> /// <param name="traceEventType">trace event severity.</param> /// <returns></returns> protected virtual LogEntry CreateLogEntry(TraceEventType traceEventType) { LogEntry log = new LogEntry(); log.Categories.Add(category); log.Priority = settings.priority; log.Severity = traceEventType; return log; } /// <summary> /// Configures the log entry. /// </summary> /// <param name="log">The log.</param> /// <param name="message">The message.</param> /// <param name="ex">The ex.</param> protected virtual void PopulateLogEntry(LogEntry log, object message, Exception ex) { log.Message = (message == null ? null : message.ToString()); if (ex != null) { AddExceptionInfo(log, ex); } } /// <summary> /// Adds the exception info. /// </summary> /// <param name="log">The log entry.</param> /// <param name="exception">The exception.</param> /// <returns></returns> protected virtual void AddExceptionInfo(LogEntry log, Exception exception) { if (exception != null && settings.exceptionFormat != null) { string errorMessage = settings.exceptionFormat .Replace("$(exception.message)", exception.Message) .Replace("$(exception.source)", exception.Source) .Replace("$(exception.targetsite)", (exception.TargetSite==null)?string.Empty:exception.TargetSite.ToString()) .Replace("$(exception.stacktrace)", exception.StackTrace) ; // StringBuilder sb = new StringBuilder(128); // sb.Append("Exception[ "); // sb.Append("message = ").Append(exception.Message).Append(separator); // sb.Append("source = ").Append(exception.Source).Append(separator); // sb.Append("targetsite = ").Append(exception.TargetSite).Append(separator); // sb.Append("stacktrace = ").Append(exception.StackTrace).Append("]"); // return sb.ToString(); log.AddErrorMessage(errorMessage); } } } }
#pragma warning disable 1591 using System; using System.Collections.Generic; using System.ComponentModel; namespace Braintree { public enum TransactionGatewayRejectionReason { [Description("application_incomplete")] APPLICATION_INCOMPLETE, [Description("avs")] AVS, [Description("avs_and_cvv")] AVS_AND_CVV, [Description("cvv")] CVV, [Description("duplicate")] DUPLICATE, [Description("fraud")] FRAUD, [Description("risk_threshold")] RISK_THRESHOLD, [Description("three_d_secure")] THREE_D_SECURE, [Description("token_issuance")] TOKEN_ISSUANCE, [Description("unrecognized")] UNRECOGNIZED } public enum TransactionEscrowStatus { [Description("hold_pending")] HOLD_PENDING, [Description("held")] HELD, [Description("release_pending")] RELEASE_PENDING, [Description("released")] RELEASED, [Description("refunded")] REFUNDED, [Description("unrecognized")] UNRECOGNIZED } public enum TransactionStatus { [Description("authorization_expired")] AUTHORIZATION_EXPIRED, [Description("authorized")] AUTHORIZED, [Description("authorizing")] AUTHORIZING, [Description("failed")] FAILED, [Description("gateway_rejected")] GATEWAY_REJECTED, [Description("processor_declined")] PROCESSOR_DECLINED, [Description("settled")] SETTLED, [Description("settling")] SETTLING, [Description("submitted_for_settlement")] SUBMITTED_FOR_SETTLEMENT, [Description("voided")] VOIDED, [Description("unrecognized")] UNRECOGNIZED, [Description("settlement_confirmed")] SETTLEMENT_CONFIRMED, [Description("settlement_declined")] SETTLEMENT_DECLINED, [Description("settlement_pending")] SETTLEMENT_PENDING } public enum TransactionIndustryType { [Description("lodging")] LODGING, [Description("travel_cruise")] TRAVEL_AND_CRUISE, [Description("travel_flight")] TRAVEL_AND_FLIGHT } public enum TransactionSource { [Description("api")] API, [Description("control_panel")] CONTROL_PANEL, [Description("recurring")] RECURRING, [Description("unrecognized")] UNRECOGNIZED } public enum TransactionType { [Description("credit")] CREDIT, [Description("sale")] SALE, [Description("unrecognized")] UNRECOGNIZED } public enum TransactionCreatedUsing { [Description("full_information")] FULL_INFORMATION, [Description("token")] TOKEN, [Description("unrecognized")] UNRECOGNIZED } public enum PaymentInstrumentType { [Description("paypal_account")] PAYPAL_ACCOUNT, [Description("paypal_here")] PAYPAL_HERE, [Description("credit_card")] CREDIT_CARD, [Description("apple_pay_card")] APPLE_PAY_CARD, [Description("android_pay_card")] ANDROID_PAY_CARD, [Description("amex_express_checkout_card")] AMEX_EXPRESS_CHECKOUT_CARD, [Description("venmo_account")] VENMO_ACCOUNT, [Description("us_bank_account")] US_BANK_ACCOUNT, [Description("visa_checkout_card")] VISA_CHECKOUT_CARD, [Description("samsung_pay_card")] SAMSUNG_PAY_CARD, [Description("local_payment")] LOCAL_PAYMENT, [Description("any")] ANY, [Description("unknown")] UNKNOWN } /// <summary> /// A transaction returned by the Braintree Gateway /// </summary> /// <example> /// Transactions can be retrieved via the gateway using the associated transaction id: /// <code> /// Transaction transaction = gateway.Transaction.Find("transactionId"); /// </code> /// For more information about Transactions, see <a href="https://developer.paypal.com/braintree/docs/reference/response/transaction/dotnet" target="_blank">https://developer.paypal.com/braintree/docs/reference/response/transaction/dotnet</a> /// </example> public class Transaction { public virtual string Id { get; protected set; } public virtual List<AddOn> AddOns { get; protected set; } public virtual decimal? Amount { get; protected set; } public virtual string AvsErrorResponseCode { get; protected set; } public virtual string AvsPostalCodeResponseCode { get; protected set; } public virtual string AvsStreetAddressResponseCode { get; protected set; } public virtual Address BillingAddress { get; protected set; } public virtual string Channel { get; protected set; } public virtual DateTime? CreatedAt { get; protected set; } public virtual CreditCard CreditCard { get; protected set; } public virtual string CurrencyIsoCode { get; protected set; } public virtual CustomerDetails CustomerDetails { get; protected set; } public virtual string CvvResponseCode { get; protected set; } public virtual Descriptor Descriptor { get; protected set; } public virtual List<Discount> Discounts { get; protected set; } public virtual List<Dispute> Disputes { get; protected set; } public virtual TransactionGatewayRejectionReason GatewayRejectionReason { get; protected set; } public virtual string GraphQLId { get; protected set; } public virtual string MerchantAccountId { get; protected set; } public virtual string OrderId { get; protected set; } public virtual string PlanId { get; protected set; } public virtual bool? ProcessedWithNetworkToken { get; protected set; } public virtual string ProcessorAuthorizationCode { get; protected set; } public virtual ProcessorResponseType ProcessorResponseType { get; protected set; } public virtual string ProcessorResponseCode { get; protected set; } public virtual string ProcessorResponseText { get; protected set; } public virtual string ProcessorSettlementResponseCode { get; protected set; } public virtual string ProcessorSettlementResponseText { get; protected set; } public virtual string AdditionalProcessorResponse { get; protected set; } public virtual string NetworkResponseCode { get; protected set; } public virtual string NetworkResponseText { get; protected set; } public virtual string VoiceReferralNumber { get; protected set; } public virtual string PurchaseOrderNumber { get; protected set; } public virtual bool? Recurring { get; protected set; } public virtual string RefundedTransactionId { get; protected set; } public virtual List<string> RefundIds { get; protected set; } public virtual List<string> PartialSettlementTransactionIds { get; protected set; } public virtual string AuthorizedTransactionId { get; protected set; } public virtual string SettlementBatchId { get; protected set; } public virtual Address ShippingAddress { get; protected set; } public virtual TransactionEscrowStatus EscrowStatus { get; protected set; } public virtual TransactionStatus Status { get; protected set; } public virtual StatusEvent[] StatusHistory { get; protected set; } public virtual List<AuthorizationAdjustment> AuthorizationAdjustments { get; protected set; } public virtual string SubscriptionId { get; protected set; } public virtual SubscriptionDetails SubscriptionDetails { get; protected set; } public virtual decimal? TaxAmount { get; protected set; } public virtual bool? TaxExempt { get; protected set; } public virtual TransactionType Type { get; protected set; } public virtual DateTime? UpdatedAt { get; protected set; } public virtual Dictionary<string, string> CustomFields { get; protected set; } public virtual decimal? ServiceFeeAmount { get; protected set; } public virtual DisbursementDetails DisbursementDetails { get; protected set; } public virtual ApplePayDetails ApplePayDetails { get; protected set; } public virtual AndroidPayDetails AndroidPayDetails { get; protected set; } public virtual PayPalDetails PayPalDetails { get; protected set; } public virtual PayPalHereDetails PayPalHereDetails { get; protected set; } public virtual LocalPaymentDetails LocalPaymentDetails { get; protected set; } public virtual VenmoAccountDetails VenmoAccountDetails { get; protected set; } public virtual UsBankAccountDetails UsBankAccountDetails { get; protected set; } public virtual VisaCheckoutCardDetails VisaCheckoutCardDetails { get; protected set; } public virtual SamsungPayCardDetails SamsungPayCardDetails { get; protected set; } public virtual PaymentInstrumentType PaymentInstrumentType { get; protected set; } public virtual RiskData RiskData { get; protected set; } public virtual ThreeDSecureInfo ThreeDSecureInfo { get; protected set; } public virtual FacilitatedDetails FacilitatedDetails { get; protected set; } public virtual FacilitatorDetails FacilitatorDetails { get; protected set; } public virtual string ScaExemptionRequested { get; protected set; } public virtual decimal? DiscountAmount { get; protected set; } public virtual decimal? ShippingAmount { get; protected set; } public virtual string ShipsFromPostalCode { get; protected set; } public virtual string NetworkTransactionId { get; protected set; } public virtual DateTime? AuthorizationExpiresAt { get; protected set; } public virtual string RetrievalReferenceNumber { get; protected set; } public virtual string AcquirerReferenceNumber { get; protected set; } public virtual decimal? InstallmentCount { get; protected set; } public virtual List<Installment> Installments { get; protected set; } public virtual List<Installment> RefundedInstallments { get; protected set; } private IBraintreeGateway Gateway; [Obsolete("Mock Use Only")] protected Transaction() { } protected internal Transaction(NodeWrapper node, IBraintreeGateway gateway) { Gateway = gateway; if (node == null) return; Id = node.GetString("id"); Amount = node.GetDecimal("amount"); AvsErrorResponseCode = node.GetString("avs-error-response-code"); AvsPostalCodeResponseCode = node.GetString("avs-postal-code-response-code"); AvsStreetAddressResponseCode = node.GetString("avs-street-address-response-code"); GatewayRejectionReason = node.GetEnum("gateway-rejection-reason", TransactionGatewayRejectionReason.UNRECOGNIZED); PaymentInstrumentType = node.GetEnum("payment-instrument-type", PaymentInstrumentType.UNKNOWN); Channel = node.GetString("channel"); GraphQLId = node.GetString("global-id"); OrderId = node.GetString("order-id"); Status = node.GetEnum("status", TransactionStatus.UNRECOGNIZED); EscrowStatus = node.GetEnum("escrow-status", TransactionEscrowStatus.UNRECOGNIZED); List<NodeWrapper> statusNodes = node.GetList("status-history/status-event"); StatusHistory = new StatusEvent[statusNodes.Count]; for (int i = 0; i < statusNodes.Count; i++) { StatusHistory[i] = new StatusEvent(statusNodes[i]); } Type = node.GetEnum("type", TransactionType.UNRECOGNIZED); ScaExemptionRequested = node.GetString("sca-exemption-requested"); MerchantAccountId = node.GetString("merchant-account-id"); ProcessedWithNetworkToken = node.GetBoolean("processed-with-network-token"); ProcessorAuthorizationCode = node.GetString("processor-authorization-code"); ProcessorResponseCode = node.GetString("processor-response-code"); ProcessorResponseText = node.GetString("processor-response-text"); ProcessorResponseType = node.GetEnum("processor-response-type", ProcessorResponseType.UNRECOGNIZED); ProcessorSettlementResponseCode = node.GetString("processor-settlement-response-code"); ProcessorSettlementResponseText = node.GetString("processor-settlement-response-text"); NetworkResponseCode = node.GetString("network-response-code"); NetworkResponseText = node.GetString("network-response-text"); AdditionalProcessorResponse = node.GetString("additional-processor-response"); VoiceReferralNumber = node.GetString("voice-referral-number"); PurchaseOrderNumber = node.GetString("purchase-order-number"); Recurring = node.GetBoolean("recurring"); RefundedTransactionId = node.GetString("refunded-transaction-id"); RefundIds = node.GetStrings("refund-ids/*"); PartialSettlementTransactionIds = node.GetStrings("partial-settlement-transaction-ids/*"); AuthorizedTransactionId = node.GetString("authorized-transaction-id"); SettlementBatchId = node.GetString("settlement-batch-id"); PlanId = node.GetString("plan-id"); SubscriptionId = node.GetString("subscription-id"); TaxAmount = node.GetDecimal("tax-amount"); TaxExempt = node.GetBoolean("tax-exempt"); CustomFields = node.GetDictionary("custom-fields"); var creditCardNode = node.GetNode("credit-card"); if (creditCardNode != null) { CreditCard = new CreditCard(creditCardNode, gateway); } var subscriptionNode = node.GetNode("subscription"); if (subscriptionNode != null) { SubscriptionDetails = new SubscriptionDetails(subscriptionNode); } var customerNode = node.GetNode("customer"); if (customerNode != null) { CustomerDetails = new CustomerDetails(customerNode, gateway); } CurrencyIsoCode = node.GetString("currency-iso-code"); CvvResponseCode = node.GetString("cvv-response-code"); var descriptorNode = node.GetNode("descriptor"); if (descriptorNode != null) { Descriptor = new Descriptor(descriptorNode); } ServiceFeeAmount = node.GetDecimal("service-fee-amount"); var disbursementDetailsNode = node.GetNode("disbursement-details"); if (disbursementDetailsNode != null) { DisbursementDetails = new DisbursementDetails(disbursementDetailsNode); } var paypalNode = node.GetNode("paypal"); if (paypalNode != null) { PayPalDetails = new PayPalDetails(paypalNode); } var paypalHereNode = node.GetNode("paypal-here"); if (paypalHereNode != null) { PayPalHereDetails = new PayPalHereDetails(paypalHereNode); } var localPaymentNode = node.GetNode("local-payment"); if (localPaymentNode != null) { LocalPaymentDetails = new LocalPaymentDetails(localPaymentNode); } var applePayNode = node.GetNode("apple-pay"); if (applePayNode != null) { ApplePayDetails = new ApplePayDetails(applePayNode); } var androidPayNode = node.GetNode("android-pay-card"); if (androidPayNode != null) { AndroidPayDetails = new AndroidPayDetails(androidPayNode); } var venmoAccountNode = node.GetNode("venmo-account"); if (venmoAccountNode != null) { VenmoAccountDetails = new VenmoAccountDetails(venmoAccountNode); } var usBankAccountNode = node.GetNode("us-bank-account"); if (usBankAccountNode != null) { UsBankAccountDetails = new UsBankAccountDetails(usBankAccountNode); } var visaCheckoutNode = node.GetNode("visa-checkout-card"); if (visaCheckoutNode != null) { VisaCheckoutCardDetails = new VisaCheckoutCardDetails(visaCheckoutNode); } var samsungPayNode = node.GetNode("samsung-pay-card"); if (samsungPayNode != null) { SamsungPayCardDetails = new SamsungPayCardDetails(samsungPayNode); } var billingAddressNode = node.GetNode("billing"); if (billingAddressNode != null) { BillingAddress = new Address(billingAddressNode); } var shippingAddressNode = node.GetNode("shipping"); if (shippingAddressNode != null) { ShippingAddress = new Address(shippingAddressNode); } CreatedAt = node.GetDateTime("created-at"); UpdatedAt = node.GetDateTime("updated-at"); AddOns = new List<AddOn>(); foreach (var addOnResponse in node.GetList("add-ons/add-on")) { AddOns.Add(new AddOn(addOnResponse)); } Discounts = new List<Discount>(); foreach (var discountResponse in node.GetList("discounts/discount")) { Discounts.Add(new Discount(discountResponse)); } Disputes = new List<Dispute>(); foreach (var dispute in node.GetList("disputes/dispute")) { Disputes.Add(new Dispute(dispute)); } AuthorizationAdjustments = new List<AuthorizationAdjustment>(); foreach (var authorizationAdjustment in node.GetList("authorization-adjustments/authorization-adjustment")) { AuthorizationAdjustments.Add(new AuthorizationAdjustment(authorizationAdjustment)); } var riskDataNode = node.GetNode("risk-data"); if (riskDataNode != null) { RiskData = new RiskData(riskDataNode); } var threeDSecureInfoNode = node.GetNode("three-d-secure-info"); if (threeDSecureInfoNode != null && !threeDSecureInfoNode.IsEmpty()) { ThreeDSecureInfo = new ThreeDSecureInfo(threeDSecureInfoNode); } var facilitatedDetailsNode = node.GetNode("facilitated-details"); if (facilitatedDetailsNode != null && !facilitatedDetailsNode.IsEmpty()) { FacilitatedDetails = new FacilitatedDetails(facilitatedDetailsNode); } var facilitatorDetailsNode = node.GetNode("facilitator-details"); if (facilitatorDetailsNode != null && !facilitatorDetailsNode.IsEmpty()) { FacilitatorDetails = new FacilitatorDetails(facilitatorDetailsNode); } DiscountAmount = node.GetDecimal("discount-amount"); ShippingAmount = node.GetDecimal("shipping-amount"); ShipsFromPostalCode = node.GetString("ships-from-postal-code"); NetworkTransactionId = node.GetString("network-transaction-id"); AuthorizationExpiresAt = node.GetDateTime("authorization-expires-at"); RetrievalReferenceNumber = node.GetString("retrieval-reference-number"); AcquirerReferenceNumber = node.GetString("acquirer-reference-number"); InstallmentCount = node.GetDecimal("installment-count"); Installments = new List<Installment>(); foreach (var installment in node.GetList("installments/installment")) { Installments.Add(new Installment(installment)); } RefundedInstallments = new List<Installment>(); foreach (var installment in node.GetList("refunded-installments/refunded-installment")) { RefundedInstallments.Add(new Installment(installment)); } } /// <summary> /// Returns the current <see cref="CreditCard"/> associated with this transaction if one exists /// </summary> /// <returns> /// The current <see cref="CreditCard"/> associated with this transaction if one exists /// </returns> /// <remarks> /// When retrieving a transaction from the gateway, the credit card used in the transaction is returned in the response. /// If the credit card record has been updated in the vault since the transaction occurred, this method can be used to /// retrieve the updated credit card information. This is typically useful in situations where a transaction fails, for /// example when a credit card expires, and a new transaction needs to be submitted once the new credit card information /// has been submitted. /// </remarks> /// <example> /// The vault <see cref="CreditCard"/> can be retrieved from the transaction directly: /// <code> /// Transaction transaction = gateway.Transaction.Find("transactionId"); /// CreditCard creditCard = transaction.GetVaultCreditCard(); /// </code> /// </example> /// <example> /// Failed transactions can be resubmitted with updated <see cref="CreditCard"/> information: /// <code> /// Transaction failedTransaction = gateway.Transaction.Find("transactionId"); /// CreditCard updatedCreditCard = transaction.GetVaultCreditCard(); /// /// TransactionRequest request = new TransactionRequest /// { /// Amount = failedTransaction.Amount, /// PaymentMethodToken = updatedCreditCard.Token /// }; /// /// Result&lt;Transaction&gt; result = gateway.Transaction.Sale(request); /// </code> /// </example> public virtual CreditCard GetVaultCreditCard() { if (CreditCard.Token == null) return null; return new CreditCardGateway(Gateway).Find(CreditCard.Token); } /// <summary> /// Returns the current <see cref="Customer"/> associated with this transaction if one exists /// </summary> /// <returns> /// The current <see cref="Customer"/> associated with this transaction if one exists /// </returns> /// <remarks> /// When retrieving a transaction from the gateway, the customer associated with the transaction is returned in the response. /// If the customer record has been updated in the vault since the transaction occurred, this method can be used to /// retrieve the updated customer information. /// </remarks> /// <example> /// The vault <see cref="Customer"/> can be retrieved from the transaction directly: /// <code> /// Transaction transaction = gateway.Transaction.Find("transactionId"); /// Customer customer = transaction.GetVaultCustomer(); /// </code> /// </example> public virtual Customer GetVaultCustomer() { if (CustomerDetails == null || CustomerDetails.Id == null) return null; return new CustomerGateway(Gateway).Find(CustomerDetails.Id); } /// <summary> /// Returns the current billing <see cref="Address"/> associated with this transaction if one exists /// </summary> /// <returns> /// The current billing <see cref="Address"/> associated with this transaction if one exists /// </returns> /// <remarks> /// When retrieving a transaction from the gateway, the billing address associated with the transaction is returned in the response. /// If the billing address has been updated in the vault since the transaction occurred, this method can be used to /// retrieve the updated billing address. /// </remarks> /// <example> /// The vault billing <see cref="Address"/> can be retrieved from the transaction directly: /// <code> /// Transaction transaction = gateway.Transaction.Find("transactionId"); /// Address billingAddress = transaction.GetVaultBillingAddress(); /// </code> /// </example> public virtual Address GetVaultBillingAddress() { if (BillingAddress.Id == null) return null; return new AddressGateway(Gateway).Find(CustomerDetails.Id, BillingAddress.Id); } /// <summary> /// Returns the current shipping <see cref="Address"/> associated with this transaction if one exists /// </summary> /// <returns> /// The current shipping <see cref="Address"/> associated with this transaction if one exists /// </returns> /// <remarks> /// When retrieving a transaction from the gateway, the shipping address associated with the transaction is returned in the response. /// If the shipping address has been updated in the vault since the transaction occurred, this method can be used to /// retrieve the updated shipping address. /// </remarks> /// <example> /// The vault shipping <see cref="Address"/> can be retrieved from the transaction directly: /// <code> /// Transaction transaction = gateway.Transaction.Find("transactionId"); /// Address shippingAddress = transaction.GetVaultShippingAddress(); /// </code> /// </example> public virtual Address GetVaultShippingAddress() { if (ShippingAddress.Id == null) return null; return new AddressGateway(Gateway).Find(CustomerDetails.Id, ShippingAddress.Id); } public bool IsDisbursed() { return DisbursementDetails.IsValid(); } /// <summary> /// Returns the list of <see cref="TransactionLineItem"/>s associated with this transaction /// </summary> /// <returns> /// The list of <see cref="TransactionLineItem"/>s associated with this transaction /// </returns> /// <example> /// The list of <see cref="TransactionLineItem"/>s can be retrieved from the transaction directly: /// <code> /// Transaction transaction = gateway.Transaction.Find("transactionId"); /// List&lt;TransactionLineItem&gt; lineItems = transaction.GetLineItems(); /// </code> /// </example> public virtual List<TransactionLineItem> GetLineItems() { return Gateway.TransactionLineItem.FindAll(Id); } } }
using System.Collections.Generic; using System.Diagnostics; namespace IxMilia.Dxf.Objects { public enum DxfFlowDirection { Down = 0, Up = 1 } public class DxfTableCellStyle { public string Name { get; set; } public double TextHeight { get; set; } public short CellAlignment { get; set; } public DxfColor TextColor { get; set; } = DxfColor.ByBlock; public DxfColor CellFillColor { get; set; } = DxfColor.FromRawValue(7); public bool IsBackgroundColorEnabled { get; set; } public int CellDataType { get; set; } public int CellUnitType { get; set; } public short BorderLineweight1 { get; set; } public short BorderLineweight2 { get; set; } public short BorderLineweight3 { get; set; } public short BorderLineweight4 { get; set; } public short BorderLineweight5 { get; set; } public short BorderLineweight6 { get; set; } public bool IsBorder1Visible { get; set; } = true; public bool IsBorder2Visible { get; set; } = true; public bool IsBorder3Visible { get; set; } = true; public bool IsBorder4Visible { get; set; } = true; public bool IsBorder5Visible { get; set; } = true; public bool IsBorder6Visible { get; set; } = true; public DxfColor Border1Color { get; set; } = DxfColor.ByBlock; public DxfColor Border2Color { get; set; } = DxfColor.ByBlock; public DxfColor Border3Color { get; set; } = DxfColor.ByBlock; public DxfColor Border4Color { get; set; } = DxfColor.ByBlock; public DxfColor Border5Color { get; set; } = DxfColor.ByBlock; public DxfColor Border6Color { get; set; } = DxfColor.ByBlock; internal static DxfTableCellStyle FromBuffer(DxfCodePairBufferReader buffer) { var seenName = false; var style = new DxfTableCellStyle(); while (buffer.ItemsRemain) { var pair = buffer.Peek(); switch (pair.Code) { case 7: if (seenName) { // found another cell style; return without consuming return style; } else { style.Name = pair.StringValue; seenName = true; } break; case 62: style.TextColor = DxfColor.FromRawValue(pair.ShortValue); break; case 63: style.CellFillColor = DxfColor.FromRawValue(pair.ShortValue); break; case 64: style.Border1Color = DxfColor.FromRawValue(pair.ShortValue); break; case 65: style.Border2Color = DxfColor.FromRawValue(pair.ShortValue); break; case 66: style.Border3Color = DxfColor.FromRawValue(pair.ShortValue); break; case 67: style.Border4Color = DxfColor.FromRawValue(pair.ShortValue); break; case 68: style.Border5Color = DxfColor.FromRawValue(pair.ShortValue); break; case 69: style.Border6Color = DxfColor.FromRawValue(pair.ShortValue); break; case 90: style.CellDataType = pair.IntegerValue; break; case 91: style.CellUnitType = pair.IntegerValue; break; case 140: style.TextHeight = pair.DoubleValue; break; case 170: style.CellAlignment = pair.ShortValue; break; case 274: style.BorderLineweight1 = pair.ShortValue; break; case 275: style.BorderLineweight2 = pair.ShortValue; break; case 276: style.BorderLineweight3 = pair.ShortValue; break; case 277: style.BorderLineweight4 = pair.ShortValue; break; case 278: style.BorderLineweight5 = pair.ShortValue; break; case 279: style.BorderLineweight6 = pair.ShortValue; break; case 283: style.IsBackgroundColorEnabled = DxfCommonConverters.BoolShort(pair.ShortValue); break; case 284: style.IsBorder1Visible = DxfCommonConverters.BoolShort(pair.ShortValue); break; case 285: style.IsBorder2Visible = DxfCommonConverters.BoolShort(pair.ShortValue); break; case 286: style.IsBorder3Visible = DxfCommonConverters.BoolShort(pair.ShortValue); break; case 287: style.IsBorder4Visible = DxfCommonConverters.BoolShort(pair.ShortValue); break; case 288: style.IsBorder5Visible = DxfCommonConverters.BoolShort(pair.ShortValue); break; case 289: style.IsBorder6Visible = DxfCommonConverters.BoolShort(pair.ShortValue); break; default: // unknown code, return without consuming the pair return style; } buffer.Advance(); } return style; } } public partial class DxfTableStyle { internal override DxfObject PopulateFromBuffer(DxfCodePairBufferReader buffer) { int code_280_index = 0; while (buffer.ItemsRemain) { var pair = buffer.Peek(); if (pair.Code == 0) { break; } while (this.TrySetExtensionData(pair, buffer)) { pair = buffer.Peek(); } if (pair.Code == 0) { break; } switch (pair.Code) { case 3: this.Description = (pair.StringValue); buffer.Advance(); break; case 7: var style = DxfTableCellStyle.FromBuffer(buffer); CellStyles.Add(style); break; case 40: this.HorizontalCellMargin = (pair.DoubleValue); buffer.Advance(); break; case 41: this.VerticalCellMargin = (pair.DoubleValue); buffer.Advance(); break; case 70: this.FlowDirection = (DxfFlowDirection)(pair.ShortValue); buffer.Advance(); break; case 71: this.Flags = (pair.ShortValue); buffer.Advance(); break; case 280: switch (code_280_index) { case 0: this.Version = (DxfVersion)(pair.ShortValue); code_280_index++; break; case 1: this.IsTitleSuppressed = BoolShort(pair.ShortValue); code_280_index++; break; default: Debug.Assert(false, "Unexpected extra values for code 280"); break; } buffer.Advance(); break; case 281: this.IsColumnHeadingSuppressed = BoolShort(pair.ShortValue); buffer.Advance(); break; default: if (!base.TrySetPair(pair)) { ExcessCodePairs.Add(pair); } buffer.Advance(); break; } } return PostParse(); } } }
namespace More.Collections.Generic { using FluentAssertions; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Xunit; public class ObservableStackTTest { [Fact] public void new_observable_stack_should_initialize_items() { // arrange var expected = new[] { "1", "2", "3" }; // act var stack = new ObservableStack<string>( expected ); // assert stack.Should().Equal( expected.Reverse() ); } [Fact] public void push_should_raise_events() { // arrange var expected = "1"; var stack = new ObservableStack<string>(); stack.MonitorEvents(); // act stack.Push( expected ); // assert stack.Peek().Should().Be( expected ); stack.ShouldRaisePropertyChangeFor( s => s.Count ); } [Fact] public void pop_should_raise_events() { // arrange var expected = "1"; var stack = new ObservableStack<string>(); stack.Push( expected ); stack.MonitorEvents(); // act var result = stack.Pop(); // assert result.Should().Be( expected ); stack.ShouldRaisePropertyChangeFor( s => s.Count ); } [Fact] public void pop_should_not_be_allowed_when_empty() { // arrange var stack = new ObservableStack<string>(); // act Action pop = () => stack.Pop(); // assert pop.ShouldThrow<InvalidOperationException>(); } [Fact] public void peek_should_return_last_item() { // arrange var stack = new ObservableStack<string>(); stack.Push( "2" ); stack.Push( "1" ); stack.Push( "3" ); // act var result = stack.Peek(); // assert result.Should().Be( "3" ); } [Fact] public void peek_should_not_be_allowed_when_empty() { // arrange var stack = new ObservableStack<string>(); // act Action peek = () => stack.Peek(); // assert peek.ShouldThrow<InvalidOperationException>(); } [Fact] public void to_array_should_return_items_in_sequence() { // arrange var stack = new ObservableStack<string>(); var expected = new[] { "3", "2", "1" }; stack.Push( "1" ); stack.Push( "2" ); stack.Push( "3" ); // act var items = stack.ToArray(); // assert items.Should().Equal( expected ); } [Fact] public void trim_should_remove_excess() { // arrange var stack = new ObservableStack<string>( 10 ); stack.Push( "1" ); stack.Push( "2" ); stack.Push( "3" ); // act Action trimExcess = stack.TrimExcess; // assert trimExcess.ShouldNotThrow(); } [Theory] [InlineData( "Two", true )] [InlineData( "Four", false )] [InlineData( null, false )] public void contains_should_return_expected_result( string value, bool expected ) { // arrange var stack = new ObservableStack<string>(); stack.Push( "One" ); stack.Push( "Two" ); stack.Push( "Three" ); // act var result = stack.Contains( value ); // assert result.Should().Be( expected ); } [Fact] public void copy_should_copy_items() { // arrange var expected = new[] { "1", "2" }; var stack = new ObservableStack<string>( expected ); var items = new string[2]; // act stack.CopyTo( items, 0 ); // assert items.Should().Equal( expected.Reverse() ); } [Fact] public void copy_should_copy_items_with_offset() { // arrange var expected = new[] { "1", "2" }; var stack = new ObservableStack<string>( expected ); var items = new string[4]; // act stack.CopyTo( items, 2 ); // assert items.Skip( 2 ).Should().Equal( expected.Reverse() ); } [Fact] public void copy_should_copy_untyped_items() { // arrange var stack = new ObservableStack<string>(); var collection = (ICollection) stack; var expected = new[] { "1", "2" }; var items = new string[2]; stack.Push( "1" ); stack.Push( "2" ); // act collection.CopyTo( items, 0 ); // assert items.Should().Equal( expected.Reverse() ); } [Fact] public void clear_should_raise_events() { // arrange var stack = new ObservableStack<string>(); stack.Push( "1" ); stack.MonitorEvents(); // act stack.Clear(); // assert stack.Should().BeEmpty(); stack.ShouldRaisePropertyChangeFor( s => s.Count ); } [Fact] public void observable_stack_should_not_be_synchronized() { // arrange var stack = (ICollection) new ObservableStack<string>(); // act // assert stack.IsSynchronized.Should().BeFalse(); stack.SyncRoot.Should().NotBeNull(); } [Fact] public void observable_stack_should_enumerate_in_typed_sequence() { // arrange var stack = new ObservableStack<string>(); stack.Push( "1" ); stack.Push( "2" ); stack.Push( "3" ); // act IEnumerable<string> items = stack; // assert items.Should().BeEquivalentTo( new[] { "1", "2", "3" } ); } [Fact] public void observable_stack_should_enumerate_in_untyped_sequence() { // arrange var stack = new ObservableStack<string>(); stack.Push( "1" ); stack.Push( "2" ); stack.Push( "3" ); // act IEnumerable items = stack; // assert items.Should().BeEquivalentTo( new[] { "1", "2", "3" } ); } [Fact] public void observable_stack_should_grow_dynamically() { // arrange var stack = new ObservableStack<string>( 3 ); // act for ( var i = 0; i < 10; i++ ) { stack.Push( ( i + 1 ).ToString() ); } // assert stack.Clear(); stack.TrimExcess(); } } }
/* * 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. */ // Uncomment to make asset Get requests for existing // #define WAIT_ON_INPROGRESS_REQUESTS using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Timers; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; //[assembly: Addin("FlotsamAssetCache", "1.1")] //[assembly: AddinDependency("OpenSim", "0.5")] namespace OpenSim.Region.CoreModules.Asset { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FlotsamAssetCache")] public class FlotsamAssetCache : ISharedRegionModule, IImprovedAssetCache, IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private bool m_Enabled; private const string m_ModuleName = "FlotsamAssetCache"; private const string m_DefaultCacheDirectory = "./assetcache"; private string m_CacheDirectory = m_DefaultCacheDirectory; private readonly List<char> m_InvalidChars = new List<char>(); private int m_LogLevel = 0; private ulong m_HitRateDisplay = 100; // How often to display hit statistics, given in requests private static ulong m_Requests; private static ulong m_RequestsForInprogress; private static ulong m_DiskHits; private static ulong m_MemoryHits; #if WAIT_ON_INPROGRESS_REQUESTS private Dictionary<string, ManualResetEvent> m_CurrentlyWriting = new Dictionary<string, ManualResetEvent>(); private int m_WaitOnInprogressTimeout = 3000; #else private HashSet<string> m_CurrentlyWriting = new HashSet<string>(); #endif private bool m_FileCacheEnabled = true; private ExpiringCache<string, AssetBase> m_MemoryCache; private bool m_MemoryCacheEnabled = false; // Expiration is expressed in hours. private const double m_DefaultMemoryExpiration = 2; private const double m_DefaultFileExpiration = 48; private TimeSpan m_MemoryExpiration = TimeSpan.FromHours(m_DefaultMemoryExpiration); private TimeSpan m_FileExpiration = TimeSpan.FromHours(m_DefaultFileExpiration); private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.FromHours(0.166); private static int m_CacheDirectoryTiers = 1; private static int m_CacheDirectoryTierLen = 3; private static int m_CacheWarnAt = 30000; private System.Timers.Timer m_CacheCleanTimer; private IAssetService m_AssetService; private List<Scene> m_Scenes = new List<Scene>(); public FlotsamAssetCache() { m_InvalidChars.AddRange(Path.GetInvalidPathChars()); m_InvalidChars.AddRange(Path.GetInvalidFileNameChars()); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return m_ModuleName; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AssetCaching", String.Empty); if (name == Name) { m_MemoryCache = new ExpiringCache<string, AssetBase>(); m_Enabled = true; m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name); IConfig assetConfig = source.Configs["AssetCache"]; if (assetConfig == null) { m_log.Debug( "[FLOTSAM ASSET CACHE]: AssetCache section missing from config (not copied config-include/FlotsamCache.ini.example? Using defaults."); } else { m_FileCacheEnabled = assetConfig.GetBoolean("FileCacheEnabled", m_FileCacheEnabled); m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory); m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", m_MemoryCacheEnabled); m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration)); #if WAIT_ON_INPROGRESS_REQUESTS m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000); #endif m_LogLevel = assetConfig.GetInt("LogLevel", m_LogLevel); m_HitRateDisplay = (ulong)assetConfig.GetLong("HitRateDisplay", (long)m_HitRateDisplay); m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration)); m_FileExpirationCleanupTimer = TimeSpan.FromHours( assetConfig.GetDouble("FileCleanupTimer", m_FileExpirationCleanupTimer.TotalHours)); m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", m_CacheDirectoryTiers); m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", m_CacheDirectoryTierLen); m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", m_CacheWarnAt); } m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory {0}", m_CacheDirectory); if (m_FileCacheEnabled && (m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero)) { m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds); m_CacheCleanTimer.AutoReset = true; m_CacheCleanTimer.Elapsed += CleanupExpiredFiles; lock (m_CacheCleanTimer) m_CacheCleanTimer.Start(); } if (m_CacheDirectoryTiers < 1) { m_CacheDirectoryTiers = 1; } else if (m_CacheDirectoryTiers > 3) { m_CacheDirectoryTiers = 3; } if (m_CacheDirectoryTierLen < 1) { m_CacheDirectoryTierLen = 1; } else if (m_CacheDirectoryTierLen > 4) { m_CacheDirectoryTierLen = 4; } MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand); MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache clear", "fcache clear [file] [memory]", "Remove all assets in the cache. If file or memory is specified then only this cache is cleared.", HandleConsoleCommand); MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand); MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IImprovedAssetCache>(this); m_Scenes.Add(scene); } } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IImprovedAssetCache>(this); m_Scenes.Remove(scene); } } public void RegionLoaded(Scene scene) { if (m_Enabled && m_AssetService == null) m_AssetService = scene.RequestModuleInterface<IAssetService>(); } //////////////////////////////////////////////////////////// // IImprovedAssetCache // private void UpdateMemoryCache(string key, AssetBase asset) { m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration); } private void UpdateFileCache(string key, AssetBase asset) { string filename = GetFileName(key); try { // If the file is already cached, don't cache it, just touch it so access time is updated if (File.Exists(filename)) { // We don't really want to know about sharing // violations here. If the file is locked, then // the other thread has updated the time for us. try { lock (m_CurrentlyWriting) { if (!m_CurrentlyWriting.Contains(filename)) File.SetLastAccessTime(filename, DateTime.Now); } } catch { } } else { // Once we start writing, make sure we flag that we're writing // that object to the cache so that we don't try to write the // same file multiple times. lock (m_CurrentlyWriting) { #if WAIT_ON_INPROGRESS_REQUESTS if (m_CurrentlyWriting.ContainsKey(filename)) { return; } else { m_CurrentlyWriting.Add(filename, new ManualResetEvent(false)); } #else if (m_CurrentlyWriting.Contains(filename)) { return; } else { m_CurrentlyWriting.Add(filename); } #endif } Util.FireAndForget( delegate { WriteFileCache(filename, asset); }); } } catch (Exception e) { m_log.ErrorFormat( "[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}", asset.ID, e.Message, e.StackTrace); } } public void Cache(AssetBase asset) { // TODO: Spawn this off to some seperate thread to do the actual writing if (asset != null) { //m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID); if (m_MemoryCacheEnabled) UpdateMemoryCache(asset.ID, asset); if (m_FileCacheEnabled) UpdateFileCache(asset.ID, asset); } } /// <summary> /// Try to get an asset from the in-memory cache. /// </summary> /// <param name="id"></param> /// <returns></returns> private AssetBase GetFromMemoryCache(string id) { AssetBase asset = null; if (m_MemoryCache.TryGetValue(id, out asset)) m_MemoryHits++; return asset; } private bool CheckFromMemoryCache(string id) { return m_MemoryCache.Contains(id); } /// <summary> /// Try to get an asset from the file cache. /// </summary> /// <param name="id"></param> /// <returns>An asset retrieved from the file cache. null if there was a problem retrieving an asset.</returns> private AssetBase GetFromFileCache(string id) { string filename = GetFileName(id); #if WAIT_ON_INPROGRESS_REQUESTS // Check if we're already downloading this asset. If so, try to wait for it to // download. if (m_WaitOnInprogressTimeout > 0) { m_RequestsForInprogress++; ManualResetEvent waitEvent; if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent)) { waitEvent.WaitOne(m_WaitOnInprogressTimeout); return Get(id); } } #else // Track how often we have the problem that an asset is requested while // it is still being downloaded by a previous request. if (m_CurrentlyWriting.Contains(filename)) { m_RequestsForInprogress++; return null; } #endif AssetBase asset = null; if (File.Exists(filename)) { try { using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFormatter bformatter = new BinaryFormatter(); asset = (AssetBase)bformatter.Deserialize(stream); m_DiskHits++; } } catch (System.Runtime.Serialization.SerializationException e) { m_log.WarnFormat( "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}", filename, id, e.Message, e.StackTrace); // If there was a problem deserializing the asset, the asset may // either be corrupted OR was serialized under an old format // {different version of AssetBase} -- we should attempt to // delete it and re-cache File.Delete(filename); } catch (Exception e) { m_log.WarnFormat( "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}", filename, id, e.Message, e.StackTrace); } } return asset; } private bool CheckFromFileCache(string id) { bool found = false; string filename = GetFileName(id); if (File.Exists(filename)) { try { using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (stream != null) found = true; } } catch (Exception e) { m_log.ErrorFormat( "[FLOTSAM ASSET CACHE]: Failed to check file {0} for asset {1}. Exception {2} {3}", filename, id, e.Message, e.StackTrace); } } return found; } public AssetBase Get(string id) { m_Requests++; AssetBase asset = null; if (m_MemoryCacheEnabled) asset = GetFromMemoryCache(id); if (asset == null && m_FileCacheEnabled) { asset = GetFromFileCache(id); if (m_MemoryCacheEnabled && asset != null) UpdateMemoryCache(id, asset); } if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0)) { m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit"); GenerateCacheHitReport().ForEach(l => m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0}", l)); } return asset; } public bool Check(string id) { if (m_MemoryCacheEnabled && CheckFromMemoryCache(id)) return true; if (m_FileCacheEnabled && CheckFromFileCache(id)) return true; return false; } public AssetBase GetCached(string id) { return Get(id); } public void Expire(string id) { if (m_LogLevel >= 2) m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id); try { if (m_FileCacheEnabled) { string filename = GetFileName(id); if (File.Exists(filename)) { File.Delete(filename); } } if (m_MemoryCacheEnabled) m_MemoryCache.Remove(id); } catch (Exception e) { m_log.WarnFormat( "[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}", id, e.Message, e.StackTrace); } } public void Clear() { if (m_LogLevel >= 2) m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches."); if (m_FileCacheEnabled) { foreach (string dir in Directory.GetDirectories(m_CacheDirectory)) { Directory.Delete(dir); } } if (m_MemoryCacheEnabled) m_MemoryCache.Clear(); } private void CleanupExpiredFiles(object source, ElapsedEventArgs e) { if (m_LogLevel >= 2) m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration); // Purge all files last accessed prior to this point DateTime purgeLine = DateTime.Now - m_FileExpiration; // An asset cache may contain local non-temporary assets that are not in the asset service. Therefore, // before cleaning up expired files we must scan the objects in the scene to make sure that we retain // such local assets if they have not been recently accessed. TouchAllSceneAssets(false); foreach (string dir in Directory.GetDirectories(m_CacheDirectory)) { CleanExpiredFiles(dir, purgeLine); } } /// <summary> /// Recurses through specified directory checking for asset files last /// accessed prior to the specified purge line and deletes them. Also /// removes empty tier directories. /// </summary> /// <param name="dir"></param> /// <param name="purgeLine"></param> private void CleanExpiredFiles(string dir, DateTime purgeLine) { try { foreach (string file in Directory.GetFiles(dir)) { if (File.GetLastAccessTime(file) < purgeLine) { File.Delete(file); } } // Recurse into lower tiers foreach (string subdir in Directory.GetDirectories(dir)) { CleanExpiredFiles(subdir, purgeLine); } // Check if a tier directory is empty, if so, delete it int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length; if (dirSize == 0) { Directory.Delete(dir); } else if (dirSize >= m_CacheWarnAt) { m_log.WarnFormat( "[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration", dir, dirSize); } } catch (Exception e) { m_log.Warn( string.Format("[FLOTSAM ASSET CACHE]: Could not complete clean of expired files in {0}, exception ", dir), e); } } /// <summary> /// Determines the filename for an AssetID stored in the file cache /// </summary> /// <param name="id"></param> /// <returns></returns> private string GetFileName(string id) { // Would it be faster to just hash the darn thing? foreach (char c in m_InvalidChars) { id = id.Replace(c, '_'); } string path = m_CacheDirectory; for (int p = 1; p <= m_CacheDirectoryTiers; p++) { string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen); path = Path.Combine(path, pathPart); } return Path.Combine(path, id); } /// <summary> /// Writes a file to the file cache, creating any nessesary /// tier directories along the way /// </summary> /// <param name="filename"></param> /// <param name="asset"></param> private void WriteFileCache(string filename, AssetBase asset) { Stream stream = null; // Make sure the target cache directory exists string directory = Path.GetDirectoryName(filename); // Write file first to a temp name, so that it doesn't look // like it's already cached while it's still writing. string tempname = Path.Combine(directory, Path.GetRandomFileName()); try { try { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } stream = File.Open(tempname, FileMode.Create); BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(stream, asset); } catch (IOException e) { m_log.WarnFormat( "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.", asset.ID, tempname, filename, directory, e.Message, e.StackTrace); return; } finally { if (stream != null) stream.Close(); } try { // Now that it's written, rename it so that it can be found. // // File.Copy(tempname, filename, true); // File.Delete(tempname); // // For a brief period, this was done as a separate copy and then temporary file delete operation to // avoid an IOException caused by move if some competing thread had already written the file. // However, this causes exceptions on Windows when other threads attempt to read a file // which is still being copied. So instead, go back to moving the file and swallow any IOException. // // This situation occurs fairly rarely anyway. We assume in this that moves are atomic on the // filesystem. File.Move(tempname, filename); if (m_LogLevel >= 2) m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID); } catch (IOException) { // If we see an IOException here it's likely that some other competing thread has written the // cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be // signally by the earlier temporary file writing code. } } finally { // Even if the write fails with an exception, we need to make sure // that we release the lock on that file, otherwise it'll never get // cached lock (m_CurrentlyWriting) { #if WAIT_ON_INPROGRESS_REQUESTS ManualResetEvent waitEvent; if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent)) { m_CurrentlyWriting.Remove(filename); waitEvent.Set(); } #else m_CurrentlyWriting.Remove(filename); #endif } } } /// <summary> /// Scan through the file cache, and return number of assets currently cached. /// </summary> /// <param name="dir"></param> /// <returns></returns> private int GetFileCacheCount(string dir) { int count = Directory.GetFiles(dir).Length; foreach (string subdir in Directory.GetDirectories(dir)) { count += GetFileCacheCount(subdir); } return count; } /// <summary> /// This notes the last time the Region had a deep asset scan performed on it. /// </summary> /// <param name="regionID"></param> private void StampRegionStatusFile(UUID regionID) { string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + regionID.ToString() + ".fac"); try { if (File.Exists(RegionCacheStatusFile)) { File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now); } else { File.WriteAllText( RegionCacheStatusFile, "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache."); } } catch (Exception e) { m_log.Warn( string.Format( "[FLOTSAM ASSET CACHE]: Could not stamp region status file for region {0}. Exception ", regionID), e); } } /// <summary> /// Iterates through all Scenes, doing a deep scan through assets /// to update the access time of all assets present in the scene or referenced by assets /// in the scene. /// </summary> /// <param name="storeUncached"> /// If true, then assets scanned which are not found in cache are added to the cache. /// </param> /// <returns>Number of distinct asset references found in the scene.</returns> private int TouchAllSceneAssets(bool storeUncached) { UuidGatherer gatherer = new UuidGatherer(m_AssetService); HashSet<UUID> uniqueUuids = new HashSet<UUID>(); Dictionary<UUID, sbyte> assets = new Dictionary<UUID, sbyte>(); foreach (Scene s in m_Scenes) { StampRegionStatusFile(s.RegionInfo.RegionID); s.ForEachSOG(delegate(SceneObjectGroup e) { gatherer.GatherAssetUuids(e, assets); foreach (UUID assetID in assets.Keys) { uniqueUuids.Add(assetID); string filename = GetFileName(assetID.ToString()); if (File.Exists(filename)) { File.SetLastAccessTime(filename, DateTime.Now); } else if (storeUncached) { AssetBase cachedAsset = m_AssetService.Get(assetID.ToString()); if (cachedAsset == null && assets[assetID] != (sbyte)AssetType.Unknown) m_log.DebugFormat( "[FLOTSAM ASSET CACHE]: Could not find asset {0}, type {1} referenced by object {2} at {3} in scene {4} when pre-caching all scene assets", assetID, assets[assetID], e.Name, e.AbsolutePosition, s.Name); } } assets.Clear(); }); } return uniqueUuids.Count; } /// <summary> /// Deletes all cache contents /// </summary> private void ClearFileCache() { foreach (string dir in Directory.GetDirectories(m_CacheDirectory)) { try { Directory.Delete(dir, true); } catch (Exception e) { m_log.WarnFormat( "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}", dir, m_CacheDirectory, e.Message, e.StackTrace); } } foreach (string file in Directory.GetFiles(m_CacheDirectory)) { try { File.Delete(file); } catch (Exception e) { m_log.WarnFormat( "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}", file, m_CacheDirectory, e.Message, e.StackTrace); } } } private List<string> GenerateCacheHitReport() { List<string> outputLines = new List<string>(); double fileHitRate = (double)m_DiskHits / m_Requests * 100.0; outputLines.Add( string.Format("File Hit Rate: {0}% for {1} requests", fileHitRate.ToString("0.00"), m_Requests)); if (m_MemoryCacheEnabled) { double memHitRate = (double)m_MemoryHits / m_Requests * 100.0; outputLines.Add( string.Format("Memory Hit Rate: {0}% for {1} requests", memHitRate.ToString("0.00"), m_Requests)); } outputLines.Add( string.Format( "Unnecessary requests due to requests for assets that are currently downloading: {0}", m_RequestsForInprogress)); return outputLines; } #region Console Commands private void HandleConsoleCommand(string module, string[] cmdparams) { ICommandConsole con = MainConsole.Instance; if (cmdparams.Length >= 2) { string cmd = cmdparams[1]; switch (cmd) { case "status": if (m_MemoryCacheEnabled) con.OutputFormat("Memory Cache: {0} assets", m_MemoryCache.Count); else con.OutputFormat("Memory cache disabled"); if (m_FileCacheEnabled) { int fileCount = GetFileCacheCount(m_CacheDirectory); con.OutputFormat("File Cache: {0} assets", fileCount); } else { con.Output("File cache disabled"); } GenerateCacheHitReport().ForEach(l => con.Output(l)); if (m_FileCacheEnabled) { con.Output("Deep scans have previously been performed on the following regions:"); foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac")) { string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac",""); DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s); con.OutputFormat("Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss")); } } break; case "clear": if (cmdparams.Length < 2) { con.Output("Usage is fcache clear [file] [memory]"); break; } bool clearMemory = false, clearFile = false; if (cmdparams.Length == 2) { clearMemory = true; clearFile = true; } foreach (string s in cmdparams) { if (s.ToLower() == "memory") clearMemory = true; else if (s.ToLower() == "file") clearFile = true; } if (clearMemory) { if (m_MemoryCacheEnabled) { m_MemoryCache.Clear(); con.Output("Memory cache cleared."); } else { con.Output("Memory cache not enabled."); } } if (clearFile) { if (m_FileCacheEnabled) { ClearFileCache(); con.Output("File cache cleared."); } else { con.Output("File cache not enabled."); } } break; case "assets": con.Output("Ensuring assets are cached for all scenes."); Util.RunThreadNoTimeout(delegate { int assetReferenceTotal = TouchAllSceneAssets(true); con.OutputFormat("Completed check with {0} assets.", assetReferenceTotal); }, "TouchAllSceneAssets", null); break; case "expire": if (cmdparams.Length < 3) { con.OutputFormat("Invalid parameters for Expire, please specify a valid date & time", cmd); break; } string s_expirationDate = ""; DateTime expirationDate; if (cmdparams.Length > 3) { s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2); } else { s_expirationDate = cmdparams[2]; } if (!DateTime.TryParse(s_expirationDate, out expirationDate)) { con.OutputFormat("{0} is not a valid date & time", cmd); break; } if (m_FileCacheEnabled) CleanExpiredFiles(m_CacheDirectory, expirationDate); else con.OutputFormat("File cache not active, not clearing."); break; default: con.OutputFormat("Unknown command {0}", cmd); break; } } else if (cmdparams.Length == 1) { con.Output("fcache assets - Attempt a deep cache of all assets in all scenes"); con.Output("fcache expire <datetime> - Purge assets older then the specified date & time"); con.Output("fcache clear [file] [memory] - Remove cached assets"); con.Output("fcache status - Display cache status"); } } #endregion #region IAssetService Members public AssetMetadata GetMetadata(string id) { AssetBase asset = Get(id); return asset.Metadata; } public byte[] GetData(string id) { AssetBase asset = Get(id); return asset.Data; } public bool Get(string id, object sender, AssetRetrieved handler) { AssetBase asset = Get(id); handler(id, sender, asset); return true; } public bool[] AssetsExist(string[] ids) { bool[] exist = new bool[ids.Length]; for (int i = 0; i < ids.Length; i++) { exist[i] = Check(ids[i]); } return exist; } public string Store(AssetBase asset) { if (asset.FullID == UUID.Zero) { asset.FullID = UUID.Random(); } Cache(asset); return asset.ID; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = Get(id); asset.Data = data; Cache(asset); return true; } public bool Delete(string id) { Expire(id); return true; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableHashSetBuilderTest : ImmutablesTestBase { [Fact] public void CreateBuilder() { var builder = ImmutableHashSet.CreateBuilder<string>(); Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer); builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); } [Fact] public void ToBuilder() { var builder = ImmutableHashSet<int>.Empty.ToBuilder(); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(2, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set = builder.ToImmutable(); Assert.Equal(builder.Count, set.Count); Assert.True(builder.Add(8)); Assert.Equal(3, builder.Count); Assert.Equal(2, set.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); } [Fact] public void BuilderFromSet() { var set = ImmutableHashSet<int>.Empty.Add(1); var builder = set.ToBuilder(); Assert.True(builder.Contains(1)); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(3, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set2 = builder.ToImmutable(); Assert.Equal(builder.Count, set2.Count); Assert.True(set2.Contains(1)); Assert.True(builder.Add(8)); Assert.Equal(4, builder.Count); Assert.Equal(3, set2.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); Assert.False(set2.Contains(8)); } [Fact] public void EnumerateBuilderWhileMutating() { var builder = ImmutableHashSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder(); CollectionAssertAreEquivalent(Enumerable.Range(1, 10).ToArray(), builder.ToArray()); var enumerator = builder.GetEnumerator(); Assert.True(enumerator.MoveNext()); builder.Add(11); // Verify that a new enumerator will succeed. CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray()); // Try enumerating further with the previous enumerable now that we've changed the collection. Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.Reset(); enumerator.MoveNext(); // resetting should fix the problem. // Verify that by obtaining a new enumerator, we can enumerate all the contents. CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray()); } [Fact] public void BuilderReusesUnchangedImmutableInstances() { var collection = ImmutableHashSet<int>.Empty.Add(1); var builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // no changes at all. builder.Add(2); var newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. } [Fact] public void EnumeratorTest() { var builder = ImmutableHashSet.Create(1).ToBuilder(); ManuallyEnumerateTest(new[] { 1 }, ((IEnumerable<int>)builder).GetEnumerator()); } [Fact] public void Clear() { var set = ImmutableHashSet.Create(1); var builder = set.ToBuilder(); builder.Clear(); Assert.Equal(0, builder.Count); } [Fact] public void KeyComparer() { var builder = ImmutableHashSet.Create("a", "B").ToBuilder(); Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer); Assert.True(builder.Contains("a")); Assert.False(builder.Contains("A")); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); Assert.Equal(2, builder.Count); Assert.True(builder.Contains("a")); Assert.True(builder.Contains("A")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void KeyComparerCollisions() { var builder = ImmutableHashSet.Create("a", "A").ToBuilder(); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Equal(1, builder.Count); Assert.True(builder.Contains("a")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); Assert.Equal(1, set.Count); Assert.True(set.Contains("a")); } [Fact] public void KeyComparerEmptyCollection() { var builder = ImmutableHashSet.Create<string>().ToBuilder(); Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void UnionWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.UnionWith(null)); builder.UnionWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); } [Fact] public void ExceptWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.ExceptWith(null)); builder.ExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1 }, builder); } [Fact] public void SymmetricExceptWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.SymmetricExceptWith(null)); builder.SymmetricExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 4 }, builder); } [Fact] public void IntersectWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IntersectWith(null)); builder.IntersectWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 2, 3 }, builder); } [Fact] public void IsProperSubsetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsProperSubsetOf(null)); Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsProperSupersetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsProperSupersetOf(null)); Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void IsSubsetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsSubsetOf(null)); Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsSupersetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsSupersetOf(null)); Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void Overlaps() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.Overlaps(null)); Assert.True(builder.Overlaps(Enumerable.Range(3, 2))); Assert.False(builder.Overlaps(Enumerable.Range(4, 3))); } [Fact] public void Remove() { var builder = ImmutableHashSet.Create("a").ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("item", () => builder.Remove(null)); Assert.False(builder.Remove("b")); Assert.True(builder.Remove("a")); } [Fact] public void SetEquals() { var builder = ImmutableHashSet.Create("a").ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.SetEquals(null)); Assert.False(builder.SetEquals(new[] { "b" })); Assert.True(builder.SetEquals(new[] { "a" })); Assert.True(builder.SetEquals(builder)); } [Fact] public void ICollectionOfTMethods() { ICollection<string> builder = ImmutableHashSet.Create("a").ToBuilder(); builder.Add("b"); Assert.True(builder.Contains("b")); var array = new string[3]; builder.CopyTo(array, 1); Assert.Null(array[0]); CollectionAssertAreEquivalent(new[] { null, "a", "b" }, array); Assert.False(builder.IsReadOnly); CollectionAssertAreEquivalent(new[] { "a", "b" }, builder.ToArray()); // tests enumerator } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.CreateBuilder<int>()); } } }
// 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; namespace System.Numerics { /// <summary> /// A structure encapsulating a 3x2 matrix. /// </summary> public struct Matrix3x2 : IEquatable<Matrix3x2> { private const float RotationEpsilon = 0.001f * MathF.PI / 180f; // 0.1% of a degree #region Public Fields /// <summary> /// The first element of the first row /// </summary> public float M11; /// <summary> /// The second element of the first row /// </summary> public float M12; /// <summary> /// The first element of the second row /// </summary> public float M21; /// <summary> /// The second element of the second row /// </summary> public float M22; /// <summary> /// The first element of the third row /// </summary> public float M31; /// <summary> /// The second element of the third row /// </summary> public float M32; #endregion Public Fields private static readonly Matrix3x2 _identity = new Matrix3x2 ( 1f, 0f, 0f, 1f, 0f, 0f ); /// <summary> /// Returns the multiplicative identity matrix. /// </summary> public static Matrix3x2 Identity { get { return _identity; } } /// <summary> /// Returns whether the matrix is the identity matrix. /// </summary> public bool IsIdentity { get { return M11 == 1f && M22 == 1f && // Check diagonal element first for early out. M12 == 0f && M21 == 0f && M31 == 0f && M32 == 0f; } } /// <summary> /// Gets or sets the translation component of this matrix. /// </summary> public Vector2 Translation { get { return new Vector2(M31, M32); } set { M31 = value.X; M32 = value.Y; } } /// <summary> /// Constructs a Matrix3x2 from the given components. /// </summary> public Matrix3x2(float m11, float m12, float m21, float m22, float m31, float m32) { this.M11 = m11; this.M12 = m12; this.M21 = m21; this.M22 = m22; this.M31 = m31; this.M32 = m32; } /// <summary> /// Creates a translation matrix from the given vector. /// </summary> /// <param name="position">The translation position.</param> /// <returns>A translation matrix.</returns> public static Matrix3x2 CreateTranslation(Vector2 position) { Matrix3x2 result; result.M11 = 1.0f; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = 1.0f; result.M31 = position.X; result.M32 = position.Y; return result; } /// <summary> /// Creates a translation matrix from the given X and Y components. /// </summary> /// <param name="xPosition">The X position.</param> /// <param name="yPosition">The Y position.</param> /// <returns>A translation matrix.</returns> public static Matrix3x2 CreateTranslation(float xPosition, float yPosition) { Matrix3x2 result; result.M11 = 1.0f; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = 1.0f; result.M31 = xPosition; result.M32 = yPosition; return result; } /// <summary> /// Creates a scale matrix from the given X and Y components. /// </summary> /// <param name="xScale">Value to scale by on the X-axis.</param> /// <param name="yScale">Value to scale by on the Y-axis.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float xScale, float yScale) { Matrix3x2 result; result.M11 = xScale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = yScale; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a scale matrix that is offset by a given center point. /// </summary> /// <param name="xScale">Value to scale by on the X-axis.</param> /// <param name="yScale">Value to scale by on the Y-axis.</param> /// <param name="centerPoint">The center point.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float xScale, float yScale, Vector2 centerPoint) { Matrix3x2 result; float tx = centerPoint.X * (1 - xScale); float ty = centerPoint.Y * (1 - yScale); result.M11 = xScale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = yScale; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a scale matrix from the given vector scale. /// </summary> /// <param name="scales">The scale to use.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(Vector2 scales) { Matrix3x2 result; result.M11 = scales.X; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scales.Y; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a scale matrix from the given vector scale with an offset from the given center point. /// </summary> /// <param name="scales">The scale to use.</param> /// <param name="centerPoint">The center offset.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(Vector2 scales, Vector2 centerPoint) { Matrix3x2 result; float tx = centerPoint.X * (1 - scales.X); float ty = centerPoint.Y * (1 - scales.Y); result.M11 = scales.X; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scales.Y; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a scale matrix that scales uniformly with the given scale. /// </summary> /// <param name="scale">The uniform scale to use.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float scale) { Matrix3x2 result; result.M11 = scale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scale; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a scale matrix that scales uniformly with the given scale with an offset from the given center. /// </summary> /// <param name="scale">The uniform scale to use.</param> /// <param name="centerPoint">The center offset.</param> /// <returns>A scaling matrix.</returns> public static Matrix3x2 CreateScale(float scale, Vector2 centerPoint) { Matrix3x2 result; float tx = centerPoint.X * (1 - scale); float ty = centerPoint.Y * (1 - scale); result.M11 = scale; result.M12 = 0.0f; result.M21 = 0.0f; result.M22 = scale; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a skew matrix from the given angles in radians. /// </summary> /// <param name="radiansX">The X angle, in radians.</param> /// <param name="radiansY">The Y angle, in radians.</param> /// <returns>A skew matrix.</returns> public static Matrix3x2 CreateSkew(float radiansX, float radiansY) { Matrix3x2 result; float xTan = MathF.Tan(radiansX); float yTan = MathF.Tan(radiansY); result.M11 = 1.0f; result.M12 = yTan; result.M21 = xTan; result.M22 = 1.0f; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a skew matrix from the given angles in radians and a center point. /// </summary> /// <param name="radiansX">The X angle, in radians.</param> /// <param name="radiansY">The Y angle, in radians.</param> /// <param name="centerPoint">The center point.</param> /// <returns>A skew matrix.</returns> public static Matrix3x2 CreateSkew(float radiansX, float radiansY, Vector2 centerPoint) { Matrix3x2 result; float xTan = MathF.Tan(radiansX); float yTan = MathF.Tan(radiansY); float tx = -centerPoint.Y * xTan; float ty = -centerPoint.X * yTan; result.M11 = 1.0f; result.M12 = yTan; result.M21 = xTan; result.M22 = 1.0f; result.M31 = tx; result.M32 = ty; return result; } /// <summary> /// Creates a rotation matrix using the given rotation in radians. /// </summary> /// <param name="radians">The amount of rotation, in radians.</param> /// <returns>A rotation matrix.</returns> public static Matrix3x2 CreateRotation(float radians) { Matrix3x2 result; radians = MathF.IEEERemainder(radians, MathF.PI * 2); float c, s; if (radians > -RotationEpsilon && radians < RotationEpsilon) { // Exact case for zero rotation. c = 1; s = 0; } else if (radians > MathF.PI / 2 - RotationEpsilon && radians < MathF.PI / 2 + RotationEpsilon) { // Exact case for 90 degree rotation. c = 0; s = 1; } else if (radians < -MathF.PI + RotationEpsilon || radians > MathF.PI - RotationEpsilon) { // Exact case for 180 degree rotation. c = -1; s = 0; } else if (radians > -MathF.PI / 2 - RotationEpsilon && radians < -MathF.PI / 2 + RotationEpsilon) { // Exact case for 270 degree rotation. c = 0; s = -1; } else { // Arbitrary rotation. c = MathF.Cos(radians); s = MathF.Sin(radians); } // [ c s ] // [ -s c ] // [ 0 0 ] result.M11 = c; result.M12 = s; result.M21 = -s; result.M22 = c; result.M31 = 0.0f; result.M32 = 0.0f; return result; } /// <summary> /// Creates a rotation matrix using the given rotation in radians and a center point. /// </summary> /// <param name="radians">The amount of rotation, in radians.</param> /// <param name="centerPoint">The center point.</param> /// <returns>A rotation matrix.</returns> public static Matrix3x2 CreateRotation(float radians, Vector2 centerPoint) { Matrix3x2 result; radians = MathF.IEEERemainder(radians, MathF.PI * 2); float c, s; if (radians > -RotationEpsilon && radians < RotationEpsilon) { // Exact case for zero rotation. c = 1; s = 0; } else if (radians > MathF.PI / 2 - RotationEpsilon && radians < MathF.PI / 2 + RotationEpsilon) { // Exact case for 90 degree rotation. c = 0; s = 1; } else if (radians < -MathF.PI + RotationEpsilon || radians > MathF.PI - RotationEpsilon) { // Exact case for 180 degree rotation. c = -1; s = 0; } else if (radians > -MathF.PI / 2 - RotationEpsilon && radians < -MathF.PI / 2 + RotationEpsilon) { // Exact case for 270 degree rotation. c = 0; s = -1; } else { // Arbitrary rotation. c = MathF.Cos(radians); s = MathF.Sin(radians); } float x = centerPoint.X * (1 - c) + centerPoint.Y * s; float y = centerPoint.Y * (1 - c) - centerPoint.X * s; // [ c s ] // [ -s c ] // [ x y ] result.M11 = c; result.M12 = s; result.M21 = -s; result.M22 = c; result.M31 = x; result.M32 = y; return result; } /// <summary> /// Calculates the determinant for this matrix. /// The determinant is calculated by expanding the matrix with a third column whose values are (0,0,1). /// </summary> /// <returns>The determinant.</returns> public float GetDeterminant() { // There isn't actually any such thing as a determinant for a non-square matrix, // but this 3x2 type is really just an optimization of a 3x3 where we happen to // know the rightmost column is always (0, 0, 1). So we expand to 3x3 format: // // [ M11, M12, 0 ] // [ M21, M22, 0 ] // [ M31, M32, 1 ] // // Sum the diagonal products: // (M11 * M22 * 1) + (M12 * 0 * M31) + (0 * M21 * M32) // // Subtract the opposite diagonal products: // (M31 * M22 * 0) + (M32 * 0 * M11) + (1 * M21 * M12) // // Collapse out the constants and oh look, this is just a 2x2 determinant! return (M11 * M22) - (M21 * M12); } /// <summary> /// Attempts to invert the given matrix. If the operation succeeds, the inverted matrix is stored in the result parameter. /// </summary> /// <param name="matrix">The source matrix.</param> /// <param name="result">The output matrix.</param> /// <returns>True if the operation succeeded, False otherwise.</returns> public static bool Invert(Matrix3x2 matrix, out Matrix3x2 result) { float det = (matrix.M11 * matrix.M22) - (matrix.M21 * matrix.M12); if (MathF.Abs(det) < float.Epsilon) { result = new Matrix3x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); return false; } float invDet = 1.0f / det; result.M11 = matrix.M22 * invDet; result.M12 = -matrix.M12 * invDet; result.M21 = -matrix.M21 * invDet; result.M22 = matrix.M11 * invDet; result.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22) * invDet; result.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32) * invDet; return true; } /// <summary> /// Linearly interpolates from matrix1 to matrix2, based on the third parameter. /// </summary> /// <param name="matrix1">The first source matrix.</param> /// <param name="matrix2">The second source matrix.</param> /// <param name="amount">The relative weighting of matrix2.</param> /// <returns>The interpolated matrix.</returns> public static Matrix3x2 Lerp(Matrix3x2 matrix1, Matrix3x2 matrix2, float amount) { Matrix3x2 result; // First row result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount; result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount; // Second row result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount; result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount; // Third row result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount; result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount; return result; } /// <summary> /// Negates the given matrix by multiplying all values by -1. /// </summary> /// <param name="value">The source matrix.</param> /// <returns>The negated matrix.</returns> public static Matrix3x2 Negate(Matrix3x2 value) { Matrix3x2 result; result.M11 = -value.M11; result.M12 = -value.M12; result.M21 = -value.M21; result.M22 = -value.M22; result.M31 = -value.M31; result.M32 = -value.M32; return result; } /// <summary> /// Adds each matrix element in value1 with its corresponding element in value2. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the summed values.</returns> public static Matrix3x2 Add(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result; result.M11 = value1.M11 + value2.M11; result.M12 = value1.M12 + value2.M12; result.M21 = value1.M21 + value2.M21; result.M22 = value1.M22 + value2.M22; result.M31 = value1.M31 + value2.M31; result.M32 = value1.M32 + value2.M32; return result; } /// <summary> /// Subtracts each matrix element in value2 from its corresponding element in value1. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the resulting values.</returns> public static Matrix3x2 Subtract(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result; result.M11 = value1.M11 - value2.M11; result.M12 = value1.M12 - value2.M12; result.M21 = value1.M21 - value2.M21; result.M22 = value1.M22 - value2.M22; result.M31 = value1.M31 - value2.M31; result.M32 = value1.M32 - value2.M32; return result; } /// <summary> /// Multiplies two matrices together and returns the resulting matrix. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The product matrix.</returns> public static Matrix3x2 Multiply(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 result; // First row result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; // Second row result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; // Third row result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; return result; } /// <summary> /// Scales all elements in a matrix by the given scalar factor. /// </summary> /// <param name="value1">The source matrix.</param> /// <param name="value2">The scaling value to use.</param> /// <returns>The resulting matrix.</returns> public static Matrix3x2 Multiply(Matrix3x2 value1, float value2) { Matrix3x2 result; result.M11 = value1.M11 * value2; result.M12 = value1.M12 * value2; result.M21 = value1.M21 * value2; result.M22 = value1.M22 * value2; result.M31 = value1.M31 * value2; result.M32 = value1.M32 * value2; return result; } /// <summary> /// Negates the given matrix by multiplying all values by -1. /// </summary> /// <param name="value">The source matrix.</param> /// <returns>The negated matrix.</returns> public static Matrix3x2 operator -(Matrix3x2 value) { Matrix3x2 m; m.M11 = -value.M11; m.M12 = -value.M12; m.M21 = -value.M21; m.M22 = -value.M22; m.M31 = -value.M31; m.M32 = -value.M32; return m; } /// <summary> /// Adds each matrix element in value1 with its corresponding element in value2. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the summed values.</returns> public static Matrix3x2 operator +(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 m; m.M11 = value1.M11 + value2.M11; m.M12 = value1.M12 + value2.M12; m.M21 = value1.M21 + value2.M21; m.M22 = value1.M22 + value2.M22; m.M31 = value1.M31 + value2.M31; m.M32 = value1.M32 + value2.M32; return m; } /// <summary> /// Subtracts each matrix element in value2 from its corresponding element in value1. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The matrix containing the resulting values.</returns> public static Matrix3x2 operator -(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 m; m.M11 = value1.M11 - value2.M11; m.M12 = value1.M12 - value2.M12; m.M21 = value1.M21 - value2.M21; m.M22 = value1.M22 - value2.M22; m.M31 = value1.M31 - value2.M31; m.M32 = value1.M32 - value2.M32; return m; } /// <summary> /// Multiplies two matrices together and returns the resulting matrix. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>The product matrix.</returns> public static Matrix3x2 operator *(Matrix3x2 value1, Matrix3x2 value2) { Matrix3x2 m; // First row m.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; m.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; // Second row m.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; m.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; // Third row m.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; m.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; return m; } /// <summary> /// Scales all elements in a matrix by the given scalar factor. /// </summary> /// <param name="value1">The source matrix.</param> /// <param name="value2">The scaling value to use.</param> /// <returns>The resulting matrix.</returns> public static Matrix3x2 operator *(Matrix3x2 value1, float value2) { Matrix3x2 m; m.M11 = value1.M11 * value2; m.M12 = value1.M12 * value2; m.M21 = value1.M21 * value2; m.M22 = value1.M22 * value2; m.M31 = value1.M31 * value2; m.M32 = value1.M32 * value2; return m; } /// <summary> /// Returns a boolean indicating whether the given matrices are equal. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>True if the matrices are equal; False otherwise.</returns> public static bool operator ==(Matrix3x2 value1, Matrix3x2 value2) { return (value1.M11 == value2.M11 && value1.M22 == value2.M22 && // Check diagonal element first for early out. value1.M12 == value2.M12 && value1.M21 == value2.M21 && value1.M31 == value2.M31 && value1.M32 == value2.M32); } /// <summary> /// Returns a boolean indicating whether the given matrices are not equal. /// </summary> /// <param name="value1">The first source matrix.</param> /// <param name="value2">The second source matrix.</param> /// <returns>True if the matrices are not equal; False if they are equal.</returns> public static bool operator !=(Matrix3x2 value1, Matrix3x2 value2) { return (value1.M11 != value2.M11 || value1.M12 != value2.M12 || value1.M21 != value2.M21 || value1.M22 != value2.M22 || value1.M31 != value2.M31 || value1.M32 != value2.M32); } /// <summary> /// Returns a boolean indicating whether the matrix is equal to the other given matrix. /// </summary> /// <param name="other">The other matrix to test equality against.</param> /// <returns>True if this matrix is equal to other; False otherwise.</returns> public bool Equals(Matrix3x2 other) { return (M11 == other.M11 && M22 == other.M22 && // Check diagonal element first for early out. M12 == other.M12 && M21 == other.M21 && M31 == other.M31 && M32 == other.M32); } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this matrix instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this matrix; False otherwise.</returns> public override bool Equals(object obj) { if (obj is Matrix3x2) { return Equals((Matrix3x2)obj); } return false; } /// <summary> /// Returns a String representing this matrix instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "{{ {{M11:{0} M12:{1}}} {{M21:{2} M22:{3}}} {{M31:{4} M32:{5}}} }}", M11, M12, M21, M22, M31, M32); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { return unchecked(M11.GetHashCode() + M12.GetHashCode() + M21.GetHashCode() + M22.GetHashCode() + M31.GetHashCode() + M32.GetHashCode()); } } }
using System; using System.Text; using Xunit; namespace System.Text.EncodingTests { //System.Test.UnicodeEncoding.GetChars(System.Byte[],System.Int32,System.Int32,System.Char[],System.Int32) public class UnicodeEncodingGetChars { private readonly RandomDataGenerator _generator = new RandomDataGenerator(); #region Positive Tests // PosTest1:Invoke the method [Fact] public void PosTest1() { int actualValue; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); actualValue = uEncoding.GetChars(bytes, 0, 20, desChars, 0); Assert.Equal(10, actualValue); } // PosTest2:Invoke the method with random char count [Fact] public void PosTest2() { int expectedValue = _generator.GetInt16(-55) % 10 + 1; int actualValue; Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, expectedValue, bytes, 0); actualValue = uEncoding.GetChars(bytes, 0, expectedValue * 2, desChars, 0); Assert.Equal(expectedValue, actualValue); } // PosTest3:Invoke the method and set charIndex as 10 [Fact] public void PosTest3() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, 10); Assert.Equal(0, actualValue); } // PosTest4:Invoke the method and set byteIndex as 20 [Fact] public void PosTest4() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; actualValue = uEncoding.GetChars(bytes, 20, 0, desChars, 10); Assert.Equal(0, actualValue); } #endregion #region Negative Tests // NegTest1:Invoke the method and set chars as null [Fact] public void NegTest1() { Char[] srcChars = GetCharArray(10); Char[] desChars = null; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; Assert.Throws<ArgumentNullException>(() => { actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, 0); }); } // NegTest2:Invoke the method and set bytes as null [Fact] public void NegTest2() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = null; UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; Assert.Throws<ArgumentNullException>(() => { actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, 0); }); } // NegTest3:Invoke the method and the destination buffer is not enough [Fact] public void NegTest3() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[5]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; Assert.Throws<ArgumentException>(() => { actualValue = uEncoding.GetChars(bytes, 0, 20, desChars, 0); }); } // NegTest4:Invoke the method and the destination buffer is not enough [Fact] public void NegTest4() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; Assert.Throws<ArgumentException>(() => { actualValue = uEncoding.GetChars(bytes, 0, 20, desChars, 5); }); } // NegTest5:Invoke the method and set byteIndex as -1 [Fact] public void NegTest5() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = uEncoding.GetChars(bytes, -1, 0, desChars, 0); }); } // NegTest6:Invoke the method and set byteIndex as 20 [Fact] public void NegTest6() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = uEncoding.GetChars(bytes, 20, 1, desChars, 10); }); } // NegTest7:Invoke the method and set byteCount as -1 [Fact] public void NegTest7() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = uEncoding.GetChars(bytes, 0, -1, desChars, 0); }); } // NegTest8:Invoke the method and set byteCount as 21 [Fact] public void NegTest8() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = uEncoding.GetChars(bytes, 0, 21, desChars, 0); }); } // NegTest9:Invoke the method and set charIndex as -1 [Fact] public void NegTest9() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, -1); }); } // NegTest10:Invoke the method and set charIndex as 11 [Fact] public void NegTest10() { Char[] srcChars = GetCharArray(10); Char[] desChars = new Char[10]; Byte[] bytes = new Byte[20]; UnicodeEncoding uEncoding = new UnicodeEncoding(); int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0); int actualValue; Assert.Throws<ArgumentOutOfRangeException>(() => { actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, 11); }); } #endregion #region Helper Methods //Create a None-Surrogate-Char Array. public Char[] GetCharArray(int length) { if (length <= 0) return new Char[] { }; Char[] charArray = new Char[length]; int i = 0; while (i < length) { Char temp = _generator.GetChar(-55); if (!Char.IsSurrogate(temp)) { charArray[i] = temp; i++; } } return charArray; } //Convert Char Array to String public String ToString(Char[] chars) { String str = "{"; for (int i = 0; i < chars.Length; i++) { str = str + @"\u" + String.Format("{0:X04}", (int)chars[i]); if (i != chars.Length - 1) str = str + ","; } str = str + "}"; return str; } #endregion } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.Serialization; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Breakpoints; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.CustomRuntimes; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Exceptions; using Microsoft.VisualStudio.Debugger.Native; using Microsoft.VisualStudio.Debugger.Stepping; using Microsoft.VisualStudio.Debugger.Symbols; namespace Microsoft.PythonTools.DkmDebugger { public class RemoteComponent : ComponentBase, IDkmModuleInstanceLoadNotification, IDkmRuntimeMonitorBreakpointHandler, IDkmRuntimeBreakpointReceived, IDkmRuntimeStepper, IDkmExceptionController, IDkmExceptionFormatter, IDkmExceptionManager, IDkmAsyncBreakCompleteReceived { public RemoteComponent() : base(Guids.RemoteComponentGuid) { } [DataContract] [MessageTo(Guids.RemoteComponentId)] internal class CreatePythonRuntimeRequest : MessageBase<CreatePythonRuntimeRequest> { [DataMember] public Guid PythonDllModuleInstanceId { get; set; } [DataMember] public Guid DebuggerHelperDllModuleInstanceId { get; set; } public override void Handle(DkmProcess process) { var pyrtInfo = process.GetPythonRuntimeInfo(); var nativeModules = process.GetNativeRuntimeInstance().GetNativeModuleInstances(); pyrtInfo.DLLs.Python = nativeModules.Single(mi => mi.UniqueId == PythonDllModuleInstanceId); pyrtInfo.DLLs.Python.FlagAsTransitionModule(); if (DebuggerHelperDllModuleInstanceId != Guid.Empty) { pyrtInfo.DLLs.DebuggerHelper = nativeModules.Single(mi => mi.UniqueId == DebuggerHelperDllModuleInstanceId); pyrtInfo.DLLs.DebuggerHelper.FlagAsTransitionModule(); process.SetDataItem(DkmDataCreationDisposition.CreateNew, new TraceManager(process)); } var runtimeId = new DkmRuntimeInstanceId(Guids.PythonRuntimeTypeGuid, 0); var runtimeInstance = DkmCustomRuntimeInstance.Create(process, runtimeId, null); new CreateModuleRequest { ModuleId = Guids.UnknownPythonModuleGuid }.Handle(process); } } void IDkmModuleInstanceLoadNotification.OnModuleInstanceLoad(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptorS eventDescriptor) { var nativeModuleInstance = moduleInstance as DkmNativeModuleInstance; if (nativeModuleInstance != null && PythonDLLs.CTypesNames.Contains(moduleInstance.Name)) { var pyrtInfo = moduleInstance.Process.GetPythonRuntimeInfo(); pyrtInfo.DLLs.CTypes = nativeModuleInstance; nativeModuleInstance.FlagAsTransitionModule(); } } void IDkmRuntimeMonitorBreakpointHandler.DisableRuntimeBreakpoint(DkmRuntimeBreakpoint runtimeBreakpoint) { var traceManager = runtimeBreakpoint.Process.GetDataItem<TraceManager>(); if (traceManager == null) { Debug.Fail("DisableRuntimeBreakpoint called before TraceMananger is initialized."); throw new InvalidOperationException(); } traceManager.RemoveBreakpoint(runtimeBreakpoint); } void IDkmRuntimeMonitorBreakpointHandler.EnableRuntimeBreakpoint(DkmRuntimeBreakpoint runtimeBreakpoint) { var bp = runtimeBreakpoint as DkmRuntimeInstructionBreakpoint; if (bp == null) { Debug.Fail("Non-Python breakpoint passed to EnableRuntimeBreakpoint."); throw new NotImplementedException(); } var instrAddr = bp.InstructionAddress as DkmCustomInstructionAddress; if (instrAddr == null || instrAddr.RuntimeInstance.Id.RuntimeType != Guids.PythonRuntimeTypeGuid) { Debug.Fail("Non-Python breakpoint passed to EnableRuntimeBreakpoint."); throw new NotImplementedException(); } var traceManager = bp.Process.GetDataItem<TraceManager>(); if (traceManager == null) { Debug.Fail("EnableRuntimeBreakpoint called before TraceMananger is initialized."); throw new InvalidOperationException(); } var loc = new SourceLocation(instrAddr.AdditionalData); bp.SetDataItem(DkmDataCreationDisposition.CreateNew, loc); traceManager.AddBreakpoint(bp); } void IDkmRuntimeMonitorBreakpointHandler.TestRuntimeBreakpoint(DkmRuntimeBreakpoint runtimeBreakpoint) { var traceManager = runtimeBreakpoint.Process.GetDataItem<TraceManager>(); if (traceManager == null) { Debug.Fail("TestRuntimeBreakpoint called before TraceMananger is initialized."); throw new InvalidOperationException(); } } void IDkmRuntimeBreakpointReceived.OnRuntimeBreakpointReceived(DkmRuntimeBreakpoint runtimeBreakpoint, DkmThread thread, bool hasException, DkmEventDescriptorS eventDescriptor) { if (runtimeBreakpoint.SourceId == Guids.LocalComponentGuid) { ulong retAddr, frameBase, vframe; thread.GetCurrentFrameInfo(out retAddr, out frameBase, out vframe); new LocalComponent.HandleBreakpointRequest { BreakpointId = runtimeBreakpoint.UniqueId, ThreadId = thread.UniqueId, FrameBase = frameBase, VFrame = vframe, ReturnAddress = retAddr }.SendHigher(thread.Process); } else if (runtimeBreakpoint.SourceId == Guids.PythonTraceManagerSourceGuid || runtimeBreakpoint.SourceId == Guids.PythonStepTargetSourceGuid) { var traceManager = runtimeBreakpoint.Process.GetDataItem<TraceManager>(); if (traceManager != null) { traceManager.OnNativeBreakpointHit(runtimeBreakpoint, thread); } } else { Debug.Fail("RemoteComponent received a notification for a breakpoint that it does not know how to handle."); throw new ArgumentException(); } } void IDkmRuntimeStepper.AfterSteppingArbitration(DkmRuntimeInstance runtimeInstance, DkmStepper stepper, DkmStepArbitrationReason reason, DkmRuntimeInstance newControllingRuntimeInstance) { } void IDkmRuntimeStepper.BeforeEnableNewStepper(DkmRuntimeInstance runtimeInstance, DkmStepper stepper) { var traceManager = runtimeInstance.Process.GetDataItem<TraceManager>(); if (traceManager == null) { Debug.Fail("OnNewControllingRuntimeInstance called before TraceMananger is initialized."); throw new InvalidOperationException(); } traceManager.BeforeEnableNewStepper(runtimeInstance, stepper); } void IDkmRuntimeStepper.NotifyStepComplete(DkmRuntimeInstance runtimeInstance, DkmStepper stepper) { } void IDkmRuntimeStepper.OnNewControllingRuntimeInstance(DkmRuntimeInstance runtimeInstance, DkmStepper stepper, DkmStepArbitrationReason reason, DkmRuntimeInstance controllingRuntimeInstance) { var traceManager = runtimeInstance.Process.GetDataItem<TraceManager>(); if (traceManager == null) { Debug.Fail("OnNewControllingRuntimeInstance called before TraceMananger is initialized."); throw new InvalidOperationException(); } traceManager.CancelStep(stepper); } bool IDkmRuntimeStepper.OwnsCurrentExecutionLocation(DkmRuntimeInstance runtimeInstance, DkmStepper stepper, DkmStepArbitrationReason reason) { if (!DebuggerOptions.UsePythonStepping) { return false; } var process = runtimeInstance.Process; var pyrtInfo = process.GetPythonRuntimeInfo(); if (pyrtInfo.DLLs.Python == null) { return false; } var thread = stepper.Thread; var ip = thread.GetCurrentRegisters(new DkmUnwoundRegister[0]).GetInstructionPointer(); return pyrtInfo.DLLs.Python.ContainsAddress(ip) || (pyrtInfo.DLLs.DebuggerHelper != null && pyrtInfo.DLLs.DebuggerHelper.ContainsAddress(ip)) || (pyrtInfo.DLLs.CTypes != null && pyrtInfo.DLLs.CTypes.ContainsAddress(ip)); } void IDkmRuntimeStepper.Step(DkmRuntimeInstance runtimeInstance, DkmStepper stepper, DkmStepArbitrationReason reason) { var traceManager = runtimeInstance.Process.GetDataItem<TraceManager>(); if (traceManager == null) { Debug.Fail("Step called before TraceMananger is initialized."); throw new InvalidOperationException(); } traceManager.Step(stepper, reason); } bool IDkmRuntimeStepper.StepControlRequested(DkmRuntimeInstance runtimeInstance, DkmStepper stepper, DkmStepArbitrationReason reason, DkmRuntimeInstance callingRuntimeInstance) { return true; } void IDkmRuntimeStepper.StopStep(DkmRuntimeInstance runtimeInstance, DkmStepper stepper) { var traceManager = runtimeInstance.Process.GetDataItem<TraceManager>(); if (traceManager == null) { Debug.Fail("StopStep called before TraceMananger is initialized."); throw new InvalidOperationException(); } traceManager.CancelStep(stepper); } void IDkmRuntimeStepper.TakeStepControl(DkmRuntimeInstance runtimeInstance, DkmStepper stepper, bool leaveGuardsInPlace, DkmStepArbitrationReason reason, DkmRuntimeInstance callingRuntimeInstance) { var traceManager = runtimeInstance.Process.GetDataItem<TraceManager>(); if (traceManager == null) { Debug.Fail("TakeStepControl called before TraceMananger is initialized."); throw new InvalidOperationException(); } traceManager.CancelStep(stepper); } [DataContract] [MessageTo(Guids.RemoteComponentId)] internal class CreateModuleRequest : MessageBase<CreateModuleRequest> { [DataMember] public Guid ModuleId { get; set; } [DataMember] public string FileName { get; set; } public CreateModuleRequest() { FileName = ""; } public override void Handle(DkmProcess process) { var pythonRuntime = process.GetPythonRuntimeInstance(); if (pythonRuntime == null) { return; } string moduleName; if (ModuleId == Guids.UnknownPythonModuleGuid) { moduleName = "<unknown>"; } else { try { moduleName = Path.GetFileName(FileName); } catch (ArgumentException) { moduleName = FileName; } } var module = DkmModule.Create(new DkmModuleId(ModuleId, Guids.PythonSymbolProviderGuid), FileName, new DkmCompilerId(Guids.MicrosoftVendorGuid, Guids.PythonLanguageGuid), process.Connection, null); var moduleInstance = DkmCustomModuleInstance.Create(moduleName, FileName, 0, pythonRuntime, null, null, DkmModuleFlags.None, DkmModuleMemoryLayout.Unknown, 0, 0, 0, "Python", false, null, null, null); moduleInstance.SetModule(module, true); } } [DataContract] [MessageTo(Guids.RemoteComponentId)] internal class RaiseExceptionRequest : MessageBase<RaiseExceptionRequest> { [DataMember] public Guid ThreadId { get; set; } [DataMember] public string Name { get; set; } [DataMember] public byte[] AdditionalInformation { get; set; } public override void Handle(DkmProcess process) { var thread = process.GetThreads().Single(t => t.UniqueId == ThreadId); var excInfo = DkmCustomExceptionInformation.Create( process.GetPythonRuntimeInstance(), Guids.PythonExceptionCategoryGuid, thread, null, Name, 0, DkmExceptionProcessingStage.Thrown | DkmExceptionProcessingStage.UserVisible | DkmExceptionProcessingStage.UserCodeSearch, null, new ReadOnlyCollection<byte>(AdditionalInformation)); excInfo.OnDebugMonitorException(); } } bool IDkmExceptionController.CanModifyProcessing(DkmExceptionInformation exception) { return false; } void IDkmExceptionController.SquashProcessing(DkmExceptionInformation exception) { throw new NotImplementedException(); } string IDkmExceptionFormatter.GetAdditionalInformation(DkmExceptionInformation exception) { var em = exception.Process.GetOrCreateDataItem(() => new ExceptionManager(exception.Process)); return em.GetAdditionalInformation(exception); } string IDkmExceptionFormatter.GetDescription(DkmExceptionInformation exception) { var em = exception.Process.GetOrCreateDataItem(() => new ExceptionManager(exception.Process)); return em.GetDescription(exception); } void IDkmExceptionManager.AddExceptionTrigger(DkmProcess process, Guid sourceId, DkmExceptionTrigger trigger) { var em = process.GetOrCreateDataItem(() => new ExceptionManager(process)); em.AddExceptionTrigger(process, sourceId, trigger); } void IDkmExceptionManager.ClearExceptionTriggers(DkmProcess process, Guid sourceId) { var em = process.GetOrCreateDataItem(() => new ExceptionManager(process)); em.ClearExceptionTriggers(process, sourceId); } [DataContract] [MessageTo(Guids.RemoteComponentId)] internal class EndFuncEvalExecutionRequest : MessageBase<EndFuncEvalExecutionRequest> { [DataMember] public Guid ThreadId { get; set; } public override void Handle(DkmProcess process) { var thread = process.GetThreads().Single(t => t.UniqueId == ThreadId); thread.EndFuncEvalExecution(DkmFuncEvalFlags.None); } } [DataContract] [MessageTo(Guids.RemoteComponentId)] internal class AbortingEvalExecutionRequest : MessageBase<AbortingEvalExecutionRequest> { public override void Handle(DkmProcess process) { process.AbortingFuncEvalExecution(DkmFuncEvalFlags.None); } } void IDkmAsyncBreakCompleteReceived.OnAsyncBreakCompleteReceived(DkmProcess process, DkmAsyncBreakStatus status, DkmThread thread, DkmEventDescriptorS eventDescriptor) { new LocalComponent.AsyncBreakReceivedNotification { ThreadId = thread.UniqueId }.SendHigher(process); } [DataContract] [MessageTo(Guids.RemoteComponentId)] internal class GetCurrentFrameInfoRequest : MessageBase<GetCurrentFrameInfoRequest, GetCurrentFrameInfoResponse> { [DataMember] public Guid ThreadId { get; set; } public override GetCurrentFrameInfoResponse Handle(DkmProcess process) { var thread = process.GetThreads().Single(t => t.UniqueId == ThreadId); var response = new GetCurrentFrameInfoResponse(); thread.GetCurrentFrameInfo(out response.RetAddr, out response.FrameBase, out response.VFrame); return response; } } [DataContract] internal class GetCurrentFrameInfoResponse { [DataMember] public ulong RetAddr, FrameBase, VFrame; } [DataContract] [MessageTo(Guids.RemoteComponentId)] internal class SetDebuggerOptions : MessageBase<SetDebuggerOptions> { [DataMember] public bool ShowNativePythonFrames, UsePythonStepping, ShowCppViewNodes, ShowPythonViewNodes; public override void Handle(DkmProcess process) { DebuggerOptions.ShowNativePythonFrames = ShowNativePythonFrames; DebuggerOptions.UsePythonStepping = UsePythonStepping; DebuggerOptions.ShowCppViewNodes = ShowCppViewNodes; DebuggerOptions.ShowPythonViewNodes = ShowPythonViewNodes; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Monitoring.Alerts; using Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.Management.Monitoring.Alerts { /// <summary> /// Operations for managing the alert rules. /// </summary> internal partial class RuleOperations : IServiceOperations<AlertsClient>, Microsoft.WindowsAzure.Management.Monitoring.Alerts.IRuleOperations { /// <summary> /// Initializes a new instance of the RuleOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RuleOperations(AlertsClient client) { this._client = client; } private AlertsClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Monitoring.Alerts.AlertsClient. /// </summary> public AlertsClient Client { get { return this._client; } } /// <param name='parameters'> /// Required. The rule to create or update. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> CreateOrUpdateAsync(RuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/alertrules/" + (parameters.Rule.Id != null ? parameters.Rule.Id.Trim() : ""); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject ruleCreateOrUpdateParametersValue = new JObject(); requestDoc = ruleCreateOrUpdateParametersValue; if (parameters.Rule != null) { if (parameters.Rule.Id != null) { ruleCreateOrUpdateParametersValue["Id"] = parameters.Rule.Id; } if (parameters.Rule.Name != null) { ruleCreateOrUpdateParametersValue["Name"] = parameters.Rule.Name; } if (parameters.Rule.Description != null) { ruleCreateOrUpdateParametersValue["Description"] = parameters.Rule.Description; } ruleCreateOrUpdateParametersValue["IsEnabled"] = parameters.Rule.IsEnabled; if (parameters.Rule.Condition != null) { JObject conditionValue = new JObject(); ruleCreateOrUpdateParametersValue["Condition"] = conditionValue; if (parameters.Rule.Condition is ThresholdRuleCondition) { conditionValue["odata.type"] = parameters.Rule.Condition.GetType().FullName; ThresholdRuleCondition derived = ((ThresholdRuleCondition)parameters.Rule.Condition); if (derived.DataSource != null) { JObject dataSourceValue = new JObject(); conditionValue["DataSource"] = dataSourceValue; if (derived.DataSource is RuleMetricDataSource) { dataSourceValue["odata.type"] = derived.DataSource.GetType().FullName; RuleMetricDataSource derived2 = ((RuleMetricDataSource)derived.DataSource); if (derived2.ResourceId != null) { dataSourceValue["ResourceId"] = derived2.ResourceId; } if (derived2.MetricNamespace != null) { dataSourceValue["MetricNamespace"] = derived2.MetricNamespace; } if (derived2.MetricName != null) { dataSourceValue["MetricName"] = derived2.MetricName; } } } conditionValue["Operator"] = derived.Operator.ToString(); conditionValue["Threshold"] = derived.Threshold; conditionValue["WindowSize"] = TypeConversion.To8601String(derived.WindowSize); } } if (parameters.Rule.Actions != null) { if (parameters.Rule.Actions is ILazyCollection == false || ((ILazyCollection)parameters.Rule.Actions).IsInitialized) { JArray actionsArray = new JArray(); foreach (RuleAction actionsItem in parameters.Rule.Actions) { JObject ruleActionValue = new JObject(); actionsArray.Add(ruleActionValue); if (actionsItem is RuleEmailAction) { ruleActionValue["odata.type"] = actionsItem.GetType().FullName; RuleEmailAction derived3 = ((RuleEmailAction)actionsItem); ruleActionValue["SendToServiceOwners"] = derived3.SendToServiceOwners; if (derived3.CustomEmails != null) { if (derived3.CustomEmails is ILazyCollection == false || ((ILazyCollection)derived3.CustomEmails).IsInitialized) { JArray customEmailsArray = new JArray(); foreach (string customEmailsItem in derived3.CustomEmails) { customEmailsArray.Add(customEmailsItem); } ruleActionValue["CustomEmails"] = customEmailsArray; } } } } ruleCreateOrUpdateParametersValue["Actions"] = actionsArray; } } ruleCreateOrUpdateParametersValue["LastUpdatedTime"] = parameters.Rule.LastUpdatedTime; } requestContent = requestDoc.ToString(Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='ruleId'> /// Required. The id of the rule to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> DeleteAsync(string ruleId, CancellationToken cancellationToken) { // Validate if (ruleId == null) { throw new ArgumentNullException("ruleId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("ruleId", ruleId); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/alertrules/" + ruleId.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='ruleId'> /// Required. The id of the rule to retrieve. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Rule operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleGetResponse> GetAsync(string ruleId, CancellationToken cancellationToken) { // Validate if (ruleId == null) { throw new ArgumentNullException("ruleId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("ruleId", ruleId); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/alertrules/" + ruleId.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result RuleGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RuleGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Rule ruleInstance = new Rule(); result.Rule = ruleInstance; JToken idValue = responseDoc["Id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ruleInstance.Id = idInstance; } JToken nameValue = responseDoc["Name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); ruleInstance.Name = nameInstance; } JToken descriptionValue = responseDoc["Description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); ruleInstance.Description = descriptionInstance; } JToken isEnabledValue = responseDoc["IsEnabled"]; if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null) { bool isEnabledInstance = ((bool)isEnabledValue); ruleInstance.IsEnabled = isEnabledInstance; } JToken conditionValue = responseDoc["Condition"]; if (conditionValue != null && conditionValue.Type != JTokenType.Null) { string typeName = ((string)conditionValue["odata.type"]); if (typeName == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition") { ThresholdRuleCondition thresholdRuleConditionInstance = new ThresholdRuleCondition(); JToken dataSourceValue = conditionValue["DataSource"]; if (dataSourceValue != null && dataSourceValue.Type != JTokenType.Null) { string typeName2 = ((string)dataSourceValue["odata.type"]); if (typeName2 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource") { RuleMetricDataSource ruleMetricDataSourceInstance = new RuleMetricDataSource(); JToken resourceIdValue = dataSourceValue["ResourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); ruleMetricDataSourceInstance.ResourceId = resourceIdInstance; } JToken metricNamespaceValue = dataSourceValue["MetricNamespace"]; if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null) { string metricNamespaceInstance = ((string)metricNamespaceValue); ruleMetricDataSourceInstance.MetricNamespace = metricNamespaceInstance; } JToken metricNameValue = dataSourceValue["MetricName"]; if (metricNameValue != null && metricNameValue.Type != JTokenType.Null) { string metricNameInstance = ((string)metricNameValue); ruleMetricDataSourceInstance.MetricName = metricNameInstance; } thresholdRuleConditionInstance.DataSource = ruleMetricDataSourceInstance; } } JToken operatorValue = conditionValue["Operator"]; if (operatorValue != null && operatorValue.Type != JTokenType.Null) { ConditionOperator operatorInstance = ((ConditionOperator)Enum.Parse(typeof(ConditionOperator), ((string)operatorValue), true)); thresholdRuleConditionInstance.Operator = operatorInstance; } JToken thresholdValue = conditionValue["Threshold"]; if (thresholdValue != null && thresholdValue.Type != JTokenType.Null) { double thresholdInstance = ((double)thresholdValue); thresholdRuleConditionInstance.Threshold = thresholdInstance; } JToken windowSizeValue = conditionValue["WindowSize"]; if (windowSizeValue != null && windowSizeValue.Type != JTokenType.Null) { TimeSpan windowSizeInstance = TypeConversion.From8601TimeSpan(((string)windowSizeValue)); thresholdRuleConditionInstance.WindowSize = windowSizeInstance; } ruleInstance.Condition = thresholdRuleConditionInstance; } } JToken actionsArray = responseDoc["Actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { string typeName3 = ((string)actionsValue["odata.type"]); if (typeName3 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction") { RuleEmailAction ruleEmailActionInstance = new RuleEmailAction(); JToken sendToServiceOwnersValue = actionsValue["SendToServiceOwners"]; if (sendToServiceOwnersValue != null && sendToServiceOwnersValue.Type != JTokenType.Null) { bool sendToServiceOwnersInstance = ((bool)sendToServiceOwnersValue); ruleEmailActionInstance.SendToServiceOwners = sendToServiceOwnersInstance; } JToken customEmailsArray = actionsValue["CustomEmails"]; if (customEmailsArray != null && customEmailsArray.Type != JTokenType.Null) { foreach (JToken customEmailsValue in ((JArray)customEmailsArray)) { ruleEmailActionInstance.CustomEmails.Add(((string)customEmailsValue)); } } ruleInstance.Actions.Add(ruleEmailActionInstance); } } } JToken lastUpdatedTimeValue = responseDoc["LastUpdatedTime"]; if (lastUpdatedTimeValue != null && lastUpdatedTimeValue.Type != JTokenType.Null) { DateTime lastUpdatedTimeInstance = ((DateTime)lastUpdatedTimeValue); ruleInstance.LastUpdatedTime = lastUpdatedTimeInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List the alert rules within a subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Rules operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/alertrules"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result RuleListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RuleListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["Value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Rule ruleInstance = new Rule(); result.Value.Add(ruleInstance); JToken idValue = valueValue["Id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); ruleInstance.Id = idInstance; } JToken nameValue = valueValue["Name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); ruleInstance.Name = nameInstance; } JToken descriptionValue = valueValue["Description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); ruleInstance.Description = descriptionInstance; } JToken isEnabledValue = valueValue["IsEnabled"]; if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null) { bool isEnabledInstance = ((bool)isEnabledValue); ruleInstance.IsEnabled = isEnabledInstance; } JToken conditionValue = valueValue["Condition"]; if (conditionValue != null && conditionValue.Type != JTokenType.Null) { string typeName = ((string)conditionValue["odata.type"]); if (typeName == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.ThresholdRuleCondition") { ThresholdRuleCondition thresholdRuleConditionInstance = new ThresholdRuleCondition(); JToken dataSourceValue = conditionValue["DataSource"]; if (dataSourceValue != null && dataSourceValue.Type != JTokenType.Null) { string typeName2 = ((string)dataSourceValue["odata.type"]); if (typeName2 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleMetricDataSource") { RuleMetricDataSource ruleMetricDataSourceInstance = new RuleMetricDataSource(); JToken resourceIdValue = dataSourceValue["ResourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); ruleMetricDataSourceInstance.ResourceId = resourceIdInstance; } JToken metricNamespaceValue = dataSourceValue["MetricNamespace"]; if (metricNamespaceValue != null && metricNamespaceValue.Type != JTokenType.Null) { string metricNamespaceInstance = ((string)metricNamespaceValue); ruleMetricDataSourceInstance.MetricNamespace = metricNamespaceInstance; } JToken metricNameValue = dataSourceValue["MetricName"]; if (metricNameValue != null && metricNameValue.Type != JTokenType.Null) { string metricNameInstance = ((string)metricNameValue); ruleMetricDataSourceInstance.MetricName = metricNameInstance; } thresholdRuleConditionInstance.DataSource = ruleMetricDataSourceInstance; } } JToken operatorValue = conditionValue["Operator"]; if (operatorValue != null && operatorValue.Type != JTokenType.Null) { ConditionOperator operatorInstance = ((ConditionOperator)Enum.Parse(typeof(ConditionOperator), ((string)operatorValue), true)); thresholdRuleConditionInstance.Operator = operatorInstance; } JToken thresholdValue = conditionValue["Threshold"]; if (thresholdValue != null && thresholdValue.Type != JTokenType.Null) { double thresholdInstance = ((double)thresholdValue); thresholdRuleConditionInstance.Threshold = thresholdInstance; } JToken windowSizeValue = conditionValue["WindowSize"]; if (windowSizeValue != null && windowSizeValue.Type != JTokenType.Null) { TimeSpan windowSizeInstance = TypeConversion.From8601TimeSpan(((string)windowSizeValue)); thresholdRuleConditionInstance.WindowSize = windowSizeInstance; } ruleInstance.Condition = thresholdRuleConditionInstance; } } JToken actionsArray = valueValue["Actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { string typeName3 = ((string)actionsValue["odata.type"]); if (typeName3 == "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.RuleEmailAction") { RuleEmailAction ruleEmailActionInstance = new RuleEmailAction(); JToken sendToServiceOwnersValue = actionsValue["SendToServiceOwners"]; if (sendToServiceOwnersValue != null && sendToServiceOwnersValue.Type != JTokenType.Null) { bool sendToServiceOwnersInstance = ((bool)sendToServiceOwnersValue); ruleEmailActionInstance.SendToServiceOwners = sendToServiceOwnersInstance; } JToken customEmailsArray = actionsValue["CustomEmails"]; if (customEmailsArray != null && customEmailsArray.Type != JTokenType.Null) { foreach (JToken customEmailsValue in ((JArray)customEmailsArray)) { ruleEmailActionInstance.CustomEmails.Add(((string)customEmailsValue)); } } ruleInstance.Actions.Add(ruleEmailActionInstance); } } } JToken lastUpdatedTimeValue = valueValue["LastUpdatedTime"]; if (lastUpdatedTimeValue != null && lastUpdatedTimeValue.Type != JTokenType.Null) { DateTime lastUpdatedTimeInstance = ((DateTime)lastUpdatedTimeValue); ruleInstance.LastUpdatedTime = lastUpdatedTimeInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using ASC.Collections; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Core.Tenants; using ASC.ElasticSearch; using ASC.Projects.Core.DataInterfaces; using ASC.Projects.Core.Domain; using ASC.Web.Projects; using ASC.Web.Projects.Core.Search; namespace ASC.Projects.Data.DAO { class CachedMilestoneDao : MilestoneDao { private readonly HttpRequestDictionary<Milestone> projectCache = new HttpRequestDictionary<Milestone>("milestone"); public CachedMilestoneDao(int tenant) : base(tenant) { } public override Milestone GetById(int id) { return projectCache.Get(id.ToString(CultureInfo.InvariantCulture), () => GetBaseById(id)); } private Milestone GetBaseById(int id) { return base.GetById(id); } public override Milestone Save(Milestone milestone) { if (milestone != null) { ResetCache(milestone.ID); } return base.Save(milestone); } public override void Delete(int id) { ResetCache(id); base.Delete(id); } private void ResetCache(int milestoneId) { projectCache.Reset(milestoneId.ToString(CultureInfo.InvariantCulture)); } } class MilestoneDao : BaseDao, IMilestoneDao { private readonly Converter<object[], Milestone> converter; public MilestoneDao(int tenant) : base(tenant) { converter = ToMilestone; } public List<Milestone> GetAll() { return Db.ExecuteList(CreateQuery()).ConvertAll(converter); } public List<Milestone> GetByProject(int projectId) { return Db.ExecuteList(CreateQuery().Where("t.project_id", projectId)) .ConvertAll(converter); } public List<Milestone> GetByFilter(TaskFilter filter, bool isAdmin, bool checkAccess) { var query = CreateQuery(); if (filter.Max > 0 && filter.Max < 150000) { query.SetFirstResult((int)filter.Offset); query.SetMaxResults((int)filter.Max * 2); } query.OrderBy("t.status", true); if (!string.IsNullOrEmpty(filter.SortBy)) { var sortColumns = filter.SortColumns["Milestone"]; sortColumns.Remove(filter.SortBy); query.OrderBy("t." + (filter.SortBy == "create_on" ? "id" : filter.SortBy), filter.SortOrder); foreach (var sort in sortColumns.Keys) { query.OrderBy("t." + (sort == "create_on" ? "id" : sort), sortColumns[sort]); } } query = CreateQueryFilter(query, filter, isAdmin, checkAccess); return Db.ExecuteList(query).ConvertAll(converter); } public int GetByFilterCount(TaskFilter filter, bool isAdmin, bool checkAccess) { var query = new SqlQuery(MilestonesTable + " t") .InnerJoin(ProjectsTable + " p", Exp.EqColumns("t.project_id", "p.id") & Exp.EqColumns("t.tenant_id", "p.tenant_id")) .Select("t.id") .GroupBy("t.id") .Where("t.tenant_id", Tenant); query = CreateQueryFilter(query, filter, isAdmin, checkAccess); var queryCount = new SqlQuery().SelectCount().From(query, "t1"); return Db.ExecuteScalar<int>(queryCount); } public List<Tuple<Guid, int, int>> GetByFilterCountForReport(TaskFilter filter, bool isAdmin, bool checkAccess) { filter = (TaskFilter)filter.Clone(); var query = new SqlQuery(MilestonesTable + " t") .InnerJoin(ProjectsTable + " p", Exp.EqColumns("t.project_id", "p.id") & Exp.EqColumns("t.tenant_id", "p.tenant_id")) .Select("t.create_by", "t.project_id") .Where("t.tenant_id", Tenant) .Where(Exp.Between("t.create_on", filter.GetFromDate(), filter.GetToDate())); if (filter.HasUserId) { query.Where(Exp.In("t.create_by", filter.GetUserIds())); filter.UserId = Guid.Empty; filter.DepartmentId = Guid.Empty; } query = CreateQueryFilter(query, filter, isAdmin, checkAccess); var queryCount = new SqlQuery() .SelectCount() .Select("t1.create_by", "t1.project_id") .GroupBy("create_by", "project_id") .From(query, "t1"); return Db.ExecuteList(queryCount).ConvertAll(b => new Tuple<Guid, int, int>(Guid.Parse((string)b[1]), Convert.ToInt32(b[2]), Convert.ToInt32(b[0]))); ; } public List<Milestone> GetByStatus(int projectId, MilestoneStatus milestoneStatus) { return Db.ExecuteList(CreateQuery().Where("t.project_id", projectId).Where("t.status", milestoneStatus)) .ConvertAll(converter); } public List<Milestone> GetUpcomingMilestones(int offset, int max, params int[] projects) { var query = CreateQuery() .SetFirstResult(offset) .Where("p.status", ProjectStatus.Open) .Where(Exp.Ge("t.deadline", TenantUtil.DateTimeNow().Date)) .Where("t.status", MilestoneStatus.Open) .SetMaxResults(max) .OrderBy("t.deadline", true); if (projects != null && 0 < projects.Length) { query.Where(Exp.In("p.id", projects.Take(0 < max ? max : projects.Length).ToArray())); } return Db.ExecuteList(query).ConvertAll(converter); } public List<Milestone> GetLateMilestones(int offset, int max) { var now = TenantUtil.DateTimeNow(); var yesterday = now.Date.AddDays(-1); var query = CreateQuery() .SetFirstResult(offset) .Where("p.status", ProjectStatus.Open) .Where(!Exp.Eq("t.status", MilestoneStatus.Closed)) .Where(Exp.Le("t.deadline", yesterday)) .SetMaxResults(max) .OrderBy("t.deadline", true); return Db.ExecuteList(query).ConvertAll(converter); } public List<Milestone> GetByDeadLine(DateTime deadline) { return Db.ExecuteList(CreateQuery().Where("t.deadline", deadline.Date).OrderBy("t.deadline", true)) .ConvertAll(converter); } public virtual Milestone GetById(int id) { return Db.ExecuteList(CreateQuery().Where("t.id", id)) .ConvertAll(converter) .SingleOrDefault(); } public List<Milestone> GetById(int[] id) { return Db.ExecuteList(CreateQuery().Where(Exp.In("t.id", id))) .ConvertAll(converter); } public bool IsExists(int id) { var count = Db.ExecuteScalar<long>(Query(MilestonesTable).SelectCount().Where("id", id)); return 0 < count; } public List<object[]> GetInfoForReminder(DateTime deadline) { var deadlineDate = deadline.Date; var q = new SqlQuery(MilestonesTable + " t") .Select("t.tenant_id", "t.id", "t.deadline") .InnerJoin(ProjectsTable + " p", Exp.EqColumns("t.tenant_id", "p.tenant_id") & Exp.EqColumns("t.project_id", "p.id")) .Where(Exp.Between("t.deadline", deadlineDate.AddDays(-1), deadlineDate.AddDays(1))) .Where("t.status", MilestoneStatus.Open) .Where("p.status", ProjectStatus.Open) .Where("t.is_notify", 1); return Db.ExecuteList(q) .ConvertAll(r => new object[] { Convert.ToInt32(r[0]), Convert.ToInt32(r[1]), Convert.ToDateTime(r[2]) }); } public virtual Milestone Save(Milestone milestone) { if (milestone.DeadLine.Kind != DateTimeKind.Local) milestone.DeadLine = TenantUtil.DateTimeFromUtc(milestone.DeadLine); var insert = Insert(MilestonesTable) .InColumnValue("id", milestone.ID) .InColumnValue("project_id", milestone.Project != null ? milestone.Project.ID : 0) .InColumnValue("title", milestone.Title) .InColumnValue("create_by", milestone.CreateBy.ToString()) .InColumnValue("create_on", TenantUtil.DateTimeToUtc(milestone.CreateOn)) .InColumnValue("last_modified_by", milestone.LastModifiedBy.ToString()) .InColumnValue("last_modified_on", TenantUtil.DateTimeToUtc(milestone.LastModifiedOn)) .InColumnValue("deadline", milestone.DeadLine) .InColumnValue("status", milestone.Status) .InColumnValue("is_notify", milestone.IsNotify) .InColumnValue("is_key", milestone.IsKey) .InColumnValue("description", milestone.Description) .InColumnValue("status_changed", milestone.StatusChangedOn) .InColumnValue("responsible_id", milestone.Responsible.ToString()) .Identity(1, 0, true); milestone.ID = Db.ExecuteScalar<int>(insert); return milestone; } public virtual void Delete(int id) { using (var tx = Db.BeginTransaction()) { Db.ExecuteNonQuery(Delete(CommentsTable).Where("target_uniq_id", ProjectEntity.BuildUniqId<Milestone>(id))); Db.ExecuteNonQuery(Update(TasksTable).Set("milestone_id", 0).Where("milestone_id", id)); Db.ExecuteNonQuery(Delete(MilestonesTable).Where("id", id)); tx.Commit(); } } public string GetLastModified() { var query = Query(MilestonesTable).SelectMax("last_modified_on").SelectCount(); var data = Db.ExecuteList(query).FirstOrDefault(); if (data == null) { return ""; } var lastModified = ""; if (data[0] != null) { lastModified += TenantUtil.DateTimeFromUtc(Convert.ToDateTime(data[0])).ToString(CultureInfo.InvariantCulture); } if (data[1] != null) { lastModified += data[1]; } return lastModified; } private SqlQuery CreateQuery() { return new SqlQuery(MilestonesTable + " t") .InnerJoin(ProjectsTable + " p", Exp.EqColumns("t.tenant_id", "p.tenant_id") & Exp.EqColumns("t.project_id", "p.id")) .Select(ProjectDao.ProjectColumns.Select(c => "p." + c).ToArray()) .Select("t.id", "t.title", "t.create_by", "t.create_on", "t.last_modified_by", "t.last_modified_on") .Select("t.deadline", "t.status", "t.is_notify", "t.is_key", "t.description", "t.responsible_id") .Select("(select sum(case pt1.status when 1 then 1 when 4 then 1 else 0 end) from projects_tasks pt1 where pt1.tenant_id = t.tenant_id and pt1.milestone_id=t.id)") .Select("(select sum(case pt2.status when 2 then 1 else 0 end) from projects_tasks pt2 where pt2.tenant_id = t.tenant_id and pt2.milestone_id=t.id)") .GroupBy("t.id") .Where("t.tenant_id", Tenant); } private SqlQuery CreateQueryFilter(SqlQuery query, TaskFilter filter, bool isAdmin, bool checkAccess) { if (filter.MilestoneStatuses.Count != 0) { query.Where(Exp.In("t.status", filter.MilestoneStatuses)); } if (filter.ProjectIds.Count != 0) { query.Where(Exp.In("t.project_id", filter.ProjectIds)); } else { if (ProjectsCommonSettings.Load().HideEntitiesInPausedProjects) { query.Where(!Exp.Eq("p.status", ProjectStatus.Paused)); } if (filter.MyProjects) { query.InnerJoin(ParticipantTable + " ppp", Exp.EqColumns("p.id", "ppp.project_id") & Exp.Eq("ppp.removed", false) & Exp.EqColumns("ppp.tenant", "t.tenant_id")); query.Where("ppp.participant_id", CurrentUserID); } } if (filter.UserId != Guid.Empty) { query.Where(Exp.Eq("t.responsible_id", filter.UserId)); } if (filter.TagId != 0) { if (filter.TagId == -1) { query.LeftOuterJoin(ProjectTagTable + " ptag", Exp.EqColumns("ptag.project_id", "t.project_id")); query.Where("ptag.tag_id", null); } else { query.InnerJoin(ProjectTagTable + " ptag", Exp.EqColumns("ptag.project_id", "t.project_id")); query.Where("ptag.tag_id", filter.TagId); } } if (filter.ParticipantId.HasValue) { var existSubtask = new SqlQuery(SubtasksTable + " pst").Select("pst.task_id").Where(Exp.EqColumns("t.tenant_id", "pst.tenant_id") & Exp.EqColumns("pt.id", "pst.task_id") & Exp.Eq("pst.status", TaskStatus.Open)); var existResponsible = new SqlQuery(TasksResponsibleTable + " ptr1").Select("ptr1.task_id").Where(Exp.EqColumns("t.tenant_id", "ptr1.tenant_id") & Exp.EqColumns("pt.id", "ptr1.task_id")); existSubtask.Where(Exp.Eq("pst.responsible_id", filter.ParticipantId.ToString())); existResponsible.Where(Exp.Eq("ptr1.responsible_id", filter.ParticipantId.ToString())); query.LeftOuterJoin(TasksTable + " as pt", Exp.EqColumns("pt.milestone_id", "t.id") & Exp.EqColumns("pt.tenant_id", "t.tenant_id")); query.Where(Exp.Exists(existSubtask) | Exp.Exists(existResponsible)); } if (!filter.FromDate.Equals(DateTime.MinValue) && !filter.FromDate.Equals(DateTime.MaxValue)) { query.Where(Exp.Ge("t.deadline", TenantUtil.DateTimeFromUtc(filter.FromDate))); } if (!filter.ToDate.Equals(DateTime.MinValue) && !filter.ToDate.Equals(DateTime.MaxValue)) { query.Where(Exp.Le("t.deadline", TenantUtil.DateTimeFromUtc(filter.ToDate))); } if (!string.IsNullOrEmpty(filter.SearchText)) { List<int> mIds; if (FactoryIndexer<MilestonesWrapper>.TrySelectIds(s => s.MatchAll(filter.SearchText), out mIds)) { query.Where(Exp.In("t.id", mIds)); } else { query.Where(Exp.Like("t.title", filter.SearchText, SqlLike.AnyWhere)); } } CheckSecurity(query, filter, isAdmin, checkAccess); return query; } private static Milestone ToMilestone(object[] r) { var offset = ProjectDao.ProjectColumns.Length; return new Milestone { Project = r[0] != null ? ProjectDao.ToProject(r) : null, ID = Convert.ToInt32(r[0 + offset]), Title = (string)r[1 + offset], CreateBy = ToGuid(r[2 + offset]), CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[3 + offset])), LastModifiedBy = ToGuid(r[4 + offset]), LastModifiedOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[5 + offset])), DeadLine = DateTime.SpecifyKind(Convert.ToDateTime(r[6 + offset]), DateTimeKind.Local), Status = (MilestoneStatus)Convert.ToInt32(r[7 + offset]), IsNotify = Convert.ToBoolean(r[8 + offset]), IsKey = Convert.ToBoolean(r[9 + offset]), Description = (string)r[10 + offset], Responsible = ToGuid(r[11 + offset]), ActiveTaskCount = Convert.ToInt32(r[12 + ProjectDao.ProjectColumns.Length]), ClosedTaskCount = Convert.ToInt32(r[13 + ProjectDao.ProjectColumns.Length]) }; } public List<Milestone> GetMilestones(Exp where) { return Db.ExecuteList(CreateQuery().Where(where)).ConvertAll(converter); } private void CheckSecurity(SqlQuery query, TaskFilter filter, bool isAdmin, bool checkAccess) { if (checkAccess) { query.Where(Exp.Eq("p.private", false)); return; } if (isAdmin) return; if (!filter.MyProjects && !filter.MyMilestones) { query.LeftOuterJoin(ParticipantTable + " ppp", Exp.Eq("ppp.participant_id", CurrentUserID) & Exp.EqColumns("ppp.project_id", "t.project_id") & Exp.EqColumns("ppp.tenant", "t.tenant_id")); } var isInTeam = !Exp.Eq("ppp.security", null) & Exp.Eq("ppp.removed", false); var canReadMilestones = !Exp.Eq("security & " + (int)ProjectTeamSecurity.Milestone, (int)ProjectTeamSecurity.Milestone); var responsible = Exp.Eq("t.responsible_id", CurrentUserID); query.Where(Exp.Eq("p.private", false) | isInTeam & (responsible | canReadMilestones)); } } }
// // Copyright (c) 2014 Piotr Fusik <piotr@fusik.info> // // 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. // // 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. // using System; using System.Collections.Generic; using System.Data; #if DOTNET35 using System.Linq; #endif using Sooda.QL; using Sooda.QL.TypedWrappers; using Sooda.Schema; using Sooda.UnitTests.BaseObjects; using Sooda.UnitTests.Objects; using NUnit.Framework; namespace Sooda.UnitTests.TestCases { [TestFixture] public class DynamicFieldsTest { #if DOTNET35 const string IntField = "IntDynamicField"; static void AddIntField(SoodaTransaction tran) { DynamicFieldManager.Add(new FieldInfo { ParentClass = tran.Schema.FindClassByName("PKInt32"), Name = IntField, TypeName = "Integer", IsNullable = false }, tran); } static void Remove(string name, SoodaTransaction tran) { FieldInfo fi = tran.Schema.FindClassByName("PKInt32").FindFieldByName(name); DynamicFieldManager.Remove(fi, tran); } const string DateTimeField = "DateTimeDynamicField"; static void AddDateTimeField(SoodaTransaction tran) { DynamicFieldManager.Add(new FieldInfo { ParentClass = tran.Schema.FindClassByName("PKInt32"), Name = DateTimeField, Type = typeof(DateTime?) }, tran); } const string ReferenceField = "ContactDynamicField"; static void AddReferenceField(SoodaTransaction tran) { DynamicFieldManager.Add(new FieldInfo { ParentClass = tran.Schema.FindClassByName("PKInt32"), Name = ReferenceField, Type = typeof(Contact), IsNullable = false }, tran); } static void UpdateReferenceField(SoodaTransaction tran) { FieldInfo fi = tran.Schema.FindClassByName("PKInt32").FindFieldByName(ReferenceField); fi.IsNullable = true; DynamicFieldManager.Update(fi, tran); } const string StringField = "StringDynamicField"; static void AddStringField(SoodaTransaction tran) { DynamicFieldManager.Add(new FieldInfo { ParentClass = tran.Schema.FindClassByName("PKInt32"), Name = StringField, TypeName = "String", Size = 128, IsNullable = false }, tran); } #endif [Test] public void IndexerGetStatic() { using (new SoodaTransaction()) { object result = Contact.Mary["Name"]; Assert.AreEqual("Mary Manager", result); result = Contact.Mary["Active"]; Assert.AreEqual(true, result); } } [Test] public void IndexerGetStaticRef() { using (new SoodaTransaction()) { object result = Contact.Ed["Manager"]; Assert.AreEqual(Contact.Mary, result); result = Contact.Mary["Manager"]; Assert.IsNull(result); } } [Test] public void IndexerGetPrimaryKey() { using (new SoodaTransaction()) { object result = Contact.Ed["ContactId"]; Assert.AreEqual(2, result); } } [Test] public void IndexerGetStaticChanged() { using (new SoodaTransaction()) { Contact.Mary.Name = "Mary Dismissed"; Contact.Mary.Active = false; object result = Contact.Mary["Name"]; Assert.AreEqual("Mary Dismissed", result); result = Contact.Mary["Active"]; Assert.AreEqual(false, result); } } [Test] public void IndexerGetStaticRefChanged() { using (new SoodaTransaction()) { Contact.Ed.Manager = Contact.Eva; Contact.Eva.Manager = null; object result = Contact.Ed["Manager"]; Assert.AreEqual(Contact.Eva, result); result = Contact.Eva["Manager"]; Assert.IsNull(result); } } [Test] [ExpectedException(typeof(Exception))] public void IndexerGetNonExisting() { using (new SoodaTransaction()) { object result = Contact.Mary["NoSuchField"]; } } [Test] [ExpectedException(typeof(InvalidOperationException))] public void IndexerSetStatic() { using (new SoodaTransaction()) { Contact.Mary["Active"] = false; } } #if DOTNET35 [Test] public void IndexerGetDynamic() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); AddDateTimeField(tran); AddReferenceField(tran); try { object value = PKInt32.GetRef(7777777)[IntField]; Assert.IsNull(value); value = PKInt32.GetRef(7777777)[DateTimeField]; Assert.IsNull(value); value = PKInt32.GetRef(7777777)[ReferenceField]; Assert.IsNull(value); } finally { Remove(ReferenceField, tran); Remove(DateTimeField, tran); Remove(IntField, tran); } } } [Test] public void IndexerSetDynamic() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); AddDateTimeField(tran); AddReferenceField(tran); try { PKInt32.GetRef(7777777)[IntField] = 42; PKInt32.GetRef(7777777)[DateTimeField] = new DateTime(2014, 10, 28); PKInt32.GetRef(7777777)[ReferenceField] = Contact.Ed; object value = PKInt32.GetRef(7777777)[IntField]; Assert.AreEqual(42, value); value = PKInt32.GetRef(7777777)[DateTimeField]; Assert.AreEqual(new DateTime(2014, 10, 28), value); value = PKInt32.GetRef(7777777)[ReferenceField]; Assert.AreEqual(Contact.Ed, value); } finally { Remove(ReferenceField, tran); Remove(DateTimeField, tran); Remove(IntField, tran); } } } [Test] [ExpectedException(typeof(InvalidCastException))] public void IndexerTypeCheck() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); try { PKInt32.GetRef(7777777)[IntField] = "invalid"; } finally { Remove(IntField, tran); } } } [Test] [ExpectedException(typeof(InvalidCastException))] public void IndexerTypeCheckReference() { using (SoodaTransaction tran = new SoodaTransaction()) { AddReferenceField(tran); try { PKInt32.GetRef(7777777)[ReferenceField] = PKInt32.GetRef(7777777); } finally { Remove(ReferenceField, tran); } } } [Test] public void NonNullString() { using (SoodaTransaction tran = new SoodaTransaction()) { AddStringField(tran); PKInt32 o = new PKInt32(); try { o.Parent = o; Assert.AreEqual("", o[StringField]); } finally { o.MarkForDelete(); Remove(StringField, tran); } } } [Test] [ExpectedException(typeof(SoodaException))] public void NonNullReference() { using (SoodaTransaction tran = new SoodaTransaction()) { AddReferenceField(tran); PKInt32 o = new PKInt32(); try { o.Parent = o; tran.Commit(); } finally { o.MarkForDelete(); Remove(ReferenceField, tran); } } } [Test] public void UpdateReferenceToNullable() { using (SoodaTransaction tran = new SoodaTransaction()) { AddReferenceField(tran); PKInt32 o = new PKInt32(); try { o.Parent = o; UpdateReferenceField(tran); tran.Commit(); } finally { o.MarkForDelete(); Remove(ReferenceField, tran); tran.Commit(); } } } [Test] public void CreateIndex() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); try { FieldInfo fi = tran.Schema.FindClassByName("PKInt32").FindFieldByName(IntField); DynamicFieldManager.CreateIndex(fi, tran); } finally { Remove(IntField, tran); } } } #endif [Test] public void FieldInfoStatic() { using (SoodaTransaction tran = new SoodaTransaction()) { FieldInfo fi = tran.Schema.FindClassByName("Contact").FindFieldByName("Name"); Assert.AreEqual("Name", fi.Name); Assert.AreEqual(FieldDataType.AnsiString, fi.DataType); Assert.IsNull(fi.References); Assert.IsFalse(fi.IsPrimaryKey); Assert.IsFalse(fi.IsNullable); Assert.AreEqual("AnsiString", fi.TypeName); Assert.AreEqual(typeof(string), fi.Type); Assert.IsFalse(fi.IsDynamic); } } #if DOTNET35 [Test] public void FieldInfoDynamic() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); AddDateTimeField(tran); AddReferenceField(tran); try { FieldInfo fi = tran.Schema.FindClassByName("PKInt32").FindFieldByName(IntField); Assert.AreEqual(IntField, fi.Name); Assert.AreEqual(FieldDataType.Integer, fi.DataType); Assert.IsNull(fi.References); Assert.IsFalse(fi.IsPrimaryKey); Assert.IsFalse(fi.IsNullable); Assert.AreEqual("Integer", fi.TypeName); Assert.AreEqual(typeof(int), fi.Type); Assert.IsTrue(fi.IsDynamic); fi = tran.Schema.FindClassByName("PKInt32").FindFieldByName(DateTimeField); Assert.AreEqual(DateTimeField, fi.Name); Assert.AreEqual(FieldDataType.DateTime, fi.DataType); Assert.IsNull(fi.References); Assert.IsFalse(fi.IsPrimaryKey); Assert.IsTrue(fi.IsNullable); Assert.AreEqual("DateTime", fi.TypeName); Assert.AreEqual(typeof(DateTime?), fi.Type); Assert.IsTrue(fi.IsDynamic); fi = tran.Schema.FindClassByName("PKInt32").FindFieldByName(ReferenceField); Assert.AreEqual(ReferenceField, fi.Name); Assert.AreEqual(FieldDataType.Integer, fi.DataType); Assert.AreEqual("Contact", fi.References); Assert.IsFalse(fi.IsPrimaryKey); Assert.IsFalse(fi.IsNullable); Assert.AreEqual("Contact", fi.TypeName); Assert.AreEqual(typeof(Contact), fi.Type); Assert.IsTrue(fi.IsDynamic); } finally { Remove(ReferenceField, tran); Remove(DateTimeField, tran); Remove(IntField, tran); } } } [Test] [ExpectedException(typeof(SoodaSchemaException))] public void DuplicateFieldWithStatic() { using (SoodaTransaction tran = new SoodaTransaction()) { DynamicFieldManager.Add(new FieldInfo { ParentClass = tran.Schema.FindClassByName("PKInt32"), Name = "Data", TypeName = "Integer", IsNullable = false }, tran); } } [Test] [ExpectedException(typeof(SoodaSchemaException))] public void DuplicateFieldWithDynamic() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); try { AddIntField(tran); } finally { Remove(IntField, tran); } } } static string TriggerText(string field, object oldVal, object newVal) { return PKInt32.GetTriggerText("Before", field, oldVal, newVal) + PKInt32.GetTriggerText("After", field, oldVal, newVal); } [Test] public void FieldUpdateTriggers() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); AddDateTimeField(tran); AddReferenceField(tran); try { PKInt32 o = PKInt32.GetRef(7777777); o[IntField] = 42; string expected = TriggerText(IntField, null, 42); o[DateTimeField] = new DateTime(2014, 10, 28); expected += TriggerText(DateTimeField, null, new DateTime(2014, 10, 28)); o[ReferenceField] = Contact.Ed; expected += TriggerText(ReferenceField, null, Contact.Ed); Assert.AreEqual(expected, o.triggersText); } finally { Remove(ReferenceField, tran); Remove(DateTimeField, tran); Remove(IntField, tran); } } } [Test] public void WhereStatic() { using (new SoodaTransaction()) { IEnumerable<Contact> ce = Contact.Linq().Where(c => (string) c["Name"] == "Mary Manager"); CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce); } } [Test] [ExpectedException(typeof(Exception))] public void WhereNonExisting() { using (new SoodaTransaction()) { Contact.Linq().Any(c => (string) c["NoSuchField"] == "Mary Manager"); } } [Test] public void WhereDynamicInsert() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); PKInt32 o = new PKInt32(); try { o.Parent = o; o[IntField] = 42; IEnumerable<PKInt32> pe = PKInt32.Linq().Where(p => (int) p[IntField] == 5); CollectionAssert.IsEmpty(pe); pe = PKInt32.Linq().Where(p => (int) p[IntField] == 42); CollectionAssert.AreEquivalent(new PKInt32[] { o }, pe); } finally { o.MarkForDelete(); Remove(IntField, tran); } } } [Test] public void WhereDynamicUpdate() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); try { PKInt32.GetRef(7777777)[IntField] = 42; IEnumerable<PKInt32> pe = PKInt32.Linq().Where(p => (int) p[IntField] == 5); CollectionAssert.IsEmpty(pe); pe = PKInt32.Linq().Where(p => (int) p[IntField] == 42); CollectionAssert.AreEquivalent(new PKInt32[] { PKInt32.GetRef(7777777) }, pe); } finally { Remove(IntField, tran); } } } [Test] public void WhereDynamicReference() { using (SoodaTransaction tran = new SoodaTransaction()) { AddReferenceField(tran); PKInt32 o = new PKInt32(); try { o.Parent = o; o[ReferenceField] = Contact.Mary; IEnumerable<PKInt32> pe = PKInt32.Linq().Where(p => ((Contact) p[ReferenceField]).LastSalary.Value == 42); CollectionAssert.IsEmpty(pe); pe = PKInt32.Linq().Where(p => ((Contact) p[ReferenceField]).LastSalary.Value == 123.123456789M); CollectionAssert.AreEquivalent(new PKInt32[] { o }, pe); pe = PKInt32.Linq().Where(p => ((Contact) p[ReferenceField]).GetLabel(false) == "Mary Manager"); CollectionAssert.AreEquivalent(new PKInt32[] { o }, pe); } finally { o.MarkForDelete(); Remove(ReferenceField, tran); } } } [Test] public void OrderBySelectStatic() { using (new SoodaTransaction()) { IEnumerable<string> se = from c in Contact.Linq() orderby c["Name"] select (string) c["Name"]; CollectionAssert.AreEqual(new string[] { "Caroline Customer", "Catie Customer", "Chris Customer", "Chuck Customer", "Ed Employee", "Eva Employee", "Mary Manager" }, se); } } [Test] [ExpectedException(typeof(Exception))] public void SelectNonExisting() { using (new SoodaTransaction()) { Contact.Linq().Select(c => c["NoSuchField"]).ToList(); } } [Test] public void SelectDynamic() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); try { PKInt32.GetRef(7777778)[IntField] = 42; IEnumerable<object> oe = PKInt32.Linq().Select(p => p[IntField]); CollectionAssert.AreEquivalent(new object[] { null, 42, null }, oe); } finally { Remove(IntField, tran); } } } static object ExecuteScalar(SoodaTransaction tran, string sql, params object[] parameters) { using (IDataReader r = tran.OpenDataSource("default").ExecuteRawQuery(sql, parameters)) { if (!r.Read()) return null; return r.GetValue(0); } } [Test] public void DontInsertNull() { using (SoodaTransaction tran = new SoodaTransaction()) { AddDateTimeField(tran); PKInt32 o = new PKInt32(); try { o.Parent = o; tran.SaveObjectChanges(); object count = ExecuteScalar(tran, "select count(*) from PKInt32 where id={0}", o.Id); Assert.AreEqual(1, count); count = ExecuteScalar(tran, "select count(*) from PKInt32_" + DateTimeField + " where id={0}", o.Id); Assert.AreEqual(0, count); } finally { o.MarkForDelete(); Remove(DateTimeField, tran); } } } [Test] public void SoodaWhereClauseDynamicInsert() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); PKInt32 o = new PKInt32(); try { o.Parent = o; o[IntField] = 42; PKInt32List pl = PKInt32.GetList(new SoodaWhereClause("IntDynamicField = 5")); CollectionAssert.IsEmpty(pl); pl = PKInt32.GetList(new SoodaWhereClause("IntDynamicField = 42")); CollectionAssert.AreEquivalent(new PKInt32[] { o }, pl); } finally { o.MarkForDelete(); Remove(IntField, tran); } } } [Test] public void SoqlDynamicInsert() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); PKInt32 o = new PKInt32(); try { o.Parent = o; o[IntField] = 42; PKInt32List pl = PKInt32.GetList(new SoqlBooleanRelationalExpression(new SoqlPathExpression(IntField), new SoqlLiteralExpression(5), SoqlRelationalOperator.Equal)); CollectionAssert.IsEmpty(pl); pl = PKInt32.GetList(new SoqlBooleanRelationalExpression(new SoqlPathExpression(IntField), new SoqlLiteralExpression(42), SoqlRelationalOperator.Equal)); CollectionAssert.AreEquivalent(new PKInt32[] { o }, pl); } finally { o.MarkForDelete(); Remove(IntField, tran); } } } [Test] public void SoqlWrapperDynamicInsert() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); PKInt32 o = new PKInt32(); try { o.Parent = o; o[IntField] = 42; PKInt32List pl = PKInt32.GetList(new SoqlInt32WrapperExpression(new SoqlPathExpression(IntField)) == 5); CollectionAssert.IsEmpty(pl); pl = PKInt32.GetList(new SoqlInt32WrapperExpression(new SoqlPathExpression(IntField)) == 42); CollectionAssert.AreEquivalent(new PKInt32[] { o }, pl); } finally { o.MarkForDelete(); Remove(IntField, tran); } } } #endif #if DOTNET4 [Test] public void DynamicGetStatic() { using (new SoodaTransaction()) { dynamic d = Contact.Mary; object result = d.Name; Assert.AreEqual("Mary Manager", result); result = d.Active; Assert.AreEqual(true, result); } } [Test] public void DynamicGetStaticRef() { using (new SoodaTransaction()) { dynamic d = Contact.Ed; object result = d.Manager; Assert.AreEqual(Contact.Mary, result); d = Contact.Mary; result = d.Manager; Assert.IsNull(result); } } [Test] public void DynamicGetPrimaryKey() { using (new SoodaTransaction()) { dynamic d = Contact.Ed; object result = d.ContactId; Assert.AreEqual(2, result); } } [Test] [ExpectedException(typeof(Exception))] public void DynamicGetNonExisting() { using (new SoodaTransaction()) { dynamic d = Contact.Mary; object result = d.NoSuchField; } } [Test] public void DynamicGetLabel() { using (new SoodaTransaction()) { dynamic d = Contact.Mary; object result = d.GetLabel(false); Assert.AreEqual("Mary Manager", result); } } [Test] public void DynamicGetCodeProperty() { using (new SoodaTransaction()) { dynamic d = Contact.Mary; object result = d.NameAndType; Assert.AreEqual("Mary Manager (Manager)", result); } } [Test] public void DynamicSetStatic() { using (new SoodaTransaction()) { dynamic d = Contact.Mary; d.Active = false; Assert.IsFalse(Contact.Mary.Active); } } [Test] public void DynamicGetDynamic() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); try { dynamic d = PKInt32.GetRef(7777777); object value = d.IntDynamicField; Assert.IsNull(value); } finally { Remove(IntField, tran); } } } [Test] public void DynamicSetDynamic() { using (SoodaTransaction tran = new SoodaTransaction()) { AddIntField(tran); try { dynamic d = PKInt32.GetRef(7777777); d.IntDynamicField = 42; object value = d.IntDynamicField; Assert.AreEqual(42, value); } finally { Remove(IntField, tran); } } } #endif } }
using System; using System.Collections.Generic; using System.Globalization; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Web; using Umbraco.Cms.Web.Common.DependencyInjection; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Routing { /// <summary> /// Provides urls. /// </summary> public class DefaultUrlProvider : IUrlProvider { private readonly ILocalizationService _localizationService; private readonly ILocalizedTextService _localizedTextService; private readonly ILogger<DefaultUrlProvider> _logger; private readonly RequestHandlerSettings _requestSettings; private readonly ISiteDomainMapper _siteDomainMapper; private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly UriUtility _uriUtility; [Obsolete("Use ctor with all parameters")] public DefaultUrlProvider(IOptions<RequestHandlerSettings> requestSettings, ILogger<DefaultUrlProvider> logger, ISiteDomainMapper siteDomainMapper, IUmbracoContextAccessor umbracoContextAccessor, UriUtility uriUtility) : this(requestSettings, logger, siteDomainMapper, umbracoContextAccessor, uriUtility, StaticServiceProvider.Instance.GetRequiredService<ILocalizationService>()) { } public DefaultUrlProvider( IOptions<RequestHandlerSettings> requestSettings, ILogger<DefaultUrlProvider> logger, ISiteDomainMapper siteDomainMapper, IUmbracoContextAccessor umbracoContextAccessor, UriUtility uriUtility, ILocalizationService localizationService) { _requestSettings = requestSettings.Value; _logger = logger; _siteDomainMapper = siteDomainMapper; _umbracoContextAccessor = umbracoContextAccessor; _uriUtility = uriUtility; _localizationService = localizationService; } #region GetOtherUrls /// <summary> /// Gets the other URLs of a published content. /// </summary> /// <param name="umbracoContextAccessor">The Umbraco context.</param> /// <param name="id">The published content id.</param> /// <param name="current">The current absolute URL.</param> /// <returns>The other URLs for the published content.</returns> /// <remarks> /// <para> /// Other URLs are those that <c>GetUrl</c> would not return in the current context, but would be valid /// URLs for the node in other contexts (different domain for current request, umbracoUrlAlias...). /// </para> /// </remarks> public virtual IEnumerable<UrlInfo> GetOtherUrls(int id, Uri current) { IUmbracoContext umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); IPublishedContent node = umbracoContext.Content.GetById(id); if (node == null) { yield break; } // look for domains, walking up the tree IPublishedContent n = node; IEnumerable<DomainAndUri> domainUris = DomainUtilities.DomainsForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, n.Id, current, false); while (domainUris == null && n != null) // n is null at root { n = n.Parent; // move to parent node domainUris = n == null ? null : DomainUtilities.DomainsForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, n.Id, current); } // no domains = exit if (domainUris == null) { yield break; } foreach (DomainAndUri d in domainUris) { var culture = d?.Culture; // although we are passing in culture here, if any node in this path is invariant, it ignores the culture anyways so this is ok var route = umbracoContext.Content.GetRouteById(id, culture); if (route == null) { continue; } // need to strip off the leading ID for the route if it exists (occurs if the route is for a node with a domain assigned) var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); var uri = new Uri(CombinePaths(d.Uri.GetLeftPart(UriPartial.Path), path)); uri = _uriUtility.UriFromUmbraco(uri, _requestSettings); yield return UrlInfo.Url(uri.ToString(), culture); } } #endregion #region GetUrl /// <inheritdoc /> public virtual UrlInfo GetUrl(IPublishedContent content, UrlMode mode, string culture, Uri current) { if (!current.IsAbsoluteUri) { throw new ArgumentException("Current URL must be absolute.", nameof(current)); } IUmbracoContext umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); // will not use cache if previewing var route = umbracoContext.Content.GetRouteById(content.Id, culture); return GetUrlFromRoute(route, umbracoContext, content.Id, current, mode, culture); } internal UrlInfo GetUrlFromRoute(string route, IUmbracoContext umbracoContext, int id, Uri current, UrlMode mode, string culture) { if (string.IsNullOrWhiteSpace(route)) { _logger.LogDebug( "Couldn't find any page with nodeId={NodeId}. This is most likely caused by the page not being published.", id); return null; } // extract domainUri and path // route is /<path> or <domainRootId>/<path> var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); var domainUri = pos == 0 ? null : DomainUtilities.DomainForNode(umbracoContext.PublishedSnapshot.Domains, _siteDomainMapper, int.Parse(route.Substring(0, pos), CultureInfo.InvariantCulture), current, culture); var defaultCulture = _localizationService.GetDefaultLanguageIsoCode(); if (domainUri is not null || culture == defaultCulture || string.IsNullOrEmpty(culture)) { var url = AssembleUrl(domainUri, path, current, mode).ToString(); return UrlInfo.Url(url, culture); } return null; } #endregion #region Utilities private Uri AssembleUrl(DomainAndUri domainUri, string path, Uri current, UrlMode mode) { Uri uri; // ignore vdir at that point, UriFromUmbraco will do it if (domainUri == null) // no domain was found { if (current == null) { mode = UrlMode.Relative; // best we can do } switch (mode) { case UrlMode.Absolute: uri = new Uri(current.GetLeftPart(UriPartial.Authority) + path); break; case UrlMode.Relative: case UrlMode.Auto: uri = new Uri(path, UriKind.Relative); break; default: throw new ArgumentOutOfRangeException(nameof(mode)); } } else // a domain was found { if (mode == UrlMode.Auto) { //this check is a little tricky, we can't just compare domains if (current != null && domainUri.Uri.GetLeftPart(UriPartial.Authority) == current.GetLeftPart(UriPartial.Authority)) { mode = UrlMode.Relative; } else { mode = UrlMode.Absolute; } } switch (mode) { case UrlMode.Absolute: uri = new Uri(CombinePaths(domainUri.Uri.GetLeftPart(UriPartial.Path), path)); break; case UrlMode.Relative: uri = new Uri(CombinePaths(domainUri.Uri.AbsolutePath, path), UriKind.Relative); break; default: throw new ArgumentOutOfRangeException(nameof(mode)); } } // UriFromUmbraco will handle vdir // meaning it will add vdir into domain URLs too! return _uriUtility.UriFromUmbraco(uri, _requestSettings); } private string CombinePaths(string path1, string path2) { var path = path1.TrimEnd(Constants.CharArrays.ForwardSlash) + path2; return path == "/" ? path : path.TrimEnd(Constants.CharArrays.ForwardSlash); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Mercurial.Attributes; namespace Mercurial { /// <summary> /// This class implements the "hg commit" command (<see href="http://www.selenic.com/mercurial/hg.1.html#commit"/>): /// commit the specified files or all outstanding changes. /// </summary> public sealed class CommitCommand : IncludeExcludeCommandBase<CommitCommand>, IMercurialCommand<RevSpec> { /// <summary> /// This field is used to specify the encoding of the commit message. /// </summary> private static readonly Encoding _Encoding = ClientExecutable.TextEncoding; /// <summary> /// This is the backing field for the <see cref="Paths"/> property. /// </summary> private readonly ListFile _Paths = new ListFile(); /// <summary> /// This is the backing field for the <see cref="Message"/> property. /// </summary> private string _Message = string.Empty; /// <summary> /// This field is used internally to temporarily hold the filename of the file /// that the <see cref="Message"/> was stored into, during command execution. /// </summary> private string _MessageFilePath; /// <summary> /// This is the backing field for the <see cref="OverrideAuthor"/> property. /// </summary> private string _OverrideAuthor = string.Empty; /// <summary> /// This is the backing field for the <see cref="RecurseSubRepositories"/> property. /// </summary> private bool _RecurseSubRepositories; /// <summary> /// Initializes a new instance of the <see cref="CommitCommand"/> class. /// </summary> public CommitCommand() : base("commit") { // Do nothing here } /// <summary> /// Gets or sets the commit message to use when committing. /// </summary> [DefaultValue("")] public string Message { get { return _Message; } set { _Message = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets a value indicating whether to automatically add new files and remove missing files before committing. /// Default is <c>false</c>. /// </summary> [BooleanArgument(TrueOption = "--addremove")] [DefaultValue(false)] public bool AddRemove { get; set; } /// <summary> /// Gets or sets a value indicating whether to mark a branch as closed, hiding it from the branch list. /// Default is <c>false</c>. /// </summary> [BooleanArgument(TrueOption = "--close-branch")] [DefaultValue(false)] public bool CloseBranch { get; set; } /// <summary> /// Gets or sets the username to use when committing; /// or <see cref="string.Empty"/> to use the username configured in the repository or by /// the current user. Default is <see cref="string.Empty"/>. /// </summary> [NullableArgument(NonNullOption = "--user")] [DefaultValue("")] public string OverrideAuthor { get { return _OverrideAuthor; } set { _OverrideAuthor = (value ?? string.Empty).Trim(); } } /// <summary> /// Gets or sets the timestamp <see cref="DateTime"/> to use when committing; /// or <c>null</c> which means use the current date and time. Default is <c>null</c>. /// </summary> [DateTimeArgument(NonNullOption = "--date")] [DefaultValue(null)] public DateTime? OverrideTimestamp { get; set; } /// <summary> /// Gets the collection of files to commit. If left empty, will commit all /// pending changes. /// </summary> public Collection<string> Paths { get { return _Paths.Collection; } } #region IMercurialCommand<RevSpec> Members /// <summary> /// Gets all the arguments to the <see cref="CommandBase{T}.Command"/>, or an /// empty array if there are none. /// </summary> /// <value></value> public override IEnumerable<string> Arguments { get { return base.Arguments.Concat( new[] { "--logfile", string.Format(CultureInfo.InvariantCulture, "\"{0}\"", _MessageFilePath), }).Concat(_Paths.GetArguments()); } } /// <summary> /// Validates the command configuration. This method should throw the necessary /// exceptions to signal missing or incorrect configuration (like attempting to /// add files to the repository without specifying which files to add.) /// </summary> /// <exception cref="InvalidOperationException"> /// The 'commit' command requires <see cref="Message"/> to be specified. /// </exception> public override void Validate() { base.Validate(); if (StringEx.IsNullOrWhiteSpace(Message)) throw new InvalidOperationException("The 'commit' command requires Message to be specified"); DebugOutput = true; } /// <summary> /// Gets or sets the result of executing the command as a <see cref="RevSpec"/> identifying the /// new changeset that was committed. /// </summary> public RevSpec Result { get; set; } /// <summary> /// Gets or sets a value indicating whether to recurse into subrepositories. This is new from /// Mercurial 2.0. Older clients will by default recurse regardless of this property. /// Default value is <c>false</c>. /// </summary> [BooleanArgument(TrueOption = "--subrepos")] [DefaultValue(false)] public bool RecurseSubRepositories { get { return _RecurseSubRepositories; } set { RequiresVersion(new Version(2, 0), "RecurseSubRepositories property of CommitCommand"); _RecurseSubRepositories = value; } } #endregion /// <summary> /// Sets the <see cref="Message"/> property to the specified value and /// returns this <see cref="CommitCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="Message"/> property. /// </param> /// <returns> /// This <see cref="CommitCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public CommitCommand WithMessage(string value) { Message = value; return this; } /// <summary> /// Sets the <see cref="AddRemove"/> property to the specified value and /// returns this <see cref="CommitCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="AddRemove"/> property, /// defaults to <c>true</c>. /// </param> /// <returns> /// This <see cref="CommitCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public CommitCommand WithAddRemove(bool value = true) { AddRemove = value; return this; } /// <summary> /// Sets the <see cref="RecurseSubRepositories"/> property to the specified value and /// returns this <see cref="CommitCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="RecurseSubRepositories"/> property, /// defaults to <c>true</c>. /// </param> /// <returns> /// This <see cref="CommitCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public CommitCommand WithRecurseSubRepositories(bool value = true) { RequiresVersion(new Version(2, 0), "RecurseSubRepositories property of CommitCommand"); RecurseSubRepositories = value; return this; } /// <summary> /// Sets the <see cref="CloseBranch"/> property to the specified value and /// returns this <see cref="CommitCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="CloseBranch"/> property, /// defaults to <c>true</c>. /// </param> /// <returns> /// This <see cref="CommitCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public CommitCommand WithCloseBranch(bool value = true) { CloseBranch = value; return this; } /// <summary> /// Sets the <see cref="OverrideAuthor"/> property to the specified value and /// returns this <see cref="CommitCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="OverrideAuthor"/> property. /// </param> /// <returns> /// This <see cref="CommitCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public CommitCommand WithOverrideAuthor(string value) { OverrideAuthor = value; return this; } /// <summary> /// Sets the <see cref="OverrideTimestamp"/> property to the specified value and /// returns this <see cref="CommitCommand"/> instance. /// </summary> /// <param name="value"> /// The new value for the <see cref="OverrideTimestamp"/> property. /// </param> /// <returns> /// This <see cref="CommitCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> public CommitCommand WithOverrideTimestamp(DateTime value) { OverrideTimestamp = value; return this; } /// <summary> /// Adds the value to the <see cref="Paths"/> collection property and /// returns this <see cref="ForgetCommand"/> instance. /// </summary> /// <param name="value"> /// The value to add to the <see cref="Paths"/> collection property. /// </param> /// <returns> /// This <see cref="ForgetCommand"/> instance. /// </returns> /// <remarks> /// This method is part of the fluent interface. /// </remarks> /// <exception cref="ArgumentNullException"> /// <para><paramref name="value"/> is <c>null</c> or empty.</para> /// </exception> public CommitCommand WithPath(string value) { if (StringEx.IsNullOrWhiteSpace(value)) throw new ArgumentNullException("value"); Paths.Add(value.Trim()); return this; } /// <summary> /// Override this method to implement code that will execute before command /// line execution. /// </summary> protected override void Prepare() { _MessageFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString().Replace("-", string.Empty).ToLowerInvariant() + ".txt"); File.WriteAllText(_MessageFilePath, Message, _Encoding); } /// <summary> /// Override this method to implement code that will execute after command /// line execution. /// </summary> protected override void Cleanup() { if (_MessageFilePath != null && File.Exists(_MessageFilePath)) File.Delete(_MessageFilePath); _Paths.Cleanup(); } /// <summary> /// This method should parse and store the appropriate execution result output /// according to the type of data the command line client would return for /// the command. /// </summary> /// <param name="exitCode"> /// The exit code from executing the command line client. /// </param> /// <param name="standardOutput"> /// The standard output from executing the command line client. /// </param> /// <remarks> /// Note that as long as you descend from <see cref="MercurialCommandBase{T}"/> you're not required to call /// the base method at all. /// </remarks> protected override void ParseStandardOutputForResults(int exitCode, string standardOutput) { base.ParseStandardOutputForResults(exitCode, standardOutput); var re = new Regex(@"^committed\s+changeset\s+\d+:(?<hash>[0-9a-f]{40})$", RegexOptions.IgnoreCase); foreach (Match ma in standardOutput.Split( new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Select(line => re.Match(line)).Where(ma => ma.Success)) { Result = RevSpec.Single(ma.Groups["hash"].Value); return; } Result = 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.Collections; using System.Collections.ObjectModel; using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Diagnostics; namespace System.Data.Odbc { public sealed class OdbcConnectionStringBuilder : DbConnectionStringBuilder { private enum Keywords { // must maintain same ordering as _validKeywords array // NamedConnection, Dsn, Driver, } private static readonly string[] s_validKeywords; private static readonly Dictionary<string, Keywords> s_keywords; private string[] _knownKeywords; private string _dsn = DbConnectionStringDefaults.Dsn; // private string _namedConnection = DbConnectionStringDefaults.NamedConnection; private string _driver = DbConnectionStringDefaults.Driver; static OdbcConnectionStringBuilder() { string[] validKeywords = new string[2]; validKeywords[(int)Keywords.Driver] = DbConnectionStringKeywords.Driver; validKeywords[(int)Keywords.Dsn] = DbConnectionStringKeywords.Dsn; // validKeywords[(int)Keywords.NamedConnection] = DbConnectionStringKeywords.NamedConnection; s_validKeywords = validKeywords; Dictionary<string, Keywords> hash = new Dictionary<string, Keywords>(2, StringComparer.OrdinalIgnoreCase); hash.Add(DbConnectionStringKeywords.Driver, Keywords.Driver); hash.Add(DbConnectionStringKeywords.Dsn, Keywords.Dsn); // hash.Add(DbConnectionStringKeywords.NamedConnection, Keywords.NamedConnection); Debug.Assert(2 == hash.Count, "initial expected size is incorrect"); s_keywords = hash; } public OdbcConnectionStringBuilder() : this((string)null) { } public OdbcConnectionStringBuilder(string connectionString) : base(true) { if (!string.IsNullOrEmpty(connectionString)) { ConnectionString = connectionString; } } public override object this[string keyword] { get { ADP.CheckArgumentNull(keyword, "keyword"); Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { return GetAt(index); } else { return base[keyword]; } } set { ADP.CheckArgumentNull(keyword, "keyword"); if (null != value) { Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { switch (index) { case Keywords.Driver: Driver = ConvertToString(value); break; case Keywords.Dsn: Dsn = ConvertToString(value); break; // case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break; default: Debug.Assert(false, "unexpected keyword"); throw ADP.KeywordNotSupported(keyword); } } else { base[keyword] = value; ClearPropertyDescriptors(); _knownKeywords = null; } } else { Remove(keyword); } } } [DisplayName(DbConnectionStringKeywords.Driver)] public string Driver { get { return _driver; } set { SetValue(DbConnectionStringKeywords.Driver, value); _driver = value; } } [DisplayName(DbConnectionStringKeywords.Dsn)] public string Dsn { get { return _dsn; } set { SetValue(DbConnectionStringKeywords.Dsn, value); _dsn = value; } } /* [DisplayName(DbConnectionStringKeywords.NamedConnection)] [ResCategoryAttribute(Res.DataCategory_NamedConnectionString)] [ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)] [RefreshPropertiesAttribute(RefreshProperties.All)] [TypeConverter(typeof(NamedConnectionStringConverter))] public string NamedConnection { get { return _namedConnection; } set { SetValue(DbConnectionStringKeywords.NamedConnection, value); _namedConnection = value; } } */ public override ICollection Keys { get { string[] knownKeywords = _knownKeywords; if (null == knownKeywords) { knownKeywords = s_validKeywords; int count = 0; foreach (string keyword in base.Keys) { bool flag = true; foreach (string s in knownKeywords) { if (s == keyword) { flag = false; break; } } if (flag) { count++; } } if (0 < count) { string[] tmp = new string[knownKeywords.Length + count]; knownKeywords.CopyTo(tmp, 0); int index = knownKeywords.Length; foreach (string keyword in base.Keys) { bool flag = true; foreach (string s in knownKeywords) { if (s == keyword) { flag = false; break; } } if (flag) { tmp[index++] = keyword; } } knownKeywords = tmp; } _knownKeywords = knownKeywords; } return new ReadOnlyCollection<string>(knownKeywords); } } public override void Clear() { base.Clear(); for (int i = 0; i < s_validKeywords.Length; ++i) { Reset((Keywords)i); } _knownKeywords = s_validKeywords; } public override bool ContainsKey(string keyword) { ADP.CheckArgumentNull(keyword, "keyword"); return s_keywords.ContainsKey(keyword) || base.ContainsKey(keyword); } private static string ConvertToString(object value) { return DbConnectionStringBuilderUtil.ConvertToString(value); } private object GetAt(Keywords index) { switch (index) { case Keywords.Driver: return Driver; case Keywords.Dsn: return Dsn; // case Keywords.NamedConnection: return NamedConnection; default: Debug.Assert(false, "unexpected keyword"); throw ADP.KeywordNotSupported(s_validKeywords[(int)index]); } } /* protected override void GetProperties(Hashtable propertyDescriptors) { object value; if (TryGetValue(DbConnectionStringSynonyms.TRUSTEDCONNECTION, out value)) { bool trusted = false; if (value is bool) { trusted = (bool)value; } else if ((value is string) && !Boolean.TryParse((string)value, out trusted)) { trusted = false; } if (trusted) { Attribute[] attributes = new Attribute[] { BrowsableAttribute.Yes, RefreshPropertiesAttribute.All, }; DbConnectionStringBuilderDescriptor descriptor; descriptor = new DbConnectionStringBuilderDescriptor(DbConnectionStringSynonyms.TRUSTEDCONNECTION, this.GetType(), typeof(bool), false, attributes); descriptor.RefreshOnChange = true; propertyDescriptors[DbConnectionStringSynonyms.TRUSTEDCONNECTION] = descriptor; if (ContainsKey(DbConnectionStringSynonyms.Pwd)) { descriptor = new DbConnectionStringBuilderDescriptor(DbConnectionStringSynonyms.Pwd, this.GetType(), typeof(string), true, attributes); propertyDescriptors[DbConnectionStringSynonyms.Pwd] = descriptor; } if (ContainsKey(DbConnectionStringSynonyms.UID)) { descriptor = new DbConnectionStringBuilderDescriptor(DbConnectionStringSynonyms.UID, this.GetType(), typeof(string), true, attributes); propertyDescriptors[DbConnectionStringSynonyms.UID] = descriptor; } } } base.GetProperties(propertyDescriptors); } */ public override bool Remove(string keyword) { ADP.CheckArgumentNull(keyword, "keyword"); if (base.Remove(keyword)) { Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { Reset(index); } else { ClearPropertyDescriptors(); _knownKeywords = null; } return true; } return false; } private void Reset(Keywords index) { switch (index) { case Keywords.Driver: _driver = DbConnectionStringDefaults.Driver; break; case Keywords.Dsn: _dsn = DbConnectionStringDefaults.Dsn; break; // case Keywords.NamedConnection: // _namedConnection = DbConnectionStringDefaults.NamedConnection; // break; default: Debug.Assert(false, "unexpected keyword"); throw ADP.KeywordNotSupported(s_validKeywords[(int)index]); } } private void SetValue(string keyword, string value) { ADP.CheckArgumentNull(value, keyword); base[keyword] = value; } public override bool TryGetValue(string keyword, out object value) { ADP.CheckArgumentNull(keyword, "keyword"); Keywords index; if (s_keywords.TryGetValue(keyword, out index)) { value = GetAt(index); return true; } return base.TryGetValue(keyword, out value); } } }
using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Attributes; using Lucene.Net.Documents; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Codec = Lucene.Net.Codecs.Codec; // NOTE: this test will fail w/ PreFlexRW codec! (Because // this test uses full binary term space, but PreFlex cannot // handle this since it requires the terms are UTF8 bytes). // // Also, SimpleText codec will consume very large amounts of // disk (but, should run successfully). Best to run w/ // -Dtests.codec=Standard, and w/ plenty of RAM, eg: // // ant test -Dtest.slow=true -Dtests.heapsize=8g // // java -server -Xmx8g -d64 -cp .:lib/junit-4.10.jar:./build/classes/test:./build/classes/test-framework:./build/classes/java -Dlucene.version=4.0-dev -Dtests.directory=MMapDirectory -DtempDir=build -ea org.junit.runner.JUnitCore Lucene.Net.Index.Test2BTerms // [SuppressCodecs("SimpleText", "Memory", "Direct")] [Ignore("SimpleText codec will consume very large amounts of memory.")] [TestFixture] public class Test2BTerms : LuceneTestCase { private const int TOKEN_LEN = 5; private static readonly BytesRef Bytes = new BytesRef(TOKEN_LEN); private sealed class MyTokenStream : TokenStream { internal readonly int TokensPerDoc; internal int TokenCount; public readonly IList<BytesRef> SavedTerms = new List<BytesRef>(); internal int NextSave; internal long TermCounter; internal readonly Random Random; public MyTokenStream(Random random, int tokensPerDoc) : base(new MyAttributeFactory(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY)) { this.TokensPerDoc = tokensPerDoc; AddAttribute<ITermToBytesRefAttribute>(); Bytes.Length = TOKEN_LEN; this.Random = random; NextSave = TestUtil.NextInt(random, 500000, 1000000); } public override bool IncrementToken() { ClearAttributes(); if (TokenCount >= TokensPerDoc) { return false; } int shift = 32; for (int i = 0; i < 5; i++) { Bytes.Bytes[i] = unchecked((byte)((TermCounter >> shift) & 0xFF)); shift -= 8; } TermCounter++; TokenCount++; if (--NextSave == 0) { SavedTerms.Add(BytesRef.DeepCopyOf(Bytes)); Console.WriteLine("TEST: save term=" + Bytes); NextSave = TestUtil.NextInt(Random, 500000, 1000000); } return true; } public override void Reset() { TokenCount = 0; } private sealed class MyTermAttributeImpl : Util.Attribute, ITermToBytesRefAttribute { public void FillBytesRef() { // no-op: the bytes was already filled by our owner's incrementToken } public BytesRef BytesRef { get { return Bytes; } } public override void Clear() { } public override bool Equals(object other) { return other == this; } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } public override void CopyTo(IAttribute target) { } public override object Clone() { throw new System.NotSupportedException(); } } private sealed class MyAttributeFactory : AttributeFactory { internal readonly AttributeFactory @delegate; public MyAttributeFactory(AttributeFactory @delegate) { this.@delegate = @delegate; } public override Util.Attribute CreateAttributeInstance<T>() { var attClass = typeof(T); if (attClass == typeof(ITermToBytesRefAttribute)) { return new MyTermAttributeImpl(); } if (attClass.GetTypeInfo().IsSubclassOf(typeof(CharTermAttribute))) { throw new System.ArgumentException("no"); } return @delegate.CreateAttributeInstance<T>(); } } } [Ignore("Very slow. Enable manually by removing Ignore.")] [Test, LongRunningTest] public virtual void Test2BTerms_Mem([ValueSource(typeof(ConcurrentMergeSchedulerFactories), "Values")]Func<IConcurrentMergeScheduler> newScheduler) { if ("Lucene3x".Equals(Codec.Default.Name)) { throw new Exception("this test cannot run with PreFlex codec"); } Console.WriteLine("Starting Test2B"); long TERM_COUNT = ((long)int.MaxValue) + 100000000; int TERMS_PER_DOC = TestUtil.NextInt(Random(), 100000, 1000000); IList<BytesRef> savedTerms = null; BaseDirectoryWrapper dir = NewFSDirectory(CreateTempDir("2BTerms")); //MockDirectoryWrapper dir = NewFSDirectory(new File("/p/lucene/indices/2bindex")); if (dir is MockDirectoryWrapper) { ((MockDirectoryWrapper)dir).Throttling = MockDirectoryWrapper.Throttling_e.NEVER; } dir.CheckIndexOnClose = false; // don't double-checkindex if (true) { IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())) .SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH) .SetRAMBufferSizeMB(256.0) .SetMergeScheduler(newScheduler()) .SetMergePolicy(NewLogMergePolicy(false, 10)) .SetOpenMode(OpenMode.CREATE)); MergePolicy mp = w.Config.MergePolicy; if (mp is LogByteSizeMergePolicy) { // 1 petabyte: ((LogByteSizeMergePolicy)mp).MaxMergeMB = 1024 * 1024 * 1024; } Documents.Document doc = new Documents.Document(); MyTokenStream ts = new MyTokenStream(Random(), TERMS_PER_DOC); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.IndexOptions = IndexOptions.DOCS_ONLY; customType.OmitNorms = true; Field field = new Field("field", ts, customType); doc.Add(field); //w.setInfoStream(System.out); int numDocs = (int)(TERM_COUNT / TERMS_PER_DOC); Console.WriteLine("TERMS_PER_DOC=" + TERMS_PER_DOC); Console.WriteLine("numDocs=" + numDocs); for (int i = 0; i < numDocs; i++) { long t0 = Environment.TickCount; w.AddDocument(doc); Console.WriteLine(i + " of " + numDocs + " " + (Environment.TickCount - t0) + " msec"); } savedTerms = ts.SavedTerms; Console.WriteLine("TEST: full merge"); w.ForceMerge(1); Console.WriteLine("TEST: close writer"); w.Dispose(); } Console.WriteLine("TEST: open reader"); IndexReader r = DirectoryReader.Open(dir); if (savedTerms == null) { savedTerms = FindTerms(r); } int numSavedTerms = savedTerms.Count; IList<BytesRef> bigOrdTerms = new List<BytesRef>(savedTerms.SubList(numSavedTerms - 10, numSavedTerms)); Console.WriteLine("TEST: test big ord terms..."); TestSavedTerms(r, bigOrdTerms); Console.WriteLine("TEST: test all saved terms..."); TestSavedTerms(r, savedTerms); r.Dispose(); Console.WriteLine("TEST: now CheckIndex..."); CheckIndex.Status status = TestUtil.CheckIndex(dir); long tc = status.SegmentInfos[0].TermIndexStatus.TermCount; Assert.IsTrue(tc > int.MaxValue, "count " + tc + " is not > " + int.MaxValue); dir.Dispose(); Console.WriteLine("TEST: done!"); } private IList<BytesRef> FindTerms(IndexReader r) { Console.WriteLine("TEST: findTerms"); TermsEnum termsEnum = MultiFields.GetTerms(r, "field").GetIterator(null); IList<BytesRef> savedTerms = new List<BytesRef>(); int nextSave = TestUtil.NextInt(Random(), 500000, 1000000); BytesRef term; while ((term = termsEnum.Next()) != null) { if (--nextSave == 0) { savedTerms.Add(BytesRef.DeepCopyOf(term)); Console.WriteLine("TEST: add " + term); nextSave = TestUtil.NextInt(Random(), 500000, 1000000); } } return savedTerms; } private void TestSavedTerms(IndexReader r, IList<BytesRef> terms) { Console.WriteLine("TEST: run " + terms.Count + " terms on reader=" + r); IndexSearcher s = NewSearcher(r); Collections.Shuffle(terms); TermsEnum termsEnum = MultiFields.GetTerms(r, "field").GetIterator(null); bool failed = false; for (int iter = 0; iter < 10 * terms.Count; iter++) { BytesRef term = terms[Random().Next(terms.Count)]; Console.WriteLine("TEST: search " + term); long t0 = Environment.TickCount; int count = s.Search(new TermQuery(new Term("field", term)), 1).TotalHits; if (count <= 0) { Console.WriteLine(" FAILED: count=" + count); failed = true; } long t1 = Environment.TickCount; Console.WriteLine(" took " + (t1 - t0) + " millis"); TermsEnum.SeekStatus result = termsEnum.SeekCeil(term); if (result != TermsEnum.SeekStatus.FOUND) { if (result == TermsEnum.SeekStatus.END) { Console.WriteLine(" FAILED: got END"); } else { Console.WriteLine(" FAILED: wrong term: got " + termsEnum.Term); } failed = true; } } Assert.IsFalse(failed); } } }
// 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 Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Net.Tests { public class WebRequestTest { static WebRequestTest() { // Capture the value of DefaultWebProxy before any tests run. // This lets us test the default value without imposing test // ordering constraints which aren't natively supported by xunit. initialDefaultWebProxy = WebRequest.DefaultWebProxy; initialDefaultWebProxyCredentials = initialDefaultWebProxy.Credentials; } private readonly NetworkCredential _explicitCredentials = new NetworkCredential("user", "password", "domain"); private static IWebProxy initialDefaultWebProxy; private static ICredentials initialDefaultWebProxyCredentials; [Fact] public void DefaultWebProxy_VerifyDefaults_Success() { Assert.NotNull(initialDefaultWebProxy); Assert.Null(initialDefaultWebProxyCredentials); } [Fact] public void DefaultWebProxy_SetThenGet_ValuesMatch() { RemoteExecutor.Invoke(() => { IWebProxy p = new WebProxy(); WebRequest.DefaultWebProxy = p; Assert.Same(p, WebRequest.DefaultWebProxy); }).Dispose(); } [Fact] public void DefaultWebProxy_SetCredentialsToNullThenGet_ValuesMatch() { IWebProxy proxy = WebRequest.DefaultWebProxy; proxy.Credentials = null; Assert.Null(proxy.Credentials); } [Fact] public void DefaultWebProxy_SetCredentialsToDefaultCredentialsThenGet_ValuesMatch() { IWebProxy proxy = WebRequest.DefaultWebProxy; proxy.Credentials = CredentialCache.DefaultCredentials; Assert.Equal(CredentialCache.DefaultCredentials, proxy.Credentials); } [Fact] public void DefaultWebProxy_SetCredentialsToExplicitCredentialsThenGet_ValuesMatch() { IWebProxy proxy = WebRequest.DefaultWebProxy; ICredentials oldCreds = proxy.Credentials; try { proxy.Credentials = _explicitCredentials; Assert.Equal(_explicitCredentials, proxy.Credentials); } finally { // Reset the credentials so as not to interfere with any subsequent tests, // e.g. DefaultWebProxy_VerifyDefaults_Success proxy.Credentials = oldCreds; } } [Theory] [InlineData("http")] [InlineData("https")] [InlineData("ftp")] public void Create_ValidWebRequestUriScheme_Success(string scheme) { var uri = new Uri($"{scheme}://example.com/folder/resource.txt"); WebRequest request = WebRequest.Create(uri); } [Theory] [InlineData("ws")] [InlineData("wss")] [InlineData("custom")] public void Create_InvalidWebRequestUriScheme_Throws(string scheme) { var uri = new Uri($"{scheme}://example.com/folder/resource.txt"); Assert.Throws<NotSupportedException>(() => WebRequest.Create(uri)); } [Fact] public void Create_NullRequestUri_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => WebRequest.Create((string)null)); Assert.Throws<ArgumentNullException>(() => WebRequest.Create((Uri)null)); } [Fact] public void CreateDefault_NullRequestUri_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => WebRequest.CreateDefault(null)); } [Fact] public void CreateHttp_NullRequestUri_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => WebRequest.CreateHttp((string)null)); Assert.Throws<ArgumentNullException>(() => WebRequest.CreateHttp((Uri)null)); } [Fact] public void CreateHttp_InvalidScheme_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => WebRequest.CreateHttp(new Uri("ftp://microsoft.com"))); } [Fact] public void BaseMembers_NotCall_ThrowsNotImplementedException() { WebRequest request = new FakeRequest(); Assert.Throws<NotImplementedException>(() => request.ConnectionGroupName); Assert.Throws<NotImplementedException>(() => request.ConnectionGroupName = null); Assert.Throws<NotImplementedException>(() => request.Method); Assert.Throws<NotImplementedException>(() => request.Method = null); Assert.Throws<NotImplementedException>(() => request.RequestUri); Assert.Throws<NotImplementedException>(() => request.Headers); Assert.Throws<NotImplementedException>(() => request.Headers = null); Assert.Throws<NotImplementedException>(() => request.ContentLength); Assert.Throws<NotImplementedException>(() => request.ContentLength = 0); Assert.Throws<NotImplementedException>(() => request.ContentType); Assert.Throws<NotImplementedException>(() => request.ContentType = null); Assert.Throws<NotImplementedException>(() => request.Credentials); Assert.Throws<NotImplementedException>(() => request.Credentials = null); Assert.Throws<NotImplementedException>(() => request.Timeout); Assert.Throws<NotImplementedException>(() => request.Timeout = 0); Assert.Throws<NotImplementedException>(() => request.UseDefaultCredentials); Assert.Throws<NotImplementedException>(() => request.UseDefaultCredentials = true); Assert.Throws<NotImplementedException>(() => request.GetRequestStream()); Assert.Throws<NotImplementedException>(() => request.GetResponse()); Assert.Throws<NotImplementedException>(() => request.BeginGetResponse(null, null)); Assert.Throws<NotImplementedException>(() => request.EndGetResponse(null)); Assert.Throws<NotImplementedException>(() => request.BeginGetRequestStream(null, null)); Assert.Throws<NotImplementedException>(() => request.EndGetRequestStream(null)); Assert.Throws<NotImplementedException>(() => request.Abort()); Assert.Throws<NotImplementedException>(() => request.PreAuthenticate); Assert.Throws<NotImplementedException>(() => request.PreAuthenticate = true); Assert.Throws<NotImplementedException>(() => request.Proxy); Assert.Throws<NotImplementedException>(() => request.Proxy = null); } [Fact] public void GetSystemWebProxy_NoArguments_ExpectNotNull() { IWebProxy webProxy = WebRequest.GetSystemWebProxy(); Assert.NotNull(webProxy); } [Fact] public void RegisterPrefix_PrefixOrCreatorNull_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => WebRequest.RegisterPrefix(null, new FakeRequestFactory())); Assert.Throws<ArgumentNullException>(() => WebRequest.RegisterPrefix("http://", null)); } [Fact] public void RegisterPrefix_HttpWithFakeFactory_Success() { bool success = WebRequest.RegisterPrefix("sta:", new FakeRequestFactory()); Assert.True(success); Assert.IsType<FakeRequest>(WebRequest.Create("sta://anything")); } [Fact] public void RegisterPrefix_DuplicateHttpWithFakeFactory_ExpectFalse() { bool success = WebRequest.RegisterPrefix("stb:", new FakeRequestFactory()); Assert.True(success); success = WebRequest.RegisterPrefix("stb:", new FakeRequestFactory()); Assert.False(success); } private class FakeRequest : WebRequest { private readonly Uri _uri; public override Uri RequestUri => _uri ?? base.RequestUri; public FakeRequest(Uri uri = null) { _uri = uri; } } private class FakeRequestFactory : IWebRequestCreate { public WebRequest Create(Uri uri) { return new FakeRequest(uri); } } } }
// The MIT License (MIT) // // CoreTweet - A .NET Twitter Library supporting Twitter API 1.1 // Copyright (c) 2013-2015 CoreTweet Development Team // // 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.IO; using System.Linq; using System.Net; using System.Text; using CoreTweet.Core; namespace CoreTweet { /// <summary> /// Provides the type of the HTTP method. /// </summary> public enum MethodType { /// <summary> /// GET method. /// </summary> Get, /// <summary> /// POST method. /// </summary> Post } /// <summary> /// Provides a set of static (Shared in Visual Basic) methods for sending a request to Twitter and some other web services. /// </summary> internal static partial class Request { private static string CreateQueryString(IEnumerable<KeyValuePair<string, string>> prm) { return prm.Select(x => UrlEncode(x.Key) + "=" + UrlEncode(x.Value)).JoinToString("&"); } private static string CreateQueryString(IEnumerable<KeyValuePair<string, object>> prm) { return CreateQueryString(prm.Select(x => new KeyValuePair<string, string>(x.Key, x.Value.ToString()))); } #if !WIN_RT private static void WriteMultipartFormData(Stream stream, string boundary, IEnumerable<KeyValuePair<string, object>> prm) { const int bufferSize = 81920; prm.ForEach(x => { var valueStream = x.Value as Stream; var valueBytes = x.Value as IEnumerable<byte>; #if !PCL var valueFile = x.Value as FileInfo; #endif var valueString = x.Value.ToString(); #if WP var valueInputStream = x.Value as Windows.Storage.Streams.IInputStream; if(valueInputStream != null) valueStream = valueInputStream.AsStreamForRead(); #endif stream.WriteString("--" + boundary + "\r\n"); if(valueStream != null || valueBytes != null #if !PCL || valueFile != null #endif ) { stream.WriteString("Content-Type: application/octet-stream\r\n"); } stream.WriteString(string.Format(@"Content-Disposition: form-data; name=""{0}""", x.Key)); #if !PCL if(valueFile != null) stream.WriteString(string.Format(@"; filename=""{0}""", valueFile.Name.Replace("\n", "%0A").Replace("\r", "%0D").Replace("\"", "%22"))); else #endif if(valueStream != null || valueBytes != null) stream.WriteString(@"; filename=""file"""); stream.WriteString("\r\n\r\n"); #if !PCL if(valueFile != null) valueStream = valueFile.OpenRead(); #endif if(valueStream != null) { var buffer = new byte[bufferSize]; int count; while((count = valueStream.Read(buffer, 0, bufferSize)) > 0) stream.Write(buffer, 0, count); } else if(valueBytes != null) { var buffer = valueBytes as byte[]; if(buffer != null) stream.Write(buffer, 0, buffer.Length); else { buffer = new byte[bufferSize]; var i = 0; foreach(var b in valueBytes) { buffer[i++] = b; if(i == bufferSize) { stream.Write(buffer, 0, bufferSize); i = 0; } } if(i > 0) stream.Write(buffer, 0, i); } } else stream.WriteString(valueString); #if !PCL if(valueFile != null) valueStream.Close(); #endif stream.WriteString("\r\n"); }); stream.WriteString("--" + boundary + "--"); } #endif #if !(PCL || WP) private const DecompressionMethods CompressionType = DecompressionMethods.GZip | DecompressionMethods.Deflate; #endif #if !(PCL || WIN_RT || WP) internal static HttpWebResponse HttpGet(string url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options) { if(prm == null) prm = new Dictionary<string,object>(); if(options == null) options = new ConnectionOptions(); var req = (HttpWebRequest)WebRequest.Create(url + '?' + CreateQueryString(prm)); req.Timeout = options.Timeout; req.ReadWriteTimeout = options.ReadWriteTimeout; req.UserAgent = options.UserAgent; req.Proxy = options.Proxy; req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader); if(options.UseCompression) req.AutomaticDecompression = CompressionType; if (options.DisableKeepAlive) req.KeepAlive = false; if(options.BeforeRequestAction != null) options.BeforeRequestAction(req); return (HttpWebResponse)req.GetResponse(); } internal static HttpWebResponse HttpPost(string url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options) { if(prm == null) prm = new Dictionary<string,object>(); if(options == null) options = new ConnectionOptions(); var data = Encoding.UTF8.GetBytes(CreateQueryString(prm)); var req = (HttpWebRequest)WebRequest.Create(url); req.ServicePoint.Expect100Continue = false; req.Method = "POST"; req.Timeout = options.Timeout; req.ReadWriteTimeout = options.ReadWriteTimeout; req.UserAgent = options.UserAgent; req.Proxy = options.Proxy; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = data.Length; req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader); if(options.UseCompression) req.AutomaticDecompression = CompressionType; if (options.DisableKeepAlive) req.KeepAlive = false; if(options.BeforeRequestAction != null) options.BeforeRequestAction(req); using(var reqstr = req.GetRequestStream()) reqstr.Write(data, 0, data.Length); return (HttpWebResponse)req.GetResponse(); } internal static HttpWebResponse HttpPostWithMultipartFormData(string url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options) { if(options == null) options = new ConnectionOptions(); var boundary = Guid.NewGuid().ToString(); var req = (HttpWebRequest)WebRequest.Create(url); req.ServicePoint.Expect100Continue = false; req.Method = "POST"; req.Timeout = options.Timeout; req.ReadWriteTimeout = options.ReadWriteTimeout; req.UserAgent = options.UserAgent; req.Proxy = options.Proxy; req.ContentType = "multipart/form-data;boundary=" + boundary; req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader); req.SendChunked = true; if(options.UseCompression) req.AutomaticDecompression = CompressionType; if (options.DisableKeepAlive) req.KeepAlive = false; if (options.BeforeRequestAction != null) options.BeforeRequestAction(req); using(var reqstr = req.GetRequestStream()) WriteMultipartFormData(reqstr, boundary, prm); return (HttpWebResponse)req.GetResponse(); } #endif /// <summary> /// Generates the signature. /// </summary> /// <param name="t">The tokens.</param> /// <param name="httpMethod">The HTTP method.</param> /// <param name="url">The URL.</param> /// <param name="prm">The parameters.</param> /// <returns>The signature.</returns> internal static string GenerateSignature(Tokens t, string httpMethod, string url, IEnumerable<KeyValuePair<string, string>> prm) { var key = Encoding.UTF8.GetBytes( string.Format("{0}&{1}", UrlEncode(t.ConsumerSecret), UrlEncode(t.AccessTokenSecret) ?? "")); var uri = new Uri(url); var prmstr = CreateQueryString(prm.OrderBy(x => x.Key).ThenBy(x => x.Value)); if(httpMethod == "GET") prmstr = new Uri("http://www.example.com/?" + prmstr).Query.TrimStart('?'); var msg = Encoding.UTF8.GetBytes( string.Format("{0}&{1}&{2}", httpMethod, UrlEncode(string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath)), UrlEncode(prmstr) )); return Convert.ToBase64String(SecurityUtils.HmacSha1(key, msg)); } /// <summary> /// Generates the parameters. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="token">The token.</param> /// <returns>The parameters.</returns> internal static Dictionary<string, string> GenerateParameters(string consumerKey, string token) { var ret = new Dictionary<string, string>() { {"oauth_consumer_key", consumerKey}, {"oauth_signature_method", "HMAC-SHA1"}, {"oauth_timestamp", ((DateTimeOffset.UtcNow - InternalUtils.unixEpoch).Ticks / 10000000L).ToString("D")}, {"oauth_nonce", new Random().Next(int.MinValue, int.MaxValue).ToString("X")}, {"oauth_version", "1.0"} }; if(!string.IsNullOrEmpty(token)) ret.Add("oauth_token", token); return ret; } /// <summary> /// Encodes the specified text. /// </summary> /// <param name="text">The text.</param> /// <returns>The encoded text.</returns> internal static string UrlEncode(string text) { if(string.IsNullOrEmpty(text)) return ""; return Encoding.UTF8.GetBytes(text) .Select(x => x < 0x80 && "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~" .Contains(((char)x).ToString()) ? ((char)x).ToString() : ('%' + x.ToString("X2"))) .JoinToString(); } } }
// Define this to enable the dispatching of load events. The implementation // of load events requires that a complete implementation of SvgDocument.Load // be supplied rather than relying on the base XmlDocument.Load behaviour. // This is required because I know of no way to hook into the key stages of // XML document creation in order to throw events at the right times during // the load process. // <developer>niklas@protocol7.com</developer> // <completed>60</completed> using System; using System.Xml; using System.Xml.Schema; using System.IO; using System.IO.Compression; using System.Collections.Generic; using System.Text.RegularExpressions; using SharpVectors.Xml; using SharpVectors.Dom.Css; using SharpVectors.Dom.Resources; namespace SharpVectors.Dom.Svg { /// <summary> /// The root object in the document object hierarchy of an Svg document. /// </summary> /// <remarks> /// <para> /// When an 'svg' element is embedded inline as a component of a /// document from another namespace, such as when an 'svg' element is /// embedded inline within an XHTML document /// [<see href="http://www.w3.org/TR/SVG/refs.html#ref-XHTML">XHTML</see>], /// then an /// <see cref="ISvgDocument">ISvgDocument</see> object will not exist; /// instead, the root object in the /// document object hierarchy will be a Document object of a different /// type, such as an HTMLDocument object. /// </para> /// <para> /// However, an <see cref="ISvgDocument">ISvgDocument</see> object will /// indeed exist when the root /// element of the XML document hierarchy is an 'svg' element, such as /// when viewing a stand-alone SVG file (i.e., a file with MIME type /// "image/svg+xml"). In this case, the /// <see cref="ISvgDocument">ISvgDocument</see> object will be the /// root object of the document object model hierarchy. /// </para> /// <para> /// In the case where an SVG document is embedded by reference, such as /// when an XHTML document has an 'object' element whose href attribute /// references an SVG document (i.e., a document whose MIME type is /// "image/svg+xml" and whose root element is thus an 'svg' element), /// there will exist two distinct DOM hierarchies. The first DOM hierarchy /// will be for the referencing document (e.g., an XHTML document). The /// second DOM hierarchy will be for the referenced SVG document. In this /// second DOM hierarchy, the root object of the document object model /// hierarchy is an <see cref="ISvgDocument">ISvgDocument</see> object. /// </para> /// <para> /// The <see cref="ISvgDocument">ISvgDocument</see> interface contains a /// similar list of attributes and /// methods to the HTMLDocument interface described in the /// <see href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html">Document /// Object Model (HTML) Level 1</see> chapter of the /// [<see href="http://www.w3.org/TR/SVG/refs.html#ref-DOM1">DOM1</see>] specification. /// </para> /// </remarks> public class SvgDocument : CssXmlDocument, ISvgDocument { #region Public Static Fields public const string SvgNamespace = "http://www.w3.org/2000/svg"; public const string XLinkNamespace = "http://www.w3.org/1999/xlink"; #endregion #region Private Fields private bool _ignoreComments; private bool _ignoreProcessingInstructions; private bool _ignoreWhitespace; private SvgWindow _window; private XmlReaderSettings _settings; #endregion #region Constructors private SvgDocument() { _ignoreComments = false; _ignoreWhitespace = false; _ignoreProcessingInstructions = false; this.PreserveWhitespace = true; } public SvgDocument(SvgWindow window) : this() { this._window = window; this._window.Document = this; // set up CSS properties AddStyleElement(SvgDocument.SvgNamespace, "style"); CssPropertyProfile = CssPropertyProfile.SvgProfile; } #endregion #region Public Events /// <summary> /// Namespace resolution event delegate. /// </summary> public delegate void ResolveNamespaceDelegate(object sender, SvgResolveNamespaceEventArgs e); /// <summary> /// URI resolution event delegate /// </summary> public delegate void ResolveUriDelegate(object sender, SvgResolveUriEventArgs e); /// <summary> /// Occurs when a namespace is being resolved. /// </summary> public event ResolveNamespaceDelegate ResolveNamespace; /// <summary> /// Occurs when an URI is resolved (always). /// </summary> public event ResolveUriDelegate ResolvingUri; #endregion #region Public Properties public XmlReaderSettings CustomSettings { get { return _settings; } set { _settings = value; } } #endregion #region NamespaceManager private XmlNamespaceManager namespaceManager; public XmlNamespaceManager NamespaceManager { get { if (namespaceManager == null) { // Setup namespace manager and add default namespaces namespaceManager = new XmlNamespaceManager(this.NameTable); namespaceManager.AddNamespace(String.Empty, SvgDocument.SvgNamespace); namespaceManager.AddNamespace("svg", SvgDocument.SvgNamespace); namespaceManager.AddNamespace("xlink", SvgDocument.XLinkNamespace); } return namespaceManager; } } #endregion #region Type handling and creation of elements public override XmlElement CreateElement(string prefix, string localName, string ns) { XmlElement result = SvgElementFactory.Create(prefix, localName, ns, this); if (result != null) { return result; } else if (ns == SvgNamespace) { return new SvgElement(prefix, localName, ns, this); } else { // Now, if the ns is empty, we try creating with the default namespace for cases // where the node is imported from an external SVG document... if (String.IsNullOrEmpty(ns)) { result = SvgElementFactory.Create(prefix, localName, SvgNamespace, this); if (result != null) { return result; } } } return base.CreateElement(prefix, localName, ns); } #endregion #region Support collections private string[] supportedFeatures = new string[] { "org.w3c.svg.static", "http://www.w3.org/TR/Svg11/feature#Shape", "http://www.w3.org/TR/Svg11/feature#BasicText", "http://www.w3.org/TR/Svg11/feature#OpacityAttribute" }; private string[] supportedExtensions = new string[] { }; public override bool Supports(string feature, string version) { foreach (string supportedFeature in supportedFeatures) { if (supportedFeature == feature) { return true; } } foreach (string supportedExtension in supportedExtensions) { if (supportedExtension == feature) { return true; } } return base.Supports(feature, version); } #endregion #region Overrides of Load private XmlReaderSettings GetXmlReaderSettings() { if (_settings != null) { return _settings; } DynamicXmlUrlResolver xmlResolver = new DynamicXmlUrlResolver(); xmlResolver.Resolving += OnXmlResolverResolving; xmlResolver.GettingEntity += OnXmlResolverGettingEntity; XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; settings.IgnoreComments = _ignoreComments; settings.IgnoreWhitespace = _ignoreWhitespace; settings.IgnoreProcessingInstructions = _ignoreProcessingInstructions; settings.XmlResolver = xmlResolver; return settings; } //private void PrepareXmlResolver(XmlReaderSettings settings) //{ // /*// TODO: 1.2 has removed the DTD, can we do this safely? // if (reader != null && reader is XmlValidatingReader) // { // XmlValidatingReader valReader = (XmlValidatingReader)reader; // valReader.ValidationType = ValidationType.None; // } // return; // LocalDtdXmlUrlResolver localDtdXmlUrlResolver = new LocalDtdXmlUrlResolver(); // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd", @"dtd\svg10.dtd"); // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/TR/SVG/DTD/svg10.dtd", @"dtd\svg10.dtd"); // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd", @"dtd\svg11-tiny.dtd"); // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd", @"dtd\svg11-basic.dtd"); // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", @"dtd\svg11.dtd"); // if (reader != null && reader is XmlValidatingReader) // { // XmlValidatingReader valReader = (XmlValidatingReader)reader; // valReader.ValidationType = ValidationType.None; // valReader.XmlResolver = localDtdXmlUrlResolver; // } // this.XmlResolver = localDtdXmlUrlResolver;*/ // //LocalDtdXmlUrlResolver localDtdXmlUrlResolver = new LocalDtdXmlUrlResolver(); // //localDtdXmlUrlResolver.AddDtd("http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd", @"dtd\svg10.dtd"); // //localDtdXmlUrlResolver.AddDtd("http://www.w3.org/TR/SVG/DTD/svg10.dtd", @"dtd\svg10.dtd"); // //localDtdXmlUrlResolver.AddDtd("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd", @"dtd\svg11-tiny.dtd"); // //localDtdXmlUrlResolver.AddDtd("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd", @"dtd\svg11-basic.dtd"); // //localDtdXmlUrlResolver.AddDtd("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", @"dtd\svg11.dtd"); // //string currentDir = Path.GetDirectoryName( // // System.Reflection.Assembly.GetExecutingAssembly().Location); // //string localDtd = Path.Combine(currentDir, "dtd"); // //if (Directory.Exists(localDtd)) // //{ // // LocalDtdXmlUrlResolver localDtdXmlUrlResolver = new LocalDtdXmlUrlResolver(); // // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd", Path.Combine(localDtd, "svg10.dtd")); // // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/TR/SVG/DTD/svg10.dtd", Path.Combine(localDtd, "svg10.dtd")); // // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd", Path.Combine(localDtd, "svg11-tiny.dtd")); // // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd", Path.Combine(localDtd, "svg11-basic.dtd")); // // localDtdXmlUrlResolver.AddDtd("http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", Path.Combine(localDtd, "svg11.dtd")); // // settings.XmlResolver = localDtdXmlUrlResolver; // //} // //else // //{ // // settings.XmlResolver = null; // //} //} /// <overloads> /// Loads an XML document.Loads the specified XML data. /// <blockquote> /// <b>Note</b> The Load method always preserves significant white /// space. The PreserveWhitespace property determines whether or not /// white space is preserved. The default is false, whites space is /// not preserved. /// </blockquote> /// </overloads> /// <summary> /// Loads the XML document from the specified URL. /// </summary> /// <param name="url"> /// URL for the file containing the XML document to load. /// </param> public override void Load(string url) { // Provide a support for the .svgz files... UriBuilder fileUrl = new UriBuilder(url); if (String.Equals(fileUrl.Scheme, "file")) { string fileExt = Path.GetExtension(url); if (String.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase)) { using (FileStream fileStream = File.OpenRead(fileUrl.Uri.LocalPath)) { using (GZipStream zipStream = new GZipStream(fileStream, CompressionMode.Decompress)) { this.Load(zipStream); } } return; } } //XmlReaderSettings settings = this.GetXmlReaderSettings(); //PrepareXmlResolver(settings); //using (XmlReader reader = XmlReader.Create(url, settings)) using (XmlReader reader = CreateValidatingXmlReader(url)) { this.Load(reader); } } /// <summary> /// Loads the XML document from the specified stream but with the /// specified base URL /// </summary> /// <param name="baseUrl"> /// Base URL for the stream from which the XML document is loaded. /// </param> /// <param name="stream"> /// The stream containing the XML document to load. /// </param> public void Load(string baseUrl, Stream stream) { //XmlReaderSettings settings = this.GetXmlReaderSettings(); //PrepareXmlResolver(settings); //using (XmlReader reader = XmlReader.Create(stream, settings, baseUrl)) using (XmlReader reader = CreateValidatingXmlReader(baseUrl, stream)) { this.Load(reader); } } /// <summary> /// Loads the XML document from the specified /// <see cref="TextReader">TextReader</see>. /// </summary> /// <param name="reader"></param> public override void Load(TextReader reader) { //XmlReaderSettings settings = this.GetXmlReaderSettings(); //PrepareXmlResolver(settings); //using (XmlReader xmlReader = XmlReader.Create(reader, settings)) using (XmlReader xmlReader = CreateValidatingXmlReader(reader)) { this.Load(xmlReader); } } /// <summary> /// Loads the XML document from the specified stream. /// </summary> /// <param name="stream"> /// The stream containing the XML document to load. /// </param> public override void Load(Stream stream) { //XmlReaderSettings settings = this.GetXmlReaderSettings(); //PrepareXmlResolver(settings); //using (XmlReader reader = XmlReader.Create(stream, settings)) using (XmlReader reader = CreateValidatingXmlReader(String.Empty, stream)) { this.Load(reader); } } #endregion #region Resource handling /// <summary> /// Entities URIs corrections are cached here. /// Currently consists in mapping '_' to '' (nothing) /// </summary> private static IDictionary<string, string> _entitiesUris; /// <summary> /// Semaphore to access _entitiesUris /// </summary> private static readonly object _entitiesUrisLock = new object(); /// <summary> /// Root where resources are embedded /// </summary> private static readonly Type _rootType = typeof(Root); /// <summary> /// Given a transformed resource name, find a possible existing resource. /// </summary> /// <param name="uri">The URI.</param> /// <returns></returns> private static string GetEntityUri(string uri) { lock (_entitiesUrisLock) { if (_entitiesUris == null) { _entitiesUris = new Dictionary<string, string>(); string[] names = _rootType.Assembly.GetManifestResourceNames(); foreach (string name in names) { if (name.StartsWith(_rootType.Namespace)) { string namePart = name.Substring(_rootType.Namespace.Length + 1); // the +1 is for the "." _entitiesUris[namePart] = name; _entitiesUris[namePart.Replace("_", "")] = name; } } } string entityUri; _entitiesUris.TryGetValue(uri, out entityUri); return entityUri; } } /// <summary> /// Handles DynamicXmlUrlResolver GettingEntity event. /// </summary> /// <param name="absoluteUri">The absolute URI.</param> /// <param name="role">The role.</param> /// <param name="ofObjectToReturn">The of object to return.</param> /// <returns></returns> private object OnXmlResolverGettingEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { string fullPath = absoluteUri.ToString(); if (!String.IsNullOrEmpty(fullPath)) { fullPath = fullPath.Replace('\\', '/'); if (fullPath.EndsWith("-//W3C//DTD SVG 1.1 Basic//EN", StringComparison.OrdinalIgnoreCase) || fullPath.EndsWith("-/W3C/DTD SVG 1.1 Basic/EN", StringComparison.OrdinalIgnoreCase)) { string resourceUri = GetEntityUri("www.w3.org.Graphics.SVG.1.1.DTD.svg11-basic.dtd"); if (resourceUri != null) return GetEntityFromUri(resourceUri, ofObjectToReturn); } else if (fullPath.EndsWith("-//W3C//DTD SVG 1.1//EN", StringComparison.OrdinalIgnoreCase) || fullPath.EndsWith("-/W3C/DTD SVG 1.1/EN", StringComparison.OrdinalIgnoreCase)) { string resourceUri = GetEntityUri("www.w3.org.Graphics.SVG.1.1.DTD.svg11.dtd"); if (resourceUri != null) return GetEntityFromUri(resourceUri, ofObjectToReturn); } else if (fullPath.EndsWith("-//W3C//DTD SVG 1.1 Full//EN", StringComparison.OrdinalIgnoreCase) || fullPath.EndsWith("-/W3C/DTD SVG 1.1 Full/EN", StringComparison.OrdinalIgnoreCase)) { string resourceUri = GetEntityUri("www.w3.org.Graphics.SVG.1.1.DTD.svg11.dtd"); if (resourceUri != null) return GetEntityFromUri(resourceUri, ofObjectToReturn); } else if (fullPath.EndsWith("-//W3C//DTD SVG 1.0//EN", StringComparison.OrdinalIgnoreCase) || fullPath.EndsWith("-/W3C/DTD SVG 1.0/EN", StringComparison.OrdinalIgnoreCase)) { string resourceUri = GetEntityUri("www.w3.org.TR.2001.REC-SVG-20010904.DTD.svg10.dtd"); if (resourceUri != null) return GetEntityFromUri(resourceUri, ofObjectToReturn); } else if (fullPath.EndsWith("-//W3C//DTD SVG 1.1 Tiny//EN", StringComparison.OrdinalIgnoreCase) || fullPath.EndsWith("-/W3C/DTD SVG 1.1 Tiny/EN", StringComparison.OrdinalIgnoreCase)) { string resourceUri = GetEntityUri("www.w3.org.Graphics.SVG.1.1.DTD.svg11-tiny.dtd"); if (resourceUri != null) return GetEntityFromUri(resourceUri, ofObjectToReturn); } } if (absoluteUri.IsFile) { return null; } string path = (absoluteUri.Host + absoluteUri.AbsolutePath.Replace('/', '.')); string foundResource = GetEntityUri(path); if (foundResource != null) return GetEntityFromUri(foundResource, ofObjectToReturn); return null; } /// <summary> /// Gets the URI direct. /// </summary> /// <param name="path">The path.</param> /// <param name="ofObjectToReturn">The of object to return.</param> /// <returns></returns> private static object GetEntityFromUri(string path, Type ofObjectToReturn) { if (ofObjectToReturn == typeof(Stream)) { using (Stream resourceStream = _rootType.Assembly.GetManifestResourceStream(path)) { if (resourceStream != null) { // we copy the contents to a MemoryStream because the loader doesn't release original streams, // resulting in an assembly lock int resourceLength = (int)resourceStream.Length; MemoryStream memoryStream = new MemoryStream(resourceLength); resourceStream.Read(memoryStream.GetBuffer(), 0, resourceLength); return memoryStream; } } } return null; } /// <summary> /// Handles DynamicXmlResolver Resolve event. /// </summary> /// <param name="relativeUri">The relative URI.</param> /// <returns></returns> private string OnXmlResolverResolving(string relativeUri) { if (this.ResolvingUri != null) { SvgResolveUriEventArgs e = new SvgResolveUriEventArgs { Uri = relativeUri }; ResolvingUri(this, e); relativeUri = e.Uri; } if (relativeUri.Equals("http://www.w3.org/2000/svg", StringComparison.OrdinalIgnoreCase)) { relativeUri = "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"; } return relativeUri; } /// <summary> /// Gets/create an XML parser context, with predefined namespaces /// </summary> /// <returns></returns> private XmlParserContext GetXmlParserContext() { DynamicXmlNamespaceManager xmlNamespaceManager = new DynamicXmlNamespaceManager(new NameTable()); xmlNamespaceManager.Resolve += OnResolveXmlNamespaceManager; XmlParserContext xmlParserContext = new XmlParserContext(null, xmlNamespaceManager, null, XmlSpace.None); return xmlParserContext; } /// <summary> /// Handles DynamicXmlNamespaceManager Resolve event. /// </summary> /// <param name="prefix">The prefix.</param> /// <returns></returns> private string OnResolveXmlNamespaceManager(string prefix) { string uri = null; if (this.ResolveNamespace != null) { SvgResolveNamespaceEventArgs e = new SvgResolveNamespaceEventArgs(prefix); ResolveNamespace(this, e); uri = e.Uri; } if (String.IsNullOrEmpty(uri)) { // some defaults added here switch (prefix) { case "rdf": uri = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; break; case "cc": uri = "http://web.resource.org/cc"; break; case "dc": uri = "http://purl.org/dc/elements/1.1/"; break; case "rdfs": uri = "http://www.w3.org/2000/01/rdf-schema#"; break; case "owl": uri = "http://www.w3.org/2002/07/owl#"; break; case "foaf": uri = "http://xmlns.com/foaf/0.1/"; break; case "xsd": uri = "http://www.w3c.org/2001/XMLSchema#"; break; case "xlink": uri = "http://www.w3.org/1999/xlink"; break; } } return uri; } /// <summary> /// Creates the validating XML reader. /// </summary> /// <param name="uri">The URI.</param> /// <returns></returns> private XmlReader CreateValidatingXmlReader(string uri) { XmlReaderSettings xmlReaderSettings = GetXmlReaderSettings(); XmlParserContext xmlParserContext = GetXmlParserContext(); return XmlReader.Create(uri, xmlReaderSettings, xmlParserContext); } /// <summary> /// Creates the validating XML reader. /// </summary> /// <param name="textReader">The text reader.</param> /// <returns></returns> private XmlReader CreateValidatingXmlReader(TextReader textReader) { XmlReaderSettings xmlReaderSettings = GetXmlReaderSettings(); XmlParserContext xmlParserContext = GetXmlParserContext(); return XmlReader.Create(textReader, xmlReaderSettings, xmlParserContext); } /// <summary> /// Creates the validating XML reader. /// </summary> /// <param name="uri">The URI.</param> /// <param name="stream">The stream.</param> /// <returns></returns> private XmlReader CreateValidatingXmlReader(string uri, Stream stream) { //return new XmlTextReader(uri, stream); XmlReaderSettings xmlReaderSettings = GetXmlReaderSettings(); if (String.IsNullOrEmpty(uri)) { return XmlReader.Create(stream, xmlReaderSettings, uri); } else { XmlParserContext xmlParserContext = GetXmlParserContext(); return XmlReader.Create(stream, xmlReaderSettings, xmlParserContext); } } /// <summary> /// Creates the validating XML reader. /// </summary> /// <param name="xmlReader">The XML reader.</param> /// <returns></returns> private XmlReader CreateValidatingXmlReader(XmlReader xmlReader) { // Note: we only have part of the job done here, we need to also use a parser context return XmlReader.Create(xmlReader, GetXmlReaderSettings()); } public XmlNode GetNodeByUri(Uri absoluteUri) { return GetNodeByUri(absoluteUri.AbsoluteUri); } public XmlNode GetNodeByUri(string absoluteUrl) { absoluteUrl = absoluteUrl.Trim(); if (absoluteUrl.StartsWith("#")) { return GetElementById(absoluteUrl.Substring(1)); } else { Uri docUri = ResolveUri(""); Uri absoluteUri = new Uri(absoluteUrl); string fragment = absoluteUri.Fragment; if (fragment.Length == 0) { // no fragment => return entire document if (docUri.AbsolutePath == absoluteUri.AbsolutePath) { return this; } else { SvgDocument doc = new SvgDocument((SvgWindow)Window); XmlReaderSettings settings = this.GetXmlReaderSettings(); settings.CloseInput = true; //PrepareXmlResolver(settings); using (XmlReader reader = XmlReader.Create( GetResource(absoluteUri).GetResponseStream(), settings, absoluteUri.AbsolutePath)) { doc.Load(reader); } return doc; } } else { // got a fragment => return XmlElement string noFragment = absoluteUri.AbsoluteUri.Replace(fragment, ""); SvgDocument doc = (SvgDocument)GetNodeByUri(new Uri(noFragment)); return doc.GetElementById(fragment.Substring(1)); } } } public Uri ResolveUri(string uri) { DirectoryInfo workingDir = this._window.WorkingDir; string baseUri = BaseURI; if (baseUri.Length == 0) { baseUri = "file:///" + workingDir.FullName.Replace('\\', '/'); } return new Uri(new Uri(baseUri), uri); } #endregion #region ISvgDocument Members /// <summary> /// The title of the document which is the text content of the first child title element of the 'svg' root element. /// </summary> public string Title { get { string result = ""; XmlNode node = SelectSingleNode("/svg:svg/svg:title[text()!='']", NamespaceManager); if (node != null) { node.Normalize(); // NOTE: should probably use spec-defined whitespace result = Regex.Replace(node.InnerText, @"\s\s+", " "); } return result; } } /// <summary> /// Returns the URI of the page that linked to this page. The value is an empty string if the user navigated to the page directly (not through a link, but, for example, via a bookmark). /// </summary> public string Referrer { get { return String.Empty; } } /// <summary> /// The domain name of the server that served the document, or a null string if the server cannot be identified by a domain name. /// </summary> public string Domain { get { if (Url.Length == 0 || Url.StartsWith(Uri.UriSchemeFile)) { return null; } else { return new Uri(Url).Host; } } } /// <summary> /// The root 'svg' element in the document hierarchy /// </summary> public ISvgSvgElement RootElement { get { return DocumentElement as ISvgSvgElement; } } internal Dictionary<string, XmlElement> collectedIds; public override XmlElement GetElementById(string elementId) { // TODO: handle element and attribute updates globally to watch for id changes. if (collectedIds == null) { collectedIds = new Dictionary<string, XmlElement>(); // TODO: handle xml:id, handle duplicate ids? XmlNodeList ids = this.SelectNodes("//*/@id"); foreach (XmlAttribute node in ids) { try { collectedIds.Add(node.Value, node.OwnerElement); } catch { // Duplicate ID... what to do? } } } // Find the item if (collectedIds.ContainsKey(elementId)) { return collectedIds[elementId]; } return null; } #endregion #region ISvgDocument Members from SVG 1.2 public ISvgWindow Window { get { return _window; } } #endregion #region Other public properties public new SvgDocument OwnerDocument { get { return base.OwnerDocument as SvgDocument; } } #endregion } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using Ctrip.Log4.Core; using Ctrip.Log4.Appender; namespace Ctrip.Log4.Util { /// <summary> /// A straightforward implementation of the <see cref="IAppenderAttachable"/> interface. /// </summary> /// <remarks> /// <para> /// This is the default implementation of the <see cref="IAppenderAttachable"/> /// interface. Implementors of the <see cref="IAppenderAttachable"/> interface /// should aggregate an instance of this type. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class AppenderAttachedImpl : IAppenderAttachable { #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="AppenderAttachedImpl"/> class. /// </para> /// </remarks> public AppenderAttachedImpl() { } #endregion Public Instance Constructors #region Public Instance Methods /// <summary> /// Append on on all attached appenders. /// </summary> /// <param name="loggingEvent">The event being logged.</param> /// <returns>The number of appenders called.</returns> /// <remarks> /// <para> /// Calls the <see cref="IAppender.DoAppend" /> method on all /// attached appenders. /// </para> /// </remarks> public int AppendLoopOnAppenders(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } // m_appenderList is null when empty if (m_appenderList == null) { return 0; } if (m_appenderArray == null) { m_appenderArray = m_appenderList.ToArray(); } foreach(IAppender appender in m_appenderArray) { try { appender.DoAppend(loggingEvent); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); } } return m_appenderList.Count; } /// <summary> /// Append on on all attached appenders. /// </summary> /// <param name="loggingEvents">The array of events being logged.</param> /// <returns>The number of appenders called.</returns> /// <remarks> /// <para> /// Calls the <see cref="IAppender.DoAppend" /> method on all /// attached appenders. /// </para> /// </remarks> public int AppendLoopOnAppenders(LoggingEvent[] loggingEvents) { if (loggingEvents == null) { throw new ArgumentNullException("loggingEvents"); } if (loggingEvents.Length == 0) { throw new ArgumentException("loggingEvents array must not be empty", "loggingEvents"); } if (loggingEvents.Length == 1) { // Fall back to single event path return AppendLoopOnAppenders(loggingEvents[0]); } // m_appenderList is null when empty if (m_appenderList == null) { return 0; } if (m_appenderArray == null) { m_appenderArray = m_appenderList.ToArray(); } foreach(IAppender appender in m_appenderArray) { try { CallAppend(appender, loggingEvents); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); } } return m_appenderList.Count; } #endregion Public Instance Methods #region Private Static Methods /// <summary> /// Calls the DoAppende method on the <see cref="IAppender"/> with /// the <see cref="LoggingEvent"/> objects supplied. /// </summary> /// <param name="appender">The appender</param> /// <param name="loggingEvents">The events</param> /// <remarks> /// <para> /// If the <paramref name="appender" /> supports the <see cref="IBulkAppender"/> /// interface then the <paramref name="loggingEvents" /> will be passed /// through using that interface. Otherwise the <see cref="LoggingEvent"/> /// objects in the array will be passed one at a time. /// </para> /// </remarks> private static void CallAppend(IAppender appender, LoggingEvent[] loggingEvents) { IBulkAppender bulkAppender = appender as IBulkAppender; if (bulkAppender != null) { bulkAppender.DoAppend(loggingEvents); } else { foreach(LoggingEvent loggingEvent in loggingEvents) { appender.DoAppend(loggingEvent); } } } #endregion #region Implementation of IAppenderAttachable /// <summary> /// Attaches an appender. /// </summary> /// <param name="newAppender">The appender to add.</param> /// <remarks> /// <para> /// If the appender is already in the list it won't be added again. /// </para> /// </remarks> public void AddAppender(IAppender newAppender) { // Null values for newAppender parameter are strictly forbidden. if (newAppender == null) { throw new ArgumentNullException("newAppender"); } m_appenderArray = null; if (m_appenderList == null) { m_appenderList = new AppenderCollection(1); } if (!m_appenderList.Contains(newAppender)) { m_appenderList.Add(newAppender); } } /// <summary> /// Gets all attached appenders. /// </summary> /// <returns> /// A collection of attached appenders, or <c>null</c> if there /// are no attached appenders. /// </returns> /// <remarks> /// <para> /// The read only collection of all currently attached appenders. /// </para> /// </remarks> public AppenderCollection Appenders { get { if (m_appenderList == null) { // We must always return a valid collection return AppenderCollection.EmptyCollection; } else { return AppenderCollection.ReadOnly(m_appenderList); } } } /// <summary> /// Gets an attached appender with the specified name. /// </summary> /// <param name="name">The name of the appender to get.</param> /// <returns> /// The appender with the name specified, or <c>null</c> if no appender with the /// specified name is found. /// </returns> /// <remarks> /// <para> /// Lookup an attached appender by name. /// </para> /// </remarks> public IAppender GetAppender(string name) { if (m_appenderList != null && name != null) { foreach(IAppender appender in m_appenderList) { if (name == appender.Name) { return appender; } } } return null; } /// <summary> /// Removes all attached appenders. /// </summary> /// <remarks> /// <para> /// Removes and closes all attached appenders /// </para> /// </remarks> public void RemoveAllAppenders() { if (m_appenderList != null) { foreach(IAppender appender in m_appenderList) { try { appender.Close(); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to Close appender ["+appender.Name+"]", ex); } } m_appenderList = null; m_appenderArray = null; } } /// <summary> /// Removes the specified appender from the list of attached appenders. /// </summary> /// <param name="appender">The appender to remove.</param> /// <returns>The appender removed from the list</returns> /// <remarks> /// <para> /// The appender removed is not closed. /// If you are discarding the appender you must call /// <see cref="IAppender.Close"/> on the appender removed. /// </para> /// </remarks> public IAppender RemoveAppender(IAppender appender) { if (appender != null && m_appenderList != null) { m_appenderList.Remove(appender); if (m_appenderList.Count == 0) { m_appenderList = null; } m_appenderArray = null; } return appender; } /// <summary> /// Removes the appender with the specified name from the list of appenders. /// </summary> /// <param name="name">The name of the appender to remove.</param> /// <returns>The appender removed from the list</returns> /// <remarks> /// <para> /// The appender removed is not closed. /// If you are discarding the appender you must call /// <see cref="IAppender.Close"/> on the appender removed. /// </para> /// </remarks> public IAppender RemoveAppender(string name) { return RemoveAppender(GetAppender(name)); } #endregion #region Private Instance Fields /// <summary> /// List of appenders /// </summary> private AppenderCollection m_appenderList; /// <summary> /// Array of appenders, used to cache the m_appenderList /// </summary> private IAppender[] m_appenderArray; #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the AppenderAttachedImpl class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(AppenderAttachedImpl); #endregion Private Static Fields } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapUrl.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using ArrayEnumeration = Novell.Directory.LDAP.VQ.Utilclass.ArrayEnumeration; namespace Novell.Directory.LDAP.VQ { /// <summary> /// Encapsulates parameters of an Ldap URL query as defined in RFC2255. /// /// An LdapUrl object can be passed to LdapConnection.search to retrieve /// search results. /// /// </summary> /// <seealso cref="LdapConnection.Search"> /// </seealso> public class LdapUrl { private void InitBlock() { scope = DEFAULT_SCOPE; } /// <summary> Returns an array of attribute names specified in the URL. /// /// </summary> /// <returns> An array of attribute names in the URL. /// </returns> virtual public String[] AttributeArray { get { return attrs; } } /// <summary> Returns an enumerator for the attribute names specified in the URL. /// /// </summary> /// <returns> An enumeration of attribute names. /// </returns> virtual public System.Collections.IEnumerator Attributes { get { return new ArrayEnumeration(attrs); } } /// <summary> Returns any Ldap URL extensions specified, or null if none are /// specified. Each extension is a type=value expression. The =value part /// MAY be omitted. The expression MAY be prefixed with '!' if it is /// mandatory for evaluation of the URL. /// /// </summary> /// <returns> string array of extensions. /// </returns> virtual public String[] Extensions { get { return extensions; } } /// <summary> Returns the search filter or <code>null</code> if none was specified. /// /// </summary> /// <returns> The search filter. /// </returns> virtual public String Filter { get { return filter; } } /// <summary> Returns the name of the Ldap server in the URL. /// /// </summary> /// <returns> The host name specified in the URL. /// </returns> virtual public String Host { get { return host; } } /// <summary> Returns the port number of the Ldap server in the URL. /// /// </summary> /// <returns> The port number in the URL. /// </returns> virtual public int Port { get { if (port == 0) { return LdapConnection.DEFAULT_PORT; } return port; } } /// <summary> Returns the depth of search. It returns one of the following from /// LdapConnection: SCOPE_BASE, SCOPE_ONE, or SCOPE_SUB. /// /// </summary> /// <returns> The search scope. /// </returns> virtual public int Scope { get { return scope; } } /// <summary> Returns true if the URL is of the type ldaps (Ldap over SSL, a predecessor /// to startTls) /// /// </summary> /// <returns> whether this is a secure Ldap url or not. /// </returns> virtual public bool Secure { get { return secure; } } private static readonly int DEFAULT_SCOPE = LdapConnection.SCOPE_BASE; // Broken out parts of the URL private bool secure = false; // URL scheme ldap/ldaps private bool ipV6 = false; // TCP/IP V6 private String host = null; // Host private int port = 0; // Port private String dn = null; // Base DN private String[] attrs = null; // Attributes private String filter = null; // Filter private int scope; // Scope private String[] extensions = null; // Extensions /// <summary> Constructs a URL object with the specified string as the URL. /// /// </summary> /// <param name="url"> An Ldap URL string, e.g. /// "ldap://ldap.example.com:80/dc=example,dc=com?cn, /// sn?sub?(objectclass=inetOrgPerson)". /// /// </param> /// <exception> MalformedURLException The specified URL cannot be parsed. /// </exception> public LdapUrl(String url) { InitBlock(); parseURL(url); return ; } /// <summary> Constructs a URL object with the specified host, port, and DN. /// /// This form is used to create URL references to a particular object /// in the directory. /// /// </summary> /// <param name="host"> Host identifier of Ldap server, or null for /// "localhost". /// /// </param> /// <param name="port"> The port number for Ldap server (use /// LdapConnection.DEFAULT_PORT for default port). /// /// </param> /// <param name="dn"> Distinguished name of the base object of the search. /// /// </param> public LdapUrl(String host, int port, String dn) { InitBlock(); this.host = host; this.port = port; this.dn = dn; return ; } /// <summary> Constructs an Ldap URL with all fields explicitly assigned, to /// specify an Ldap search operation. /// /// </summary> /// <param name="host"> Host identifier of Ldap server, or null for /// "localhost". /// /// </param> /// <param name="port"> The port number for Ldap server (use /// LdapConnection.DEFAULT_PORT for default port). /// /// </param> /// <param name="dn"> Distinguished name of the base object of the search. /// /// /// </param> /// <param name="attrNames">Names or OIDs of attributes to retrieve. Passing a /// null array signifies that all user attributes are to be /// retrieved. Passing a value of "*" allows you to specify /// that all user attributes as well as any specified /// operational attributes are to be retrieved. /// /// /// </param> /// <param name="scope"> Depth of search (in DN namespace). Use one of /// SCOPE_BASE, SCOPE_ONE, SCOPE_SUB from LdapConnection. /// /// /// </param> /// <param name="filter"> The search filter specifying the search criteria. /// /// /// </param> /// <param name="extensions"> Extensions provide a mechanism to extend the /// functionality of Ldap URLs. Currently no /// Ldap URL extensions are defined. Each extension /// specification is a type=value expression, and may /// be <code>null</code> or empty. The =value part may be /// omitted. The expression may be prefixed with '!' if it /// is mandatory for the evaluation of the URL. /// </param> public LdapUrl(String host, int port, String dn, String[] attrNames, int scope, String filter, String[] extensions) { InitBlock(); this.host = host; this.port = port; this.dn = dn; attrs = new String[attrNames.Length]; attrNames.CopyTo(attrs, 0); this.scope = scope; this.filter = filter; this.extensions = new String[extensions.Length]; extensions.CopyTo(this.extensions, 0); return ; } /// <summary> Constructs an Ldap URL with all fields explicitly assigned, including /// isSecure, to specify an Ldap search operation. /// /// </summary> /// <param name="host"> Host identifier of Ldap server, or null for /// "localhost". /// /// /// </param> /// <param name="port"> The port number for Ldap server (use /// LdapConnection.DEFAULT_PORT for default port). /// /// /// </param> /// <param name="dn"> Distinguished name of the base object of the search. /// /// /// </param> /// <param name="attrNames">Names or OIDs of attributes to retrieve. Passing a /// null array signifies that all user attributes are to be /// retrieved. Passing a value of "*" allows you to specify /// that all user attributes as well as any specified /// operational attributes are to be retrieved. /// /// /// </param> /// <param name="scope"> Depth of search (in DN namespace). Use one of /// SCOPE_BASE, SCOPE_ONE, SCOPE_SUB from LdapConnection. /// /// /// </param> /// <param name="filter"> The search filter specifying the search criteria. /// from LdapConnection: SCOPE_BASE, SCOPE_ONE, SCOPE_SUB. /// /// /// </param> /// <param name="extensions"> Extensions provide a mechanism to extend the /// functionality of Ldap URLs. Currently no /// Ldap URL extensions are defined. Each extension /// specification is a type=value expression, and may /// be <code>null</code> or empty. The =value part may be /// omitted. The expression may be prefixed with '!' if it /// is mandatory for the evaluation of the URL. /// /// /// </param> /// <param name="secure"> If true creates an Ldap URL of the ldaps type /// </param> public LdapUrl(String host, int port, String dn, String[] attrNames, int scope, String filter, String[] extensions, bool secure) { InitBlock(); this.host = host; this.port = port; this.dn = dn; attrs = attrNames; this.scope = scope; this.filter = filter; this.extensions = new String[extensions.Length]; extensions.CopyTo(this.extensions, 0); this.secure = secure; return ; } /// <summary> Returns a clone of this URL object. /// /// </summary> /// <returns> clone of this URL object. /// </returns> public object Clone() { try { return MemberwiseClone(); } catch (Exception ce) { throw new Exception("Internal error, cannot create clone"); } } /// <summary> Decodes a URL-encoded string. /// /// Any occurences of %HH are decoded to the hex value represented. /// However, this method does NOT decode "+" into " ". /// /// </summary> /// <param name="URLEncoded"> String to decode. /// /// </param> /// <returns> The decoded string. /// /// </returns> /// <exception> MalformedURLException The URL could not be parsed. /// </exception> public static String decode(String URLEncoded) { int searchStart = 0; int fieldStart; fieldStart = URLEncoded.IndexOf("%", searchStart); // Return now if no encoded data if (fieldStart < 0) { return URLEncoded; } // Decode the %HH value and copy to new string buffer int fieldEnd = 0; // end of previous field int dataLen = URLEncoded.Length; System.Text.StringBuilder decoded = new System.Text.StringBuilder(dataLen); while (true) { if (fieldStart > (dataLen - 3)) { throw new UriFormatException("LdapUrl.decode: must be two hex characters following escape character '%'"); } if (fieldStart < 0) fieldStart = dataLen; // Copy to string buffer from end of last field to start of next decoded.Append(URLEncoded.Substring(fieldEnd, (fieldStart) - (fieldEnd))); fieldStart += 1; if (fieldStart >= dataLen) break; fieldEnd = fieldStart + 2; try { decoded.Append((char) Convert.ToInt32(URLEncoded.Substring(fieldStart, (fieldEnd) - (fieldStart)), 16)); } catch (FormatException ex) { throw new UriFormatException("LdapUrl.decode: error converting hex characters to integer \"" + ex.Message + "\""); } searchStart = fieldEnd; if (searchStart == dataLen) break; fieldStart = URLEncoded.IndexOf("%", searchStart); } return (decoded.ToString()); } /// <summary> Encodes an arbitrary string using the URL encoding rules. /// /// Any illegal characters are encoded as %HH. /// /// </summary> /// <param name="toEncode"> The string to encode. /// /// </param> /// <returns> The URL-encoded string. /// /// Comment: An illegal character consists of any non graphical US-ASCII character, Unsafe, or reserved characters. /// </returns> public static String encode(String toEncode) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(toEncode.Length); //empty but initial capicity of 'length' String temp; char currChar; for (int i = 0; i < toEncode.Length; i++) { currChar = toEncode[i]; if ((((int) currChar <= 0x1F) || ((int) currChar == 0x7F) || (((int) currChar >= 0x80) && ((int) currChar <= 0xFF))) || ((currChar == '<') || (currChar == '>') || (currChar == '\"') || (currChar == '#') || (currChar == '%') || (currChar == '{') || (currChar == '}') || (currChar == '|') || (currChar == '\\') || (currChar == '^') || (currChar == '~') || (currChar == '[') || (currChar == '\'')) || ((currChar == ';') || (currChar == '/') || (currChar == '?') || (currChar == ':') || (currChar == '@') || (currChar == '=') || (currChar == '&'))) { temp = Convert.ToString(currChar, 16); if (temp.Length == 1) buffer.Append("%0" + temp); //if(temp.length()==2) this can only be two or one digit long. else buffer.Append("%" + Convert.ToString(currChar, 16)); } else buffer.Append(currChar); } return buffer.ToString(); } /// <summary> Returns the base distinguished name encapsulated in the URL. /// /// </summary> /// <returns> The base distinguished name specified in the URL, or null if none. /// </returns> public virtual String getDN() { return dn; } /// <summary> Sets the base distinguished name encapsulated in the URL.</summary> /* package */ internal virtual void setDN(String dn) { this.dn = dn; return ; } /// <summary> Returns a valid string representation of this Ldap URL. /// /// </summary> /// <returns> The string representation of the Ldap URL. /// </returns> public override String ToString() { System.Text.StringBuilder url = new System.Text.StringBuilder(256); // Scheme if (secure) { url.Append("ldaps://"); } else { url.Append("ldap://"); } // Host:port/dn if (ipV6) { url.Append("[" + host + "]"); } else { url.Append(host); } // Port not specified if (port != 0) { url.Append(":" + port); } if (((object) dn == null) && (attrs == null) && (scope == DEFAULT_SCOPE) && ((object) filter == null) && (extensions == null)) { return url.ToString(); } url.Append("/"); if ((object) dn != null) { url.Append(dn); } if ((attrs == null) && (scope == DEFAULT_SCOPE) && ((object) filter == null) && (extensions == null)) { return url.ToString(); } // attributes url.Append("?"); if (attrs != null) { //should we check also for attrs != "*" for (int i = 0; i < attrs.Length; i++) { url.Append(attrs[i]); if (i < (attrs.Length - 1)) { url.Append(","); } } } if ((scope == DEFAULT_SCOPE) && ((object) filter == null) && (extensions == null)) { return url.ToString(); } // scope url.Append("?"); if (scope != DEFAULT_SCOPE) { if (scope == LdapConnection.SCOPE_ONE) { url.Append("one"); } else { url.Append("sub"); } } if (((object) filter == null) && (extensions == null)) { return url.ToString(); } // filter if ((object) filter == null) { url.Append("?"); } else { url.Append("?" + Filter); } if (extensions == null) { return url.ToString(); } // extensions url.Append("?"); if (extensions != null) { for (int i = 0; i < extensions.Length; i++) { url.Append(extensions[i]); if (i < (extensions.Length - 1)) { url.Append(","); } } } return url.ToString(); } private String[] parseList(String listStr, char delimiter, int listStart, int listEnd) // end of list + 1 { String[] list; // Check for and empty string if ((listEnd - listStart) < 1) { return null; } // First count how many items are specified int itemStart = listStart; int itemEnd; int itemCount = 0; while (itemStart > 0) { // itemStart == 0 if no delimiter found itemCount += 1; itemEnd = listStr.IndexOf((Char) delimiter, itemStart); if ((itemEnd > 0) && (itemEnd < listEnd)) { itemStart = itemEnd + 1; } else { break; } } // Now fill in the array with the attributes itemStart = listStart; list = new String[itemCount]; itemCount = 0; while (itemStart > 0) { itemEnd = listStr.IndexOf((Char) delimiter, itemStart); if (itemStart <= listEnd) { if (itemEnd < 0) itemEnd = listEnd; if (itemEnd > listEnd) itemEnd = listEnd; list[itemCount] = listStr.Substring(itemStart, (itemEnd) - (itemStart)); itemStart = itemEnd + 1; itemCount += 1; } else { break; } } return list; } private void parseURL(String url) { int scanStart = 0; int scanEnd = url.Length; if ((object) url == null) throw new UriFormatException("LdapUrl: URL cannot be null"); // Check if URL is enclosed by < & > if (url[scanStart] == '<') { if (url[scanEnd - 1] != '>') throw new UriFormatException("LdapUrl: URL bad enclosure"); scanStart += 1; scanEnd -= 1; } // Determine the URL scheme and set appropriate default port if (url.Substring(scanStart, (scanStart + 4) - (scanStart)).ToUpper().Equals("URL:".ToUpper())) { scanStart += 4; } if (url.Substring(scanStart, (scanStart + 7) - (scanStart)).ToUpper().Equals("ldap://".ToUpper())) { scanStart += 7; port = LdapConnection.DEFAULT_PORT; } else if (url.Substring(scanStart, (scanStart + 8) - (scanStart)).ToUpper().Equals("ldaps://".ToUpper())) { secure = true; scanStart += 8; port = LdapConnection.DEFAULT_SSL_PORT; } else { throw new UriFormatException("LdapUrl: URL scheme is not ldap"); } // Find where host:port ends and dn begins int dnStart = url.IndexOf("/", scanStart); int hostPortEnd = scanEnd; bool novell = false; if (dnStart < 0) { /* * Kludge. check for ldap://111.222.333.444:389??cn=abc,o=company * * Check for broken Novell referral format. The dn is in * the scope position, but the required slash is missing. * This is illegal syntax but we need to account for it. * Fortunately it can't be confused with anything real. */ dnStart = url.IndexOf("?", scanStart); if (dnStart > 0) { if (url[dnStart + 1] == '?') { hostPortEnd = dnStart; dnStart += 1; novell = true; } else { dnStart = - 1; } } } else { hostPortEnd = dnStart; } // Check for IPV6 "[ipaddress]:port" int portStart; int hostEnd = hostPortEnd; if (url[scanStart] == '[') { hostEnd = url.IndexOf((Char) ']', scanStart + 1); if ((hostEnd >= hostPortEnd) || (hostEnd == - 1)) { throw new UriFormatException("LdapUrl: \"]\" is missing on IPV6 host name"); } // Get host w/o the [ & ] host = url.Substring(scanStart + 1, (hostEnd) - (scanStart + 1)); portStart = url.IndexOf(":", hostEnd); if ((portStart < hostPortEnd) && (portStart != - 1)) { // port is specified port = Int32.Parse(url.Substring(portStart + 1, (hostPortEnd) - (portStart + 1))); } else { } } else { portStart = url.IndexOf(":", scanStart); // Isolate the host and port if ((portStart < 0) || (portStart > hostPortEnd)) { // no port is specified, we keep the default host = url.Substring(scanStart, (hostPortEnd) - (scanStart)); } else { // port specified in URL host = url.Substring(scanStart, (portStart) - (scanStart)); port = Int32.Parse(url.Substring(portStart + 1, (hostPortEnd) - (portStart + 1))); } } scanStart = hostPortEnd + 1; if ((scanStart >= scanEnd) || (dnStart < 0)) return ; // Parse out the base dn scanStart = dnStart + 1; int attrsStart = url.IndexOf((Char) '?', scanStart); if (attrsStart < 0) { dn = url.Substring(scanStart, (scanEnd) - (scanStart)); } else { dn = url.Substring(scanStart, (attrsStart) - (scanStart)); } scanStart = attrsStart + 1; // Wierd novell syntax can have nothing beyond the dn if ((scanStart >= scanEnd) || (attrsStart < 0) || novell) return ; // Parse out the attributes int scopeStart = url.IndexOf((Char) '?', scanStart); if (scopeStart < 0) scopeStart = scanEnd - 1; attrs = parseList(url, ',', attrsStart + 1, scopeStart); scanStart = scopeStart + 1; if (scanStart >= scanEnd) return ; // Parse out the scope int filterStart = url.IndexOf((Char) '?', scanStart); String scopeStr; if (filterStart < 0) { scopeStr = url.Substring(scanStart, (scanEnd) - (scanStart)); } else { scopeStr = url.Substring(scanStart, (filterStart) - (scanStart)); } if (scopeStr.ToUpper().Equals("".ToUpper())) { scope = LdapConnection.SCOPE_BASE; } else if (scopeStr.ToUpper().Equals("base".ToUpper())) { scope = LdapConnection.SCOPE_BASE; } else if (scopeStr.ToUpper().Equals("one".ToUpper())) { scope = LdapConnection.SCOPE_ONE; } else if (scopeStr.ToUpper().Equals("sub".ToUpper())) { scope = LdapConnection.SCOPE_SUB; } else { throw new UriFormatException("LdapUrl: URL invalid scope"); } scanStart = filterStart + 1; if ((scanStart >= scanEnd) || (filterStart < 0)) return ; // Parse out the filter scanStart = filterStart + 1; String filterStr; int extStart = url.IndexOf((Char) '?', scanStart); if (extStart < 0) { filterStr = url.Substring(scanStart, (scanEnd) - (scanStart)); } else { filterStr = url.Substring(scanStart, (extStart) - (scanStart)); } if (!filterStr.Equals("")) { filter = filterStr; // Only modify if not the default filter } scanStart = extStart + 1; if ((scanStart >= scanEnd) || (extStart < 0)) return ; // Parse out the extensions int end = url.IndexOf((Char) '?', scanStart); if (end > 0) throw new UriFormatException("LdapUrl: URL has too many ? fields"); extensions = parseList(url, ',', scanStart, scanEnd); return ; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace TestResources { public static class AnalyzerTests { private static byte[] _FaultyAnalyzer; public static byte[] FaultyAnalyzer => ResourceLoader.GetOrCreateResource(ref _FaultyAnalyzer, "Analyzers.FaultyAnalyzer.dll"); } public static class AssemblyLoadTests { private static byte[] _Alpha; public static byte[] Alpha => ResourceLoader.GetOrCreateResource(ref _Alpha, "AssemblyLoadTests.Alpha.dll"); private static byte[] _Beta; public static byte[] Beta => ResourceLoader.GetOrCreateResource(ref _Beta, "AssemblyLoadTests.Beta.dll"); private static byte[] _Delta; public static byte[] Delta => ResourceLoader.GetOrCreateResource(ref _Delta, "AssemblyLoadTests.Delta.dll"); private static byte[] _Gamma; public static byte[] Gamma => ResourceLoader.GetOrCreateResource(ref _Gamma, "AssemblyLoadTests.Gamma.dll"); } public static class DiagnosticTests { private static byte[] _badresfile; public static byte[] badresfile => ResourceLoader.GetOrCreateResource(ref _badresfile, "DiagnosticTests.badresfile.res"); private static byte[] _ErrTestLib01; public static byte[] ErrTestLib01 => ResourceLoader.GetOrCreateResource(ref _ErrTestLib01, "DiagnosticTests.ErrTestLib01.dll"); private static byte[] _ErrTestLib02; public static byte[] ErrTestLib02 => ResourceLoader.GetOrCreateResource(ref _ErrTestLib02, "DiagnosticTests.ErrTestLib02.dll"); private static byte[] _ErrTestLib11; public static byte[] ErrTestLib11 => ResourceLoader.GetOrCreateResource(ref _ErrTestLib11, "DiagnosticTests.ErrTestLib11.dll"); private static byte[] _ErrTestMod01; public static byte[] ErrTestMod01 => ResourceLoader.GetOrCreateResource(ref _ErrTestMod01, "DiagnosticTests.ErrTestMod01.netmodule"); private static byte[] _ErrTestMod02; public static byte[] ErrTestMod02 => ResourceLoader.GetOrCreateResource(ref _ErrTestMod02, "DiagnosticTests.ErrTestMod02.netmodule"); } public static class Basic { private static byte[] _Members; public static byte[] Members => ResourceLoader.GetOrCreateResource(ref _Members, "MetadataTests.Members.dll"); private static byte[] _NativeApp; public static byte[] NativeApp => ResourceLoader.GetOrCreateResource(ref _NativeApp, "MetadataTests.NativeApp.exe"); } } namespace TestResources.MetadataTests { public static class InterfaceAndClass { private static byte[] _CSClasses01; public static byte[] CSClasses01 => ResourceLoader.GetOrCreateResource(ref _CSClasses01, "MetadataTests.InterfaceAndClass.CSClasses01.dll"); private static byte[] _CSInterfaces01; public static byte[] CSInterfaces01 => ResourceLoader.GetOrCreateResource(ref _CSInterfaces01, "MetadataTests.InterfaceAndClass.CSInterfaces01.dll"); private static byte[] _VBClasses01; public static byte[] VBClasses01 => ResourceLoader.GetOrCreateResource(ref _VBClasses01, "MetadataTests.InterfaceAndClass.VBClasses01.dll"); private static byte[] _VBClasses02; public static byte[] VBClasses02 => ResourceLoader.GetOrCreateResource(ref _VBClasses02, "MetadataTests.InterfaceAndClass.VBClasses02.dll"); private static byte[] _VBInterfaces01; public static byte[] VBInterfaces01 => ResourceLoader.GetOrCreateResource(ref _VBInterfaces01, "MetadataTests.InterfaceAndClass.VBInterfaces01.dll"); } public static class Interop { private static byte[] _IndexerWithByRefParam; public static byte[] IndexerWithByRefParam => ResourceLoader.GetOrCreateResource(ref _IndexerWithByRefParam, "MetadataTests.Interop.IndexerWithByRefParam.dll"); private static byte[] _Interop_Mock01; public static byte[] Interop_Mock01 => ResourceLoader.GetOrCreateResource(ref _Interop_Mock01, "MetadataTests.Interop.Interop.Mock01.dll"); private static byte[] _Interop_Mock01_Impl; public static byte[] Interop_Mock01_Impl => ResourceLoader.GetOrCreateResource(ref _Interop_Mock01_Impl, "MetadataTests.Interop.Interop.Mock01.Impl.dll"); } public static class Invalid { private static byte[] _ClassLayout; public static byte[] ClassLayout => ResourceLoader.GetOrCreateResource(ref _ClassLayout, "MetadataTests.Invalid.ClassLayout.dll"); private static byte[] _CustomAttributeTableUnsorted; public static byte[] CustomAttributeTableUnsorted => ResourceLoader.GetOrCreateResource(ref _CustomAttributeTableUnsorted, "MetadataTests.Invalid.CustomAttributeTableUnsorted.dll"); private static byte[] _EmptyModuleTable; public static byte[] EmptyModuleTable => ResourceLoader.GetOrCreateResource(ref _EmptyModuleTable, "MetadataTests.Invalid.EmptyModuleTable.netmodule"); private static byte[] _IncorrectCustomAssemblyTableSize_TooManyMethodSpecs; public static byte[] IncorrectCustomAssemblyTableSize_TooManyMethodSpecs => ResourceLoader.GetOrCreateResource(ref _IncorrectCustomAssemblyTableSize_TooManyMethodSpecs, "MetadataTests.Invalid.IncorrectCustomAssemblyTableSize_TooManyMethodSpecs.dll"); private static byte[] _InvalidDynamicAttributeArgs; public static byte[] InvalidDynamicAttributeArgs => ResourceLoader.GetOrCreateResource(ref _InvalidDynamicAttributeArgs, "MetadataTests.Invalid.InvalidDynamicAttributeArgs.dll"); private static byte[] _InvalidFuncDelegateName; public static byte[] InvalidFuncDelegateName => ResourceLoader.GetOrCreateResource(ref _InvalidFuncDelegateName, "MetadataTests.Invalid.InvalidFuncDelegateName.dll"); private static byte[] _InvalidGenericType; public static byte[] InvalidGenericType => ResourceLoader.GetOrCreateResource(ref _InvalidGenericType, "MetadataTests.Invalid.InvalidGenericType.dll"); private static byte[] _InvalidModuleName; public static byte[] InvalidModuleName => ResourceLoader.GetOrCreateResource(ref _InvalidModuleName, "MetadataTests.Invalid.InvalidModuleName.dll"); private static byte[] _LongTypeFormInSignature; public static byte[] LongTypeFormInSignature => ResourceLoader.GetOrCreateResource(ref _LongTypeFormInSignature, "MetadataTests.Invalid.LongTypeFormInSignature.dll"); private static string _ManyMethodSpecs; public static string ManyMethodSpecs => ResourceLoader.GetOrCreateResource(ref _ManyMethodSpecs, "MetadataTests.Invalid.ManyMethodSpecs.vb"); private static byte[] _Obfuscated; public static byte[] Obfuscated => ResourceLoader.GetOrCreateResource(ref _Obfuscated, "MetadataTests.Invalid.Obfuscated.dll"); private static byte[] _Obfuscated2; public static byte[] Obfuscated2 => ResourceLoader.GetOrCreateResource(ref _Obfuscated2, "MetadataTests.Invalid.Obfuscated2.dll"); public static class Signatures { private static byte[] _SignatureCycle2; public static byte[] SignatureCycle2 => ResourceLoader.GetOrCreateResource(ref _SignatureCycle2, "MetadataTests.Invalid.Signatures.SignatureCycle2.exe"); private static byte[] _TypeSpecInWrongPlace; public static byte[] TypeSpecInWrongPlace => ResourceLoader.GetOrCreateResource(ref _TypeSpecInWrongPlace, "MetadataTests.Invalid.Signatures.TypeSpecInWrongPlace.exe"); } } public static class NetModule01 { private static byte[] _AppCS; public static byte[] AppCS => ResourceLoader.GetOrCreateResource(ref _AppCS, "MetadataTests.NetModule01.AppCS.exe"); private static byte[] _ModuleCS00; public static byte[] ModuleCS00 => ResourceLoader.GetOrCreateResource(ref _ModuleCS00, "MetadataTests.NetModule01.ModuleCS00.mod"); private static byte[] _ModuleCS01; public static byte[] ModuleCS01 => ResourceLoader.GetOrCreateResource(ref _ModuleCS01, "MetadataTests.NetModule01.ModuleCS01.mod"); private static byte[] _ModuleVB01; public static byte[] ModuleVB01 => ResourceLoader.GetOrCreateResource(ref _ModuleVB01, "MetadataTests.NetModule01.ModuleVB01.mod"); } } namespace TestResources.NetFX { public static class aacorlib_v15_0_3928 { private static string _aacorlib_v15_0_3928_cs; public static string aacorlib_v15_0_3928_cs => ResourceLoader.GetOrCreateResource(ref _aacorlib_v15_0_3928_cs, "NetFX.aacorlib.aacorlib.v15.0.3928.cs"); } public static class Minimal { private static byte[] _mincorlib; public static byte[] mincorlib => ResourceLoader.GetOrCreateResource(ref _mincorlib, "NetFX.Minimal.mincorlib.dll"); } } namespace TestResources { public static class PerfTests { private static string _CSPerfTest; public static string CSPerfTest => ResourceLoader.GetOrCreateResource(ref _CSPerfTest, "PerfTests.CSPerfTest.cs"); private static string _VBPerfTest; public static string VBPerfTest => ResourceLoader.GetOrCreateResource(ref _VBPerfTest, "PerfTests.VBPerfTest.vb"); } public static class General { private static byte[] _BigVisitor; public static byte[] BigVisitor => ResourceLoader.GetOrCreateResource(ref _BigVisitor, "SymbolsTests.BigVisitor.dll"); private static byte[] _DelegateByRefParamArray; public static byte[] DelegateByRefParamArray => ResourceLoader.GetOrCreateResource(ref _DelegateByRefParamArray, "SymbolsTests.Delegates.DelegateByRefParamArray.dll"); private static byte[] _DelegatesWithoutInvoke; public static byte[] DelegatesWithoutInvoke => ResourceLoader.GetOrCreateResource(ref _DelegatesWithoutInvoke, "SymbolsTests.Delegates.DelegatesWithoutInvoke.dll"); private static byte[] _shiftJisSource; public static byte[] ShiftJisSource => ResourceLoader.GetOrCreateResource(ref _shiftJisSource, "Encoding.sjis.cs"); private static byte[] _Events; public static byte[] Events => ResourceLoader.GetOrCreateResource(ref _Events, "SymbolsTests.Events.dll"); private static byte[] _CSharpExplicitInterfaceImplementation; public static byte[] CSharpExplicitInterfaceImplementation => ResourceLoader.GetOrCreateResource(ref _CSharpExplicitInterfaceImplementation, "SymbolsTests.ExplicitInterfaceImplementation.CSharpExplicitInterfaceImplementation.dll"); private static byte[] _CSharpExplicitInterfaceImplementationEvents; public static byte[] CSharpExplicitInterfaceImplementationEvents => ResourceLoader.GetOrCreateResource(ref _CSharpExplicitInterfaceImplementationEvents, "SymbolsTests.ExplicitInterfaceImplementation.CSharpExplicitInterfaceImplementationEvents.dll"); private static byte[] _CSharpExplicitInterfaceImplementationProperties; public static byte[] CSharpExplicitInterfaceImplementationProperties => ResourceLoader.GetOrCreateResource(ref _CSharpExplicitInterfaceImplementationProperties, "SymbolsTests.ExplicitInterfaceImplementation.CSharpExplicitInterfaceImplementationProperties.dll"); private static byte[] _ILExplicitInterfaceImplementation; public static byte[] ILExplicitInterfaceImplementation => ResourceLoader.GetOrCreateResource(ref _ILExplicitInterfaceImplementation, "SymbolsTests.ExplicitInterfaceImplementation.ILExplicitInterfaceImplementation.dll"); private static byte[] _ILExplicitInterfaceImplementationProperties; public static byte[] ILExplicitInterfaceImplementationProperties => ResourceLoader.GetOrCreateResource(ref _ILExplicitInterfaceImplementationProperties, "SymbolsTests.ExplicitInterfaceImplementation.ILExplicitInterfaceImplementationProperties.dll"); private static byte[] _FSharpTestLibrary; public static byte[] FSharpTestLibrary => ResourceLoader.GetOrCreateResource(ref _FSharpTestLibrary, "SymbolsTests.FSharpTestLibrary.dll"); private static byte[] _Indexers; public static byte[] Indexers => ResourceLoader.GetOrCreateResource(ref _Indexers, "SymbolsTests.Indexers.dll"); private static byte[] _InheritIComparable; public static byte[] InheritIComparable => ResourceLoader.GetOrCreateResource(ref _InheritIComparable, "SymbolsTests.InheritIComparable.dll"); private static byte[] _MDTestLib1; public static byte[] MDTestLib1 => ResourceLoader.GetOrCreateResource(ref _MDTestLib1, "SymbolsTests.MDTestLib1.dll"); private static byte[] _MDTestLib2; public static byte[] MDTestLib2 => ResourceLoader.GetOrCreateResource(ref _MDTestLib2, "SymbolsTests.MDTestLib2.dll"); private static byte[] _nativeCOFFResources; public static byte[] nativeCOFFResources => ResourceLoader.GetOrCreateResource(ref _nativeCOFFResources, "SymbolsTests.nativeCOFFResources.obj"); private static byte[] _Properties; public static byte[] Properties => ResourceLoader.GetOrCreateResource(ref _Properties, "SymbolsTests.Properties.dll"); private static byte[] _PropertiesWithByRef; public static byte[] PropertiesWithByRef => ResourceLoader.GetOrCreateResource(ref _PropertiesWithByRef, "SymbolsTests.PropertiesWithByRef.dll"); private static byte[] _Regress40025DLL; public static byte[] Regress40025DLL => ResourceLoader.GetOrCreateResource(ref _Regress40025DLL, "SymbolsTests.Regress40025DLL.dll"); private static byte[] _snKey; public static byte[] snKey => ResourceLoader.GetOrCreateResource(ref _snKey, "SymbolsTests.snKey.snk"); private static byte[] _snKey2; public static byte[] snKey2 => ResourceLoader.GetOrCreateResource(ref _snKey2, "SymbolsTests.snKey2.snk"); private static byte[] _snPublicKey; public static byte[] snPublicKey => ResourceLoader.GetOrCreateResource(ref _snPublicKey, "SymbolsTests.snPublicKey.snk"); private static byte[] _snPublicKey2; public static byte[] snPublicKey2 => ResourceLoader.GetOrCreateResource(ref _snPublicKey2, "SymbolsTests.snPublicKey2.snk"); private static byte[] _CSharpErrors; public static byte[] CSharpErrors => ResourceLoader.GetOrCreateResource(ref _CSharpErrors, "SymbolsTests.UseSiteErrors.CSharpErrors.dll"); private static byte[] _ILErrors; public static byte[] ILErrors => ResourceLoader.GetOrCreateResource(ref _ILErrors, "SymbolsTests.UseSiteErrors.ILErrors.dll"); private static byte[] _Unavailable; public static byte[] Unavailable => ResourceLoader.GetOrCreateResource(ref _Unavailable, "SymbolsTests.UseSiteErrors.Unavailable.dll"); private static byte[] _VBConversions; public static byte[] VBConversions => ResourceLoader.GetOrCreateResource(ref _VBConversions, "SymbolsTests.VBConversions.dll"); private static byte[] _Culture_AR_SA; public static byte[] Culture_AR_SA => ResourceLoader.GetOrCreateResource(ref _Culture_AR_SA, "SymbolsTests.Versioning.AR_SA.Culture.dll"); private static byte[] _Culture_EN_US; public static byte[] Culture_EN_US => ResourceLoader.GetOrCreateResource(ref _Culture_EN_US, "SymbolsTests.Versioning.EN_US.Culture.dll"); private static byte[] _C1; public static byte[] C1 => ResourceLoader.GetOrCreateResource(ref _C1, "SymbolsTests.Versioning.V1.C.dll"); private static byte[] _C2; public static byte[] C2 => ResourceLoader.GetOrCreateResource(ref _C2, "SymbolsTests.Versioning.V2.C.dll"); private static byte[] _With_Spaces; public static byte[] With_Spaces => ResourceLoader.GetOrCreateResource(ref _With_Spaces, "SymbolsTests.With Spaces.dll"); private static byte[] _With_SpacesModule; public static byte[] With_SpacesModule => ResourceLoader.GetOrCreateResource(ref _With_SpacesModule, "SymbolsTests.With Spaces.netmodule"); } } namespace TestResources.SymbolsTests { public static class CorLibrary { private static byte[] _FakeMsCorLib; public static byte[] FakeMsCorLib => ResourceLoader.GetOrCreateResource(ref _FakeMsCorLib, "SymbolsTests.CorLibrary.FakeMsCorLib.dll"); private static byte[] _GuidTest2; public static byte[] GuidTest2 => ResourceLoader.GetOrCreateResource(ref _GuidTest2, "SymbolsTests.CorLibrary.GuidTest2.exe"); private static byte[] _NoMsCorLibRef; public static byte[] NoMsCorLibRef => ResourceLoader.GetOrCreateResource(ref _NoMsCorLibRef, "SymbolsTests.CorLibrary.NoMsCorLibRef.dll"); } public static class CustomModifiers { private static byte[] _CppCli; public static byte[] CppCli => ResourceLoader.GetOrCreateResource(ref _CppCli, "SymbolsTests.CustomModifiers.CppCli.dll"); private static byte[] _Modifiers; public static byte[] Modifiers => ResourceLoader.GetOrCreateResource(ref _Modifiers, "SymbolsTests.CustomModifiers.Modifiers.dll"); private static byte[] _ModifiersModule; public static byte[] ModifiersModule => ResourceLoader.GetOrCreateResource(ref _ModifiersModule, "SymbolsTests.CustomModifiers.Modifiers.netmodule"); private static byte[] _ModoptTests; public static byte[] ModoptTests => ResourceLoader.GetOrCreateResource(ref _ModoptTests, "SymbolsTests.CustomModifiers.ModoptTests.dll"); } public static class Cyclic { private static byte[] _Cyclic1; public static byte[] Cyclic1 => ResourceLoader.GetOrCreateResource(ref _Cyclic1, "SymbolsTests.Cyclic.Cyclic1.dll"); private static byte[] _Cyclic2; public static byte[] Cyclic2 => ResourceLoader.GetOrCreateResource(ref _Cyclic2, "SymbolsTests.Cyclic.Cyclic2.dll"); } public static class CyclicInheritance { private static byte[] _Class1; public static byte[] Class1 => ResourceLoader.GetOrCreateResource(ref _Class1, "SymbolsTests.CyclicInheritance.Class1.dll"); private static byte[] _Class2; public static byte[] Class2 => ResourceLoader.GetOrCreateResource(ref _Class2, "SymbolsTests.CyclicInheritance.Class2.dll"); private static byte[] _Class3; public static byte[] Class3 => ResourceLoader.GetOrCreateResource(ref _Class3, "SymbolsTests.CyclicInheritance.Class3.dll"); } public static class CyclicStructure { private static byte[] _cycledstructs; public static byte[] cycledstructs => ResourceLoader.GetOrCreateResource(ref _cycledstructs, "SymbolsTests.CyclicStructure.cycledstructs.dll"); } public static class DifferByCase { private static byte[] _Consumer; public static byte[] Consumer => ResourceLoader.GetOrCreateResource(ref _Consumer, "SymbolsTests.DifferByCase.Consumer.dll"); private static byte[] _CsharpCaseSen; public static byte[] CsharpCaseSen => ResourceLoader.GetOrCreateResource(ref _CsharpCaseSen, "SymbolsTests.DifferByCase.CsharpCaseSen.dll"); private static byte[] _CSharpDifferCaseOverloads; public static byte[] CSharpDifferCaseOverloads => ResourceLoader.GetOrCreateResource(ref _CSharpDifferCaseOverloads, "SymbolsTests.DifferByCase.CSharpDifferCaseOverloads.dll"); private static byte[] _TypeAndNamespaceDifferByCase; public static byte[] TypeAndNamespaceDifferByCase => ResourceLoader.GetOrCreateResource(ref _TypeAndNamespaceDifferByCase, "SymbolsTests.DifferByCase.TypeAndNamespaceDifferByCase.dll"); } public static class Fields { private static byte[] _ConstantFields; public static byte[] ConstantFields => ResourceLoader.GetOrCreateResource(ref _ConstantFields, "SymbolsTests.Fields.ConstantFields.dll"); private static byte[] _CSFields; public static byte[] CSFields => ResourceLoader.GetOrCreateResource(ref _CSFields, "SymbolsTests.Fields.CSFields.dll"); private static byte[] _VBFields; public static byte[] VBFields => ResourceLoader.GetOrCreateResource(ref _VBFields, "SymbolsTests.Fields.VBFields.dll"); } public static class Interface { private static byte[] _MDInterfaceMapping; public static byte[] MDInterfaceMapping => ResourceLoader.GetOrCreateResource(ref _MDInterfaceMapping, "SymbolsTests.Interface.MDInterfaceMapping.dll"); private static byte[] _StaticMethodInInterface; public static byte[] StaticMethodInInterface => ResourceLoader.GetOrCreateResource(ref _StaticMethodInInterface, "SymbolsTests.Interface.StaticMethodInInterface.dll"); } public static class Metadata { private static byte[] _AttributeInterop01; public static byte[] AttributeInterop01 => ResourceLoader.GetOrCreateResource(ref _AttributeInterop01, "SymbolsTests.Metadata.AttributeInterop01.dll"); private static byte[] _AttributeInterop02; public static byte[] AttributeInterop02 => ResourceLoader.GetOrCreateResource(ref _AttributeInterop02, "SymbolsTests.Metadata.AttributeInterop02.dll"); private static byte[] _AttributeTestDef01; public static byte[] AttributeTestDef01 => ResourceLoader.GetOrCreateResource(ref _AttributeTestDef01, "SymbolsTests.Metadata.AttributeTestDef01.dll"); private static byte[] _AttributeTestLib01; public static byte[] AttributeTestLib01 => ResourceLoader.GetOrCreateResource(ref _AttributeTestLib01, "SymbolsTests.Metadata.AttributeTestLib01.dll"); private static byte[] _DynamicAttribute; public static byte[] DynamicAttribute => ResourceLoader.GetOrCreateResource(ref _DynamicAttribute, "SymbolsTests.Metadata.DynamicAttribute.dll"); private static byte[] _InvalidCharactersInAssemblyName; public static byte[] InvalidCharactersInAssemblyName => ResourceLoader.GetOrCreateResource(ref _InvalidCharactersInAssemblyName, "SymbolsTests.Metadata.InvalidCharactersInAssemblyName.dll"); private static byte[] _InvalidPublicKey; public static byte[] InvalidPublicKey => ResourceLoader.GetOrCreateResource(ref _InvalidPublicKey, "SymbolsTests.Metadata.InvalidPublicKey.dll"); private static byte[] _MDTestAttributeApplicationLib; public static byte[] MDTestAttributeApplicationLib => ResourceLoader.GetOrCreateResource(ref _MDTestAttributeApplicationLib, "SymbolsTests.Metadata.MDTestAttributeApplicationLib.dll"); private static byte[] _MDTestAttributeDefLib; public static byte[] MDTestAttributeDefLib => ResourceLoader.GetOrCreateResource(ref _MDTestAttributeDefLib, "SymbolsTests.Metadata.MDTestAttributeDefLib.dll"); private static byte[] _MscorlibNamespacesAndTypes; public static byte[] MscorlibNamespacesAndTypes => ResourceLoader.GetOrCreateResource(ref _MscorlibNamespacesAndTypes, "SymbolsTests.Metadata.MscorlibNamespacesAndTypes.bsl"); } public static class Methods { private static byte[] _ByRefReturn; public static byte[] ByRefReturn => ResourceLoader.GetOrCreateResource(ref _ByRefReturn, "SymbolsTests.Methods.ByRefReturn.dll"); private static byte[] _CSMethods; public static byte[] CSMethods => ResourceLoader.GetOrCreateResource(ref _CSMethods, "SymbolsTests.Methods.CSMethods.dll"); private static byte[] _ILMethods; public static byte[] ILMethods => ResourceLoader.GetOrCreateResource(ref _ILMethods, "SymbolsTests.Methods.ILMethods.dll"); private static byte[] _VBMethods; public static byte[] VBMethods => ResourceLoader.GetOrCreateResource(ref _VBMethods, "SymbolsTests.Methods.VBMethods.dll"); } public static class MissingTypes { private static byte[] _CL2; public static byte[] CL2 => ResourceLoader.GetOrCreateResource(ref _CL2, "SymbolsTests.MissingTypes.CL2.dll"); private static byte[] _CL3; public static byte[] CL3 => ResourceLoader.GetOrCreateResource(ref _CL3, "SymbolsTests.MissingTypes.CL3.dll"); private static string _CL3_VB; public static string CL3_VB => ResourceLoader.GetOrCreateResource(ref _CL3_VB, "SymbolsTests.MissingTypes.CL3.vb"); private static byte[] _MDMissingType; public static byte[] MDMissingType => ResourceLoader.GetOrCreateResource(ref _MDMissingType, "SymbolsTests.MissingTypes.MDMissingType.dll"); private static byte[] _MDMissingTypeLib; public static byte[] MDMissingTypeLib => ResourceLoader.GetOrCreateResource(ref _MDMissingTypeLib, "SymbolsTests.MissingTypes.MDMissingTypeLib.dll"); private static byte[] _MDMissingTypeLib_New; public static byte[] MDMissingTypeLib_New => ResourceLoader.GetOrCreateResource(ref _MDMissingTypeLib_New, "SymbolsTests.MissingTypes.MDMissingTypeLib_New.dll"); private static byte[] _MissingTypesEquality1; public static byte[] MissingTypesEquality1 => ResourceLoader.GetOrCreateResource(ref _MissingTypesEquality1, "SymbolsTests.MissingTypes.MissingTypesEquality1.dll"); private static byte[] _MissingTypesEquality2; public static byte[] MissingTypesEquality2 => ResourceLoader.GetOrCreateResource(ref _MissingTypesEquality2, "SymbolsTests.MissingTypes.MissingTypesEquality2.dll"); } public static class MultiModule { private static byte[] _Consumer; public static byte[] Consumer => ResourceLoader.GetOrCreateResource(ref _Consumer, "SymbolsTests.MultiModule.Consumer.dll"); private static byte[] _mod2; public static byte[] mod2 => ResourceLoader.GetOrCreateResource(ref _mod2, "SymbolsTests.MultiModule.mod2.netmodule"); private static byte[] _mod3; public static byte[] mod3 => ResourceLoader.GetOrCreateResource(ref _mod3, "SymbolsTests.MultiModule.mod3.netmodule"); private static byte[] _MultiModuleDll; public static byte[] MultiModuleDll => ResourceLoader.GetOrCreateResource(ref _MultiModuleDll, "SymbolsTests.MultiModule.MultiModule.dll"); } public static class MultiTargeting { private static byte[] _Source1Module; public static byte[] Source1Module => ResourceLoader.GetOrCreateResource(ref _Source1Module, "SymbolsTests.MultiTargeting.Source1Module.netmodule"); private static byte[] _Source3Module; public static byte[] Source3Module => ResourceLoader.GetOrCreateResource(ref _Source3Module, "SymbolsTests.MultiTargeting.Source3Module.netmodule"); private static byte[] _Source4Module; public static byte[] Source4Module => ResourceLoader.GetOrCreateResource(ref _Source4Module, "SymbolsTests.MultiTargeting.Source4Module.netmodule"); private static byte[] _Source5Module; public static byte[] Source5Module => ResourceLoader.GetOrCreateResource(ref _Source5Module, "SymbolsTests.MultiTargeting.Source5Module.netmodule"); private static byte[] _Source7Module; public static byte[] Source7Module => ResourceLoader.GetOrCreateResource(ref _Source7Module, "SymbolsTests.MultiTargeting.Source7Module.netmodule"); } public static class netModule { private static byte[] _CrossRefLib; public static byte[] CrossRefLib => ResourceLoader.GetOrCreateResource(ref _CrossRefLib, "SymbolsTests.netModule.CrossRefLib.dll"); private static byte[] _CrossRefModule1; public static byte[] CrossRefModule1 => ResourceLoader.GetOrCreateResource(ref _CrossRefModule1, "SymbolsTests.netModule.CrossRefModule1.netmodule"); private static byte[] _CrossRefModule2; public static byte[] CrossRefModule2 => ResourceLoader.GetOrCreateResource(ref _CrossRefModule2, "SymbolsTests.netModule.CrossRefModule2.netmodule"); private static byte[] _hash_module; public static byte[] hash_module => ResourceLoader.GetOrCreateResource(ref _hash_module, "SymbolsTests.netModule.hash_module.netmodule"); private static byte[] _netModule1; public static byte[] netModule1 => ResourceLoader.GetOrCreateResource(ref _netModule1, "SymbolsTests.netModule.netModule1.netmodule"); private static byte[] _netModule2; public static byte[] netModule2 => ResourceLoader.GetOrCreateResource(ref _netModule2, "SymbolsTests.netModule.netModule2.netmodule"); private static byte[] _x64COFF; public static byte[] x64COFF => ResourceLoader.GetOrCreateResource(ref _x64COFF, "SymbolsTests.netModule.x64COFF.obj"); } public static class NoPia { private static byte[] _A; public static byte[] A => ResourceLoader.GetOrCreateResource(ref _A, "SymbolsTests.NoPia.A.dll"); private static byte[] _B; public static byte[] B => ResourceLoader.GetOrCreateResource(ref _B, "SymbolsTests.NoPia.B.dll"); private static byte[] _C; public static byte[] C => ResourceLoader.GetOrCreateResource(ref _C, "SymbolsTests.NoPia.C.dll"); private static byte[] _D; public static byte[] D => ResourceLoader.GetOrCreateResource(ref _D, "SymbolsTests.NoPia.D.dll"); private static byte[] _ExternalAsm1; public static byte[] ExternalAsm1 => ResourceLoader.GetOrCreateResource(ref _ExternalAsm1, "SymbolsTests.NoPia.ExternalAsm1.dll"); private static byte[] _GeneralPia; public static byte[] GeneralPia => ResourceLoader.GetOrCreateResource(ref _GeneralPia, "SymbolsTests.NoPia.GeneralPia.dll"); private static byte[] _GeneralPiaCopy; public static byte[] GeneralPiaCopy => ResourceLoader.GetOrCreateResource(ref _GeneralPiaCopy, "SymbolsTests.NoPia.GeneralPiaCopy.dll"); private static byte[] _Library1; public static byte[] Library1 => ResourceLoader.GetOrCreateResource(ref _Library1, "SymbolsTests.NoPia.Library1.dll"); private static byte[] _Library2; public static byte[] Library2 => ResourceLoader.GetOrCreateResource(ref _Library2, "SymbolsTests.NoPia.Library2.dll"); private static byte[] _LocalTypes1; public static byte[] LocalTypes1 => ResourceLoader.GetOrCreateResource(ref _LocalTypes1, "SymbolsTests.NoPia.LocalTypes1.dll"); private static byte[] _LocalTypes2; public static byte[] LocalTypes2 => ResourceLoader.GetOrCreateResource(ref _LocalTypes2, "SymbolsTests.NoPia.LocalTypes2.dll"); private static byte[] _LocalTypes3; public static byte[] LocalTypes3 => ResourceLoader.GetOrCreateResource(ref _LocalTypes3, "SymbolsTests.NoPia.LocalTypes3.dll"); private static byte[] _MissingPIAAttributes; public static byte[] MissingPIAAttributes => ResourceLoader.GetOrCreateResource(ref _MissingPIAAttributes, "SymbolsTests.NoPia.MissingPIAAttributes.dll"); private static byte[] _NoPIAGenerics1_Asm1; public static byte[] NoPIAGenerics1_Asm1 => ResourceLoader.GetOrCreateResource(ref _NoPIAGenerics1_Asm1, "SymbolsTests.NoPia.NoPIAGenerics1-Asm1.dll"); private static byte[] _Pia1; public static byte[] Pia1 => ResourceLoader.GetOrCreateResource(ref _Pia1, "SymbolsTests.NoPia.Pia1.dll"); private static byte[] _Pia1Copy; public static byte[] Pia1Copy => ResourceLoader.GetOrCreateResource(ref _Pia1Copy, "SymbolsTests.NoPia.Pia1Copy.dll"); private static byte[] _Pia2; public static byte[] Pia2 => ResourceLoader.GetOrCreateResource(ref _Pia2, "SymbolsTests.NoPia.Pia2.dll"); private static byte[] _Pia3; public static byte[] Pia3 => ResourceLoader.GetOrCreateResource(ref _Pia3, "SymbolsTests.NoPia.Pia3.dll"); private static byte[] _Pia4; public static byte[] Pia4 => ResourceLoader.GetOrCreateResource(ref _Pia4, "SymbolsTests.NoPia.Pia4.dll"); private static byte[] _Pia5; public static byte[] Pia5 => ResourceLoader.GetOrCreateResource(ref _Pia5, "SymbolsTests.NoPia.Pia5.dll"); } } namespace TestResources.SymbolsTests.RetargetingCycle { public static class RetV1 { private static byte[] _ClassA; public static byte[] ClassA => ResourceLoader.GetOrCreateResource(ref _ClassA, "SymbolsTests.RetargetingCycle.V1.ClassA.dll"); private static byte[] _ClassB; public static byte[] ClassB => ResourceLoader.GetOrCreateResource(ref _ClassB, "SymbolsTests.RetargetingCycle.V1.ClassB.netmodule"); } public static class RetV2 { private static byte[] _ClassA; public static byte[] ClassA => ResourceLoader.GetOrCreateResource(ref _ClassA, "SymbolsTests.RetargetingCycle.V2.ClassA.dll"); private static byte[] _ClassB; public static byte[] ClassB => ResourceLoader.GetOrCreateResource(ref _ClassB, "SymbolsTests.RetargetingCycle.V2.ClassB.dll"); } } namespace TestResources.SymbolsTests { public static class TypeForwarders { private static byte[] _Forwarded; public static byte[] Forwarded => ResourceLoader.GetOrCreateResource(ref _Forwarded, "SymbolsTests.TypeForwarders.Forwarded.netmodule"); private static byte[] _TypeForwarder; public static byte[] TypeForwarder => ResourceLoader.GetOrCreateResource(ref _TypeForwarder, "SymbolsTests.TypeForwarders.TypeForwarder.dll"); private static byte[] _TypeForwarderBase; public static byte[] TypeForwarderBase => ResourceLoader.GetOrCreateResource(ref _TypeForwarderBase, "SymbolsTests.TypeForwarders.TypeForwarderBase.dll"); private static byte[] _TypeForwarderLib; public static byte[] TypeForwarderLib => ResourceLoader.GetOrCreateResource(ref _TypeForwarderLib, "SymbolsTests.TypeForwarders.TypeForwarderLib.dll"); } public static class V1 { private static byte[] _MTTestLib1; public static byte[] MTTestLib1 => ResourceLoader.GetOrCreateResource(ref _MTTestLib1, "SymbolsTests.V1.MTTestLib1.Dll"); private static string _MTTestLib1_V1; public static string MTTestLib1_V1 => ResourceLoader.GetOrCreateResource(ref _MTTestLib1_V1, "SymbolsTests.V1.MTTestLib1_V1.vb"); private static byte[] _MTTestLib2; public static byte[] MTTestLib2 => ResourceLoader.GetOrCreateResource(ref _MTTestLib2, "SymbolsTests.V1.MTTestLib2.Dll"); private static string _MTTestLib2_V1; public static string MTTestLib2_V1 => ResourceLoader.GetOrCreateResource(ref _MTTestLib2_V1, "SymbolsTests.V1.MTTestLib2_V1.vb"); private static byte[] _MTTestModule1; public static byte[] MTTestModule1 => ResourceLoader.GetOrCreateResource(ref _MTTestModule1, "SymbolsTests.V1.MTTestModule1.netmodule"); private static byte[] _MTTestModule2; public static byte[] MTTestModule2 => ResourceLoader.GetOrCreateResource(ref _MTTestModule2, "SymbolsTests.V1.MTTestModule2.netmodule"); } public static class V2 { private static byte[] _MTTestLib1; public static byte[] MTTestLib1 => ResourceLoader.GetOrCreateResource(ref _MTTestLib1, "SymbolsTests.V2.MTTestLib1.Dll"); private static string _MTTestLib1_V2; public static string MTTestLib1_V2 => ResourceLoader.GetOrCreateResource(ref _MTTestLib1_V2, "SymbolsTests.V2.MTTestLib1_V2.vb"); private static byte[] _MTTestLib3; public static byte[] MTTestLib3 => ResourceLoader.GetOrCreateResource(ref _MTTestLib3, "SymbolsTests.V2.MTTestLib3.Dll"); private static string _MTTestLib3_V2; public static string MTTestLib3_V2 => ResourceLoader.GetOrCreateResource(ref _MTTestLib3_V2, "SymbolsTests.V2.MTTestLib3_V2.vb"); private static byte[] _MTTestModule1; public static byte[] MTTestModule1 => ResourceLoader.GetOrCreateResource(ref _MTTestModule1, "SymbolsTests.V2.MTTestModule1.netmodule"); private static byte[] _MTTestModule3; public static byte[] MTTestModule3 => ResourceLoader.GetOrCreateResource(ref _MTTestModule3, "SymbolsTests.V2.MTTestModule3.netmodule"); } public static class V3 { private static byte[] _MTTestLib1; public static byte[] MTTestLib1 => ResourceLoader.GetOrCreateResource(ref _MTTestLib1, "SymbolsTests.V3.MTTestLib1.Dll"); private static string _MTTestLib1_V3; public static string MTTestLib1_V3 => ResourceLoader.GetOrCreateResource(ref _MTTestLib1_V3, "SymbolsTests.V3.MTTestLib1_V3.vb"); private static byte[] _MTTestLib4; public static byte[] MTTestLib4 => ResourceLoader.GetOrCreateResource(ref _MTTestLib4, "SymbolsTests.V3.MTTestLib4.Dll"); private static string _MTTestLib4_V3; public static string MTTestLib4_V3 => ResourceLoader.GetOrCreateResource(ref _MTTestLib4_V3, "SymbolsTests.V3.MTTestLib4_V3.vb"); private static byte[] _MTTestModule1; public static byte[] MTTestModule1 => ResourceLoader.GetOrCreateResource(ref _MTTestModule1, "SymbolsTests.V3.MTTestModule1.netmodule"); private static byte[] _MTTestModule4; public static byte[] MTTestModule4 => ResourceLoader.GetOrCreateResource(ref _MTTestModule4, "SymbolsTests.V3.MTTestModule4.netmodule"); } public static class WithEvents { private static byte[] _SimpleWithEvents; public static byte[] SimpleWithEvents => ResourceLoader.GetOrCreateResource(ref _SimpleWithEvents, "SymbolsTests.WithEvents.SimpleWithEvents.dll"); } } namespace TestResources { public static class WinRt { private static byte[] _W1; public static byte[] W1 => ResourceLoader.GetOrCreateResource(ref _W1, "WinRt.W1.winmd"); private static byte[] _W2; public static byte[] W2 => ResourceLoader.GetOrCreateResource(ref _W2, "WinRt.W2.winmd"); private static byte[] _WB; public static byte[] WB => ResourceLoader.GetOrCreateResource(ref _WB, "WinRt.WB.winmd"); private static byte[] _WB_Version1; public static byte[] WB_Version1 => ResourceLoader.GetOrCreateResource(ref _WB_Version1, "WinRt.WB_Version1.winmd"); private static byte[] _WImpl; public static byte[] WImpl => ResourceLoader.GetOrCreateResource(ref _WImpl, "WinRt.WImpl.winmd"); private static byte[] _Windows_dump; public static byte[] Windows_dump => ResourceLoader.GetOrCreateResource(ref _Windows_dump, "WinRt.Windows.ildump"); private static byte[] _Windows_Languages_WinRTTest; public static byte[] Windows_Languages_WinRTTest => ResourceLoader.GetOrCreateResource(ref _Windows_Languages_WinRTTest, "WinRt.Windows.Languages.WinRTTest.winmd"); private static byte[] _Windows; public static byte[] Windows => ResourceLoader.GetOrCreateResource(ref _Windows, "WinRt.Windows.winmd"); private static byte[] _WinMDPrefixing_dump; public static byte[] WinMDPrefixing_dump => ResourceLoader.GetOrCreateResource(ref _WinMDPrefixing_dump, "WinRt.WinMDPrefixing.ildump"); private static byte[] _WinMDPrefixing; public static byte[] WinMDPrefixing => ResourceLoader.GetOrCreateResource(ref _WinMDPrefixing, "WinRt.WinMDPrefixing.winmd"); } }
// // FilteringXmlSerializerTests.cs // // Author: // Scott Peterson <lunchtimemama@gmail.com> // // Copyright (c) 2010 Scott Peterson // // 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 NUnit.Framework; using Mono.Upnp.Dcp.MediaServer1.Xml; using Mono.Upnp.Xml; namespace Mono.Upnp.Dcp.MediaServer1.Tests { [TestFixture] public class FilteringXmlSerializerTests { readonly XmlSerializer<FilteringContext> xml_serializer = new XmlSerializer<FilteringContext> ( (serializer, type) => new FilteringDelegateSerializationCompiler (serializer, type)); const string foo = "www.foo.org"; const string bar = "www.bar.org"; const string bat = "www.bat.org"; [XmlType ("data", foo)] [XmlNamespace (bat, "bat")] [XmlNamespace (bar, "bar")] class Data { [XmlElement ("manditoryFooElement", foo)] public string ManditoryFooElement { get; set; } [XmlElement ("manditoryBarElement", bar)] public string ManditoryBarElement { get; set; } [XmlElement ("manditoryBatElement", bat)] public string ManditoryBatElement { get; set; } [XmlAttribute ("manditoryAttribute")] public string ManditoryAttribute { get; set; } [XmlAttribute ("manditoryBarAttribute", bar)] public string ManditoryBarAttribute { get; set; } [XmlAttribute ("manditoryBatAttribute", bat)] public string ManditoryBatAttribute { get; set; } [XmlElement ("optionalFooElement", foo, OmitIfNull = true)] public string OptionalFooElement { get; set; } [XmlElement ("optionalBarElement", bar, OmitIfNull = true)] public string OptionalBarElement { get; set; } [XmlElement ("optionalBatElement", bat, OmitIfNull = true)] public string OptionalBatElement { get; set; } [XmlAttribute ("optionalAttribute", OmitIfNull = true)] public string OptionalAttribute { get; set; } [XmlAttribute ("optionalBarAttribute", bar, OmitIfNull = true)] public string OptionalBarAttribute { get; set; } [XmlAttribute ("optionalBatAttribute", bat, OmitIfNull = true)] public string OptionalBatAttribute { get; set; } } static XmlSerializationOptions<FilteringContext> Options<T> (params string[] filters) { return new XmlSerializationOptions<FilteringContext> { XmlDeclarationType = XmlDeclarationType.None, Context = new FilteringContext (typeof (T), filters) }; } [Test] public void NoFilterWithNoData () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute="""" " + @"bar:manditoryBarAttribute="""" " + @"bat:manditoryBatAttribute="""" xmlns=""www.foo.org"">" + "<manditoryFooElement />" + "<bar:manditoryBarElement />" + "<bat:manditoryBatElement />" + "</data>", xml_serializer.GetString (new Data (), Options<Data> ())); } static Data FullData { get { return new Data { ManditoryFooElement = "Manditory Foo Element", ManditoryBarElement = "Manditory Bar Element", ManditoryBatElement = "Manditory Bat Element", ManditoryAttribute = "Manditory Attribute", ManditoryBarAttribute = "Manditory Bar Attribute", ManditoryBatAttribute = "Manditory Bat Attribute", OptionalFooElement = "Optional Foo Element", OptionalBarElement = "Optional Bar Element", OptionalBatElement = "Optional Bat Element", OptionalAttribute = "Optional Attribute", OptionalBarAttribute = "Optional Bar Attribute", OptionalBatAttribute = "Optional Bat Attribute" }; } } [Test] public void NoFilterWithAllData () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute=""Manditory Attribute"" " + @"bar:manditoryBarAttribute=""Manditory Bar Attribute"" " + @"bat:manditoryBatAttribute=""Manditory Bat Attribute"" xmlns=""www.foo.org"">" + "<manditoryFooElement>Manditory Foo Element</manditoryFooElement>" + "<bar:manditoryBarElement>Manditory Bar Element</bar:manditoryBarElement>" + "<bat:manditoryBatElement>Manditory Bat Element</bat:manditoryBatElement>" + "</data>", xml_serializer.GetString (FullData, Options<Data> ())); } [Test] public void WildCardWithNoData () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute="""" " + @"bar:manditoryBarAttribute="""" " + @"bat:manditoryBatAttribute="""" xmlns=""www.foo.org"">" + "<manditoryFooElement />" + "<bar:manditoryBarElement />" + "<bat:manditoryBatElement />" + "</data>", xml_serializer.GetString (new Data (), Options<Data> ("*"))); } [Test] public void WildCardWithAllData () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute=""Manditory Attribute"" " + @"bar:manditoryBarAttribute=""Manditory Bar Attribute"" " + @"bat:manditoryBatAttribute=""Manditory Bat Attribute"" " + @"optionalAttribute=""Optional Attribute"" " + @"bar:optionalBarAttribute=""Optional Bar Attribute"" " + @"bat:optionalBatAttribute=""Optional Bat Attribute"" xmlns=""www.foo.org"">" + "<manditoryFooElement>Manditory Foo Element</manditoryFooElement>" + "<bar:manditoryBarElement>Manditory Bar Element</bar:manditoryBarElement>" + "<bat:manditoryBatElement>Manditory Bat Element</bat:manditoryBatElement>" + "<optionalFooElement>Optional Foo Element</optionalFooElement>" + "<bar:optionalBarElement>Optional Bar Element</bar:optionalBarElement>" + "<bat:optionalBatElement>Optional Bat Element</bat:optionalBatElement>" + "</data>", xml_serializer.GetString (FullData, Options<Data> ("*"))); } [Test] public void UnprefixedFilterWithAllData () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute=""Manditory Attribute"" " + @"bar:manditoryBarAttribute=""Manditory Bar Attribute"" " + @"bat:manditoryBatAttribute=""Manditory Bat Attribute"" xmlns=""www.foo.org"">" + "<manditoryFooElement>Manditory Foo Element</manditoryFooElement>" + "<bar:manditoryBarElement>Manditory Bar Element</bar:manditoryBarElement>" + "<bat:manditoryBatElement>Manditory Bat Element</bat:manditoryBatElement>" + "<optionalFooElement>Optional Foo Element</optionalFooElement>" + "</data>", xml_serializer.GetString (FullData, Options<Data> ("optionalFooElement"))); } [Test] public void PrefixedFilterWithAllData () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute=""Manditory Attribute"" " + @"bar:manditoryBarAttribute=""Manditory Bar Attribute"" " + @"bat:manditoryBatAttribute=""Manditory Bat Attribute"" xmlns=""www.foo.org"">" + "<manditoryFooElement>Manditory Foo Element</manditoryFooElement>" + "<bar:manditoryBarElement>Manditory Bar Element</bar:manditoryBarElement>" + "<bat:manditoryBatElement>Manditory Bat Element</bat:manditoryBatElement>" + "<bar:optionalBarElement>Optional Bar Element</bar:optionalBarElement>" + "</data>", xml_serializer.GetString (FullData, Options<Data> ("bar:optionalBarElement"))); } [Test] public void TwoPrefixedFiltersWithAllData () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute=""Manditory Attribute"" " + @"bar:manditoryBarAttribute=""Manditory Bar Attribute"" " + @"bat:manditoryBatAttribute=""Manditory Bat Attribute"" xmlns=""www.foo.org"">" + "<manditoryFooElement>Manditory Foo Element</manditoryFooElement>" + "<bar:manditoryBarElement>Manditory Bar Element</bar:manditoryBarElement>" + "<bat:manditoryBatElement>Manditory Bat Element</bat:manditoryBatElement>" + "<bar:optionalBarElement>Optional Bar Element</bar:optionalBarElement>" + "<bat:optionalBatElement>Optional Bat Element</bat:optionalBatElement>" + "</data>", xml_serializer.GetString (FullData, Options<Data> ("bar:optionalBarElement", "bat:optionalBatElement"))); } [Test] public void UnprefixedAndPrefixedFiltersWithAllData () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute=""Manditory Attribute"" " + @"bar:manditoryBarAttribute=""Manditory Bar Attribute"" " + @"bat:manditoryBatAttribute=""Manditory Bat Attribute"" xmlns=""www.foo.org"">" + "<manditoryFooElement>Manditory Foo Element</manditoryFooElement>" + "<bar:manditoryBarElement>Manditory Bar Element</bar:manditoryBarElement>" + "<bat:manditoryBatElement>Manditory Bat Element</bat:manditoryBatElement>" + "<optionalFooElement>Optional Foo Element</optionalFooElement>" + "<bar:optionalBarElement>Optional Bar Element</bar:optionalBarElement>" + "</data>", xml_serializer.GetString (FullData, Options<Data> ("optionalFooElement", "bar:optionalBarElement"))); } [Test] public void FilterAndWildCardWithAllData () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute=""Manditory Attribute"" " + @"bar:manditoryBarAttribute=""Manditory Bar Attribute"" " + @"bat:manditoryBatAttribute=""Manditory Bat Attribute"" " + @"optionalAttribute=""Optional Attribute"" " + @"bar:optionalBarAttribute=""Optional Bar Attribute"" " + @"bat:optionalBatAttribute=""Optional Bat Attribute"" xmlns=""www.foo.org"">" + "<manditoryFooElement>Manditory Foo Element</manditoryFooElement>" + "<bar:manditoryBarElement>Manditory Bar Element</bar:manditoryBarElement>" + "<bat:manditoryBatElement>Manditory Bat Element</bat:manditoryBatElement>" + "<optionalFooElement>Optional Foo Element</optionalFooElement>" + "<bar:optionalBarElement>Optional Bar Element</bar:optionalBarElement>" + "<bat:optionalBatElement>Optional Bat Element</bat:optionalBatElement>" + "</data>", xml_serializer.GetString (FullData, Options<Data> ("optionalFooElement", "*"))); } [Test] public void IncludeOptionalAttribute () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute=""Manditory Attribute"" " + @"bar:manditoryBarAttribute=""Manditory Bar Attribute"" " + @"bat:manditoryBatAttribute=""Manditory Bat Attribute"" " + @"optionalAttribute=""Optional Attribute"" xmlns=""www.foo.org"">" + "<manditoryFooElement>Manditory Foo Element</manditoryFooElement>" + "<bar:manditoryBarElement>Manditory Bar Element</bar:manditoryBarElement>" + "<bat:manditoryBatElement>Manditory Bat Element</bat:manditoryBatElement>" + "</data>", xml_serializer.GetString (FullData, Options<Data> ("@optionalAttribute"))); } [Test] public void IncludeOptionalNamespacedAttribute () { Assert.AreEqual ( @"<data xmlns:bar=""www.bar.org"" xmlns:bat=""www.bat.org"" " + @"manditoryAttribute=""Manditory Attribute"" " + @"bar:manditoryBarAttribute=""Manditory Bar Attribute"" " + @"bat:manditoryBatAttribute=""Manditory Bat Attribute"" " + @"bar:optionalBarAttribute=""Optional Bar Attribute"" xmlns=""www.foo.org"">" + "<manditoryFooElement>Manditory Foo Element</manditoryFooElement>" + "<bar:manditoryBarElement>Manditory Bar Element</bar:manditoryBarElement>" + "<bat:manditoryBatElement>Manditory Bat Element</bat:manditoryBatElement>" + "</data>", xml_serializer.GetString (FullData, Options<Data> ("@bar:optionalBarAttribute"))); } [XmlType ("nestedData", foo)] [XmlNamespace (bar, "bar")] class NestedData { [XmlAttribute ("attribute", OmitIfNull = true)] public string Attribute { get; set; } [XmlAttribute ("barAttribute", bar, OmitIfNull = true)] public string BarAttribute { get; set; } [XmlElement ("nested", OmitIfNull = true)] public NestedData Nested { get; set; } [XmlElement ("barNested", bar, OmitIfNull = true)] public NestedData BarNested { get; set; } } static NestedData FullNestedData { get { return new NestedData { Attribute = "Attribute", BarAttribute = "Bar Attribute", Nested = new NestedData { Attribute = "Nested Attribute", BarAttribute = "Nested Bar Attribute" }, BarNested = new NestedData { Attribute = "Bar Nested Attribute", BarAttribute = "Bar Nested Bar Attribute" } }; } } [Test] public void NestedDataWithAnAttribute () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" " + @"attribute=""Attribute"" xmlns=""www.foo.org"" />", xml_serializer.GetString (FullNestedData, Options<NestedData> ("@attribute"))); } [Test] public void NestedDataWithAttributeAndNamespacedAttribute () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" " + @"attribute=""Attribute"" " + @"bar:barAttribute=""Bar Attribute"" xmlns=""www.foo.org"" />", xml_serializer.GetString (FullNestedData, Options<NestedData> ("@attribute", "@bar:barAttribute"))); } [Test] public void NestedDataWithNoAttributes () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" xmlns=""www.foo.org""><nested /></nestedData>", xml_serializer.GetString (FullNestedData, Options<NestedData> ("nested"))); } [Test] public void NamespacedNestedDataWithNoAttributes () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" xmlns=""www.foo.org""><bar:barNested /></nestedData>", xml_serializer.GetString (FullNestedData, Options<NestedData> ("bar:barNested"))); } [Test] public void NestedDataWithAttribute () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" xmlns=""www.foo.org"">" + @"<nested attribute=""Nested Attribute"" />"+ "</nestedData>", xml_serializer.GetString (FullNestedData, Options<NestedData> ("nested", "nested@attribute"))); } [Test] public void NestedDataWithNamespacedAttribute () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" xmlns=""www.foo.org"">" + @"<nested bar:barAttribute=""Nested Bar Attribute"" />"+ "</nestedData>", xml_serializer.GetString (FullNestedData, Options<NestedData> ("nested", "nested@bar:barAttribute"))); } [Test] public void NamespacedNestedDataWithAttribute () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" xmlns=""www.foo.org"">" + @"<bar:barNested attribute=""Bar Nested Attribute"" />"+ "</nestedData>", xml_serializer.GetString (FullNestedData, Options<NestedData> ("bar:barNested", "bar:barNested@attribute"))); } [Test] public void NamespacedNestedDataWithNamespacedAttribute () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" xmlns=""www.foo.org"">" + @"<bar:barNested bar:barAttribute=""Bar Nested Bar Attribute"" />"+ "</nestedData>", xml_serializer.GetString (FullNestedData, Options<NestedData> ("bar:barNested", "bar:barNested@bar:barAttribute"))); } [Test] public void NestedAttributeButNoNestedData () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" xmlns=""www.foo.org"" />", xml_serializer.GetString (FullNestedData, Options<NestedData> ("nested@attribute"))); } [Test] public void EmptyNestedDataAndAnAttribute () { Assert.AreEqual ( @"<nestedData xmlns:bar=""www.bar.org"" " + @"attribute=""Attribute"" xmlns=""www.foo.org"">" + "<nested />" + "</nestedData>", xml_serializer.GetString (FullNestedData, Options<NestedData> ("@attribute", "nested"))); } [XmlType ("container", foo)] [XmlNamespace (bar, "bar")] class Container<T> { [XmlElement ("content")] public T Content { get; set; } } [Test] public void ContainedNestedData () { Assert.AreEqual ( @"<container xmlns:bar=""www.bar.org"" xmlns=""www.foo.org"">" + @"<content attribute=""Attribute"">" + "<nested />" + "</content>" + "</container>", xml_serializer.GetString ( new Container<NestedData> { Content = FullNestedData }, Options<NestedData> ("@attribute", "nested"))); } [Test] public void ContainedWildCardNestedData () { Assert.AreEqual ( @"<container xmlns:bar=""www.bar.org"" xmlns=""www.foo.org"">" + @"<content attribute=""Attribute"" bar:barAttribute=""Bar Attribute"">" + @"<nested attribute=""Nested Attribute"" bar:barAttribute=""Nested Bar Attribute"" />" + @"<bar:barNested attribute=""Bar Nested Attribute"" bar:barAttribute=""Bar Nested Bar Attribute"" />" + "</content>" + "</container>", xml_serializer.GetString ( new Container<NestedData> { Content = FullNestedData }, Options<NestedData> ("*"))); } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using OpenTK.Audio.OpenAL; namespace OpenTK.Audio { /// <summary> /// Provides methods to instantiate, use and destroy an audio device for recording. /// Static methods are provided to list available devices known by the driver. /// </summary> public sealed class AudioCapture : IDisposable { #region Fields // This must stay private info so the end-user cannot call any Alc commands for the recording device. IntPtr Handle; // Alc.CaptureStop should be called prior to device shutdown, this keeps track of Alc.CaptureStart/Stop calls. bool _isrecording = false; ALFormat sample_format; int sample_frequency; #endregion #region Constructors static AudioCapture() { if (AudioDeviceEnumerator.IsOpenALSupported) // forces enumeration { } } /// <summary> /// Opens the default device for audio recording. /// Implicitly set parameters are: 22050Hz, 16Bit Mono, 4096 samples ringbuffer. /// </summary> public AudioCapture() : this(AudioCapture.DefaultDevice, 22050, ALFormat.Mono16, 4096) { } /// <summary>Opens a device for audio recording.</summary> /// <param name="deviceName">The device name.</param> /// <param name="frequency">The frequency that the data should be captured at.</param> /// <param name="sampleFormat">The requested capture buffer format.</param> /// <param name="bufferSize">The size of OpenAL's capture internal ring-buffer. This value expects number of samples, not bytes.</param> public AudioCapture(string deviceName, int frequency, ALFormat sampleFormat, int bufferSize) { if (!AudioDeviceEnumerator.IsOpenALSupported) throw new DllNotFoundException("openal32.dll"); if (frequency <= 0) throw new ArgumentOutOfRangeException("frequency"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); // Try to open specified device. If it fails, try to open default device. device_name = deviceName; Handle = Alc.CaptureOpenDevice(deviceName, frequency, sampleFormat, bufferSize); if (Handle == IntPtr.Zero) { Debug.WriteLine(ErrorMessage(deviceName, frequency, sampleFormat, bufferSize)); device_name = "IntPtr.Zero"; Handle = Alc.CaptureOpenDevice(null, frequency, sampleFormat, bufferSize); } if (Handle == IntPtr.Zero) { Debug.WriteLine(ErrorMessage("IntPtr.Zero", frequency, sampleFormat, bufferSize)); device_name = AudioDeviceEnumerator.DefaultRecordingDevice; Handle = Alc.CaptureOpenDevice(AudioDeviceEnumerator.DefaultRecordingDevice, frequency, sampleFormat, bufferSize); } if (Handle == IntPtr.Zero) { // Everything we tried failed. Capture may not be supported, bail out. Debug.WriteLine(ErrorMessage(AudioDeviceEnumerator.DefaultRecordingDevice, frequency, sampleFormat, bufferSize)); device_name = "None"; throw new AudioDeviceException("All attempts to open capture devices returned IntPtr.Zero. See debug log for verbose list."); } // handle is not null, check for some Alc Error CheckErrors(); SampleFormat = sampleFormat; SampleFrequency = frequency; } #endregion Constructor #region Public Members #region CurrentDevice private string device_name; /// <summary> /// The name of the device associated with this instance. /// </summary> public string CurrentDevice { get { return device_name; } } #endregion #region AvailableDevices /// <summary> /// Returns a list of strings containing all known recording devices. /// </summary> public static IList<string> AvailableDevices { get { return AudioDeviceEnumerator.AvailableRecordingDevices; } } #endregion #region DefaultDevice /// <summary> /// Returns the name of the device that will be used as recording default. /// </summary> public static string DefaultDevice { get { return AudioDeviceEnumerator.DefaultRecordingDevice; } } #endregion #region CheckErrors /// <summary> /// Checks for ALC error conditions. /// </summary> /// <exception cref="OutOfMemoryException">Raised when an out of memory error is detected.</exception> /// <exception cref="AudioValueException">Raised when an invalid value is detected.</exception> /// <exception cref="AudioDeviceException">Raised when an invalid device is detected.</exception> /// <exception cref="AudioContextException">Raised when an invalid context is detected.</exception> public void CheckErrors() { new AudioDeviceErrorChecker(Handle).Dispose(); } #endregion #region CurrentError /// <summary>Returns the ALC error code for this device.</summary> public AlcError CurrentError { get { return Alc.GetError(Handle); } } #endregion #region Start & Stop /// <summary> /// Start recording samples. /// The number of available samples can be obtained through the <see cref="AvailableSamples"/> property. /// The data can be queried with any <see cref="ReadSamples(IntPtr, int)"/> method. /// </summary> public void Start() { Alc.CaptureStart(Handle); _isrecording = true; } /// <summary>Stop recording samples. This will not clear previously recorded samples.</summary> public void Stop() { Alc.CaptureStop(Handle); _isrecording = false; } #endregion Start & Stop Capture #region AvailableSamples /// <summary>Returns the number of available samples for capture.</summary> public int AvailableSamples { get { // TODO: Investigate inconsistency between documentation and actual usage. // Doc claims the 3rd param is Number-of-Bytes, but it appears to be Number-of-Int32s int result; Alc.GetInteger(Handle, AlcGetInteger.CaptureSamples, 1, out result); return result; } } #endregion Available samples property #region ReadSamples /// <summary>Fills the specified buffer with samples from the internal capture ring-buffer. This method does not block: it is an error to specify a sampleCount larger than AvailableSamples.</summary> /// <param name="buffer">A pointer to a previously initialized and pinned array.</param> /// <param name="sampleCount">The number of samples to be written to the buffer.</param> public void ReadSamples(IntPtr buffer, int sampleCount) { Alc.CaptureSamples(Handle, buffer, sampleCount); } /// <summary>Fills the specified buffer with samples from the internal capture ring-buffer. This method does not block: it is an error to specify a sampleCount larger than AvailableSamples.</summary> /// <param name="buffer">The buffer to fill.</param> /// <param name="sampleCount">The number of samples to be written to the buffer.</param> /// <exception cref="System.ArgumentNullException">Raised when buffer is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Raised when sampleCount is larger than the buffer.</exception> public void ReadSamples<TBuffer>(TBuffer[] buffer, int sampleCount) where TBuffer : struct { if (buffer == null) throw new ArgumentNullException("buffer"); int buffer_size = BlittableValueType<TBuffer>.Stride * buffer.Length; // This is more of a heuristic than a 100% valid check. However, it will work // correctly for 99.9% of all use cases. // This should never produce a false positive, but a false negative might // be produced with compressed sample formats (which are very rare). // Still, this is better than no check at all. if (sampleCount * GetSampleSize(SampleFormat) > buffer_size) throw new ArgumentOutOfRangeException("sampleCount"); GCHandle buffer_ptr = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { ReadSamples(buffer_ptr.AddrOfPinnedObject(), sampleCount); } finally { buffer_ptr.Free(); } } #endregion #region SampleFormat & SampleFrequency /// <summary> /// Gets the OpenTK.Audio.ALFormat for this instance. /// </summary> public ALFormat SampleFormat { get { return sample_format; } private set { sample_format = value; } } /// <summary> /// Gets the sampling rate for this instance. /// </summary> public int SampleFrequency { get { return sample_frequency; } private set { sample_frequency = value; } } #endregion #region IsRunning /// <summary> /// Gets a value indicating whether this instance is currently capturing samples. /// </summary> public bool IsRunning { get { return _isrecording; } } #endregion #endregion #region Private Members // Retrieves the sample size in bytes for various ALFormats. // Compressed formats always return 1. static int GetSampleSize(ALFormat format) { switch (format) { case ALFormat.Mono8: return 1; case ALFormat.Mono16: return 2; case ALFormat.Stereo8: return 2; case ALFormat.Stereo16: return 4; case ALFormat.MonoFloat32Ext: return 4; case ALFormat.MonoDoubleExt: return 8; case ALFormat.StereoFloat32Ext: return 8; case ALFormat.StereoDoubleExt: return 16; case ALFormat.MultiQuad8Ext: return 4; case ALFormat.MultiQuad16Ext: return 8; case ALFormat.MultiQuad32Ext: return 16; case ALFormat.Multi51Chn8Ext: return 6; case ALFormat.Multi51Chn16Ext: return 12; case ALFormat.Multi51Chn32Ext: return 24; case ALFormat.Multi61Chn8Ext: return 7; case ALFormat.Multi71Chn16Ext: return 14; case ALFormat.Multi71Chn32Ext: return 28; case ALFormat.MultiRear8Ext: return 1; case ALFormat.MultiRear16Ext: return 2; case ALFormat.MultiRear32Ext: return 4; default: return 1; // Unknown sample size. } } // Converts an error code to an error string with additional information. string ErrorMessage(string devicename, int frequency, ALFormat bufferformat, int buffersize) { string alcerrmsg; AlcError alcerrcode = CurrentError; switch (alcerrcode) { case AlcError.OutOfMemory: alcerrmsg = alcerrcode.ToString() + ": The specified device is invalid, or can not capture audio."; break; case AlcError.InvalidValue: alcerrmsg = alcerrcode.ToString() + ": One of the parameters has an invalid value."; break; default: alcerrmsg = alcerrcode.ToString(); break; } return "The handle returned by Alc.CaptureOpenDevice is null." + "\nAlc Error: " + alcerrmsg + "\nDevice Name: " + devicename + "\nCapture frequency: " + frequency + "\nBuffer format: " + bufferformat + "\nBuffer Size: " + buffersize; } #endregion #region IDisposable Members /// <summary> /// Finalizes this instance. /// </summary> ~AudioCapture() { Dispose(); } private bool IsDisposed; /// <summary>Closes the device and disposes the instance.</summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool manual) { if (!this.IsDisposed) { if (this.Handle != IntPtr.Zero) { if (this._isrecording) this.Stop(); Alc.CaptureCloseDevice(this.Handle); } this.IsDisposed = true; } } #endregion Destructor } }
using System; using System.Collections.Generic; using Newtonsoft.Json; /* * AvaTax API Client Library * * (c) 2004-2018 Avalara, Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Ted Spence * @author Zhenya Frolov * @author Greg Hester */ namespace Avalara.AvaTax.RestClient { /// <summary> /// An individual tax detail element. Represents the amount of tax calculated for a particular jurisdiction, for a particular line in an invoice. /// </summary> public class TransactionLineDetailModel { /// <summary> /// The unique ID number of this tax detail. /// </summary> public Int64? id { get; set; } /// <summary> /// The unique ID number of the line within this transaction. /// </summary> public Int64? transactionLineId { get; set; } /// <summary> /// The unique ID number of this transaction. /// </summary> public Int64? transactionId { get; set; } /// <summary> /// The unique ID number of the address used for this tax detail. /// </summary> public Int64? addressId { get; set; } /// <summary> /// The two character ISO 3166 country code of the country where this tax detail is assigned. /// </summary> public String country { get; set; } /// <summary> /// The two-or-three character ISO region code for the region where this tax detail is assigned. /// </summary> public String region { get; set; } /// <summary> /// For U.S. transactions, the Federal Information Processing Standard (FIPS) code for the county where this tax detail is assigned. /// </summary> public String countyFIPS { get; set; } /// <summary> /// For U.S. transactions, the Federal Information Processing Standard (FIPS) code for the state where this tax detail is assigned. /// </summary> public String stateFIPS { get; set; } /// <summary> /// The amount of this line that was considered exempt in this tax detail. /// </summary> public Decimal? exemptAmount { get; set; } /// <summary> /// The unique ID number of the exemption reason for this tax detail. /// </summary> public Int32? exemptReasonId { get; set; } /// <summary> /// True if this detail element represented an in-state transaction. /// </summary> public Boolean? inState { get; set; } /// <summary> /// The code of the jurisdiction to which this tax detail applies. /// </summary> public String jurisCode { get; set; } /// <summary> /// The name of the jurisdiction to which this tax detail applies. /// </summary> public String jurisName { get; set; } /// <summary> /// The unique ID number of the jurisdiction to which this tax detail applies. /// </summary> public Int32? jurisdictionId { get; set; } /// <summary> /// The Avalara-specified signature code of the jurisdiction to which this tax detail applies. /// </summary> public String signatureCode { get; set; } /// <summary> /// The state assigned number of the jurisdiction to which this tax detail applies. /// </summary> public String stateAssignedNo { get; set; } /// <summary> /// (DEPRECATED) The type of the jurisdiction to which this tax detail applies. /// NOTE: Use jurisdictionTypeId instead. /// </summary> public JurisTypeId? jurisType { get; set; } /// <summary> /// The type of the jurisdiction in which this tax detail applies. /// </summary> public JurisdictionType? jurisdictionType { get; set; } /// <summary> /// The amount of this line item that was considered nontaxable in this tax detail. /// </summary> public Decimal? nonTaxableAmount { get; set; } /// <summary> /// The rule according to which portion of this detail was considered nontaxable. /// </summary> public Int32? nonTaxableRuleId { get; set; } /// <summary> /// The type of nontaxability that was applied to this tax detail. /// </summary> public TaxRuleTypeId? nonTaxableType { get; set; } /// <summary> /// The rate at which this tax detail was calculated. /// </summary> public Decimal? rate { get; set; } /// <summary> /// The unique ID number of the rule according to which this tax detail was calculated. /// </summary> public Int32? rateRuleId { get; set; } /// <summary> /// The unique ID number of the source of the rate according to which this tax detail was calculated. /// </summary> public Int32? rateSourceId { get; set; } /// <summary> /// For Streamlined Sales Tax customers, the SST Electronic Return code under which this tax detail should be applied. /// </summary> public String serCode { get; set; } /// <summary> /// Indicates whether this tax detail applies to the origin or destination of the transaction. /// </summary> public Sourcing? sourcing { get; set; } /// <summary> /// The amount of tax for this tax detail. /// </summary> public Decimal? tax { get; set; } /// <summary> /// The taxable amount of this tax detail. /// </summary> public Decimal? taxableAmount { get; set; } /// <summary> /// The type of tax that was calculated. Depends on the company's nexus settings as well as the jurisdiction's tax laws. /// </summary> public TaxType? taxType { get; set; } /// <summary> /// The id of the tax subtype. /// </summary> public String taxSubTypeId { get; set; } /// <summary> /// The id of the tax type group. /// </summary> public String taxTypeGroupId { get; set; } /// <summary> /// The name of the tax against which this tax amount was calculated. /// </summary> public String taxName { get; set; } /// <summary> /// The type of the tax authority to which this tax will be remitted. /// </summary> public Int32? taxAuthorityTypeId { get; set; } /// <summary> /// The unique ID number of the tax region. /// </summary> public Int32? taxRegionId { get; set; } /// <summary> /// The amount of tax that was calculated. This amount may be different if a tax override was used. /// If the customer specified a tax override, this calculated tax value represents the amount of tax that would /// have been charged if Avalara had calculated the tax for the rule. /// </summary> public Decimal? taxCalculated { get; set; } /// <summary> /// The amount of tax override that was specified for this tax line. /// </summary> public Decimal? taxOverride { get; set; } /// <summary> /// (DEPRECATED) The rate type for this tax detail. Please use rateTypeCode instead. /// </summary> public RateType? rateType { get; set; } /// <summary> /// Indicates the code of the rate type that was used to calculate this tax detail. Use [ListRateTypesByCountry](https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Definitions/ListRateTypesByCountry/) API for a full list of rate type codes. /// </summary> public String rateTypeCode { get; set; } /// <summary> /// Number of units in this line item that were calculated to be taxable according to this rate detail. /// </summary> public Decimal? taxableUnits { get; set; } /// <summary> /// Number of units in this line item that were calculated to be nontaxable according to this rate detail. /// </summary> public Decimal? nonTaxableUnits { get; set; } /// <summary> /// Number of units in this line item that were calculated to be exempt according to this rate detail. /// </summary> public Decimal? exemptUnits { get; set; } /// <summary> /// When calculating units, what basis of measurement did we use for calculating the units? /// </summary> public String unitOfBasis { get; set; } /// <summary> /// True if this value is a non-passthrough tax. /// /// A non-passthrough tax is a tax that may not be charged to a customer; it must be paid directly by the company. /// </summary> public Boolean? isNonPassThru { get; set; } /// <summary> /// Convert this object to a JSON string of itself /// </summary> /// <returns>A JSON string of this object</returns> public override string ToString() { return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; namespace System.Data.SqlClient { public sealed class SqlBulkCopyColumnMappingCollection : ICollection, IEnumerable, IList { private enum MappingSchema { Undefined = 0, NamesNames = 1, NemesOrdinals = 2, OrdinalsNames = 3, OrdinalsOrdinals = 4, } private readonly List<object> _list = new List<object>(); private MappingSchema _mappingSchema = MappingSchema.Undefined; internal SqlBulkCopyColumnMappingCollection() { } public int Count => _list.Count; internal bool ReadOnly { get; set; } bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => NonGenericList.SyncRoot; bool IList.IsFixedSize => false; // This always returns false in the full framework, regardless // of the value of the internal ReadOnly property. bool IList.IsReadOnly => false; object IList.this[int index] { get { return NonGenericList[index]; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } NonGenericList[index] = value; } } public SqlBulkCopyColumnMapping this[int index] => (SqlBulkCopyColumnMapping)_list[index]; public SqlBulkCopyColumnMapping Add(SqlBulkCopyColumnMapping bulkCopyColumnMapping) { AssertWriteAccess(); Debug.Assert(string.IsNullOrEmpty(bulkCopyColumnMapping.SourceColumn) || bulkCopyColumnMapping._internalSourceColumnOrdinal == -1, "BulkLoadAmbiguousSourceColumn"); if (((string.IsNullOrEmpty(bulkCopyColumnMapping.SourceColumn)) && (bulkCopyColumnMapping.SourceOrdinal == -1)) || ((string.IsNullOrEmpty(bulkCopyColumnMapping.DestinationColumn)) && (bulkCopyColumnMapping.DestinationOrdinal == -1))) { throw SQL.BulkLoadNonMatchingColumnMapping(); } _list.Add(bulkCopyColumnMapping); return bulkCopyColumnMapping; } public SqlBulkCopyColumnMapping Add(string sourceColumn, string destinationColumn) { AssertWriteAccess(); return Add(new SqlBulkCopyColumnMapping(sourceColumn, destinationColumn)); } public SqlBulkCopyColumnMapping Add(int sourceColumnIndex, string destinationColumn) { AssertWriteAccess(); return Add(new SqlBulkCopyColumnMapping(sourceColumnIndex, destinationColumn)); } public SqlBulkCopyColumnMapping Add(string sourceColumn, int destinationColumnIndex) { AssertWriteAccess(); return Add(new SqlBulkCopyColumnMapping(sourceColumn, destinationColumnIndex)); } public SqlBulkCopyColumnMapping Add(int sourceColumnIndex, int destinationColumnIndex) { AssertWriteAccess(); return Add(new SqlBulkCopyColumnMapping(sourceColumnIndex, destinationColumnIndex)); } private void AssertWriteAccess() { if (ReadOnly) { throw SQL.BulkLoadMappingInaccessible(); } } public void Clear() { AssertWriteAccess(); _list.Clear(); } public bool Contains(SqlBulkCopyColumnMapping value) => _list.Contains(value); public void CopyTo(SqlBulkCopyColumnMapping[] array, int index) => _list.CopyTo(array, index); internal void CreateDefaultMapping(int columnCount) { for (int i = 0; i < columnCount; i++) { _list.Add(new SqlBulkCopyColumnMapping(i, i)); } } public IEnumerator GetEnumerator() => _list.GetEnumerator(); public int IndexOf(SqlBulkCopyColumnMapping value) => _list.IndexOf(value); public void Insert(int index, SqlBulkCopyColumnMapping value) { AssertWriteAccess(); _list.Insert(index, value); } public void Remove(SqlBulkCopyColumnMapping value) { AssertWriteAccess(); _list.Remove(value); } public void RemoveAt(int index) { AssertWriteAccess(); _list.RemoveAt(index); } internal void ValidateCollection() { MappingSchema mappingSchema; foreach (SqlBulkCopyColumnMapping a in _list) { mappingSchema = a.SourceOrdinal != -1 ? (a.DestinationOrdinal != -1 ? MappingSchema.OrdinalsOrdinals : MappingSchema.OrdinalsNames) : (a.DestinationOrdinal != -1 ? MappingSchema.NemesOrdinals : MappingSchema.NamesNames); if (_mappingSchema == MappingSchema.Undefined) { _mappingSchema = mappingSchema; } else { if (_mappingSchema != mappingSchema) { throw SQL.BulkLoadMappingsNamesOrOrdinalsOnly(); } } } } void ICollection.CopyTo(Array array, int index) => NonGenericList.CopyTo(array, index); int IList.Add(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return NonGenericList.Add(value); } bool IList.Contains(object value) => NonGenericList.Contains(value); int IList.IndexOf(object value) => NonGenericList.IndexOf(value); void IList.Insert(int index, object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } NonGenericList.Insert(index, value); } void IList.Remove(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } bool removed = _list.Remove(value); // This throws on full framework, so it will also throw here. if (!removed) { throw new ArgumentException(SR.Arg_RemoveArgNotFound); } } private IList NonGenericList => _list; } }
// 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.Text; using System; using System.Diagnostics.Contracts; namespace System.Text { // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // internal class EncoderNLS : Encoder { // Need a place for the last left over character, most of our encodings use this internal char charLeftOver; protected Encoding m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_charsUsed; internal EncoderNLS(Encoding encoding) { this.m_encoding = encoding; this.m_fallback = this.m_encoding.EncoderFallback; this.Reset(); } // This one is used when deserializing (like UTF7Encoding.Encoder) internal EncoderNLS() { this.m_encoding = null; this.Reset(); } public override void Reset() { this.charLeftOver = (char)0; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid empty input problem if (chars.Length == 0) chars = new char[1]; // Just call the pointer version int result = -1; fixed (char* pChars = chars) { result = GetByteCount(pChars + index, count, flush); } return result; } public unsafe override int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); this.m_mustFlush = flush; this.m_throwOnOverflow = true; return m_encoding.GetByteCount(chars, count, this); } public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); if (chars.Length == 0) chars = new char[1]; int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) bytes = new byte[1]; // Just call pointer version fixed (char* pChars = chars) fixed (byte* pBytes = bytes) // Remember that charCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush); } internal unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); this.m_mustFlush = flush; this.m_throwOnOverflow = true; return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); } // This method is used when your output buffer might not be large enough for the entire result. // Just call the pointer version. (This gets bytes) public override unsafe void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid empty input problem if (chars.Length == 0) chars = new char[1]; if (bytes.Length == 0) bytes = new byte[1]; // Just call the pointer version (can't do this for non-msft encoders) fixed (char* pChars = chars) { fixed (byte* pBytes = bytes) { Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } // This is the version that uses pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting bytes private unsafe void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // We don't want to throw this.m_mustFlush = flush; this.m_throwOnOverflow = false; this.m_charsUsed = 0; // Do conversion bytesUsed = this.m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = this.m_charsUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (charsUsed == charCount) && (!flush || !this.HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); // Our data thingys are now full, we can return } public Encoding Encoding { get { return m_encoding; } } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our encoder? internal virtual bool HasState { get { return (this.charLeftOver != (char)0); } } // Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow) internal void ClearMustFlush() { m_mustFlush = false; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Globalization; using System.IO; using System.Management.Automation.Internal; using System.Management.Automation; using System.Diagnostics.CodeAnalysis; namespace Microsoft.PowerShell.Commands { /// <summary> /// The implementation of the "import-localizeddata" cmdlet. /// </summary> [Cmdlet(VerbsData.Import, "LocalizedData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113342")] public sealed class ImportLocalizedData : PSCmdlet { #region Parameters /// <summary> /// The path from which to import the aliases. /// </summary> [Parameter(Position = 0)] [Alias("Variable")] [ValidateNotNullOrEmpty] public string BindingVariable { get { return _bindingVariable; } set { _bindingVariable = value; } } private string _bindingVariable; /// <summary> /// The scope to import the aliases to. /// </summary> [Parameter(Position = 1)] public string UICulture { get { return _uiculture; } set { _uiculture = value; } } private string _uiculture; /// <summary> /// The scope to import the aliases to. /// </summary> [Parameter] public string BaseDirectory { get { return _baseDirectory; } set { _baseDirectory = value; } } private string _baseDirectory; /// <summary> /// The scope to import the aliases to. /// </summary> [Parameter] public string FileName { get { return _fileName; } set { _fileName = value; } } private string _fileName; /// <summary> /// The command allowed in the data file. If unspecified, then ConvertFrom-StringData is allowed. /// </summary> [Parameter] [ValidateTrustedData] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] public string[] SupportedCommand { get { return _commandsAllowed; } set { _setSupportedCommand = true; _commandsAllowed = value; } } private string[] _commandsAllowed = new string[] { "ConvertFrom-StringData" }; private bool _setSupportedCommand = false; #endregion Parameters #region Command code /// <summary> /// The main processing loop of the command. /// </summary> protected override void ProcessRecord() { string path = GetFilePath(); if (path == null) { return; } if (!File.Exists(path)) { InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.FileNotExist, path); WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound, path)); return; } // Prevent additional commands in ConstrainedLanguage mode if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { if (_setSupportedCommand) { NotSupportedException nse = PSTraceSource.NewNotSupportedException( ImportLocalizedDataStrings.CannotDefineSupportedCommand); ThrowTerminatingError( new ErrorRecord(nse, "CannotDefineSupportedCommand", ErrorCategory.PermissionDenied, null)); } } string script = GetScript(path); if (script == null) { return; } try { var scriptBlock = Context.Engine.ParseScriptBlock(script, false); scriptBlock.CheckRestrictedLanguage(SupportedCommand, null, false); object result; PSLanguageMode oldLanguageMode = Context.LanguageMode; Context.LanguageMode = PSLanguageMode.RestrictedLanguage; try { result = scriptBlock.InvokeReturnAsIs(); if (result == AutomationNull.Value) { result = null; } } finally { Context.LanguageMode = oldLanguageMode; } if (_bindingVariable != null) { VariablePath variablePath = new VariablePath(_bindingVariable); if (variablePath.IsUnscopedVariable) { variablePath = variablePath.CloneAndSetLocal(); } if (string.IsNullOrEmpty(variablePath.UnqualifiedPath)) { InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.IncorrectVariableName, _bindingVariable); WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.InvalidArgument, _bindingVariable)); return; } SessionStateScope scope = null; PSVariable variable = SessionState.Internal.GetVariableItem(variablePath, out scope); if (variable == null) { variable = new PSVariable(variablePath.UnqualifiedPath, result, ScopedItemOptions.None); Context.EngineSessionState.SetVariable(variablePath, variable, false, CommandOrigin.Internal); } else { variable.Value = result; if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { // Mark untrusted values for assignments to 'Global:' variables, and 'Script:' variables in // a module scope, if it's necessary. ExecutionContext.MarkObjectAsUntrustedForVariableAssignment(variable, scope, Context.EngineSessionState); } } } // If binding variable is null, write the object to stream else { WriteObject(result); } } catch (RuntimeException e) { PSInvalidOperationException ioe = PSTraceSource.NewInvalidOperationException(e, ImportLocalizedDataStrings.ErrorLoadingDataFile, path, e.Message); throw ioe; } return; } private string GetFilePath() { if (string.IsNullOrEmpty(_fileName)) { if (InvocationExtent == null || string.IsNullOrEmpty(InvocationExtent.File)) { throw PSTraceSource.NewInvalidOperationException(ImportLocalizedDataStrings.NotCalledFromAScriptFile); } } string dir = _baseDirectory; if (string.IsNullOrEmpty(dir)) { if (InvocationExtent != null && !string.IsNullOrEmpty(InvocationExtent.File)) { dir = Path.GetDirectoryName(InvocationExtent.File); } else { dir = "."; } } dir = PathUtils.ResolveFilePath(dir, this); string fileName = _fileName; if (string.IsNullOrEmpty(fileName)) { fileName = InvocationExtent.File; } else { if (!string.IsNullOrEmpty(Path.GetDirectoryName(fileName))) { throw PSTraceSource.NewInvalidOperationException(ImportLocalizedDataStrings.FileNameParameterCannotHavePath); } } fileName = Path.GetFileNameWithoutExtension(fileName); CultureInfo culture = null; if (_uiculture == null) { culture = CultureInfo.CurrentUICulture; } else { try { culture = CultureInfo.GetCultureInfo(_uiculture); } catch (ArgumentException) { throw PSTraceSource.NewArgumentException("Culture"); } } CultureInfo currentCulture = culture; string filePath; string fullFileName = fileName + ".psd1"; while (currentCulture != null && !string.IsNullOrEmpty(currentCulture.Name)) { filePath = Path.Combine(dir, currentCulture.Name, fullFileName); if (File.Exists(filePath)) { return filePath; } currentCulture = currentCulture.Parent; } filePath = Path.Combine(dir, fullFileName); if (File.Exists(filePath)) { return filePath; } InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.CannotFindPsd1File, fullFileName, Path.Combine(dir, culture.Name) ); WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound, Path.Combine(dir, culture.Name, fullFileName))); return null; } private string GetScript(string filePath) { InvalidOperationException ioe = null; try { // 197751: WR BUG BASH: Powershell: localized text display as garbage // leaving the encoding to be decided by the StreamReader. StreamReader // will read the preamble and decide proper encoding. using (FileStream scriptStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (StreamReader scriptReader = new StreamReader(scriptStream)) { return scriptReader.ReadToEnd(); } } catch (ArgumentException e) { ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.ErrorOpeningFile, filePath, e.Message); } catch (IOException e) { ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.ErrorOpeningFile, filePath, e.Message); } catch (NotSupportedException e) { ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.ErrorOpeningFile, filePath, e.Message); } catch (UnauthorizedAccessException e) { ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.ErrorOpeningFile, filePath, e.Message); } WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.OpenError, filePath)); return null; } #endregion Command code } }
// // 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.Azure.Management.NotificationHubs.Models; namespace Microsoft.Azure.Management.NotificationHubs { /// <summary> /// The Management API includes operations for managing notification hubs. /// </summary> public partial interface INotificationHubOperations { /// <summary> /// Checks the availability of the given notificationHub in a /// namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx /// for more information) /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// The notificationHub name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response of the Check NameAvailability operation. /// </returns> Task<CheckAvailabilityResponse> CheckAvailabilityAsync(string resourceGroupName, string namespaceName, CheckAvailabilityParameters parameters, CancellationToken cancellationToken); /// <summary> /// Creates a new NotificationHub in a namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx /// for more information) /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='parameters'> /// Parameters supplied to the create a Namespace Resource. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the NotificationHub /// </returns> Task<NotificationHubCreateOrUpdateResponse> CreateAsync(string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The create NotificationHub authorization rule operation creates an /// authorization rule for a NotificationHub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The namespace authorizationRuleName name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the AuthorizationRules /// </returns> Task<SharedAccessAuthorizationRuleCreateOrUpdateResponse> CreateOrUpdateAuthorizationRuleAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken); /// <summary> /// Deletes a notification hub associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string namespaceName, string notificationHubName, CancellationToken cancellationToken); /// <summary> /// The delete a notificationHub authorization rule operation /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The namespace authorizationRuleName name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> DeleteAuthorizationRuleAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, CancellationToken cancellationToken); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the Get NotificationHub operation. /// </returns> Task<NotificationHubGetResponse> GetAsync(string resourceGroupName, string namespaceName, string notificationHubName, CancellationToken cancellationToken); /// <summary> /// The get authorization rule operation gets an authorization rule for /// a NotificationHub by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace to get the authorization rule for. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The entity name to get the authorization rule for. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the Get Namespace operation. /// </returns> Task<SharedAccessAuthorizationRuleGetResponse> GetAuthorizationRuleAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, CancellationToken cancellationToken); /// <summary> /// Lists the PNS Credentials associated with a notification hub . /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the Get NotificationHub operation. /// </returns> Task<NotificationHubGetResponse> GetPnsCredentialsAsync(string resourceGroupName, string namespaceName, string notificationHubName, CancellationToken cancellationToken); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the List NotificationHub operation. /// </returns> Task<NotificationHubListResponse> ListAsync(string resourceGroupName, string namespaceName, CancellationToken cancellationToken); /// <summary> /// The get authorization rules operation gets the authorization rules /// for a NotificationHub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The NotificationHub to get the authorization rule for. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response of the List Namespace operation. /// </returns> Task<SharedAccessAuthorizationRuleListResponse> ListAuthorizationRulesAsync(string resourceGroupName, string namespaceName, string notificationHubName, CancellationToken cancellationToken); /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the /// NotificationHub (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx /// for more information) /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the NotificationHub for the specified /// authorizationRule. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Namespace/NotificationHub Connection String /// </returns> Task<ResourceListKeys> ListKeysAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, CancellationToken cancellationToken); /// <summary> /// Creates a new NotificationHub in a namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx /// for more information) /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='parameters'> /// Parameters supplied to the create a Namespace Resource. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the NotificationHub /// </returns> Task<NotificationHubCreateOrUpdateResponse> UpdateAsync(string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters, CancellationToken cancellationToken); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Static; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Tests.Process; using NUnit.Framework; /// <summary> /// Test utility methods. /// </summary> public static class TestUtils { /** Indicates long running and/or memory/cpu intensive test. */ public const string CategoryIntensive = "LONG_TEST"; /** Indicates examples tests. */ public const string CategoryExamples = "EXAMPLES_TEST"; /** */ public const int DfltBusywaitSleepInterval = 200; /** */ private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess ? new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms1g", "-Xmx4g", "-ea", "-DIGNITE_QUIET=true", "-Duser.timezone=UTC" } : new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms512m", "-Xmx512m", "-ea", "-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000", "-DIGNITE_QUIET=true" }; /** */ private static readonly IList<string> JvmDebugOpts = new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" }; /** */ public static bool JvmDebug = true; /** */ [ThreadStatic] private static Random _random; /** */ private static int _seed = Environment.TickCount; /// <summary> /// Kill Ignite processes. /// </summary> public static void KillProcesses() { IgniteProcess.KillAll(); } /// <summary> /// /// </summary> public static Random Random { get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); } } /// <summary> /// /// </summary> /// <returns></returns> public static IList<string> TestJavaOptions(bool? jvmDebug = null) { IList<string> ops = new List<string>(TestJvmOpts); if (jvmDebug ?? JvmDebug) { foreach (string opt in JvmDebugOpts) ops.Add(opt); } return ops; } /// <summary> /// /// </summary> /// <returns></returns> public static string CreateTestClasspath() { return Classpath.CreateClasspath(forceTestClasspath: true); } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> public static void RunMultiThreaded(Action action, int threadNum) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { action(); } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> /// <param name="duration">Duration of test execution in seconds</param> public static void RunMultiThreaded(Action action, int threadNum, int duration) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); bool stop = false; for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { while (true) { Thread.MemoryBarrier(); // ReSharper disable once AccessToModifiedClosure if (stop) break; action(); } } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); Thread.Sleep(duration * 1000); stop = true; Thread.MemoryBarrier(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// Wait for particular topology size. /// </summary> /// <param name="grid">Grid.</param> /// <param name="size">Size.</param> /// <param name="timeout">Timeout.</param> /// <returns> /// <c>True</c> if topology took required size. /// </returns> public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000) { int left = timeout; while (true) { if (grid.GetCluster().GetNodes().Count != size) { if (left > 0) { Thread.Sleep(100); left -= 100; } else break; } else return true; } return false; } /// <summary> /// Asserts that the handle registry is empty. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, 0, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, expectedCount, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="grid">The grid to check.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="timeout">Timeout, in milliseconds.</param> public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout) { var handleRegistry = ((Ignite)grid).HandleRegistry; expectedCount++; // Skip default lifecycle bean if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout)) return; var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleBeanHolder)).ToList(); if (items.Any()) Assert.Fail("HandleRegistry is not empty in grid '{0}' (expected {1}, actual {2}):\n '{3}'", grid.Name, expectedCount, handleRegistry.Count, items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y)); } /// <summary> /// Waits for condition, polling in busy wait loop. /// </summary> /// <param name="cond">Condition.</param> /// <param name="timeout">Timeout, in milliseconds.</param> /// <returns>True if condition predicate returned true within interval; false otherwise.</returns> public static bool WaitForCondition(Func<bool> cond, int timeout) { if (timeout <= 0) return cond(); var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval); while (DateTime.Now < maxTime) { if (cond()) return true; Thread.Sleep(DfltBusywaitSleepInterval); } return false; } /// <summary> /// Gets the static discovery. /// </summary> public static TcpDiscoverySpi GetStaticDiscovery() { return new TcpDiscoverySpi { IpFinder = new TcpDiscoveryStaticIpFinder { Endpoints = new[] { "127.0.0.1:47500" } }, SocketTimeout = TimeSpan.FromSeconds(0.3) }; } /// <summary> /// Gets the default code-based test configuration. /// </summary> public static IgniteConfiguration GetTestConfiguration(bool? jvmDebug = null) { return new IgniteConfiguration { DiscoverySpi = GetStaticDiscovery(), Localhost = "127.0.0.1", JvmOptions = TestJavaOptions(jvmDebug), JvmClasspath = CreateTestClasspath() }; } /// <summary> /// Runs the test in new process. /// </summary> [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] public static void RunTestInNewProcess(string fixtureName, string testName) { var procStart = new ProcessStartInfo { FileName = typeof(TestUtils).Assembly.Location, Arguments = fixtureName + " " + testName, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; var proc = System.Diagnostics.Process.Start(procStart); Assert.IsNotNull(proc); Console.WriteLine(proc.StandardOutput.ReadToEnd()); Console.WriteLine(proc.StandardError.ReadToEnd()); Assert.IsTrue(proc.WaitForExit(15000)); Assert.AreEqual(0, proc.ExitCode); } } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; using NakedFramework; using NakedFramework.Architecture.Component; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.FacetFactory; using NakedFramework.Architecture.Reflect; using NakedFramework.Architecture.Spec; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Core.Util; using NakedFramework.Metamodel.Facet; using NakedFramework.Metamodel.Utils; using NakedFramework.ParallelReflector.FacetFactory; using NakedFramework.ParallelReflector.Utils; using NakedObjects.Reflector.Facet; using NakedObjects.Reflector.Utils; namespace NakedObjects.Reflector.FacetFactory; /// <summary> /// Sets up all the <see cref="IFacet" />s for an action in a single shot /// </summary> public sealed class ActionMethodsFacetFactory : DomainObjectFacetFactoryProcessor, IMethodPrefixBasedFacetFactory, IMethodIdentifyingFacetFactory { private static readonly string[] FixedPrefixes = { RecognisedMethodsAndPrefixes.AutoCompletePrefix, RecognisedMethodsAndPrefixes.ParameterDefaultPrefix, RecognisedMethodsAndPrefixes.ParameterChoicesPrefix, RecognisedMethodsAndPrefixes.DisablePrefix, RecognisedMethodsAndPrefixes.HidePrefix, RecognisedMethodsAndPrefixes.ValidatePrefix, RecognisedMethodsAndPrefixes.DisablePrefix }; private readonly ILogger<ActionMethodsFacetFactory> logger; public ActionMethodsFacetFactory(IFacetFactoryOrder<ActionMethodsFacetFactory> order, ILoggerFactory loggerFactory) : base(order.Order, loggerFactory, FeatureType.ActionsAndActionParameters) => logger = loggerFactory.CreateLogger<ActionMethodsFacetFactory>(); public string[] Prefixes => FixedPrefixes; private static bool IsQueryOnly(MethodInfo method) => method.GetCustomAttribute<IdempotentAttribute>() is null && method.GetCustomAttribute<QueryOnlyAttribute>() is not null; // separate methods to reproduce old reflector behaviour private static bool IsParameterCollection(Type type) => type is not null && ( CollectionUtils.IsGenericEnumerable(type) || type.IsArray || type == typeof(string) || CollectionUtils.IsCollectionButNotArray(type)); private static bool IsCollection(Type type) { return type is not null && ( CollectionUtils.IsGenericEnumerable(type) || type.IsArray || type == typeof(string) || CollectionUtils.IsCollectionButNotArray(type) || IsCollection(type.BaseType) || type.GetInterfaces().Where(i => i.IsPublic).Any(IsCollection)); } private bool ParametersAreSupported(MethodInfo method, IClassStrategy classStrategy) { foreach (var parameterInfo in method.GetParameters()) { if (classStrategy.IsIgnored(parameterInfo.ParameterType)) { logger.LogWarning($"Ignoring method: {method.DeclaringType}.{method.Name} because parameter '{parameterInfo.Name}' is of type {parameterInfo.ParameterType}"); return false; } } return true; } /// <summary> /// Must be called after the <c>CheckForXxxPrefix</c> methods. /// </summary> private static void DefaultNamedFacet(ICollection<IFacet> actionFacets, string name, ISpecification action) => actionFacets.Add(new MemberNamedFacetInferred(name)); private void FindAndRemoveValidMethod(IReflector reflector, ICollection<IFacet> actionFacets, IMethodRemover methodRemover, Type type, MethodType methodType, string capitalizedName, Type[] parms, ISpecification action) { var method = MethodHelpers.FindMethod(reflector, type, methodType, $"{RecognisedMethodsAndPrefixes.ValidatePrefix}{capitalizedName}", typeof(string), parms); methodRemover.SafeRemoveMethod(method); if (method is not null) { actionFacets.Add(new ActionValidationFacet(method, Logger<ActionValidationFacet>())); } } private void FindAndRemoveParametersDefaultsMethod(IReflector reflector, IMethodRemover methodRemover, Type type, string capitalizedName, Type[] paramTypes, string[] paramNames, IActionParameterSpecImmutable[] parameters) { for (var i = 0; i < paramTypes.Length; i++) { var paramType = paramTypes[i]; var paramName = paramNames[i]; var methodUsingIndex = MethodHelpers.FindMethodWithOrWithoutParameters(reflector, type, MethodType.Object, $"{RecognisedMethodsAndPrefixes.ParameterDefaultPrefix}{i}{capitalizedName}", paramType, paramTypes); var methodUsingName = MethodHelpers.FindMethod( reflector, type, MethodType.Object, $"{RecognisedMethodsAndPrefixes.ParameterDefaultPrefix}{capitalizedName}", paramType, new[] { paramType }, new[] { paramName }); if (methodUsingIndex is not null && methodUsingName != null) { logger.LogWarning($"Duplicate defaults parameter methods {methodUsingIndex.Name} and {methodUsingName.Name} using {methodUsingName.Name}"); } var methodToUse = methodUsingName ?? methodUsingIndex; if (methodToUse != null) { // deliberately not removing both if duplicate to show that method is duplicate methodRemover.SafeRemoveMethod(methodToUse); // add facets directly to parameters, not to actions var spec = parameters[i]; FacetUtils.AddFacet(new ActionDefaultsFacetViaMethod(methodToUse, Logger<ActionDefaultsFacetViaMethod>()), spec); } } } private IImmutableDictionary<string, ITypeSpecBuilder> FindAndRemoveParametersChoicesMethod(IReflector reflector, IMethodRemover methodRemover, Type type, string capitalizedName, Type[] paramTypes, string[] paramNames, MethodInfo actionMethod, IActionParameterSpecImmutable[] parameters, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) { for (var i = 0; i < paramTypes.Length; i++) { var paramType = paramTypes[i]; var paramName = paramNames[i]; var isMultiple = false; if (CollectionUtils.IsGenericEnumerable(paramType)) { paramType = paramType.GetGenericArguments().First(); isMultiple = true; } var returnType = typeof(IEnumerable<>).MakeGenericType(paramType); var methodName = $"{RecognisedMethodsAndPrefixes.ParameterChoicesPrefix}{i}{capitalizedName}"; var methods = ObjectMethodHelpers.FindMethods( reflector, type, MethodType.Object, methodName, returnType); if (methods.Length > 1) { methods.Skip(1).ForEach(m => logger.LogWarning($"Found multiple action choices methods: {methodName} in type: {type} ignoring method(s) with params: {m.GetParameters().Select(p => p.Name).Aggregate("", (s, t) => $"{s} {t}")}")); } var methodUsingIndex = methods.FirstOrDefault(); var methodUsingName = MethodHelpers.FindMethod( reflector, type, MethodType.Object, $"{RecognisedMethodsAndPrefixes.ParameterChoicesPrefix}{capitalizedName}", returnType, new[] { paramType }, new[] { paramName }); if (methodUsingIndex is not null && methodUsingName != null) { logger.LogWarning($"Duplicate choices parameter methods {methodUsingIndex.Name} and {methodUsingName.Name} using {methodUsingName.Name}"); } var methodToUse = methodUsingName ?? methodUsingIndex; if (methodToUse != null) { // add facets directly to parameters, not to actions var parameterNamesAndTypes = new List<(string, IObjectSpecImmutable)>(); foreach (var p in methodToUse.GetParameters()) { IObjectSpecBuilder oSpec; (oSpec, metamodel) = reflector.LoadSpecification<IObjectSpecBuilder>(p.ParameterType, metamodel); var name = p.Name?.ToLower(); parameterNamesAndTypes.Add((name, oSpec)); } var mismatchedParm = false; // all parameter names and types must match foreach (var (pName, _) in parameterNamesAndTypes) { var actionParm = actionMethod.GetParameters().SingleOrDefault(p => p.Name?.ToLower() == pName); var choicesParm = methodToUse.GetParameters().SingleOrDefault(p => p.Name?.ToLower() == pName); if (actionParm is null) { logger.LogWarning($"Choices method: {methodToUse.DeclaringType}.{methodToUse.Name} has non matching parameter name: {pName}"); mismatchedParm = true; } else if (actionParm.ParameterType != choicesParm?.ParameterType) { logger.LogWarning($"Choices method parameter: {methodToUse.DeclaringType}.{methodToUse.Name}.{pName} has non matching type: {choicesParm?.ParameterType} should be: {actionParm.ParameterType}"); mismatchedParm = true; } } if (!mismatchedParm) { // deliberately not removing both if duplicate to show that method is duplicate methodRemover.SafeRemoveMethod(methodToUse); var spec = parameters[i]; FacetUtils.AddFacet(new ActionChoicesFacetViaMethod(methodToUse, parameterNamesAndTypes.ToArray(), returnType, Logger<ActionChoicesFacetViaMethod>(), isMultiple), spec); } } } return metamodel; } private void FindAndRemoveParametersAutoCompleteMethod(IReflector reflector, IMethodRemover methodRemover, Type type, string capitalizedName, Type[] paramTypes, IActionParameterSpecImmutable[] parameters) { for (var i = 0; i < paramTypes.Length; i++) { // only support on strings and reference types var paramType = paramTypes[i]; if (paramType.IsClass || paramType.IsInterface) { //returning an IQueryable ... //.. or returning a single object var method = FindAutoCompleteMethod(reflector, type, capitalizedName, i, typeof(IQueryable<>).MakeGenericType(paramType)) ?? FindAutoCompleteMethod(reflector, type, capitalizedName, i, paramType); //... or returning an enumerable of string if (method is null && TypeUtils.IsString(paramType)) { method = FindAutoCompleteMethod(reflector, type, capitalizedName, i, typeof(IEnumerable<string>)); } if (method is not null) { var pageSizeAttr = method.GetCustomAttribute<PageSizeAttribute>(); var minLengthAttr = (MinLengthAttribute)Attribute.GetCustomAttribute(method.GetParameters().First(), typeof(MinLengthAttribute)); var pageSize = pageSizeAttr?.Value ?? 0; // default to 0 ie system default var minLength = minLengthAttr?.Length ?? 0; // deliberately not removing both if duplicate to show that method is duplicate methodRemover.SafeRemoveMethod(method); // add facets directly to parameters, not to actions var spec = parameters[i]; FacetUtils.AddFacet(new AutoCompleteFacet(method, pageSize, minLength, Logger<AutoCompleteFacet>()), spec); } } } } private static MethodInfo FindAutoCompleteMethod(IReflector reflector, Type type, string capitalizedName, int i, Type returnType) => MethodHelpers.FindMethod(reflector, type, MethodType.Object, $"{RecognisedMethodsAndPrefixes.AutoCompletePrefix}{i}{capitalizedName}", returnType, new[] { typeof(string) }); private void FindAndRemoveParametersValidateMethod(IReflector reflector, IMethodRemover methodRemover, Type type, string capitalizedName, Type[] paramTypes, string[] paramNames, IActionParameterSpecImmutable[] parameters) { for (var i = 0; i < paramTypes.Length; i++) { var methodUsingIndex = MethodHelpers.FindMethod(reflector, type, MethodType.Object, $"{RecognisedMethodsAndPrefixes.ValidatePrefix}{i}{capitalizedName}", typeof(string), new[] { paramTypes[i] }); var methodUsingName = MethodHelpers.FindMethod(reflector, type, MethodType.Object, $"{RecognisedMethodsAndPrefixes.ValidatePrefix}{capitalizedName}", typeof(string), new[] { paramTypes[i] }, new[] { paramNames[i] }); if (methodUsingIndex is not null && methodUsingName is not null) { logger.LogWarning($"Duplicate validate parameter methods {methodUsingIndex.Name} and {methodUsingName.Name} using {methodUsingName.Name}"); } var methodToUse = methodUsingName ?? methodUsingIndex; if (methodToUse is not null) { // deliberately not removing both if duplicate to show that method is duplicate methodRemover.SafeRemoveMethod(methodToUse); // add facets directly to parameters, not to actions var spec = parameters[i]; FacetUtils.AddFacet(new ActionParameterValidation(methodToUse, Logger<ActionParameterValidation>()), spec); } } } #region IMethodIdentifyingFacetFactory Members public override IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, MethodInfo actionMethod, IMethodRemover methodRemover, ISpecificationBuilder action, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) { var capitalizedName = NameUtils.CapitalizeName(actionMethod.Name); var type = actionMethod.DeclaringType; var facets = new List<IFacet>(); ITypeSpecBuilder onType; (onType, metamodel) = reflector.LoadSpecification(type, metamodel); IObjectSpecBuilder returnSpec; (returnSpec, metamodel) = reflector.LoadSpecification<IObjectSpecBuilder>(actionMethod.ReturnType, metamodel); IObjectSpecBuilder elementSpec = null; var isQueryable = IsQueryOnly(actionMethod) || CollectionUtils.IsQueryable(actionMethod.ReturnType); if (returnSpec is not null && IsCollection(actionMethod.ReturnType)) { var elementType = CollectionUtils.ElementType(actionMethod.ReturnType); (elementSpec, metamodel) = reflector.LoadSpecification<IObjectSpecBuilder>(elementType, metamodel); } methodRemover.SafeRemoveMethod(actionMethod); facets.Add(new ActionInvocationFacetViaMethod(actionMethod, onType, returnSpec, elementSpec, isQueryable, Logger<ActionInvocationFacetViaMethod>())); var methodType = actionMethod.IsStatic ? MethodType.Class : MethodType.Object; var paramTypes = actionMethod.GetParameters().Select(p => p.ParameterType).ToArray(); FindAndRemoveValidMethod(reflector, facets, methodRemover, type, methodType, capitalizedName, paramTypes, action); DefaultNamedFacet(facets, actionMethod.Name, action); // must be called after the checkForXxxPrefix methods MethodHelpers.AddHideForSessionFacetNone(facets, action); MethodHelpers.AddDisableForSessionFacetNone(facets, action); ObjectMethodHelpers.FindDefaultHideMethod(reflector, facets, type, methodType, "ActionDefault", action, LoggerFactory); ObjectMethodHelpers.FindAndRemoveHideMethod(reflector, facets, type, methodType, capitalizedName, action, LoggerFactory, methodRemover); ObjectMethodHelpers.FindDefaultDisableMethod(reflector, facets, type, methodType, "ActionDefault", action, LoggerFactory); ObjectMethodHelpers.FindAndRemoveDisableMethod(reflector, facets, type, methodType, capitalizedName, action, LoggerFactory, methodRemover); if (action is IActionSpecImmutable actionSpecImmutable) { // Process the action's parameters names, descriptions and optional // an alternative design would be to have another facet factory processing just ActionParameter, and have it remove these // supporting methods. However, the FacetFactory API doesn't allow for methods of the class to be removed while processing // action parameters, only while processing Methods (ie actions) var actionParameters = actionSpecImmutable.Parameters; var paramNames = actionMethod.GetParameters().Select(p => p.Name).ToArray(); FindAndRemoveParametersAutoCompleteMethod(reflector, methodRemover, type, capitalizedName, paramTypes, actionParameters); metamodel = FindAndRemoveParametersChoicesMethod(reflector, methodRemover, type, capitalizedName, paramTypes, paramNames, actionMethod, actionParameters, metamodel); FindAndRemoveParametersDefaultsMethod(reflector, methodRemover, type, capitalizedName, paramTypes, paramNames, actionParameters); FindAndRemoveParametersValidateMethod(reflector, methodRemover, type, capitalizedName, paramTypes, paramNames, actionParameters); } FacetUtils.AddFacets(facets, action); return metamodel; } public override IImmutableDictionary<string, ITypeSpecBuilder> ProcessParams(IReflector reflector, MethodInfo method, int paramNum, ISpecificationBuilder holder, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) { var parameter = method.GetParameters()[paramNum]; var facets = new List<IFacet>(); if (parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>)) { facets.Add(new NullableFacetAlways()); } IObjectSpecBuilder returnSpec; (returnSpec, metamodel) = reflector.LoadSpecification<IObjectSpecBuilder>(parameter.ParameterType, metamodel); if (returnSpec is not null && IsParameterCollection(parameter.ParameterType)) { var elementType = CollectionUtils.ElementType(parameter.ParameterType); IObjectSpecImmutable elementSpec; (elementSpec, metamodel) = reflector.LoadSpecification<IObjectSpecImmutable>(elementType, metamodel); facets.Add(new ElementTypeFacet(elementType, elementSpec)); } FacetUtils.AddFacets(facets, holder); return metamodel; } public IList<MethodInfo> FindActions(IList<MethodInfo> candidates, IClassStrategy classStrategy) { return candidates.Where(methodInfo => !classStrategy.IsIgnored(methodInfo) && !methodInfo.IsStatic && !methodInfo.IsGenericMethod && !classStrategy.IsIgnored(methodInfo.ReturnType) && ParametersAreSupported(methodInfo, classStrategy)).ToArray(); } #endregion }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // ReSharper disable MemberCanBeProtected.Global // ReSharper disable UnassignedField.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global namespace Apache.Ignite.Core.Tests { using System; using System.Collections; using System.Collections.Generic; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Lifecycle beans test. /// </summary> public class LifecycleTest { /** Configuration: without Java beans. */ private const string CfgNoBeans = "Config/Lifecycle/lifecycle-no-beans.xml"; /** Configuration: with Java beans. */ private const string CfgBeans = "Config/Lifecycle//lifecycle-beans.xml"; /** Whether to throw an error on lifecycle event. */ internal static bool ThrowErr; /** Events: before start. */ internal static IList<Event> BeforeStartEvts; /** Events: after start. */ internal static IList<Event> AfterStartEvts; /** Events: before stop. */ internal static IList<Event> BeforeStopEvts; /** Events: after stop. */ internal static IList<Event> AfterStopEvts; /// <summary> /// Set up routine. /// </summary> [SetUp] public void SetUp() { ThrowErr = false; BeforeStartEvts = new List<Event>(); AfterStartEvts = new List<Event>(); BeforeStopEvts = new List<Event>(); AfterStopEvts = new List<Event>(); } /// <summary> /// Tear down routine. /// </summary> [TearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Test without Java beans. /// </summary> [Test] public void TestWithoutBeans() { // 1. Test start events. IIgnite grid = Start(CfgNoBeans); Assert.AreEqual(2, grid.GetConfiguration().LifecycleHandlers.Count); Assert.AreEqual(2, BeforeStartEvts.Count); CheckEvent(BeforeStartEvts[0], null, null, 0, null); CheckEvent(BeforeStartEvts[1], null, null, 0, null); Assert.AreEqual(2, AfterStartEvts.Count); CheckEvent(AfterStartEvts[0], grid, grid, 0, null); CheckEvent(AfterStartEvts[1], grid, grid, 0, null); // 2. Test stop events. var stoppingCnt = 0; var stoppedCnt = 0; grid.Stopping += (sender, args) => { stoppingCnt++; }; grid.Stopped += (sender, args) => { stoppedCnt++; }; Ignition.Stop(grid.Name, false); Assert.AreEqual(1, stoppingCnt); Assert.AreEqual(1, stoppedCnt); Assert.AreEqual(2, BeforeStartEvts.Count); Assert.AreEqual(2, AfterStartEvts.Count); Assert.AreEqual(2, BeforeStopEvts.Count); CheckEvent(BeforeStopEvts[0], grid, grid, 0, null); CheckEvent(BeforeStopEvts[1], grid, grid, 0, null); Assert.AreEqual(2, AfterStopEvts.Count); CheckEvent(AfterStopEvts[0], grid, grid, 0, null); CheckEvent(AfterStopEvts[1], grid, grid, 0, null); } /// <summary> /// Test with Java beans. /// </summary> [Test] public void TestWithBeans() { // 1. Test .NET start events. IIgnite grid = Start(CfgBeans); Assert.AreEqual(2, grid.GetConfiguration().LifecycleHandlers.Count); Assert.AreEqual(4, BeforeStartEvts.Count); CheckEvent(BeforeStartEvts[0], null, null, 0, null); CheckEvent(BeforeStartEvts[1], null, null, 1, "1"); CheckEvent(BeforeStartEvts[2], null, null, 0, null); CheckEvent(BeforeStartEvts[3], null, null, 0, null); Assert.AreEqual(4, AfterStartEvts.Count); CheckEvent(AfterStartEvts[0], grid, grid, 0, null); CheckEvent(AfterStartEvts[1], grid, grid, 1, "1"); CheckEvent(AfterStartEvts[2], grid, grid, 0, null); CheckEvent(AfterStartEvts[3], grid, grid, 0, null); // 2. Test Java start events. var res = grid.GetCompute().ExecuteJavaTask<IList>( "org.apache.ignite.platform.lifecycle.PlatformJavaLifecycleTask", null); Assert.AreEqual(2, res.Count); Assert.AreEqual(3, res[0]); Assert.AreEqual(3, res[1]); // 3. Test .NET stop events. Ignition.Stop(grid.Name, false); Assert.AreEqual(4, BeforeStartEvts.Count); Assert.AreEqual(4, AfterStartEvts.Count); Assert.AreEqual(4, BeforeStopEvts.Count); CheckEvent(BeforeStopEvts[0], grid, grid, 0, null); CheckEvent(BeforeStopEvts[1], grid, grid, 1, "1"); CheckEvent(BeforeStopEvts[2], grid, grid, 0, null); CheckEvent(BeforeStopEvts[3], grid, grid, 0, null); Assert.AreEqual(4, AfterStopEvts.Count); CheckEvent(AfterStopEvts[0], grid, grid, 0, null); CheckEvent(AfterStopEvts[1], grid, grid, 1, "1"); CheckEvent(AfterStopEvts[2], grid, grid, 0, null); CheckEvent(AfterStopEvts[3], grid, grid, 0, null); } /// <summary> /// Test behavior when error is thrown from lifecycle beans. /// </summary> [Test] public void TestError() { ThrowErr = true; var ex = Assert.Throws<IgniteException>(() => Start(CfgNoBeans)); Assert.AreEqual("Lifecycle exception.", ex.Message); } /// <summary> /// Start grid. /// </summary> /// <param name="cfgPath">Spring configuration path.</param> /// <returns>Grid.</returns> private static IIgnite Start(string cfgPath) { return Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = cfgPath, LifecycleHandlers = new List<ILifecycleHandler> {new Bean(), new Bean()} }); } /// <summary> /// Check event. /// </summary> /// <param name="evt">Event.</param> /// <param name="expGrid1">Expected grid 1.</param> /// <param name="expGrid2">Expected grid 2.</param> /// <param name="expProp1">Expected property 1.</param> /// <param name="expProp2">Expected property 2.</param> private static void CheckEvent(Event evt, IIgnite expGrid1, IIgnite expGrid2, int expProp1, string expProp2) { Assert.AreEqual(expGrid1, evt.Grid1); Assert.AreEqual(expGrid2, evt.Grid2); Assert.AreEqual(expProp1, evt.Prop1); Assert.AreEqual(expProp2, evt.Prop2); } } public abstract class AbstractBean { [InstanceResource] public IIgnite Grid1; public int Property1 { get; set; } } public class Bean : AbstractBean, ILifecycleHandler { [InstanceResource] public IIgnite Grid2; public string Property2 { get; set; } /** <inheritDoc /> */ public void OnLifecycleEvent(LifecycleEventType evtType) { if (LifecycleTest.ThrowErr) throw new Exception("Lifecycle exception."); Event evt = new Event { Grid1 = Grid1, Grid2 = Grid2, Prop1 = Property1, Prop2 = Property2 }; switch (evtType) { case LifecycleEventType.BeforeNodeStart: LifecycleTest.BeforeStartEvts.Add(evt); break; case LifecycleEventType.AfterNodeStart: LifecycleTest.AfterStartEvts.Add(evt); break; case LifecycleEventType.BeforeNodeStop: LifecycleTest.BeforeStopEvts.Add(evt); break; case LifecycleEventType.AfterNodeStop: LifecycleTest.AfterStopEvts.Add(evt); break; } } } public class Event { public IIgnite Grid1; public IIgnite Grid2; public int Prop1; public string Prop2; } }