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. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text.Encodings.Web; using System.Text.Unicode; using Xunit; namespace Microsoft.Framework.WebEncoders { public class UnicodeEncoderBaseTests { [Fact] public void Ctor_WithCustomFilters() { // Arrange var filter = new TextEncoderSettings(); filter.AllowCharacters('a', 'b'); filter.AllowCharacters('\0', '&', '\uFFFF', 'd'); UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(filter); // Act & assert Assert.Equal("a", encoder.Encode("a")); Assert.Equal("b", encoder.Encode("b")); Assert.Equal("[U+0063]", encoder.Encode("c")); Assert.Equal("d", encoder.Encode("d")); Assert.Equal("[U+0000]", encoder.Encode("\0")); // we still always encode control chars Assert.Equal("[U+0026]", encoder.Encode("&")); // we still always encode HTML-special chars Assert.Equal("[U+FFFF]", encoder.Encode("\uFFFF")); // we still always encode non-chars and other forbidden chars } [Fact] public void Ctor_WithUnicodeRanges() { // Arrange UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(new TextEncoderSettings(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols)); // Act & assert Assert.Equal("[U+0061]", encoder.Encode("a")); Assert.Equal("\u00E9", encoder.Encode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */)); Assert.Equal("\u2601", encoder.Encode("\u2601" /* CLOUD */)); } [Fact] public void Encode_AllRangesAllowed_StillEncodesForbiddenChars_Simple() { // Arrange UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); const string input = "Hello <>&\'\"+ there!"; const string expected = "Hello [U+003C][U+003E][U+0026][U+0027][U+0022][U+002B] there!"; // Act & assert Assert.Equal(expected, encoder.Encode(input)); } [Fact] public void Encode_AllRangesAllowed_StillEncodesForbiddenChars_Extended() { // Arrange UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); // Act & assert - BMP chars for (int i = 0; i <= 0xFFFF; i++) { string input = new String((char)i, 1); string expected; if (IsSurrogateCodePoint(i)) { expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char } else { bool mustEncode = false; switch (i) { case '<': case '>': case '&': case '\"': case '\'': case '+': mustEncode = true; break; } if (i <= 0x001F || (0x007F <= i && i <= 0x9F)) { mustEncode = true; // control char } else if (!UnicodeHelpers.IsCharacterDefined((char)i)) { mustEncode = true; // undefined (or otherwise disallowed) char } if (mustEncode) { expected = String.Format(CultureInfo.InvariantCulture, "[U+{0:X4}]", i); } else { expected = input; // no encoding } } string retVal = encoder.Encode(input); Assert.Equal(expected, retVal); } // Act & assert - astral chars for (int i = 0x10000; i <= 0x10FFFF; i++) { string input = Char.ConvertFromUtf32(i); string expected = String.Format(CultureInfo.InvariantCulture, "[U+{0:X}]", i); string retVal = encoder.Encode(input); Assert.Equal(expected, retVal); } } [Fact] public void Encode_BadSurrogates_ReturnsUnicodeReplacementChar() { // Arrange UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); // allow all codepoints // "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>" const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800"; const string expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD[U+103FF]e\uFFFD"; // Act string retVal = encoder.Encode(input); // Assert Assert.Equal(expected, retVal); } [Fact] public void Encode_EmptyStringInput_ReturnsEmptyString() { // Arrange UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); // Act & assert Assert.Equal("", encoder.Encode("")); } [Fact] public void Encode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance() { // Arrange UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); string input = "Hello, there!"; // Act & assert Assert.Same(input, encoder.Encode(input)); } [Fact] public void Encode_NullInput_ReturnsNull() { // Arrange UnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); // Act & assert Assert.Null(encoder.Encode(null)); } [Fact] public void Encode_WithCharsRequiringEncodingAtBeginning() { Assert.Equal("[U+0026]Hello, there!", new CustomUnicodeEncoderBase(UnicodeRanges.All).Encode("&Hello, there!")); } [Fact] public void Encode_WithCharsRequiringEncodingAtEnd() { Assert.Equal("Hello, there![U+0026]", new CustomUnicodeEncoderBase(UnicodeRanges.All).Encode("Hello, there!&")); } [Fact] public void Encode_WithCharsRequiringEncodingInMiddle() { Assert.Equal("Hello, [U+0026]there!", new CustomUnicodeEncoderBase(UnicodeRanges.All).Encode("Hello, &there!")); } [Fact] public void Encode_WithCharsRequiringEncodingInterspersed() { Assert.Equal("Hello, [U+003C]there[U+003E]!", new CustomUnicodeEncoderBase(UnicodeRanges.All).Encode("Hello, <there>!")); } [Fact] public void Encode_CharArray_ParameterChecking_NegativeTestCases() { // Arrange CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(); // Act & assert Assert.Throws<ArgumentNullException>(() => encoder.Encode((char[])null, 0, 0, new StringWriter())); Assert.Throws<ArgumentNullException>(() => encoder.Encode("abc".ToCharArray(), 0, 3, null)); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), -1, 2, new StringWriter())); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), 2, 2, new StringWriter())); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), 4, 0, new StringWriter())); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), 2, -1, new StringWriter())); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc".ToCharArray(), 1, 3, new StringWriter())); } //[Fact] //public void Encode_CharArray_ZeroCount_DoesNotCallIntoTextWriter() //{ // // Arrange // CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(); // TextWriter output = new Mock<TextWriter>(MockBehavior.Strict).Object; // // Act // encoder.Encode("abc".ToCharArray(), 2, 0, output); // // Assert // // If we got this far (without TextWriter throwing), success! //} [Fact] public void Encode_CharArray_AllCharsValid() { // Arrange CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); StringWriter output = new StringWriter(); // Act encoder.Encode("abc&xyz".ToCharArray(), 4, 2, output); // Assert Assert.Equal("xy", output.ToString()); } [Fact] public void Encode_CharArray_AllCharsInvalid() { // Arrange CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(); StringWriter output = new StringWriter(); // Act encoder.Encode("abc&xyz".ToCharArray(), 4, 2, output); // Assert Assert.Equal("[U+0078][U+0079]", output.ToString()); } [Fact] public void Encode_CharArray_SomeCharsValid() { // Arrange CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); StringWriter output = new StringWriter(); // Act encoder.Encode("abc&xyz".ToCharArray(), 2, 3, output); // Assert Assert.Equal("c[U+0026]x", output.ToString()); } [Fact] public void Encode_StringSubstring_ParameterChecking_NegativeTestCases() { // Arrange CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(); // Act & assert Assert.Throws<ArgumentNullException>(() => encoder.Encode((string)null, 0, 0, new StringWriter())); Assert.Throws<ArgumentNullException>(() => encoder.Encode("abc", 0, 3, null)); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", -1, 2, new StringWriter())); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", 2, 2, new StringWriter())); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", 4, 0, new StringWriter())); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", 2, -1, new StringWriter())); Assert.Throws<ArgumentOutOfRangeException>(() => encoder.Encode("abc", 1, 3, new StringWriter())); } //[Fact] //public void Encode_StringSubstring_ZeroCount_DoesNotCallIntoTextWriter() //{ // // Arrange // CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(); // TextWriter output = new Mock<TextWriter>(MockBehavior.Strict).Object; // // Act // encoder.Encode("abc", 2, 0, output); // // Assert // // If we got this far (without TextWriter throwing), success! //} [Fact] public void Encode_StringSubstring_AllCharsValid() { // Arrange CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); StringWriter output = new StringWriter(); // Act encoder.Encode("abc&xyz", 4, 2, output); // Assert Assert.Equal("xy", output.ToString()); } //[Fact] //public void Encode_StringSubstring_EntireString_AllCharsValid_ForwardDirectlyToOutput() //{ // // Arrange // CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); // var mockWriter = new Mock<TextWriter>(MockBehavior.Strict); // mockWriter.Setup(o => o.Write("abc")).Verifiable(); // // Act // encoder.Encode("abc", 0, 3, mockWriter.Object); // // Assert // mockWriter.Verify(); //} [Fact] public void Encode_StringSubstring_AllCharsInvalid() { // Arrange CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(); StringWriter output = new StringWriter(); // Act encoder.Encode("abc&xyz", 4, 2, output); // Assert Assert.Equal("[U+0078][U+0079]", output.ToString()); } [Fact] public void Encode_StringSubstring_SomeCharsValid() { // Arrange CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); StringWriter output = new StringWriter(); // Act encoder.Encode("abc&xyz", 2, 3, output); // Assert Assert.Equal("c[U+0026]x", output.ToString()); } [Fact] public void Encode_StringSubstring_EntireString_SomeCharsValid() { // Arrange CustomUnicodeEncoderBase encoder = new CustomUnicodeEncoderBase(UnicodeRanges.All); StringWriter output = new StringWriter(); // Act const string input = "abc&xyz"; encoder.Encode(input, 0, input.Length, output); // Assert Assert.Equal("abc[U+0026]xyz", output.ToString()); } private static bool IsSurrogateCodePoint(int codePoint) { return (0xD800 <= codePoint && codePoint <= 0xDFFF); } private sealed class CustomTextEncoderSettings : TextEncoderSettings { private readonly int[] _allowedCodePoints; public CustomTextEncoderSettings(params int[] allowedCodePoints) { _allowedCodePoints = allowedCodePoints; } public override IEnumerable<int> GetAllowedCodePoints() { return _allowedCodePoints; } } private sealed class CustomUnicodeEncoderBase : UnicodeEncoderBase { // We pass a (known bad) value of 1 for 'max output chars per input char', // which also tests that the code behaves properly even if the original // estimate is incorrect. public CustomUnicodeEncoderBase(TextEncoderSettings filter) : base(filter, maxOutputCharsPerInputChar: 1) { } public CustomUnicodeEncoderBase(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges)) { } protected override void WriteEncodedScalar(ref Writer writer, uint value) { writer.Write(String.Format(CultureInfo.InvariantCulture, "[U+{0:X4}]", value)); } } } }
using System; using System.Linq; using System.Security.Cryptography; using Microsoft.VisualStudio.TestTools.UnitTesting; using stellar_dotnet_sdk; using stellar_dotnet_sdk.responses; using stellar_dotnet_sdk.xdr; using Memo = stellar_dotnet_sdk.Memo; using TimeBounds = stellar_dotnet_sdk.TimeBounds; using Transaction = stellar_dotnet_sdk.Transaction; using XdrTransaction = stellar_dotnet_sdk.xdr.Transaction; namespace stellar_dotnet_sdk_test { [TestClass] public class TransactionTest { [TestInitialize] public void Initialize() { Network.UseTestNetwork(); } [TestCleanup] public void Cleanup() { Network.Use(null); } [TestMethod] public void TestBuilderSuccessTestnet() { // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var sequenceNumber = 2908908335136768L; var account = new Account(source.AccountId, sequenceNumber); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .Build(); transaction.Sign(source); Assert.AreEqual( "AAAAAF7FIiDToW1fOYUFBC0dmyufJbFTOa2GQESGz+S2h5ViAAAAZAAKVaMAAAABAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAAEqBfIAAAAAAAAAAABtoeVYgAAAEDLki9Oi700N60Lo8gUmEFHbKvYG4QSqXiLIt9T0ru2O5BphVl/jR9tYtHAD+UeDYhgXNgwUxqTEu1WukvEyYcD", transaction.ToEnvelopeXdrBase64()); Assert.AreEqual(transaction.SourceAccount.AccountId, source.AccountId); Assert.AreEqual(transaction.SequenceNumber, sequenceNumber + 1); Assert.AreEqual(transaction.Fee, 100); } [TestMethod] public void TestFromXdr() { var transaction = Transaction.FromEnvelopeXdr("AAAAAF7FIiDToW1fOYUFBC0dmyufJbFTOa2GQESGz+S2h5ViAAAAZAAKVaMAAAABAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAAEqBfIAAAAAAAAAAABtoeVYgAAAEDLki9Oi700N60Lo8gUmEFHbKvYG4QSqXiLIt9T0ru2O5BphVl/jR9tYtHAD+UeDYhgXNgwUxqTEu1WukvEyYcD"); var transaction2 = Transaction.FromEnvelopeXdr(transaction.ToEnvelopeXdr()); Assert.AreEqual(transaction.SourceAccount.AccountId, transaction2.SourceAccount.AccountId); Assert.AreEqual(transaction.SequenceNumber, transaction2.SequenceNumber); Assert.AreEqual(transaction.Fee, transaction2.Fee); Assert.AreEqual( ((CreateAccountOperation) transaction.Operations[0]).StartingBalance, ((CreateAccountOperation) transaction2.Operations[0]).StartingBalance ); CollectionAssert.AreEqual(transaction.Signatures, transaction2.Signatures); } [TestMethod] public void TestBuilderMemoText() { // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var account = new Account(source.AccountId, 2908908335136768); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .AddMemo(Memo.Text("Hello world!")) .Build(); transaction.Sign(source); Assert.AreEqual( "AAAAAF7FIiDToW1fOYUFBC0dmyufJbFTOa2GQESGz+S2h5ViAAAAZAAKVaMAAAABAAAAAAAAAAEAAAAMSGVsbG8gd29ybGQhAAAAAQAAAAAAAAAAAAAAAO3gUmG83C+VCqO6FztuMtXJF/l7grZA7MjRzqdZ9W8QAAAABKgXyAAAAAAAAAAAAbaHlWIAAABAxzofBhoayuUnz8t0T1UNWrTgmJ+lCh9KaeOGu2ppNOz9UGw0abGLhv+9oWQsstaHx6YjwWxL+8GBvwBUVWRlBQ==", transaction.ToEnvelopeXdrBase64()); var transaction2 = Transaction.FromEnvelopeXdr(transaction.ToEnvelopeXdr()); Assert.AreEqual(transaction.SourceAccount.AccountId, transaction2.SourceAccount.AccountId); Assert.AreEqual(transaction.SequenceNumber, transaction2.SequenceNumber); Assert.AreEqual(transaction.Memo, transaction2.Memo); Assert.AreEqual(transaction.Fee, transaction2.Fee); Assert.AreEqual( ((CreateAccountOperation) transaction.Operations[0]).StartingBalance, ((CreateAccountOperation) transaction2.Operations[0]).StartingBalance ); } [TestMethod] public void TestBuilderTimeBounds() { // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var account = new Account(source.AccountId, 2908908335136768L); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .AddTimeBounds(new TimeBounds(42, 1337)) .AddMemo(Memo.Hash("abcdef")) .Build(); transaction.Sign(source); // Convert transaction to binary XDR and back again to make sure timebounds are correctly de/serialized. var bytes = transaction.ToEnvelopeXdrBase64().ToCharArray(); var xdrDataInputStream = new XdrDataInputStream(Convert.FromBase64CharArray(bytes, 0, bytes.Length)); var decodedTransaction = XdrTransaction.Decode(xdrDataInputStream); Assert.AreEqual(decodedTransaction.TimeBounds.MinTime.InnerValue.InnerValue, 42); Assert.AreEqual(decodedTransaction.TimeBounds.MaxTime.InnerValue.InnerValue, 1337); var transaction2 = Transaction.FromEnvelopeXdr(transaction.ToEnvelopeXdr()); Assert.AreEqual(transaction.SourceAccount.AccountId, transaction2.SourceAccount.AccountId); Assert.AreEqual(transaction.SequenceNumber, transaction2.SequenceNumber); Assert.AreEqual(transaction.Memo, transaction2.Memo); Assert.AreEqual(transaction.TimeBounds, transaction2.TimeBounds); Assert.AreEqual(transaction.Fee, transaction2.Fee); Assert.AreEqual( ((CreateAccountOperation) transaction.Operations[0]).StartingBalance, ((CreateAccountOperation) transaction2.Operations[0]).StartingBalance ); } [TestMethod] public void TestBuilderFee() { // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var account = new Account(source.AccountId, 2908908335136768L); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .SetFee(173) .Build(); // Convert transaction to binary XDR and back again to make sure fee is correctly de/serialized. var bytes = transaction.ToUnsignedEnvelopeXdrBase64().ToCharArray(); var xdrDataInputStream = new XdrDataInputStream(Convert.FromBase64CharArray(bytes, 0, bytes.Length)); var decodedTransaction = XdrTransaction.Decode(xdrDataInputStream); Assert.AreEqual(decodedTransaction.Fee.InnerValue, 173 * 2); var transaction2 = Transaction.FromEnvelopeXdr(transaction.ToUnsignedEnvelopeXdr()); Assert.AreEqual(transaction.SourceAccount.AccountId, transaction2.SourceAccount.AccountId); Assert.AreEqual(transaction.SequenceNumber, transaction2.SequenceNumber); Assert.AreEqual(transaction.Memo, transaction2.Memo); Assert.AreEqual(transaction.TimeBounds, transaction2.TimeBounds); Assert.AreEqual(transaction.Fee, transaction2.Fee); Assert.AreEqual( ((CreateAccountOperation) transaction.Operations[0]).StartingBalance, ((CreateAccountOperation) transaction2.Operations[0]).StartingBalance ); Assert.AreEqual( ((CreateAccountOperation) transaction.Operations[1]).StartingBalance, ((CreateAccountOperation) transaction2.Operations[1]).StartingBalance ); } [TestMethod] public void TestBuilderSuccessPublic() { Network.UsePublicNetwork(); // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var account = new Account(source.AccountId, 2908908335136768L); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .Build(); transaction.Sign(source); Assert.AreEqual( "AAAAAF7FIiDToW1fOYUFBC0dmyufJbFTOa2GQESGz+S2h5ViAAAAZAAKVaMAAAABAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA7eBSYbzcL5UKo7oXO24y1ckX+XuCtkDsyNHOp1n1bxAAAAAEqBfIAAAAAAAAAAABtoeVYgAAAEDzfR5PgRFim5Wdvq9ImdZNWGBxBWwYkQPa9l5iiBdtPLzAZv6qj+iOfSrqinsoF0XrLkwdIcZQVtp3VRHhRoUE", transaction.ToEnvelopeXdrBase64()); } [TestMethod] public void TestSha256HashSigning() { Network.UsePublicNetwork(); var source = KeyPair.FromAccountId("GBBM6BKZPEHWYO3E3YKREDPQXMS4VK35YLNU7NFBRI26RAN7GI5POFBB"); var destination = KeyPair.FromAccountId("GDJJRRMBK4IWLEPJGIE6SXD2LP7REGZODU7WDC3I2D6MR37F4XSHBKX2"); var account = new Account(source.AccountId, 0L); var transaction = new Transaction.Builder(account) .AddOperation(new PaymentOperation.Builder(destination, new AssetTypeNative(), "2000").Build()) .Build(); var preimage = new byte[64]; var rngCsp = new RNGCryptoServiceProvider(); rngCsp.GetBytes(preimage); var hash = Util.Hash(preimage); transaction.Sign(preimage); Assert.IsTrue(transaction.Signatures[0].Signature.InnerValue.Equals(preimage)); var length = hash.Length; var rangeHashCopy = hash.Skip(length - 4).Take(4).ToArray(); Assert.IsTrue(transaction.Signatures[0].Hint.InnerValue.SequenceEqual(rangeHashCopy)); } [TestMethod] public void TestToBase64EnvelopeXdrBuilderNoSignatures() { // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var account = new Account(source.AccountId, 2908908335136768L); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .Build(); try { transaction.ToEnvelopeXdrBase64(); Assert.Fail(); } catch (Exception exception) { Assert.IsTrue(exception.Message.Contains("Transaction must be signed by at least one signer.")); } } [TestMethod] public void TestToUnsignedEnvelopeXdr() { // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var account = new Account(source.AccountId, 2908908335136768L); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .Build(); try { transaction.ToUnsignedEnvelopeXdr(); } catch (Exception exception) { Assert.Fail("Expected no exception, but got: " + exception.Message); } } [TestMethod] public void TestToUnsignedEnvelopeXdrBase64() { // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var account = new Account(source.AccountId, 2908908335136768L); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .Build(); try { transaction.ToUnsignedEnvelopeXdrBase64(); } catch (Exception exception) { Assert.Fail("Expected no exception, but got: " + exception.Message); } } [TestMethod] public void TestNoOperations() { // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var account = new Account(source.AccountId, 2908908335136768L); try { var unused = new Transaction.Builder(account).Build(); Assert.Fail(); } catch (Exception exception) { Assert.IsTrue(exception.Message.Contains("At least one operation required")); Assert.AreEqual(2908908335136768L, account.SequenceNumber); } } [TestMethod] public void TestTryingToAddMemoTwice() { // GBPMKIRA2OQW2XZZQUCQILI5TMVZ6JNRKM423BSAISDM7ZFWQ6KWEBC4 var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); try { var account = new Account(source.AccountId, 2908908335136768L); new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .AddMemo(Memo.None()) .AddMemo(Memo.None()); Assert.Fail(); } catch (Exception exception) { Assert.IsTrue(exception.Message.Contains("Memo has been already added.")); } } [TestMethod] public void TestExplicitNetworkArgument() { var source = KeyPair.FromSecretSeed("SCH27VUZZ6UAKB67BDNF6FA42YMBMQCBKXWGMFD5TZ6S5ZZCZFLRXKHS"); var destination = KeyPair.FromAccountId("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR"); var sequenceNumber = 2908908335136768L; var account = new Account(source.AccountId, sequenceNumber); var transaction = new Transaction.Builder(account) .AddOperation(new CreateAccountOperation.Builder(destination, "2000").Build()) .Build(); Network.UsePublicNetwork(); var publicNetworkHash = transaction.Hash(); Network.UseTestNetwork(); var testNetworkHash = transaction.Hash(); Assert.IsFalse(testNetworkHash.SequenceEqual(publicNetworkHash)); var network = Network.Public(); var explicitPublicNetworkHash = transaction.Hash(network); Assert.IsTrue(publicNetworkHash.SequenceEqual(explicitPublicNetworkHash)); } [TestMethod] public void TestFromAccountResponse() { var response = new AccountResponse("GDW6AUTBXTOC7FIKUO5BOO3OGLK4SF7ZPOBLMQHMZDI45J2Z6VXRB5NR", 123); var transaction = new Transaction.Builder(response) .AddOperation(new CreateAccountOperation.Builder(response.KeyPair, "2000").Build()) .Build(); Assert.IsNotNull(transaction); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; using System.Runtime.Versioning; namespace System.Xml { // Specifies formatting options for XmlTextWriter. public enum Formatting { // No special formatting is done (this is the default). None, //This option causes child elements to be indented using the Indentation and IndentChar properties. // It only indents Element Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-element-content) // and not Mixed Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-mixed-content) // according to the XML 1.0 definitions of these terms. Indented, }; // Represents a writer that provides fast non-cached forward-only way of generating XML streams // containing XML documents that conform to the W3CExtensible Markup Language (XML) 1.0 specification // and the Namespaces in XML specification. [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class XmlTextWriter : XmlWriter { // // Private types // private enum NamespaceState { Uninitialized, NotDeclaredButInScope, DeclaredButNotWrittenOut, DeclaredAndWrittenOut } private struct TagInfo { internal string name; internal string prefix; internal string defaultNs; internal NamespaceState defaultNsState; internal XmlSpace xmlSpace; internal string xmlLang; internal int prevNsTop; internal int prefixCount; internal bool mixed; // whether to pretty print the contents of this element. internal void Init(int nsTop) { name = null; defaultNs = String.Empty; defaultNsState = NamespaceState.Uninitialized; xmlSpace = XmlSpace.None; xmlLang = null; prevNsTop = nsTop; prefixCount = 0; mixed = false; } } private struct Namespace { internal string prefix; internal string ns; internal bool declared; internal int prevNsIndex; internal void Set(string prefix, string ns, bool declared) { this.prefix = prefix; this.ns = ns; this.declared = declared; this.prevNsIndex = -1; } } private enum SpecialAttr { None, XmlSpace, XmlLang, XmlNs }; // State machine is working through autocomplete private enum State { Start, Prolog, PostDTD, Element, Attribute, Content, AttrOnly, Epilog, Error, Closed, } private enum Token { PI, Doctype, Comment, CData, StartElement, EndElement, LongEndElement, StartAttribute, EndAttribute, Content, Base64, RawData, Whitespace, Empty } // // Fields // // output private TextWriter _textWriter; private XmlTextEncoder _xmlEncoder; private Encoding _encoding; // formatting private Formatting _formatting; private bool _indented; // perf - faster to check a boolean. private int _indentation; private char _indentChar; // element stack private TagInfo[] _stack; private int _top; // state machine for AutoComplete private State[] _stateTable; private State _currentState; private Token _lastToken; // Base64 content private XmlTextWriterBase64Encoder _base64Encoder; // misc private char _quoteChar; private char _curQuoteChar; private bool _namespaces; private SpecialAttr _specialAttr; private string _prefixForXmlNs; private bool _flush; // namespaces private Namespace[] _nsStack; private int _nsTop; private Dictionary<string, int> _nsHashtable; private bool _useNsHashtable; // char types private XmlCharType _xmlCharType = XmlCharType.Instance; // // Constants and constant tables // private const int NamespaceStackInitialSize = 8; #if DEBUG private const int MaxNamespacesWalkCount = 3; #else private const int MaxNamespacesWalkCount = 16; #endif private static string[] s_stateName = { "Start", "Prolog", "PostDTD", "Element", "Attribute", "Content", "AttrOnly", "Epilog", "Error", "Closed", }; private static string[] s_tokenName = { "PI", "Doctype", "Comment", "CData", "StartElement", "EndElement", "LongEndElement", "StartAttribute", "EndAttribute", "Content", "Base64", "RawData", "Whitespace", "Empty" }; private static readonly State[] s_stateTableDefault = { // State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog // /* Token.PI */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.Doctype */ State.PostDTD, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, /* Token.Comment */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.CData */ State.Content, State.Content, State.Error, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.StartElement */ State.Element, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Element, /* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.StartAttribute */ State.AttrOnly, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error, /* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Epilog, State.Error, /* Token.Content */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog, /* Token.Base64 */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog, /* Token.RawData */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog, /* Token.Whitespace */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog, }; private static readonly State[] s_stateTableDocument = { // State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog // /* Token.PI */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.Doctype */ State.Error, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, /* Token.Comment */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog, /* Token.CData */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.StartElement */ State.Error, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Error, /* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error, /* Token.StartAttribute */ State.Error, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error, /* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Error, State.Error, /* Token.Content */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error, /* Token.Base64 */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error, /* Token.RawData */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog, /* Token.Whitespace */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog, }; // // Constructors // internal XmlTextWriter() { _namespaces = true; _formatting = Formatting.None; _indentation = 2; _indentChar = ' '; // namespaces _nsStack = new Namespace[NamespaceStackInitialSize]; _nsTop = -1; // element stack _stack = new TagInfo[10]; _top = 0;// 0 is an empty sentanial element _stack[_top].Init(-1); _quoteChar = '"'; _stateTable = s_stateTableDefault; _currentState = State.Start; _lastToken = Token.Empty; } // Creates an instance of the XmlTextWriter class using the specified stream. public XmlTextWriter(Stream w, Encoding encoding) : this() { _encoding = encoding; if (encoding != null) _textWriter = new StreamWriter(w, encoding); else _textWriter = new StreamWriter(w); _xmlEncoder = new XmlTextEncoder(_textWriter); _xmlEncoder.QuoteChar = _quoteChar; } // Creates an instance of the XmlTextWriter class using the specified file. public XmlTextWriter(String filename, Encoding encoding) : this(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read), encoding) { } // Creates an instance of the XmlTextWriter class using the specified TextWriter. public XmlTextWriter(TextWriter w) : this() { _textWriter = w; _encoding = w.Encoding; _xmlEncoder = new XmlTextEncoder(w); _xmlEncoder.QuoteChar = _quoteChar; } // // XmlTextWriter properties // // Gets the XmlTextWriter base stream. public Stream BaseStream { get { StreamWriter streamWriter = _textWriter as StreamWriter; return (streamWriter == null ? null : streamWriter.BaseStream); } } // Gets or sets a value indicating whether to do namespace support. public bool Namespaces { get { return _namespaces; } set { if (_currentState != State.Start) throw new InvalidOperationException(SR.Xml_NotInWriteState); _namespaces = value; } } // Indicates how the output is formatted. public Formatting Formatting { get { return _formatting; } set { _formatting = value; _indented = value == Formatting.Indented; } } // Gets or sets how many IndentChars to write for each level in the hierarchy when Formatting is set to "Indented". public int Indentation { get { return _indentation; } set { if (value < 0) throw new ArgumentException(SR.Xml_InvalidIndentation); _indentation = value; } } // Gets or sets which character to use for indenting when Formatting is set to "Indented". public char IndentChar { get { return _indentChar; } set { _indentChar = value; } } // Gets or sets which character to use to quote attribute values. public char QuoteChar { get { return _quoteChar; } set { if (value != '"' && value != '\'') { throw new ArgumentException(SR.Xml_InvalidQuote); } _quoteChar = value; _xmlEncoder.QuoteChar = value; } } // // XmlWriter implementation // // Writes out the XML declaration with the version "1.0". public override void WriteStartDocument() { StartDocument(-1); } // Writes out the XML declaration with the version "1.0" and the standalone attribute. public override void WriteStartDocument(bool standalone) { StartDocument(standalone ? 1 : 0); } // Closes any open elements or attributes and puts the writer back in the Start state. public override void WriteEndDocument() { try { AutoCompleteAll(); if (_currentState != State.Epilog) { if (_currentState == State.Closed) { throw new ArgumentException(SR.Xml_ClosedOrError); } else { throw new ArgumentException(SR.Xml_NoRoot); } } _stateTable = s_stateTableDefault; _currentState = State.Start; _lastToken = Token.Empty; } catch { _currentState = State.Error; throw; } } // Writes out the DOCTYPE declaration with the specified name and optional attributes. public override void WriteDocType(string name, string pubid, string sysid, string subset) { try { ValidateName(name, false); AutoComplete(Token.Doctype); _textWriter.Write("<!DOCTYPE "); _textWriter.Write(name); if (pubid != null) { _textWriter.Write(" PUBLIC " + _quoteChar); _textWriter.Write(pubid); _textWriter.Write(_quoteChar + " " + _quoteChar); _textWriter.Write(sysid); _textWriter.Write(_quoteChar); } else if (sysid != null) { _textWriter.Write(" SYSTEM " + _quoteChar); _textWriter.Write(sysid); _textWriter.Write(_quoteChar); } if (subset != null) { _textWriter.Write("["); _textWriter.Write(subset); _textWriter.Write("]"); } _textWriter.Write('>'); } catch { _currentState = State.Error; throw; } } // Writes out the specified start tag and associates it with the given namespace and prefix. public override void WriteStartElement(string prefix, string localName, string ns) { try { AutoComplete(Token.StartElement); PushStack(); _textWriter.Write('<'); if (_namespaces) { // Propagate default namespace and mix model down the stack. _stack[_top].defaultNs = _stack[_top - 1].defaultNs; if (_stack[_top - 1].defaultNsState != NamespaceState.Uninitialized) _stack[_top].defaultNsState = NamespaceState.NotDeclaredButInScope; _stack[_top].mixed = _stack[_top - 1].mixed; if (ns == null) { // use defined prefix if (prefix != null && prefix.Length != 0 && (LookupNamespace(prefix) == -1)) { throw new ArgumentException(SR.Xml_UndefPrefix); } } else { if (prefix == null) { string definedPrefix = FindPrefix(ns); if (definedPrefix != null) { prefix = definedPrefix; } else { PushNamespace(null, ns, false); // new default } } else if (prefix.Length == 0) { PushNamespace(null, ns, false); // new default } else { if (ns.Length == 0) { prefix = null; } VerifyPrefixXml(prefix, ns); PushNamespace(prefix, ns, false); // define } } _stack[_top].prefix = null; if (prefix != null && prefix.Length != 0) { _stack[_top].prefix = prefix; _textWriter.Write(prefix); _textWriter.Write(':'); } } else { if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0)) { throw new ArgumentException(SR.Xml_NoNamespaces); } } _stack[_top].name = localName; _textWriter.Write(localName); } catch { _currentState = State.Error; throw; } } // Closes one element and pops the corresponding namespace scope. public override void WriteEndElement() { InternalWriteEndElement(false); } // Closes one element and pops the corresponding namespace scope. public override void WriteFullEndElement() { InternalWriteEndElement(true); } // Writes the start of an attribute. public override void WriteStartAttribute(string prefix, string localName, string ns) { try { AutoComplete(Token.StartAttribute); _specialAttr = SpecialAttr.None; if (_namespaces) { if (prefix != null && prefix.Length == 0) { prefix = null; } if (ns == XmlReservedNs.NsXmlNs && prefix == null && localName != "xmlns") { prefix = "xmlns"; } if (prefix == "xml") { if (localName == "lang") { _specialAttr = SpecialAttr.XmlLang; } else if (localName == "space") { _specialAttr = SpecialAttr.XmlSpace; } /* bug54408. to be fwd compatible we need to treat xml prefix as reserved and not really insist on a specific value. Who knows in the future it might be OK to say xml:blabla else { throw new ArgumentException(SR.Xml_InvalidPrefix); }*/ } else if (prefix == "xmlns") { if (XmlReservedNs.NsXmlNs != ns && ns != null) { throw new ArgumentException(SR.Xml_XmlnsBelongsToReservedNs); } if (localName == null || localName.Length == 0) { localName = prefix; prefix = null; _prefixForXmlNs = null; } else { _prefixForXmlNs = localName; } _specialAttr = SpecialAttr.XmlNs; } else if (prefix == null && localName == "xmlns") { if (XmlReservedNs.NsXmlNs != ns && ns != null) { // add the below line back in when DOM is fixed throw new ArgumentException(SR.Xml_XmlnsBelongsToReservedNs); } _specialAttr = SpecialAttr.XmlNs; _prefixForXmlNs = null; } else { if (ns == null) { // use defined prefix if (prefix != null && (LookupNamespace(prefix) == -1)) { throw new ArgumentException(SR.Xml_UndefPrefix); } } else if (ns.Length == 0) { // empty namespace require null prefix prefix = string.Empty; } else { // ns.Length != 0 VerifyPrefixXml(prefix, ns); if (prefix != null && LookupNamespaceInCurrentScope(prefix) != -1) { prefix = null; } // Now verify prefix validity string definedPrefix = FindPrefix(ns); if (definedPrefix != null && (prefix == null || prefix == definedPrefix)) { prefix = definedPrefix; } else { if (prefix == null) { prefix = GeneratePrefix(); // need a prefix if } PushNamespace(prefix, ns, false); } } } if (prefix != null && prefix.Length != 0) { _textWriter.Write(prefix); _textWriter.Write(':'); } } else { if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0)) { throw new ArgumentException(SR.Xml_NoNamespaces); } if (localName == "xml:lang") { _specialAttr = SpecialAttr.XmlLang; } else if (localName == "xml:space") { _specialAttr = SpecialAttr.XmlSpace; } } _xmlEncoder.StartAttribute(_specialAttr != SpecialAttr.None); _textWriter.Write(localName); _textWriter.Write('='); if (_curQuoteChar != _quoteChar) { _curQuoteChar = _quoteChar; _xmlEncoder.QuoteChar = _quoteChar; } _textWriter.Write(_curQuoteChar); } catch { _currentState = State.Error; throw; } } // Closes the attribute opened by WriteStartAttribute. public override void WriteEndAttribute() { try { AutoComplete(Token.EndAttribute); } catch { _currentState = State.Error; throw; } } // Writes out a &lt;![CDATA[...]]&gt; block containing the specified text. public override void WriteCData(string text) { try { AutoComplete(Token.CData); if (null != text && text.IndexOf("]]>", StringComparison.Ordinal) >= 0) { throw new ArgumentException(SR.Xml_InvalidCDataChars); } _textWriter.Write("<![CDATA["); if (null != text) { _xmlEncoder.WriteRawWithSurrogateChecking(text); } _textWriter.Write("]]>"); } catch { _currentState = State.Error; throw; } } // Writes out a comment <!--...--> containing the specified text. public override void WriteComment(string text) { try { if (null != text && (text.IndexOf("--", StringComparison.Ordinal) >= 0 || (text.Length != 0 && text[text.Length - 1] == '-'))) { throw new ArgumentException(SR.Xml_InvalidCommentChars); } AutoComplete(Token.Comment); _textWriter.Write("<!--"); if (null != text) { _xmlEncoder.WriteRawWithSurrogateChecking(text); } _textWriter.Write("-->"); } catch { _currentState = State.Error; throw; } } // Writes out a processing instruction with a space between the name and text as follows: <?name text?> public override void WriteProcessingInstruction(string name, string text) { try { if (null != text && text.IndexOf("?>", StringComparison.Ordinal) >= 0) { throw new ArgumentException(SR.Xml_InvalidPiChars); } if (0 == String.Compare(name, "xml", StringComparison.OrdinalIgnoreCase) && _stateTable == s_stateTableDocument) { throw new ArgumentException(SR.Xml_DupXmlDecl); } AutoComplete(Token.PI); InternalWriteProcessingInstruction(name, text); } catch { _currentState = State.Error; throw; } } // Writes out an entity reference as follows: "&"+name+";". public override void WriteEntityRef(string name) { try { ValidateName(name, false); AutoComplete(Token.Content); _xmlEncoder.WriteEntityRef(name); } catch { _currentState = State.Error; throw; } } // Forces the generation of a character entity for the specified Unicode character value. public override void WriteCharEntity(char ch) { try { AutoComplete(Token.Content); _xmlEncoder.WriteCharEntity(ch); } catch { _currentState = State.Error; throw; } } // Writes out the given whitespace. public override void WriteWhitespace(string ws) { try { if (null == ws) { ws = String.Empty; } if (!_xmlCharType.IsOnlyWhitespace(ws)) { throw new ArgumentException(SR.Xml_NonWhitespace); } AutoComplete(Token.Whitespace); _xmlEncoder.Write(ws); } catch { _currentState = State.Error; throw; } } // Writes out the specified text content. public override void WriteString(string text) { try { if (null != text && text.Length != 0) { AutoComplete(Token.Content); _xmlEncoder.Write(text); } } catch { _currentState = State.Error; throw; } } // Writes out the specified surrogate pair as a character entity. public override void WriteSurrogateCharEntity(char lowChar, char highChar) { try { AutoComplete(Token.Content); _xmlEncoder.WriteSurrogateCharEntity(lowChar, highChar); } catch { _currentState = State.Error; throw; } } // Writes out the specified text content. public override void WriteChars(Char[] buffer, int index, int count) { try { AutoComplete(Token.Content); _xmlEncoder.Write(buffer, index, count); } catch { _currentState = State.Error; throw; } } // Writes raw markup from the specified character buffer. public override void WriteRaw(Char[] buffer, int index, int count) { try { AutoComplete(Token.RawData); _xmlEncoder.WriteRaw(buffer, index, count); } catch { _currentState = State.Error; throw; } } // Writes raw markup from the specified character string. public override void WriteRaw(String data) { try { AutoComplete(Token.RawData); _xmlEncoder.WriteRawWithSurrogateChecking(data); } catch { _currentState = State.Error; throw; } } // Encodes the specified binary bytes as base64 and writes out the resulting text. public override void WriteBase64(byte[] buffer, int index, int count) { try { if (!_flush) { AutoComplete(Token.Base64); } _flush = true; // No need for us to explicitly validate the args. The StreamWriter will do // it for us. if (null == _base64Encoder) { _base64Encoder = new XmlTextWriterBase64Encoder(_xmlEncoder); } // Encode will call WriteRaw to write out the encoded characters _base64Encoder.Encode(buffer, index, count); } catch { _currentState = State.Error; throw; } } // Encodes the specified binary bytes as binhex and writes out the resulting text. public override void WriteBinHex(byte[] buffer, int index, int count) { try { AutoComplete(Token.Content); BinHexEncoder.Encode(buffer, index, count, this); } catch { _currentState = State.Error; throw; } } // Returns the state of the XmlWriter. public override WriteState WriteState { get { switch (_currentState) { case State.Start: return WriteState.Start; case State.Prolog: case State.PostDTD: return WriteState.Prolog; case State.Element: return WriteState.Element; case State.Attribute: case State.AttrOnly: return WriteState.Attribute; case State.Content: case State.Epilog: return WriteState.Content; case State.Error: return WriteState.Error; case State.Closed: return WriteState.Closed; default: Debug.Assert(false); return WriteState.Error; } } } // Closes the XmlWriter and the underlying stream/TextWriter. public override void Close() { try { AutoCompleteAll(); } catch { // never fail } finally { _currentState = State.Closed; _textWriter.Dispose(); } } // Flushes whatever is in the buffer to the underlying stream/TextWriter and flushes the underlying stream/TextWriter. public override void Flush() { _textWriter.Flush(); } // Writes out the specified name, ensuring it is a valid Name according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name public override void WriteName(string name) { try { AutoComplete(Token.Content); InternalWriteName(name, false); } catch { _currentState = State.Error; throw; } } // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace. public override void WriteQualifiedName(string localName, string ns) { try { AutoComplete(Token.Content); if (_namespaces) { if (ns != null && ns.Length != 0 && ns != _stack[_top].defaultNs) { string prefix = FindPrefix(ns); if (prefix == null) { if (_currentState != State.Attribute) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } prefix = GeneratePrefix(); // need a prefix if PushNamespace(prefix, ns, false); } if (prefix.Length != 0) { InternalWriteName(prefix, true); _textWriter.Write(':'); } } } else if (ns != null && ns.Length != 0) { throw new ArgumentException(SR.Xml_NoNamespaces); } InternalWriteName(localName, true); } catch { _currentState = State.Error; throw; } } // Returns the closest prefix defined in the current namespace scope for the specified namespace URI. public override string LookupPrefix(string ns) { if (ns == null || ns.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } string s = FindPrefix(ns); if (s == null && ns == _stack[_top].defaultNs) { s = string.Empty; } return s; } // Gets an XmlSpace representing the current xml:space scope. public override XmlSpace XmlSpace { get { for (int i = _top; i > 0; i--) { XmlSpace xs = _stack[i].xmlSpace; if (xs != XmlSpace.None) return xs; } return XmlSpace.None; } } // Gets the current xml:lang scope. public override string XmlLang { get { for (int i = _top; i > 0; i--) { String xlang = _stack[i].xmlLang; if (xlang != null) return xlang; } return null; } } // Writes out the specified name, ensuring it is a valid NmToken // according to the XML specification (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public override void WriteNmToken(string name) { try { AutoComplete(Token.Content); if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } if (!ValidateNames.IsNmtokenNoNamespaces(name)) { throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name)); } _textWriter.Write(name); } catch { _currentState = State.Error; throw; } } // // Private implementation methods // private void StartDocument(int standalone) { try { if (_currentState != State.Start) { throw new InvalidOperationException(SR.Xml_NotTheFirst); } _stateTable = s_stateTableDocument; _currentState = State.Prolog; StringBuilder bufBld = new StringBuilder(128); bufBld.Append("version=" + _quoteChar + "1.0" + _quoteChar); if (_encoding != null) { bufBld.Append(" encoding="); bufBld.Append(_quoteChar); bufBld.Append(_encoding.WebName); bufBld.Append(_quoteChar); } if (standalone >= 0) { bufBld.Append(" standalone="); bufBld.Append(_quoteChar); bufBld.Append(standalone == 0 ? "no" : "yes"); bufBld.Append(_quoteChar); } InternalWriteProcessingInstruction("xml", bufBld.ToString()); } catch { _currentState = State.Error; throw; } } private void AutoComplete(Token token) { if (_currentState == State.Closed) { throw new InvalidOperationException(SR.Xml_Closed); } else if (_currentState == State.Error) { throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, s_tokenName[(int)token], s_stateName[(int)State.Error])); } State newState = _stateTable[(int)token * 8 + (int)_currentState]; if (newState == State.Error) { throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, s_tokenName[(int)token], s_stateName[(int)_currentState])); } switch (token) { case Token.Doctype: if (_indented && _currentState != State.Start) { Indent(false); } break; case Token.StartElement: case Token.Comment: case Token.PI: case Token.CData: if (_currentState == State.Attribute) { WriteEndAttributeQuote(); WriteEndStartTag(false); } else if (_currentState == State.Element) { WriteEndStartTag(false); } if (token == Token.CData) { _stack[_top].mixed = true; } else if (_indented && _currentState != State.Start) { Indent(false); } break; case Token.EndElement: case Token.LongEndElement: if (_flush) { FlushEncoders(); } if (_currentState == State.Attribute) { WriteEndAttributeQuote(); } if (_currentState == State.Content) { token = Token.LongEndElement; } else { WriteEndStartTag(token == Token.EndElement); } if (s_stateTableDocument == _stateTable && _top == 1) { newState = State.Epilog; } break; case Token.StartAttribute: if (_flush) { FlushEncoders(); } if (_currentState == State.Attribute) { WriteEndAttributeQuote(); _textWriter.Write(' '); } else if (_currentState == State.Element) { _textWriter.Write(' '); } break; case Token.EndAttribute: if (_flush) { FlushEncoders(); } WriteEndAttributeQuote(); break; case Token.Whitespace: case Token.Content: case Token.RawData: case Token.Base64: if (token != Token.Base64 && _flush) { FlushEncoders(); } if (_currentState == State.Element && _lastToken != Token.Content) { WriteEndStartTag(false); } if (newState == State.Content) { _stack[_top].mixed = true; } break; default: throw new InvalidOperationException(SR.Xml_InvalidOperation); } _currentState = newState; _lastToken = token; } private void AutoCompleteAll() { if (_flush) { FlushEncoders(); } while (_top > 0) { WriteEndElement(); } } private void InternalWriteEndElement(bool longFormat) { try { if (_top <= 0) { throw new InvalidOperationException(SR.Xml_NoStartTag); } // if we are in the element, we need to close it. AutoComplete(longFormat ? Token.LongEndElement : Token.EndElement); if (_lastToken == Token.LongEndElement) { if (_indented) { Indent(true); } _textWriter.Write('<'); _textWriter.Write('/'); if (_namespaces && _stack[_top].prefix != null) { _textWriter.Write(_stack[_top].prefix); _textWriter.Write(':'); } _textWriter.Write(_stack[_top].name); _textWriter.Write('>'); } // pop namespaces int prevNsTop = _stack[_top].prevNsTop; if (_useNsHashtable && prevNsTop < _nsTop) { PopNamespaces(prevNsTop + 1, _nsTop); } _nsTop = prevNsTop; _top--; } catch { _currentState = State.Error; throw; } } private void WriteEndStartTag(bool empty) { _xmlEncoder.StartAttribute(false); for (int i = _nsTop; i > _stack[_top].prevNsTop; i--) { if (!_nsStack[i].declared) { _textWriter.Write(" xmlns"); _textWriter.Write(':'); _textWriter.Write(_nsStack[i].prefix); _textWriter.Write('='); _textWriter.Write(_quoteChar); _xmlEncoder.Write(_nsStack[i].ns); _textWriter.Write(_quoteChar); } } // Default if ((_stack[_top].defaultNs != _stack[_top - 1].defaultNs) && (_stack[_top].defaultNsState == NamespaceState.DeclaredButNotWrittenOut)) { _textWriter.Write(" xmlns"); _textWriter.Write('='); _textWriter.Write(_quoteChar); _xmlEncoder.Write(_stack[_top].defaultNs); _textWriter.Write(_quoteChar); _stack[_top].defaultNsState = NamespaceState.DeclaredAndWrittenOut; } _xmlEncoder.EndAttribute(); if (empty) { _textWriter.Write(" /"); } _textWriter.Write('>'); } private void WriteEndAttributeQuote() { if (_specialAttr != SpecialAttr.None) { // Ok, now to handle xmlspace, etc. HandleSpecialAttribute(); } _xmlEncoder.EndAttribute(); _textWriter.Write(_curQuoteChar); } private void Indent(bool beforeEndElement) { // pretty printing. if (_top == 0) { _textWriter.WriteLine(); } else if (!_stack[_top].mixed) { _textWriter.WriteLine(); int i = beforeEndElement ? _top - 1 : _top; for (i *= _indentation; i > 0; i--) { _textWriter.Write(_indentChar); } } } // pushes new namespace scope, and returns generated prefix, if one // was needed to resolve conflicts. private void PushNamespace(string prefix, string ns, bool declared) { if (XmlReservedNs.NsXmlNs == ns) { throw new ArgumentException(SR.Xml_CanNotBindToReservedNamespace); } if (prefix == null) { switch (_stack[_top].defaultNsState) { case NamespaceState.DeclaredButNotWrittenOut: Debug.Assert(declared == true, "Unexpected situation!!"); // the first namespace that the user gave us is what we // like to keep. break; case NamespaceState.Uninitialized: case NamespaceState.NotDeclaredButInScope: // we now got a brand new namespace that we need to remember _stack[_top].defaultNs = ns; break; default: Debug.Assert(false, "Should have never come here"); return; } _stack[_top].defaultNsState = (declared ? NamespaceState.DeclaredAndWrittenOut : NamespaceState.DeclaredButNotWrittenOut); } else { if (prefix.Length != 0 && ns.Length == 0) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); } int existingNsIndex = LookupNamespace(prefix); if (existingNsIndex != -1 && _nsStack[existingNsIndex].ns == ns) { // it is already in scope. if (declared) { _nsStack[existingNsIndex].declared = true; } } else { // see if prefix conflicts for the current element if (declared) { if (existingNsIndex != -1 && existingNsIndex > _stack[_top].prevNsTop) { _nsStack[existingNsIndex].declared = true; // old one is silenced now } } AddNamespace(prefix, ns, declared); } } } private void AddNamespace(string prefix, string ns, bool declared) { int nsIndex = ++_nsTop; if (nsIndex == _nsStack.Length) { Namespace[] newStack = new Namespace[nsIndex * 2]; Array.Copy(_nsStack, newStack, nsIndex); _nsStack = newStack; } _nsStack[nsIndex].Set(prefix, ns, declared); if (_useNsHashtable) { AddToNamespaceHashtable(nsIndex); } else if (nsIndex == MaxNamespacesWalkCount) { // add all _nsHashtable = new Dictionary<string, int>(new SecureStringHasher()); for (int i = 0; i <= nsIndex; i++) { AddToNamespaceHashtable(i); } _useNsHashtable = true; } } private void AddToNamespaceHashtable(int namespaceIndex) { string prefix = _nsStack[namespaceIndex].prefix; int existingNsIndex; if (_nsHashtable.TryGetValue(prefix, out existingNsIndex)) { _nsStack[namespaceIndex].prevNsIndex = existingNsIndex; } _nsHashtable[prefix] = namespaceIndex; } private void PopNamespaces(int indexFrom, int indexTo) { Debug.Assert(_useNsHashtable); for (int i = indexTo; i >= indexFrom; i--) { Debug.Assert(_nsHashtable.ContainsKey(_nsStack[i].prefix)); if (_nsStack[i].prevNsIndex == -1) { _nsHashtable.Remove(_nsStack[i].prefix); } else { _nsHashtable[_nsStack[i].prefix] = _nsStack[i].prevNsIndex; } } } private string GeneratePrefix() { int temp = _stack[_top].prefixCount++ + 1; return "d" + _top.ToString("d", CultureInfo.InvariantCulture) + "p" + temp.ToString("d", CultureInfo.InvariantCulture); } private void InternalWriteProcessingInstruction(string name, string text) { _textWriter.Write("<?"); ValidateName(name, false); _textWriter.Write(name); _textWriter.Write(' '); if (null != text) { _xmlEncoder.WriteRawWithSurrogateChecking(text); } _textWriter.Write("?>"); } private int LookupNamespace(string prefix) { if (_useNsHashtable) { int nsIndex; if (_nsHashtable.TryGetValue(prefix, out nsIndex)) { return nsIndex; } } else { for (int i = _nsTop; i >= 0; i--) { if (_nsStack[i].prefix == prefix) { return i; } } } return -1; } private int LookupNamespaceInCurrentScope(string prefix) { if (_useNsHashtable) { int nsIndex; if (_nsHashtable.TryGetValue(prefix, out nsIndex)) { if (nsIndex > _stack[_top].prevNsTop) { return nsIndex; } } } else { for (int i = _nsTop; i > _stack[_top].prevNsTop; i--) { if (_nsStack[i].prefix == prefix) { return i; } } } return -1; } private string FindPrefix(string ns) { for (int i = _nsTop; i >= 0; i--) { if (_nsStack[i].ns == ns) { if (LookupNamespace(_nsStack[i].prefix) == i) { return _nsStack[i].prefix; } } } return null; } // There are three kind of strings we write out - Name, LocalName and Prefix. // Both LocalName and Prefix can be represented with NCName == false and Name // can be represented as NCName == true private void InternalWriteName(string name, bool isNCName) { ValidateName(name, isNCName); _textWriter.Write(name); } // This method is used for validation of the DOCTYPE, processing instruction and entity names plus names // written out by the user via WriteName and WriteQualifiedName. // Unfortunatelly the names of elements and attributes are not validated by the XmlTextWriter. // Also this method does not check wheather the character after ':' is a valid start name character. It accepts // all valid name characters at that position. This can't be changed because of backwards compatibility. private unsafe void ValidateName(string name, bool isNCName) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } int nameLength = name.Length; // Namespaces supported if (_namespaces) { // We can't use ValidateNames.ParseQName here because of backwards compatibility bug we need to preserve. // The bug is that the character after ':' is validated only as a NCName characters instead of NCStartName. int colonPosition = -1; // Parse NCName (may be prefix, may be local name) int position = ValidateNames.ParseNCName(name); Continue: if (position == nameLength) { return; } // we have prefix:localName if (name[position] == ':') { if (!isNCName) { // first colon in qname if (colonPosition == -1) { // make sure it is not the first or last characters if (position > 0 && position + 1 < nameLength) { colonPosition = position; // Because of the back-compat bug (described above) parse the rest as Nmtoken position++; position += ValidateNames.ParseNmtoken(name, position); goto Continue; } } } } } // Namespaces not supported else { if (ValidateNames.IsNameNoNamespaces(name)) { return; } } throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name)); } private void HandleSpecialAttribute() { string value = _xmlEncoder.AttributeValue; switch (_specialAttr) { case SpecialAttr.XmlLang: _stack[_top].xmlLang = value; break; case SpecialAttr.XmlSpace: // validate XmlSpace attribute value = XmlConvert.TrimString(value); if (value == "default") { _stack[_top].xmlSpace = XmlSpace.Default; } else if (value == "preserve") { _stack[_top].xmlSpace = XmlSpace.Preserve; } else { throw new ArgumentException(SR.Format(SR.Xml_InvalidXmlSpace, value)); } break; case SpecialAttr.XmlNs: VerifyPrefixXml(_prefixForXmlNs, value); PushNamespace(_prefixForXmlNs, value, true); break; } } private void VerifyPrefixXml(string prefix, string ns) { if (prefix != null && prefix.Length == 3) { if ( (prefix[0] == 'x' || prefix[0] == 'X') && (prefix[1] == 'm' || prefix[1] == 'M') && (prefix[2] == 'l' || prefix[2] == 'L') ) { if (XmlReservedNs.NsXml != ns) { throw new ArgumentException(SR.Xml_InvalidPrefix); } } } } private void PushStack() { if (_top == _stack.Length - 1) { TagInfo[] na = new TagInfo[_stack.Length + 10]; if (_top > 0) Array.Copy(_stack, na, _top + 1); _stack = na; } _top++; // Move up stack _stack[_top].Init(_nsTop); } private void FlushEncoders() { if (null != _base64Encoder) { // The Flush will call WriteRaw to write out the rest of the encoded characters _base64Encoder.Flush(); } _flush = false; } } }
namespace java.security.cert { [global::MonoJavaBridge.JavaClass(typeof(global::java.security.cert.X509Certificate_))] public abstract partial class X509Certificate : java.security.cert.Certificate, X509Extension { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static X509Certificate() { InitJNI(); } protected X509Certificate(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _hasUnsupportedCriticalExtension14972; public abstract bool hasUnsupportedCriticalExtension(); internal static global::MonoJavaBridge.MethodId _getCriticalExtensionOIDs14973; public abstract global::java.util.Set getCriticalExtensionOIDs(); internal static global::MonoJavaBridge.MethodId _getNonCriticalExtensionOIDs14974; public abstract global::java.util.Set getNonCriticalExtensionOIDs(); internal static global::MonoJavaBridge.MethodId _getExtensionValue14975; public abstract byte[] getExtensionValue(java.lang.String arg0); internal static global::MonoJavaBridge.MethodId _getSignature14976; public abstract byte[] getSignature(); internal static global::MonoJavaBridge.MethodId _getBasicConstraints14977; public abstract int getBasicConstraints(); internal static global::MonoJavaBridge.MethodId _getVersion14978; public abstract int getVersion(); internal static global::MonoJavaBridge.MethodId _getSerialNumber14979; public abstract global::java.math.BigInteger getSerialNumber(); internal static global::MonoJavaBridge.MethodId _getIssuerDN14980; public abstract global::java.security.Principal getIssuerDN(); internal static global::MonoJavaBridge.MethodId _getTBSCertificate14981; public abstract byte[] getTBSCertificate(); internal static global::MonoJavaBridge.MethodId _checkValidity14982; public abstract void checkValidity(); internal static global::MonoJavaBridge.MethodId _checkValidity14983; public abstract void checkValidity(java.util.Date arg0); internal static global::MonoJavaBridge.MethodId _getIssuerX500Principal14984; public virtual global::javax.security.auth.x500.X500Principal getIssuerX500Principal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate._getIssuerX500Principal14984)) as javax.security.auth.x500.X500Principal; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate.staticClass, global::java.security.cert.X509Certificate._getIssuerX500Principal14984)) as javax.security.auth.x500.X500Principal; } internal static global::MonoJavaBridge.MethodId _getSubjectDN14985; public abstract global::java.security.Principal getSubjectDN(); internal static global::MonoJavaBridge.MethodId _getSubjectX500Principal14986; public virtual global::javax.security.auth.x500.X500Principal getSubjectX500Principal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate._getSubjectX500Principal14986)) as javax.security.auth.x500.X500Principal; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate.staticClass, global::java.security.cert.X509Certificate._getSubjectX500Principal14986)) as javax.security.auth.x500.X500Principal; } internal static global::MonoJavaBridge.MethodId _getNotBefore14987; public abstract global::java.util.Date getNotBefore(); internal static global::MonoJavaBridge.MethodId _getNotAfter14988; public abstract global::java.util.Date getNotAfter(); internal static global::MonoJavaBridge.MethodId _getSigAlgName14989; public abstract global::java.lang.String getSigAlgName(); internal static global::MonoJavaBridge.MethodId _getSigAlgOID14990; public abstract global::java.lang.String getSigAlgOID(); internal static global::MonoJavaBridge.MethodId _getSigAlgParams14991; public abstract byte[] getSigAlgParams(); internal static global::MonoJavaBridge.MethodId _getIssuerUniqueID14992; public abstract bool[] getIssuerUniqueID(); internal static global::MonoJavaBridge.MethodId _getSubjectUniqueID14993; public abstract bool[] getSubjectUniqueID(); internal static global::MonoJavaBridge.MethodId _getKeyUsage14994; public abstract bool[] getKeyUsage(); internal static global::MonoJavaBridge.MethodId _getExtendedKeyUsage14995; public virtual global::java.util.List getExtendedKeyUsage() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate._getExtendedKeyUsage14995)) as java.util.List; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate.staticClass, global::java.security.cert.X509Certificate._getExtendedKeyUsage14995)) as java.util.List; } internal static global::MonoJavaBridge.MethodId _getSubjectAlternativeNames14996; public virtual global::java.util.Collection getSubjectAlternativeNames() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Collection>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate._getSubjectAlternativeNames14996)) as java.util.Collection; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Collection>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate.staticClass, global::java.security.cert.X509Certificate._getSubjectAlternativeNames14996)) as java.util.Collection; } internal static global::MonoJavaBridge.MethodId _getIssuerAlternativeNames14997; public virtual global::java.util.Collection getIssuerAlternativeNames() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Collection>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate._getIssuerAlternativeNames14997)) as java.util.Collection; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Collection>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate.staticClass, global::java.security.cert.X509Certificate._getIssuerAlternativeNames14997)) as java.util.Collection; } internal static global::MonoJavaBridge.MethodId _X509Certificate14998; protected X509Certificate() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.security.cert.X509Certificate.staticClass, global::java.security.cert.X509Certificate._X509Certificate14998); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.security.cert.X509Certificate.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/security/cert/X509Certificate")); global::java.security.cert.X509Certificate._hasUnsupportedCriticalExtension14972 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "hasUnsupportedCriticalExtension", "()Z"); global::java.security.cert.X509Certificate._getCriticalExtensionOIDs14973 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getCriticalExtensionOIDs", "()Ljava/util/Set;"); global::java.security.cert.X509Certificate._getNonCriticalExtensionOIDs14974 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getNonCriticalExtensionOIDs", "()Ljava/util/Set;"); global::java.security.cert.X509Certificate._getExtensionValue14975 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getExtensionValue", "(Ljava/lang/String;)[B"); global::java.security.cert.X509Certificate._getSignature14976 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getSignature", "()[B"); global::java.security.cert.X509Certificate._getBasicConstraints14977 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getBasicConstraints", "()I"); global::java.security.cert.X509Certificate._getVersion14978 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getVersion", "()I"); global::java.security.cert.X509Certificate._getSerialNumber14979 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getSerialNumber", "()Ljava/math/BigInteger;"); global::java.security.cert.X509Certificate._getIssuerDN14980 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getIssuerDN", "()Ljava/security/Principal;"); global::java.security.cert.X509Certificate._getTBSCertificate14981 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getTBSCertificate", "()[B"); global::java.security.cert.X509Certificate._checkValidity14982 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "checkValidity", "()V"); global::java.security.cert.X509Certificate._checkValidity14983 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "checkValidity", "(Ljava/util/Date;)V"); global::java.security.cert.X509Certificate._getIssuerX500Principal14984 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getIssuerX500Principal", "()Ljavax/security/auth/x500/X500Principal;"); global::java.security.cert.X509Certificate._getSubjectDN14985 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getSubjectDN", "()Ljava/security/Principal;"); global::java.security.cert.X509Certificate._getSubjectX500Principal14986 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getSubjectX500Principal", "()Ljavax/security/auth/x500/X500Principal;"); global::java.security.cert.X509Certificate._getNotBefore14987 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getNotBefore", "()Ljava/util/Date;"); global::java.security.cert.X509Certificate._getNotAfter14988 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getNotAfter", "()Ljava/util/Date;"); global::java.security.cert.X509Certificate._getSigAlgName14989 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getSigAlgName", "()Ljava/lang/String;"); global::java.security.cert.X509Certificate._getSigAlgOID14990 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getSigAlgOID", "()Ljava/lang/String;"); global::java.security.cert.X509Certificate._getSigAlgParams14991 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getSigAlgParams", "()[B"); global::java.security.cert.X509Certificate._getIssuerUniqueID14992 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getIssuerUniqueID", "()[Z"); global::java.security.cert.X509Certificate._getSubjectUniqueID14993 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getSubjectUniqueID", "()[Z"); global::java.security.cert.X509Certificate._getKeyUsage14994 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getKeyUsage", "()[Z"); global::java.security.cert.X509Certificate._getExtendedKeyUsage14995 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getExtendedKeyUsage", "()Ljava/util/List;"); global::java.security.cert.X509Certificate._getSubjectAlternativeNames14996 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getSubjectAlternativeNames", "()Ljava/util/Collection;"); global::java.security.cert.X509Certificate._getIssuerAlternativeNames14997 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "getIssuerAlternativeNames", "()Ljava/util/Collection;"); global::java.security.cert.X509Certificate._X509Certificate14998 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.security.cert.X509Certificate))] public sealed partial class X509Certificate_ : java.security.cert.X509Certificate { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static X509Certificate_() { InitJNI(); } internal X509Certificate_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _hasUnsupportedCriticalExtension14999; public override bool hasUnsupportedCriticalExtension() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._hasUnsupportedCriticalExtension14999); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._hasUnsupportedCriticalExtension14999); } internal static global::MonoJavaBridge.MethodId _getCriticalExtensionOIDs15000; public override global::java.util.Set getCriticalExtensionOIDs() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getCriticalExtensionOIDs15000)) as java.util.Set; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getCriticalExtensionOIDs15000)) as java.util.Set; } internal static global::MonoJavaBridge.MethodId _getNonCriticalExtensionOIDs15001; public override global::java.util.Set getNonCriticalExtensionOIDs() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getNonCriticalExtensionOIDs15001)) as java.util.Set; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getNonCriticalExtensionOIDs15001)) as java.util.Set; } internal static global::MonoJavaBridge.MethodId _getExtensionValue15002; public override byte[] getExtensionValue(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getExtensionValue15002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getExtensionValue15002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; } internal static global::MonoJavaBridge.MethodId _getSignature15003; public override byte[] getSignature() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getSignature15003)) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getSignature15003)) as byte[]; } internal static global::MonoJavaBridge.MethodId _getBasicConstraints15004; public override int getBasicConstraints() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getBasicConstraints15004); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getBasicConstraints15004); } internal static global::MonoJavaBridge.MethodId _getVersion15005; public override int getVersion() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getVersion15005); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getVersion15005); } internal static global::MonoJavaBridge.MethodId _getSerialNumber15006; public override global::java.math.BigInteger getSerialNumber() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getSerialNumber15006)) as java.math.BigInteger; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getSerialNumber15006)) as java.math.BigInteger; } internal static global::MonoJavaBridge.MethodId _getIssuerDN15007; public override global::java.security.Principal getIssuerDN() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Principal>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getIssuerDN15007)) as java.security.Principal; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Principal>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getIssuerDN15007)) as java.security.Principal; } internal static global::MonoJavaBridge.MethodId _getTBSCertificate15008; public override byte[] getTBSCertificate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getTBSCertificate15008)) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getTBSCertificate15008)) as byte[]; } internal static global::MonoJavaBridge.MethodId _checkValidity15009; public override void checkValidity() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._checkValidity15009); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._checkValidity15009); } internal static global::MonoJavaBridge.MethodId _checkValidity15010; public override void checkValidity(java.util.Date arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._checkValidity15010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._checkValidity15010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getSubjectDN15011; public override global::java.security.Principal getSubjectDN() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Principal>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getSubjectDN15011)) as java.security.Principal; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Principal>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getSubjectDN15011)) as java.security.Principal; } internal static global::MonoJavaBridge.MethodId _getNotBefore15012; public override global::java.util.Date getNotBefore() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getNotBefore15012)) as java.util.Date; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getNotBefore15012)) as java.util.Date; } internal static global::MonoJavaBridge.MethodId _getNotAfter15013; public override global::java.util.Date getNotAfter() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getNotAfter15013)) as java.util.Date; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getNotAfter15013)) as java.util.Date; } internal static global::MonoJavaBridge.MethodId _getSigAlgName15014; public override global::java.lang.String getSigAlgName() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getSigAlgName15014)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getSigAlgName15014)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getSigAlgOID15015; public override global::java.lang.String getSigAlgOID() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getSigAlgOID15015)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getSigAlgOID15015)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getSigAlgParams15016; public override byte[] getSigAlgParams() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getSigAlgParams15016)) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getSigAlgParams15016)) as byte[]; } internal static global::MonoJavaBridge.MethodId _getIssuerUniqueID15017; public override bool[] getIssuerUniqueID() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<bool>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getIssuerUniqueID15017)) as bool[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<bool>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getIssuerUniqueID15017)) as bool[]; } internal static global::MonoJavaBridge.MethodId _getSubjectUniqueID15018; public override bool[] getSubjectUniqueID() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<bool>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getSubjectUniqueID15018)) as bool[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<bool>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getSubjectUniqueID15018)) as bool[]; } internal static global::MonoJavaBridge.MethodId _getKeyUsage15019; public override bool[] getKeyUsage() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<bool>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getKeyUsage15019)) as bool[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<bool>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getKeyUsage15019)) as bool[]; } internal static global::MonoJavaBridge.MethodId _toString15020; public override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._toString15020)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._toString15020)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getEncoded15021; public override byte[] getEncoded() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getEncoded15021)) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getEncoded15021)) as byte[]; } internal static global::MonoJavaBridge.MethodId _verify15022; public override void verify(java.security.PublicKey arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._verify15022, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._verify15022, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _verify15023; public override void verify(java.security.PublicKey arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._verify15023, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._verify15023, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getPublicKey15024; public override global::java.security.PublicKey getPublicKey() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.PublicKey>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_._getPublicKey15024)) as java.security.PublicKey; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.PublicKey>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.cert.X509Certificate_.staticClass, global::java.security.cert.X509Certificate_._getPublicKey15024)) as java.security.PublicKey; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.security.cert.X509Certificate_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/security/cert/X509Certificate")); global::java.security.cert.X509Certificate_._hasUnsupportedCriticalExtension14999 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "hasUnsupportedCriticalExtension", "()Z"); global::java.security.cert.X509Certificate_._getCriticalExtensionOIDs15000 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getCriticalExtensionOIDs", "()Ljava/util/Set;"); global::java.security.cert.X509Certificate_._getNonCriticalExtensionOIDs15001 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getNonCriticalExtensionOIDs", "()Ljava/util/Set;"); global::java.security.cert.X509Certificate_._getExtensionValue15002 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getExtensionValue", "(Ljava/lang/String;)[B"); global::java.security.cert.X509Certificate_._getSignature15003 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getSignature", "()[B"); global::java.security.cert.X509Certificate_._getBasicConstraints15004 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getBasicConstraints", "()I"); global::java.security.cert.X509Certificate_._getVersion15005 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getVersion", "()I"); global::java.security.cert.X509Certificate_._getSerialNumber15006 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getSerialNumber", "()Ljava/math/BigInteger;"); global::java.security.cert.X509Certificate_._getIssuerDN15007 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getIssuerDN", "()Ljava/security/Principal;"); global::java.security.cert.X509Certificate_._getTBSCertificate15008 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getTBSCertificate", "()[B"); global::java.security.cert.X509Certificate_._checkValidity15009 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "checkValidity", "()V"); global::java.security.cert.X509Certificate_._checkValidity15010 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "checkValidity", "(Ljava/util/Date;)V"); global::java.security.cert.X509Certificate_._getSubjectDN15011 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getSubjectDN", "()Ljava/security/Principal;"); global::java.security.cert.X509Certificate_._getNotBefore15012 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getNotBefore", "()Ljava/util/Date;"); global::java.security.cert.X509Certificate_._getNotAfter15013 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getNotAfter", "()Ljava/util/Date;"); global::java.security.cert.X509Certificate_._getSigAlgName15014 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getSigAlgName", "()Ljava/lang/String;"); global::java.security.cert.X509Certificate_._getSigAlgOID15015 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getSigAlgOID", "()Ljava/lang/String;"); global::java.security.cert.X509Certificate_._getSigAlgParams15016 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getSigAlgParams", "()[B"); global::java.security.cert.X509Certificate_._getIssuerUniqueID15017 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getIssuerUniqueID", "()[Z"); global::java.security.cert.X509Certificate_._getSubjectUniqueID15018 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getSubjectUniqueID", "()[Z"); global::java.security.cert.X509Certificate_._getKeyUsage15019 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getKeyUsage", "()[Z"); global::java.security.cert.X509Certificate_._toString15020 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "toString", "()Ljava/lang/String;"); global::java.security.cert.X509Certificate_._getEncoded15021 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getEncoded", "()[B"); global::java.security.cert.X509Certificate_._verify15022 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "verify", "(Ljava/security/PublicKey;)V"); global::java.security.cert.X509Certificate_._verify15023 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "verify", "(Ljava/security/PublicKey;Ljava/lang/String;)V"); global::java.security.cert.X509Certificate_._getPublicKey15024 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate_.staticClass, "getPublicKey", "()Ljava/security/PublicKey;"); } } }
using System; using System.Web.Mvc; using Aranasoft.Cobweb.Mvc.Validation.Assertions; using Aranasoft.Cobweb.Mvc.Validation.Extensions; using Aranasoft.Cobweb.Mvc.Validation.Tests.TestableTypes; using FluentAssertions; using NUnit.Framework; namespace Aranasoft.Cobweb.Mvc.Validation.Tests.Routing.GivenDefaultRoute { [TestFixture] public class WithDataTypeControllerUrl : GivenDefaultRoute { [Test] public void ItShouldMapControllerUrlToDefaultAction() { "~/DataTypeInput".Should().MapTo<DataTypeInputController>(controller => controller.Index()); } [Test] public void ItShouldMapActionUrlToNoArgumentAction() { "~/DataTypeInput/WithNothing".Should() .MapTo<DataTypeInputController>(controller => controller.WithNothing()); } [Test] public void ItShouldMapActionUrlWithTrailingSlashToNoArgumentAction() { "~/DataTypeInput/WithNothing/".Should() .MapTo<DataTypeInputController>(controller => controller.WithNothing()); } [Test] public void ItShouldPostActionUrlToNoArgumentAction() { "~/DataTypeInput/PostNothing".WithMethod(HttpVerbs.Post) .Should() .MapTo<DataTypeInputController>(controller => controller.PostNothing()); } [Test] public void ItShouldPostActionUrlWithTrailingSlashToNoArgumentAction() { "~/DataTypeInput/PostNothing/".WithMethod(HttpVerbs.Post) .Should() .MapTo<DataTypeInputController>(controller => controller.PostNothing()); } [Test, Ignore("Fix: Need to do Action Selection on Controller")] public void ItShouldNotMapActionUrlWithIncorrectActionToNoArgumentAction() { "~/DataTypeInput/WithNothing".WithMethod(HttpVerbs.Post) .Should() .BeNull(); } [Test, Ignore("Fix: Need to do Action Selection on Controller")] public void ItShouldNotMapActionUrlWithTrailingSlashAndIncorrectActionToNoArgumentAction() { "~/DataTypeInput/WithNothing/".WithMethod(HttpVerbs.Post) .Should() .BeNull(); } [Test, Ignore("Fix: Need to do Action Selection on Controller")] public void ItShouldNotPostActionUrlWithIncorrectActionToNoArgumentAction() { "~/DataTypeInput/PostNothing".WithMethod(HttpVerbs.Get) .Should() .BeNull(); } [Test, Ignore("Fix: Need to do Action Selection on Controller")] public void ItShouldNotPostActionUrlWithTrailingSlashAndIncorrectActionToNoArgumentAction() { "~/DataTypeInput/PostNothing/".WithMethod(HttpVerbs.Get) .Should() .BeNull(); } [Test] public void ItShouldIgnoreValueOnUrlToNoArgumentAction() { "~/DataTypeInput/WithNothing/27".Should() .MapTo<DataTypeInputController>(controller => controller.WithNothing()); } [Test] public void ItShouldIgnoreValueWithTrailingSlashOnUrlToNoArgumentAction() { "~/DataTypeInput/WithNothing/27/".Should() .MapTo<DataTypeInputController>(controller => controller.WithNothing()); } [Test, Ignore("Fix Me?")] public void ItShouldIgnoreMultipleValuesOnUrlToNoArgumentAction() { "~/DataTypeInput/WithNothing/27/1".Should() .MapTo<DataTypeInputController>(controller => controller.WithNothing()); } [Test, Ignore("Fix Me?")] public void ItShouldMapEmptyIntToDefaultActionParamaterValue() { "~/DataTypeInput/WithInteger".Should() .MapTo<DataTypeInputController>(controller => controller.WithInteger(default(int))); } [Test, Ignore("Fix Me?")] public void ItShouldMapEmptyIntAndTrailingSlashToDefaultActionParamaterValue() { "~/DataTypeInput/WithInteger/".Should() .MapTo<DataTypeInputController>(controller => controller.WithInteger(default(int))); } [Test] public void ItShouldMapSpecifiedIntToSpecifiedActionParamater() { "~/DataTypeInput/WithInteger/27".Should() .MapTo<DataTypeInputController>(controller => controller.WithInteger(27)); } [Test] public void ItShouldMapSpecifiedIntAndTrailingSlashToSpecifiedActionParamater() { "~/DataTypeInput/WithInteger/27/".Should() .MapTo<DataTypeInputController>(controller => controller.WithInteger(27)); } [Test] public void ItShouldPostSpecifiedIntToSpecifiedActionParamater() { "~/DataTypeInput/PostInteger/27".WithMethod(HttpVerbs.Post) .Should() .MapTo<DataTypeInputController>(controller => controller.PostInteger(27)); } [Test] public void ItShouldPostSpecifiedIntAndTrailingSlashToSpecifiedActionParamater() { "~/DataTypeInput/PostInteger/27/".WithMethod(HttpVerbs.Post) .Should() .MapTo<DataTypeInputController>(controller => controller.PostInteger(27)); } [Test] public void ItShouldMapEmptyNullableIntToEmptyActionParamater() { "~/DataTypeInput/WithNullInteger".Should() .MapTo<DataTypeInputController>(controller => controller.WithNullInteger(null)); } [Test] public void ItShouldMapEmptyNullableIntAndTrailingSlashToEmptyActionParamater() { "~/DataTypeInput/WithNullInteger/".Should() .MapTo<DataTypeInputController>(controller => controller.WithNullInteger(null)); } [Test] public void ItShouldMapSpecifiedNullableIntToSpecifiedActionParamater() { "~/DataTypeInput/WithNullInteger/27".Should() .MapTo<DataTypeInputController>(controller => controller.WithNullInteger(27)); } [Test] public void ItShouldMapSpecifiedNullableIntAndTrailingSlashToSpecifiedActionParamater() { "~/DataTypeInput/WithNullInteger/27/".Should() .MapTo<DataTypeInputController>(controller => controller.WithNullInteger(27)); } [Test] public void ItShouldMapEmptyStringToEmptyActionParamater() { "~/DataTypeInput/WithString".Should() .MapTo<DataTypeInputController>(controller => controller.WithString(null)); } [Test] public void ItShouldMapEmptyStringTrailingSlashToEmptyActionParamater() { "~/DataTypeInput/WithString/".Should() .MapTo<DataTypeInputController>(controller => controller.WithString(null)); } [Test] public void ItShouldMapSpecifiedStringToSpecifiedActionParamater() { "~/DataTypeInput/WithString/35".Should() .MapTo<DataTypeInputController>(controller => controller.WithString("35")); } [Test] public void ItShouldMapSpecifiedStringTrailingSlashToSpecifiedActionParamater() { "~/DataTypeInput/WithString/35/".Should() .MapTo<DataTypeInputController>(controller => controller.WithString("35")); } [Test, Ignore("Fix Me?")] public void ItShouldMapEmptyGuidToEmptyActionParamater() { "~/DataTypeInput/WithGuid".Should() .MapTo<DataTypeInputController>(controller => controller.WithGuid(default(Guid))); } [Test, Ignore("Fix Me?")] public void ItShouldMapEmptyGuidTrailingSlashToEmptyActionParamater() { "~/DataTypeInput/WithGuid/".Should() .MapTo<DataTypeInputController>(controller => controller.WithGuid(default(Guid))); } [Test] public void ItShouldMapSpecifiedGuidToSpecifiedActionParamater() { var expected = Guid.Parse("88E262E5-9E61-4F98-BB0C-3837D2749C1A"); const string actualUrl = "~/DataTypeInput/WithGuid/88E262E5-9E61-4F98-BB0C-3837D2749C1A"; actualUrl.Should() .MapTo<DataTypeInputController>(controller => controller.WithGuid(expected)); } [Test] public void ItShouldMapSpecifiedGuidTrailingSlashToSpecifiedActionParamater() { var expected = Guid.Parse("88E262E5-9E61-4F98-BB0C-3837D2749C1A"); const string actualUrl = "~/DataTypeInput/WithGuid/88E262E5-9E61-4F98-BB0C-3837D2749C1A/"; actualUrl.Should() .MapTo<DataTypeInputController>(controller => controller.WithGuid(expected)); } [Test] public void ItShouldMapSpecifiedDateTimeToSpecifiedActionParamater() { var expected = 1.July(2015); const string actualUrl = "~/DataTypeInput/WithDateTime/2015-07-01"; actualUrl.Should() .MapTo<DataTypeInputController>(controller => controller.WithDateTime(expected)); } [Test] public void ItShouldMapSpecifiedDateTimeAndTrailingSlashToSpecifiedActionParamater() { var expected = 1.July(2015); const string actualUrl = "~/DataTypeInput/WithDateTime/2015-07-01/"; actualUrl.Should() .MapTo<DataTypeInputController>(controller => controller.WithDateTime(expected)); } [Test] public void ItShouldMapEmptyNullableDateTimeToEmptyActionParamater() { "~/DataTypeInput/WithNullDateTime".Should() .MapTo<DataTypeInputController>(controller => controller.WithNullDateTime(null)); } [Test] public void ItShouldMapEmptyNullableDateTimeAndTrailingSlashToEmptyActionParamater() { "~/DataTypeInput/WithNullDateTime/".Should() .MapTo<DataTypeInputController>(controller => controller.WithNullDateTime(null)); } [Test] public void ItShouldMapSpecifiedNullableDateTimeToSpecifiedActionParamater() { var expected = 1.July(2015); const string actualUrl = "~/DataTypeInput/WithNullDateTime/2015-07-01"; actualUrl.Should() .MapTo<DataTypeInputController>(controller => controller.WithNullDateTime( expected)); } [Test] public void ItShouldMapSpecifiedNullableDateTimeAndTrailingSlashToSpecifiedActionParamater() { var expected = 1.July(2015); const string actualUrl = "~/DataTypeInput/WithNullDateTime/2015-07-01/"; actualUrl.Should() .MapTo<DataTypeInputController>(controller => controller.WithNullDateTime( expected)); } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading; using Common.Logging; using Quartz.Impl; namespace Quartz.Examples.Example13 { /// <summary> /// Used to test/show the clustering features of AdoJobStore. /// </summary> /// <remarks> /// /// <para> /// All instances MUST use a different properties file, because their instance /// Ids must be different, however all other properties should be the same. /// </para> /// /// <para> /// If you want it to clear out existing jobs & triggers, pass a command-line /// argument called "clearJobs". /// </para> /// /// <para> /// You should probably start with a "fresh" set of tables (assuming you may /// have some data lingering in it from other tests), since mixing data from a /// non-clustered setup with a clustered one can be bad. /// </para> /// /// <para> /// Try killing one of the cluster instances while they are running, and see /// that the remaining instance(s) recover the in-progress jobs. Note that /// detection of the failure may take up to 15 or so seconds with the default /// settings. /// </para> /// /// <para> /// Also try running it with/without the shutdown-hook plugin registered with /// the scheduler. (quartz.plugins.management.ShutdownHookPlugin). /// </para> /// /// <para> /// <i>Note:</i> Never run clustering on separate machines, unless their /// clocks are synchronized using some form of time-sync service (daemon). /// </para> /// </remarks> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> public class ClusterExample : IExample { private static readonly ILog log = LogManager.GetLogger(typeof (ClusterExample)); public virtual void Run(bool inClearJobs, bool inScheduleJobs) { NameValueCollection properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "TestScheduler"; properties["quartz.scheduler.instanceId"] = "instance_one"; properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "5"; properties["quartz.threadPool.threadPriority"] = "Normal"; properties["quartz.jobStore.misfireThreshold"] = "60000"; properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz"; properties["quartz.jobStore.useProperties"] = "false"; properties["quartz.jobStore.dataSource"] = "default"; properties["quartz.jobStore.tablePrefix"] = "QRTZ_"; properties["quartz.jobStore.clustered"] = "true"; // if running SQLite we need this // properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz"; properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz"; properties["quartz.dataSource.default.connectionString"] = "Server=(local);Database=quartz;Trusted_Connection=True;"; properties["quartz.dataSource.default.provider"] = "SqlServer-20"; // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(properties); IScheduler sched = sf.GetScheduler(); if (inClearJobs) { log.Warn("***** Deleting existing jobs/triggers *****"); sched.Clear(); } log.Info("------- Initialization Complete -----------"); if (inScheduleJobs) { log.Info("------- Scheduling Jobs ------------------"); string schedId = sched.SchedulerInstanceId; int count = 1; IJobDetail job = JobBuilder.Create<SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); ISimpleTrigger trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5))) .Build(); log.InfoFormat("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds); count++; job = JobBuilder.Create<SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(2, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5))) .Build(); log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds)); sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create<SimpleRecoveryStatefulJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(3))) .Build(); log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds)); sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create<SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(4))) .Build(); log.Info(string.Format("{0} will run at: {1} & repeat: {2}/{3}", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval)); sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create<SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromMilliseconds(4500))) .Build(); log.Info(string.Format("{0} will run at: {1} & repeat: {2}/{3}", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval)); sched.ScheduleJob(job, trigger); } // jobs don't start firing until start() has been called... log.Info("------- Starting Scheduler ---------------"); sched.Start(); log.Info("------- Started Scheduler ----------------"); log.Info("------- Waiting for one hour... ----------"); Thread.Sleep(TimeSpan.FromHours(1)); log.Info("------- Shutting Down --------------------"); sched.Shutdown(); log.Info("------- Shutdown Complete ----------------"); } public string Name { get { throw new NotImplementedException(); } } public void Run() { bool clearJobs = true; bool scheduleJobs = true; /* TODO for (int i = 0; i < args.Length; i++) { if (args[i].ToUpper().Equals("clearJobs".ToUpper())) { clearJobs = true; } else if (args[i].ToUpper().Equals("dontScheduleJobs".ToUpper())) { scheduleJobs = false; } } */ ClusterExample example = new ClusterExample(); example.Run(clearJobs, scheduleJobs); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; #if !SILVERLIGHT namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Net; using System.Net.Mail; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Sends log messages by email using SMTP protocol. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/Mail-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Mail/Simple/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Mail/Simple/Example.cs" /> /// <p> /// Mail target works best when used with BufferingWrapper target /// which lets you send multiple log messages in single mail /// </p> /// <p> /// To set up the buffered mail target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Mail/Buffered/NLog.config" /> /// <p> /// To set up the buffered mail target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Mail/Buffered/Example.cs" /> /// </example> [Target("Mail")] public class MailTarget : TargetWithLayoutHeaderAndFooter { private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent."; /// <summary> /// Initializes a new instance of the <see cref="MailTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This one is safe.")] public MailTarget() { this.Body = "${message}${newline}"; this.Subject = "Message from NLog on ${machinename}"; this.Encoding = Encoding.UTF8; this.SmtpPort = 25; this.SmtpAuthentication = SmtpAuthenticationMode.None; this.Timeout = 10000; } /// <summary> /// Gets or sets sender's email address (e.g. joe@domain.com). /// </summary> /// <docgen category='Message Options' order='10' /> [RequiredParameter] public Layout From { get; set; } /// <summary> /// Gets or sets recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). /// </summary> /// <docgen category='Message Options' order='11' /> [RequiredParameter] public Layout To { get; set; } /// <summary> /// Gets or sets CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). /// </summary> /// <docgen category='Message Options' order='12' /> public Layout CC { get; set; } /// <summary> /// Gets or sets BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). /// </summary> /// <docgen category='Message Options' order='13' /> public Layout Bcc { get; set; } /// <summary> /// Gets or sets a value indicating whether to add new lines between log entries. /// </summary> /// <value>A value of <c>true</c> if new lines should be added; otherwise, <c>false</c>.</value> /// <docgen category='Layout Options' order='99' /> public bool AddNewLines { get; set; } /// <summary> /// Gets or sets the mail subject. /// </summary> /// <docgen category='Message Options' order='5' /> [DefaultValue("Message from NLog on ${machinename}")] [RequiredParameter] public Layout Subject { get; set; } /// <summary> /// Gets or sets mail message body (repeated for each log message send in one mail). /// </summary> /// <remarks>Alias for the <c>Layout</c> property.</remarks> /// <docgen category='Message Options' order='6' /> [DefaultValue("${message}${newline}")] public Layout Body { get { return this.Layout; } set { this.Layout = value; } } /// <summary> /// Gets or sets encoding to be used for sending e-mail. /// </summary> /// <docgen category='Layout Options' order='20' /> [DefaultValue("UTF8")] public Encoding Encoding { get; set; } /// <summary> /// Gets or sets a value indicating whether to send message as HTML instead of plain text. /// </summary> /// <docgen category='Layout Options' order='11' /> [DefaultValue(false)] public bool Html { get; set; } /// <summary> /// Gets or sets SMTP Server to be used for sending. /// </summary> /// <docgen category='SMTP Options' order='10' /> public Layout SmtpServer { get; set; } /// <summary> /// Gets or sets SMTP Authentication mode. /// </summary> /// <docgen category='SMTP Options' order='11' /> [DefaultValue("None")] public SmtpAuthenticationMode SmtpAuthentication { get; set; } /// <summary> /// Gets or sets the username used to connect to SMTP server (used when SmtpAuthentication is set to "basic"). /// </summary> /// <docgen category='SMTP Options' order='12' /> public Layout SmtpUserName { get; set; } /// <summary> /// Gets or sets the password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic"). /// </summary> /// <docgen category='SMTP Options' order='13' /> public Layout SmtpPassword { get; set; } /// <summary> /// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server. /// </summary> /// <docgen category='SMTP Options' order='14' />. [DefaultValue(false)] public bool EnableSsl { get; set; } /// <summary> /// Gets or sets the port number that SMTP Server is listening on. /// </summary> /// <docgen category='SMTP Options' order='15' /> [DefaultValue(25)] public int SmtpPort { get; set; } /// <summary> /// Gets or sets a value indicating whether the default Settings from System.Net.MailSettings should be used. /// </summary> /// <docgen category='SMTP Options' order='16' /> [DefaultValue(false)] public bool UseSystemNetMailSettings { get; set; } /// <summary> /// Specifies how outgoing email messages will be handled. /// </summary> /// <docgen category='SMTP Options' order='18' /> [DefaultValue(SmtpDeliveryMethod.Network)] public SmtpDeliveryMethod DeliveryMethod { get; set; } /// <summary> /// Gets or sets the folder where applications save mail messages to be processed by the local SMTP server. /// </summary> /// <docgen category='SMTP Options' order='17' /> [DefaultValue(null)] public string PickupDirectoryLocation { get; set; } /// <summary> /// Gets or sets the priority used for sending mails. /// </summary> public Layout Priority { get; set; } /// <summary> /// Gets or sets a value indicating whether NewLine characters in the body should be replaced with <br/> tags. /// </summary> /// <remarks>Only happens when <see cref="Html"/> is set to true.</remarks> [DefaultValue(false)] public bool ReplaceNewlineWithBrTagInHtml { get; set; } /// <summary> /// Gets or sets a value indicating the SMTP client timeout. /// </summary> /// <remarks>Warning: zero is not infinit waiting</remarks> [DefaultValue(10000)] public int Timeout { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is a factory method.")] internal virtual ISmtpClient CreateSmtpClient() { return new MySmtpClient(); } /// <summary> /// Renders the logging event message and adds it to the internal ArrayList of log messages. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { this.Write(new[] { logEvent }); } /// <summary> /// Renders an array logging events. /// </summary> /// <param name="logEvents">Array of logging events.</param> protected override void Write(AsyncLogEventInfo[] logEvents) { foreach (var bucket in logEvents.BucketSort(c => this.GetSmtpSettingsKey(c.LogEvent))) { var eventInfos = bucket.Value; this.ProcessSingleMailMessage(eventInfos); } } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> protected override void InitializeTarget() { CheckRequiredParameters(); base.InitializeTarget(); } /// <summary> /// Create mail and send with SMTP /// </summary> /// <param name="events">event printed in the body of the event</param> private void ProcessSingleMailMessage([NotNull] List<AsyncLogEventInfo> events) { try { if (events.Count == 0) { throw new NLogRuntimeException("We need at least one event."); } LogEventInfo firstEvent = events[0].LogEvent; LogEventInfo lastEvent = events[events.Count - 1].LogEvent; // unbuffered case, create a local buffer, append header, body and footer var bodyBuffer = CreateBodyBuffer(events, firstEvent, lastEvent); using (var msg = CreateMailMessage(lastEvent, bodyBuffer.ToString())) { using (ISmtpClient client = this.CreateSmtpClient()) { if (!UseSystemNetMailSettings) ConfigureMailClient(lastEvent, client); InternalLogger.Debug("Sending mail to {0} using {1}:{2} (ssl={3})", msg.To, client.Host, client.Port, client.EnableSsl); InternalLogger.Trace(" Subject: '{0}'", msg.Subject); InternalLogger.Trace(" From: '{0}'", msg.From.ToString()); client.Send(msg); foreach (var ev in events) { ev.Continuation(null); } } } } catch (Exception exception) { //always log InternalLogger.Error(exception, "Error sending mail."); if (exception.MustBeRethrown()) { throw; } foreach (var ev in events) { ev.Continuation(exception); } } } /// <summary> /// Create buffer for body /// </summary> /// <param name="events">all events</param> /// <param name="firstEvent">first event for header</param> /// <param name="lastEvent">last event for footer</param> /// <returns></returns> private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, LogEventInfo firstEvent, LogEventInfo lastEvent) { var bodyBuffer = new StringBuilder(); if (this.Header != null) { bodyBuffer.Append(this.Header.Render(firstEvent)); if (this.AddNewLines) { bodyBuffer.Append("\n"); } } foreach (AsyncLogEventInfo eventInfo in events) { bodyBuffer.Append(this.Layout.Render(eventInfo.LogEvent)); if (this.AddNewLines) { bodyBuffer.Append("\n"); } } if (this.Footer != null) { bodyBuffer.Append(this.Footer.Render(lastEvent)); if (this.AddNewLines) { bodyBuffer.Append("\n"); } } return bodyBuffer; } /// <summary> /// Set properties of <paramref name="client"/> /// </summary> /// <param name="lastEvent">last event for username/password</param> /// <param name="client">client to set properties on</param> internal void ConfigureMailClient(LogEventInfo lastEvent, ISmtpClient client) { CheckRequiredParameters(); if (this.SmtpServer == null && string.IsNullOrEmpty(this.PickupDirectoryLocation)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer/PickupDirectoryLocation")); } if (this.DeliveryMethod == SmtpDeliveryMethod.Network && this.SmtpServer == null) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer")); } if (this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(this.PickupDirectoryLocation)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "PickupDirectoryLocation")); } if (this.SmtpServer != null && this.DeliveryMethod == SmtpDeliveryMethod.Network) { var renderedSmtpServer = this.SmtpServer.Render(lastEvent); if (string.IsNullOrEmpty(renderedSmtpServer)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer" )); } client.Host = renderedSmtpServer; client.Port = this.SmtpPort; client.EnableSsl = this.EnableSsl; if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm) { InternalLogger.Trace(" Using NTLM authentication."); client.Credentials = CredentialCache.DefaultNetworkCredentials; } else if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic) { string username = this.SmtpUserName.Render(lastEvent); string password = this.SmtpPassword.Render(lastEvent); InternalLogger.Trace(" Using basic authentication: Username='{0}' Password='{1}'", username, new string('*', password.Length)); client.Credentials = new NetworkCredential(username, password); } } if (!string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { client.PickupDirectoryLocation = this.PickupDirectoryLocation; } // In case DeliveryMethod = PickupDirectoryFromIis we will not require Host nor PickupDirectoryLocation client.DeliveryMethod = this.DeliveryMethod; client.Timeout = this.Timeout; } private void CheckRequiredParameters() { if (!this.UseSystemNetMailSettings && this.SmtpServer == null && this.DeliveryMethod == SmtpDeliveryMethod.Network) { throw new NLogConfigurationException( string.Format("The MailTarget's '{0}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=Network. The email message will not be sent.", "SmtpServer")); } if (!this.UseSystemNetMailSettings && string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { throw new NLogConfigurationException( string.Format("The MailTarget's '{0}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=SpecifiedPickupDirectory. The email message will not be sent.", "PickupDirectoryLocation")); } } /// <summary> /// Create key for grouping. Needed for multiple events in one mailmessage /// </summary> /// <param name="logEvent">event for rendering layouts </param> ///<returns>string to group on</returns> private string GetSmtpSettingsKey(LogEventInfo logEvent) { var sb = new StringBuilder(); AppendLayout(sb, logEvent, this.From); AppendLayout(sb, logEvent, this.To); AppendLayout(sb, logEvent, this.CC); AppendLayout(sb, logEvent, this.Bcc); AppendLayout(sb, logEvent, this.SmtpServer); AppendLayout(sb, logEvent, this.SmtpPassword); AppendLayout(sb, logEvent, this.SmtpUserName); return sb.ToString(); } /// <summary> /// Append rendered layout to the stringbuilder /// </summary> /// <param name="sb">append to this</param> /// <param name="logEvent">event for rendering <paramref name="layout"/></param> /// <param name="layout">append if not <c>null</c></param> private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout) { sb.Append("|"); if (layout != null) sb.Append(layout.Render(logEvent)); } /// <summary> /// Create the mailmessage with the addresses, properties and body. /// </summary> private MailMessage CreateMailMessage(LogEventInfo lastEvent, string body) { var msg = new MailMessage(); var renderedFrom = this.From == null ? null : this.From.Render(lastEvent); if (string.IsNullOrEmpty(renderedFrom)) { throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From"); } msg.From = new MailAddress(renderedFrom); var addedTo = AddAddresses(msg.To, this.To, lastEvent); var addedCc = AddAddresses(msg.CC, this.CC, lastEvent); var addedBcc = AddAddresses(msg.Bcc, this.Bcc, lastEvent); if (!addedTo && !addedCc && !addedBcc) { throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "To/Cc/Bcc"); } msg.Subject = this.Subject == null ? string.Empty : this.Subject.Render(lastEvent).Trim(); msg.BodyEncoding = this.Encoding; msg.IsBodyHtml = this.Html; if (this.Priority != null) { var renderedPriority = this.Priority.Render(lastEvent); try { msg.Priority = (MailPriority)Enum.Parse(typeof(MailPriority), renderedPriority, true); } catch { InternalLogger.Warn("Could not convert '{0}' to MailPriority, valid values are Low, Normal and High. Using normal priority as fallback."); msg.Priority = MailPriority.Normal; } } msg.Body = body; if (msg.IsBodyHtml && ReplaceNewlineWithBrTagInHtml && msg.Body != null) msg.Body = msg.Body.Replace(EnvironmentHelper.NewLine, "<br/>"); return msg; } /// <summary> /// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/> /// </summary> /// <param name="mailAddressCollection">Addresses appended to this list</param> /// <param name="layout">layout with addresses, ; separated</param> /// <param name="logEvent">event for rendering the <paramref name="layout"/></param> /// <returns>added a address?</returns> private static bool AddAddresses(MailAddressCollection mailAddressCollection, Layout layout, LogEventInfo logEvent) { var added = false; if (layout != null) { foreach (string mail in layout.Render(logEvent).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { mailAddressCollection.Add(mail); added = true; } } return added; } } } #endif
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.UI.Core; using Windows.UI.Xaml; namespace DevExpress.Mvvm.Native { public static class TypeExtensions { public static bool IsAssignableFrom(this Type sourceType, Type objType) { if(sourceType == null) throw new ArgumentException("sourceType"); if(objType == null) return false; return sourceType.GetTypeInfo().IsAssignableFrom(objType.GetTypeInfo()); } public static Type GetBaseType(this Type sourceType) { if(sourceType == null) throw new ArgumentException("sourceType"); return sourceType.GetTypeInfo().BaseType; } public static MethodInfo GetMethod(this Type type, string methodName) { return type.GetRuntimeMethods().First(mi => mi.Name == methodName); } public static MethodInfo GetMethod(this Type type, string methodName, Type[] types) { return type.GetRuntimeMethod(methodName, types); } public static EventInfo GetEvent(this Type type, string eventName) { return type.GetRuntimeEvent(eventName); } public static ConstructorInfo[] GetConstructors(this Type sourceType) { if(sourceType == null) throw new ArgumentException("sourceType"); return sourceType.GetTypeInfo().DeclaredConstructors.ToArray(); } public static ConstructorInfo GetConstructor(this Type sourceType, Type[] types) { if(sourceType == null) throw new ArgumentException("sourceType"); if (types == null || types.Any(t => t == null)) throw new ArgumentNullException("types"); return sourceType.GetTypeInfo().DeclaredConstructors.Where(ci => CheckParametersTypes(ci.GetParameters(), types)).FirstOrDefault(); } static bool CheckParametersTypes(ParameterInfo[] parameters, Type[] types) { if(parameters.Length != types.Length) return false; for(int i = 0; i < types.Length; i++) if(parameters[i].ParameterType != types[i]) return false; return true; } public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo) { if(propertyInfo == null) throw new ArgumentException("propertyInfo"); return propertyInfo.GetMethod; } public static FieldInfo[] GetFields(this Type sourceType) { if(sourceType == null) throw new ArgumentException("sourceType"); return sourceType.GetRuntimeFields().ToArray(); } public static FieldInfo GetField(this Type sourceType, string name) { if(sourceType == null) throw new ArgumentException("sourceType"); return sourceType.GetRuntimeField(name); } public static bool GetIsEnum(this Type sourceType) { if(sourceType == null) throw new ArgumentException("sourceType"); return sourceType.GetTypeInfo().IsEnum; } public static bool GetIsPrimitive(this Type sourceType) { if(sourceType == null) throw new ArgumentException("sourceType"); return sourceType.GetTypeInfo().IsPrimitive; } public static bool GetIsValueType(this Type sourceType) { if(sourceType == null) throw new ArgumentException("sourceType"); return sourceType.GetTypeInfo().IsValueType; } public static FieldInfo[] GetPublicStaticFields(this Type type) { return type.GetTypeInfo().DeclaredFields.Where(fi => fi.IsStatic).ToArray(); } public static bool IsSubclassOf(this Type type, Type c) { return type.GetTypeInfo().IsSubclassOf(type); } public static bool IsDefined(this Type type, Type attributeType, bool inherit) { return type.GetTypeInfo().IsDefined(attributeType, inherit); } public static bool IsClass(this Type type) { return type.GetTypeInfo().IsClass; } public static MethodInfo[] GetMethods(this Type type) { return type.GetRuntimeMethods().ToArray(); } public static Assembly GetAssembly(this Type type) { return type.GetTypeInfo().Assembly; } public static Type GetReflectedType(this MethodInfo mi) { return mi.DeclaringType; } public static Type[] GetExportedTypes(this Assembly assembly) { return assembly.ExportedTypes.ToArray(); } public static MethodInfo GetSetMethod(this PropertyInfo pi) { return pi.SetMethod; } public static PropertyInfo GetProperty(this Type type, string propertyName) { while(type != typeof(object) && type != null) { PropertyInfo pi = type.GetTypeInfo().GetDeclaredProperty(propertyName); if(IsInstanceProperty(pi)) return pi; type = type.GetTypeInfo().BaseType; } return null; } public static PropertyInfo[] GetProperties(this Type sourceType) { if(sourceType == null) throw new ArgumentException("sourceType"); return sourceType.GetRuntimeProperties().Where(pi => IsInstanceProperty(pi)).ToArray(); } static bool IsInstanceProperty(PropertyInfo pi) { return pi != null && pi.GetMethod != null && !pi.GetMethod.IsStatic; } public static Type[] GetGenericArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } public static Type[] GetInterfaces(this Type type) { return type.GetTypeInfo().ImplementedInterfaces.ToArray(); } public static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } public static bool IsPrimitive(this Type type) { return type.GetTypeInfo().IsPrimitive; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsPublic(this Type type) { return type.GetTypeInfo().IsPublic; } public static bool IsNestedPublic(this Type type) { return type.GetTypeInfo().IsNestedPublic; } public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } static Dictionary<Type, TypeCode> typeCodes; static Dictionary<TypeCode, Type> types; public static TypeCode GetTypeCode(this Type type) { if (type == null) return TypeCode.Empty; if (typeCodes == null) { typeCodes = new Dictionary<Type, TypeCode>(); typeCodes[typeof(Boolean)] = TypeCode.Boolean; typeCodes[typeof(Byte)] = TypeCode.Byte; typeCodes[typeof(Char)] = TypeCode.Char; typeCodes[typeof(DateTime)] = TypeCode.DateTime; typeCodes[typeof(Decimal)] = TypeCode.Decimal; typeCodes[typeof(DBNull)] = TypeCode.DBNull; typeCodes[typeof(Double)] = TypeCode.Double; typeCodes[typeof(Int16)] = TypeCode.Int16; typeCodes[typeof(Int32)] = TypeCode.Int32; typeCodes[typeof(Int64)] = TypeCode.Int64; typeCodes[typeof(SByte)] = TypeCode.SByte; typeCodes[typeof(Single)] = TypeCode.Single; typeCodes[typeof(String)] = TypeCode.String; typeCodes[typeof(UInt16)] = TypeCode.UInt16; typeCodes[typeof(UInt32)] = TypeCode.UInt32; typeCodes[typeof(UInt64)] = TypeCode.UInt64; } TypeCode typeCode; if (typeCodes.TryGetValue(type, out typeCode)) return typeCode; return TypeCode.Object; } public static Type ToType(this TypeCode typeCode) { if (types == null) { types = new Dictionary<TypeCode, Type>(); types[TypeCode.Boolean] = typeof(Boolean); types[TypeCode.Byte] = typeof(Byte); types[TypeCode.Char] = typeof(Char); types[TypeCode.DateTime] = typeof(DateTime); types[TypeCode.Decimal] = typeof(Decimal); types[TypeCode.DBNull] = typeof(DBNull); types[TypeCode.Double] = typeof(Double); types[TypeCode.Int16] = typeof(Int16); types[TypeCode.Int32] = typeof(Int32); types[TypeCode.Int64] = typeof(Int64); types[TypeCode.SByte] = typeof(SByte); types[TypeCode.Single] = typeof(Single); types[TypeCode.String] = typeof(String); types[TypeCode.UInt16] = typeof(UInt16); types[TypeCode.UInt32] = typeof(UInt32); types[TypeCode.UInt64] = typeof(UInt64); } Type type; if (types.TryGetValue(typeCode, out type)) return type; return typeof(object); } public static bool IsInstanceOfType(this Type type, object obj) { return obj != null && IsAssignableFrom(type, obj.GetType()); } internal static bool ImplementInterface(this Type type, Type t) { while (type != null) { Type[] interfaces = type.GetTypeInfo().ImplementedInterfaces.ToArray(); if (interfaces == null) { for (int i = 0; i < interfaces.Length; i++) { if (interfaces[i] == t || (interfaces[i] != null && interfaces[i].ImplementInterface(t))) { return true; } } } type = type.GetTypeInfo().BaseType; } return false; } #region event const string EventAddMethodPrefix = "add_"; const string EventRemoveMethodPrefix = "remove_"; public static ParameterInfo[] GetEventHandlerParameters(this EventInfo eventInfo) { return eventInfo.EventHandlerType.GetTypeInfo().GetDeclaredMethod("Invoke").GetParameters(); } public static object AddEventHandlerEx(this EventInfo eventInfo, object target, Delegate handler) { MethodInfo addEventHandlerMethod = eventInfo.DeclaringType.GetRuntimeMethod(EventAddMethodPrefix + eventInfo.Name, new Type[] { eventInfo.EventHandlerType }); return addEventHandlerMethod.Invoke(target, new object[] { handler }) ?? handler; } public static void RemoveEventHandlerEx(this EventInfo eventInfo, object target, object handlerRegistrationToken) { MethodInfo removeEventHandlerMethod = eventInfo.DeclaringType.GetRuntimeMethod(EventRemoveMethodPrefix + eventInfo.Name, new Type[] { typeof(EventRegistrationToken) }) ?? eventInfo.DeclaringType.GetRuntimeMethod(EventRemoveMethodPrefix + eventInfo.Name, new Type[] { eventInfo.EventHandlerType }); removeEventHandlerMethod.Invoke(target, new object[] { handlerRegistrationToken }); } #endregion } public static class StringExtensions { public static StringComparison InvariantCultureComparison { get { return StringComparison.Ordinal; } } public static StringComparison InvariantCultureIgnoreCaseComparison { get { return StringComparison.OrdinalIgnoreCase; } } public static string ToLowerInvariantCulture(this string str) { return str.ToLowerInvariant(); } public static string ToUpperInvariantCulture(this string str) { return str.ToUpperInvariant(); } public static string ToLowerCurrentCulture(this string str) { return str.ToLower(); } public static string ToUpperCurrentCulture(this string str) { return str.ToUpper(); } public static UnicodeCategory GetUnicodeCategory(this char c) { return CharUnicodeInfo.GetUnicodeCategory(c); } } public enum TypeCode { Empty = 0, Object = 1, DBNull = 2, Boolean = 3, Char = 4, SByte = 5, Byte = 6, Int16 = 7, UInt16 = 8, Int32 = 9, UInt32 = 10, Int64 = 11, UInt64 = 12, Single = 13, Double = 14, Decimal = 15, DateTime = 16, String = 18, } [AttributeUsage(AttributeTargets.All)] public sealed class BrowsableAttribute : Attribute { public static readonly BrowsableAttribute Default = Yes; public static readonly BrowsableAttribute No = new BrowsableAttribute(false); public static readonly BrowsableAttribute Yes = new BrowsableAttribute(true); private bool browsable = true; public BrowsableAttribute(bool browsable) { this.browsable = browsable; } public override bool Equals(object obj) { if (obj == this) { return true; } BrowsableAttribute attribute = obj as BrowsableAttribute; return ((attribute != null) && (attribute.Browsable == this.browsable)); } public override int GetHashCode() { return this.browsable.GetHashCode(); } public bool Browsable { get { return this.browsable; } } } }
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; namespace ZXing.Datamatrix.Encoder { /// <summary> /// DataMatrix ECC 200 data encoder following the algorithm described in ISO/IEC 16022:200(E) in /// annex S. /// </summary> internal static class HighLevelEncoder { /// <summary> /// Padding character /// </summary> public const char PAD = (char)129; /// <summary> /// mode latch to C40 encodation mode /// </summary> public const char LATCH_TO_C40 = (char)230; /// <summary> /// mode latch to Base 256 encodation mode /// </summary> public const char LATCH_TO_BASE256 = (char)231; /// <summary> /// FNC1 Codeword /// </summary> public const char FNC1 = (char)232; /// <summary> /// Structured Append Codeword /// </summary> public const char STRUCTURED_APPEND = (char)233; /// <summary> /// Reader Programming /// </summary> public const char READER_PROGRAMMING = (char)234; /// <summary> /// Upper Shift /// </summary> public const char UPPER_SHIFT = (char)235; /// <summary> /// 05 Macro /// </summary> public const char MACRO_05 = (char)236; /// <summary> /// 06 Macro /// </summary> public const char MACRO_06 = (char)237; /// <summary> /// mode latch to ANSI X.12 encodation mode /// </summary> public const char LATCH_TO_ANSIX12 = (char)238; /// <summary> /// mode latch to Text encodation mode /// </summary> public const char LATCH_TO_TEXT = (char)239; /// <summary> /// mode latch to EDIFACT encodation mode /// </summary> public const char LATCH_TO_EDIFACT = (char)240; /// <summary> /// ECI character (Extended Channel Interpretation) /// </summary> public const char ECI = (char)241; /// <summary> /// Unlatch from C40 encodation /// </summary> public const char C40_UNLATCH = (char)254; /// <summary> /// Unlatch from X12 encodation /// </summary> public const char X12_UNLATCH = (char)254; /// <summary> /// 05 Macro header /// </summary> public const String MACRO_05_HEADER = "[)>\u001E05\u001D"; /// <summary> /// 06 Macro header /// </summary> public const String MACRO_06_HEADER = "[)>\u001E06\u001D"; /// <summary> /// Macro trailer /// </summary> public const String MACRO_TRAILER = "\u001E\u0004"; /* /// <summary> /// Converts the message to a byte array using the default encoding (cp437) as defined by the /// specification /// </summary> /// <param name="msg">the message</param> /// <returns>the byte array of the message</returns> public static byte[] getBytesForMessage(String msg) { return Encoding.GetEncoding("CP437").GetBytes(msg); //See 4.4.3 and annex B of ISO/IEC 15438:2001(E) } */ private static char randomize253State(char ch, int codewordPosition) { int pseudoRandom = ((149 * codewordPosition) % 253) + 1; int tempVariable = ch + pseudoRandom; return tempVariable <= 254 ? (char)tempVariable : (char)(tempVariable - 254); } /// <summary> /// Performs message encoding of a DataMatrix message using the algorithm described in annex P /// of ISO/IEC 16022:2000(E). /// </summary> /// <param name="msg">the message</param> /// <returns>the encoded message (the char values range from 0 to 255)</returns> public static String encodeHighLevel(String msg) { return encodeHighLevel(msg, SymbolShapeHint.FORCE_NONE, null, null, Encodation.ASCII); } /// <summary> /// Performs message encoding of a DataMatrix message using the algorithm described in annex P /// of ISO/IEC 16022:2000(E). /// </summary> /// <param name="msg">the message</param> /// <param name="shape">requested shape. May be {@code SymbolShapeHint.FORCE_NONE},{@code SymbolShapeHint.FORCE_SQUARE} or {@code SymbolShapeHint.FORCE_RECTANGLE}.</param> /// <param name="minSize">the minimum symbol size constraint or null for no constraint</param> /// <param name="maxSize">the maximum symbol size constraint or null for no constraint</param> /// <param name="defaultEncodation"></param> /// <returns>the encoded message (the char values range from 0 to 255)</returns> public static String encodeHighLevel(String msg, SymbolShapeHint shape, Dimension minSize, Dimension maxSize, int defaultEncodation) { //the codewords 0..255 are encoded as Unicode characters Encoder[] encoders = { new ASCIIEncoder(), new C40Encoder(), new TextEncoder(), new X12Encoder(), new EdifactEncoder(), new Base256Encoder() }; var context = new EncoderContext(msg); context.setSymbolShape(shape); context.setSizeConstraints(minSize, maxSize); if (msg.StartsWith(MACRO_05_HEADER) && msg.EndsWith(MACRO_TRAILER)) { context.writeCodeword(MACRO_05); context.setSkipAtEnd(2); context.Pos += MACRO_05_HEADER.Length; } else if (msg.StartsWith(MACRO_06_HEADER) && msg.EndsWith(MACRO_TRAILER)) { context.writeCodeword(MACRO_06); context.setSkipAtEnd(2); context.Pos += MACRO_06_HEADER.Length; } int encodingMode = defaultEncodation; //Default mode switch (encodingMode) { case Encodation.BASE256: context.writeCodeword(HighLevelEncoder.LATCH_TO_BASE256); break; case Encodation.C40: context.writeCodeword(HighLevelEncoder.LATCH_TO_C40); break; case Encodation.X12: context.writeCodeword(HighLevelEncoder.LATCH_TO_ANSIX12); break; case Encodation.TEXT: context.writeCodeword(HighLevelEncoder.LATCH_TO_TEXT); break; case Encodation.EDIFACT: context.writeCodeword(HighLevelEncoder.LATCH_TO_EDIFACT); break; case Encodation.ASCII: break; default: throw new InvalidOperationException("Illegal mode: " + encodingMode); } while (context.HasMoreCharacters) { encoders[encodingMode].encode(context); if (context.NewEncoding >= 0) { encodingMode = context.NewEncoding; context.resetEncoderSignal(); } } int len = context.Codewords.Length; context.updateSymbolInfo(); int capacity = context.SymbolInfo.dataCapacity; if (len < capacity) { if (encodingMode != Encodation.ASCII && encodingMode != Encodation.BASE256) { context.writeCodeword('\u00fe'); //Unlatch (254) } } //Padding StringBuilder codewords = context.Codewords; if (codewords.Length < capacity) { codewords.Append(PAD); } while (codewords.Length < capacity) { codewords.Append(randomize253State(PAD, codewords.Length + 1)); } return context.Codewords.ToString(); } internal static int lookAheadTest(String msg, int startpos, int currentMode) { if (startpos >= msg.Length) { return currentMode; } float[] charCounts; //step J if (currentMode == Encodation.ASCII) { charCounts = new [] { 0, 1, 1, 1, 1, 1.25f }; } else { charCounts = new [] { 1, 2, 2, 2, 2, 2.25f }; charCounts[currentMode] = 0; } int charsProcessed = 0; while (true) { //step K if ((startpos + charsProcessed) == msg.Length) { var min = Int32.MaxValue; var mins = new byte[6]; var intCharCounts = new int[6]; min = findMinimums(charCounts, intCharCounts, min, mins); var minCount = getMinimumCount(mins); if (intCharCounts[Encodation.ASCII] == min) { return Encodation.ASCII; } if (minCount == 1 && mins[Encodation.BASE256] > 0) { return Encodation.BASE256; } if (minCount == 1 && mins[Encodation.EDIFACT] > 0) { return Encodation.EDIFACT; } if (minCount == 1 && mins[Encodation.TEXT] > 0) { return Encodation.TEXT; } if (minCount == 1 && mins[Encodation.X12] > 0) { return Encodation.X12; } return Encodation.C40; } char c = msg[startpos + charsProcessed]; charsProcessed++; //step L if (isDigit(c)) { charCounts[Encodation.ASCII] += 0.5f; } else if (isExtendedASCII(c)) { charCounts[Encodation.ASCII] = (int)Math.Ceiling(charCounts[Encodation.ASCII]); charCounts[Encodation.ASCII] += 2; } else { charCounts[Encodation.ASCII] = (int)Math.Ceiling(charCounts[Encodation.ASCII]); charCounts[Encodation.ASCII]++; } //step M if (isNativeC40(c)) { charCounts[Encodation.C40] += 2.0f / 3.0f; } else if (isExtendedASCII(c)) { charCounts[Encodation.C40] += 8.0f / 3.0f; } else { charCounts[Encodation.C40] += 4.0f / 3.0f; } //step N if (isNativeText(c)) { charCounts[Encodation.TEXT] += 2.0f / 3.0f; } else if (isExtendedASCII(c)) { charCounts[Encodation.TEXT] += 8.0f / 3.0f; } else { charCounts[Encodation.TEXT] += 4.0f / 3.0f; } //step O if (isNativeX12(c)) { charCounts[Encodation.X12] += 2.0f / 3.0f; } else if (isExtendedASCII(c)) { charCounts[Encodation.X12] += 13.0f / 3.0f; } else { charCounts[Encodation.X12] += 10.0f / 3.0f; } //step P if (isNativeEDIFACT(c)) { charCounts[Encodation.EDIFACT] += 3.0f / 4.0f; } else if (isExtendedASCII(c)) { charCounts[Encodation.EDIFACT] += 17.0f / 4.0f; } else { charCounts[Encodation.EDIFACT] += 13.0f / 4.0f; } // step Q if (isSpecialB256(c)) { charCounts[Encodation.BASE256] += 4; } else { charCounts[Encodation.BASE256]++; } //step R if (charsProcessed >= 4) { var intCharCounts = new int[6]; var mins = new byte[6]; findMinimums(charCounts, intCharCounts, Int32.MaxValue, mins); int minCount = getMinimumCount(mins); if (intCharCounts[Encodation.ASCII] < intCharCounts[Encodation.BASE256] && intCharCounts[Encodation.ASCII] < intCharCounts[Encodation.C40] && intCharCounts[Encodation.ASCII] < intCharCounts[Encodation.TEXT] && intCharCounts[Encodation.ASCII] < intCharCounts[Encodation.X12] && intCharCounts[Encodation.ASCII] < intCharCounts[Encodation.EDIFACT]) { return Encodation.ASCII; } if (intCharCounts[Encodation.BASE256] < intCharCounts[Encodation.ASCII] || (mins[Encodation.C40] + mins[Encodation.TEXT] + mins[Encodation.X12] + mins[Encodation.EDIFACT]) == 0) { return Encodation.BASE256; } if (minCount == 1 && mins[Encodation.EDIFACT] > 0) { return Encodation.EDIFACT; } if (minCount == 1 && mins[Encodation.TEXT] > 0) { return Encodation.TEXT; } if (minCount == 1 && mins[Encodation.X12] > 0) { return Encodation.X12; } if (intCharCounts[Encodation.C40] + 1 < intCharCounts[Encodation.ASCII] && intCharCounts[Encodation.C40] + 1 < intCharCounts[Encodation.BASE256] && intCharCounts[Encodation.C40] + 1 < intCharCounts[Encodation.EDIFACT] && intCharCounts[Encodation.C40] + 1 < intCharCounts[Encodation.TEXT]) { if (intCharCounts[Encodation.C40] < intCharCounts[Encodation.X12]) { return Encodation.C40; } if (intCharCounts[Encodation.C40] == intCharCounts[Encodation.X12]) { int p = startpos + charsProcessed + 1; while (p < msg.Length) { char tc = msg[p]; if (isX12TermSep(tc)) { return Encodation.X12; } if (!isNativeX12(tc)) { break; } p++; } return Encodation.C40; } } } } } private static int findMinimums(float[] charCounts, int[] intCharCounts, int min, byte[] mins) { SupportClass.Fill(mins, (byte)0); for (int i = 0; i < 6; i++) { intCharCounts[i] = (int)Math.Ceiling(charCounts[i]); int current = intCharCounts[i]; if (min > current) { min = current; SupportClass.Fill(mins, (byte)0); } if (min == current) { mins[i]++; } } return min; } private static int getMinimumCount(byte[] mins) { int minCount = 0; for (int i = 0; i < 6; i++) { minCount += mins[i]; } return minCount; } internal static bool isDigit(char ch) { return ch >= '0' && ch <= '9'; } internal static bool isExtendedASCII(char ch) { return ch >= 128 && ch <= 255; } internal static bool isNativeC40(char ch) { return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'); } internal static bool isNativeText(char ch) { return (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z'); } internal static bool isNativeX12(char ch) { return isX12TermSep(ch) || (ch == ' ') || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z'); } internal static bool isX12TermSep(char ch) { return (ch == '\r') //CR || (ch == '*') || (ch == '>'); } internal static bool isNativeEDIFACT(char ch) { return ch >= ' ' && ch <= '^'; } internal static bool isSpecialB256(char ch) { return false; //TODO NOT IMPLEMENTED YET!!! } /// <summary> /// Determines the number of consecutive characters that are encodable using numeric compaction. /// </summary> /// <param name="msg">the message</param> /// <param name="startpos">the start position within the message</param> /// <returns>the requested character count</returns> public static int determineConsecutiveDigitCount(String msg, int startpos) { int count = 0; int len = msg.Length; int idx = startpos; if (idx < len) { char ch = msg[idx]; while (isDigit(ch) && idx < len) { count++; idx++; if (idx < len) { ch = msg[idx]; } } } return count; } internal static void illegalCharacter(char c) { throw new ArgumentException(String.Format("Illegal character: {0} (0x{1:X})", c, (int)c)); } } }
using System; using System.Data; using System.Data.Common; using Microsoft.Practices.EnterpriseLibrary.Data; using System.Collections.Generic; namespace Carvalho.QuePexinxa.CamadaAcessoDados { public static class Promocao { public static void Gravar(Carvalho.QuePexinxa.CamadaEntidades.Promocao promocao) { Database conexao; DbCommand comando; try { conexao = DatabaseFactory.CreateDatabase(); using (comando = conexao.GetStoredProcCommand("[dbo].[GravarPromocao]")) { conexao.AddInParameter(comando, "@PromocaoID", DbType.Int32, promocao.PromocaoID); conexao.AddInParameter(comando, "@ProdutoID", DbType.Int32, promocao.ProdutoID); conexao.AddInParameter(comando, "@DataInicio", DbType.DateTime, promocao.DataInicio); conexao.AddInParameter(comando, "@DataFim", DbType.DateTime, promocao.DataFim); conexao.AddInParameter(comando, "@ValorAntigo", DbType.Double, promocao.ValorAntigo); conexao.AddInParameter(comando, "@ValorAtual", DbType.Double, promocao.ValorAtual); conexao.AddInParameter(comando, "@UsuarioID", DbType.Int32, promocao.UsuarioID); conexao.ExecuteNonQuery(comando); } } catch (DbException ex) { throw new ApplicationException("Erro ao gravar o registro", ex); } } public static void Excluir(int promocaoID) { Database conexao; DbCommand comando; try { conexao = DatabaseFactory.CreateDatabase(); using (comando = conexao.GetStoredProcCommand("[dbo].[ExcluirPromocao]")) { conexao.AddInParameter(comando, "@PromocaoID", DbType.Int32, promocaoID); conexao.ExecuteNonQuery(comando); } } catch (DbException ex) { throw new ApplicationException("Erro ao excluir o registro", ex); } } public static Carvalho.QuePexinxa.CamadaEntidades.Promocao Selecionar(Carvalho.QuePexinxa.CamadaEntidades.Promocao promocao) { Database conexao; DbCommand comando; IDataReader retorno; try { conexao = DatabaseFactory.CreateDatabase(); using (comando = conexao.GetStoredProcCommand("[dbo].[SelecionarPromocao]")) { conexao.AddInParameter(comando, "@PromocaoID", DbType.Int32, promocao.PromocaoID); retorno = conexao.ExecuteReader(comando); if (retorno.Read()) { promocao.PromocaoID = Convert.ToInt32(retorno["PromocaoID"]); promocao.ProdutoID = Convert.ToInt32(retorno["ProdutoID"]); promocao.DataInicio = Convert.ToDateTime(retorno["DataInicio"]); promocao.DataFim = Convert.ToDateTime(retorno["DataFim"]); promocao.ValorAntigo = Convert.ToDouble(retorno["ValorAntigo"]); promocao.ValorAtual = Convert.ToDouble(retorno["ValorAtual"]); } retorno.Close(); } return promocao; } catch (DbException ex) { throw new ApplicationException("Erro ao selecionar o registro", ex); } catch (IndexOutOfRangeException ex) { throw new ApplicationException("Erro ao listar os registros", ex); } } public static List<Carvalho.QuePexinxa.CamadaEntidades.Promocao> Listar(int lojistaID) { List<Carvalho.QuePexinxa.CamadaEntidades.Promocao> listaPromocao = new List<Carvalho.QuePexinxa.CamadaEntidades.Promocao>(); Database conexao; DbCommand comando; IDataReader retorno; try { conexao = DatabaseFactory.CreateDatabase(); using (comando = conexao.GetStoredProcCommand("[dbo].[ListarPromocaoPorLojista]")) { conexao.AddInParameter(comando, "@LojistaID", DbType.Int32, lojistaID); retorno = conexao.ExecuteReader(comando); while (retorno.Read()) { Carvalho.QuePexinxa.CamadaEntidades.Promocao objPromocao = new Carvalho.QuePexinxa.CamadaEntidades.Promocao(); objPromocao.PromocaoID = Convert.ToInt32(retorno["PromocaoID"]); objPromocao.Lojista = retorno["Lojista"].ToString(); objPromocao.Categoria = retorno["Categoria"].ToString(); objPromocao.Produto = retorno["Produto"].ToString(); objPromocao.DataInicio = Convert.ToDateTime(retorno["DataInicio"]); objPromocao.DataFim = Convert.ToDateTime(retorno["DataFim"]); objPromocao.ValorAntigo = Convert.ToDouble(retorno["ValorAntigo"]); objPromocao.ValorAtual = Convert.ToDouble(retorno["ValorAtual"]); listaPromocao.Add(objPromocao); objPromocao = null; } retorno.Close(); } return listaPromocao; } catch (DbException ex) { throw new ApplicationException("Erro ao listar os registros", ex); } catch (IndexOutOfRangeException ex) { throw new ApplicationException("Erro ao listar os registros", ex); } } public static List<Carvalho.QuePexinxa.CamadaEntidades.Promocao> ListarHomologada(int lojistaID) { List<Carvalho.QuePexinxa.CamadaEntidades.Promocao> listaPromocao = new List<Carvalho.QuePexinxa.CamadaEntidades.Promocao>(); Database conexao; DbCommand comando; IDataReader retorno; try { conexao = DatabaseFactory.CreateDatabase(); using (comando = conexao.GetStoredProcCommand("[dbo].[ListarPromocaoPorLojistaHomologada]")) { conexao.AddInParameter(comando, "@LojistaID", DbType.Int32, lojistaID); retorno = conexao.ExecuteReader(comando); while (retorno.Read()) { Carvalho.QuePexinxa.CamadaEntidades.Promocao objPromocao = new Carvalho.QuePexinxa.CamadaEntidades.Promocao(); objPromocao.PromocaoID = Convert.ToInt32(retorno["PromocaoID"]); objPromocao.Lojista = retorno["Lojista"].ToString(); objPromocao.Categoria = retorno["Categoria"].ToString(); objPromocao.Produto = retorno["Produto"].ToString(); objPromocao.DataInicio = Convert.ToDateTime(retorno["DataInicio"]); objPromocao.DataFim = Convert.ToDateTime(retorno["DataFim"]); objPromocao.ValorAntigo = Convert.ToDouble(retorno["ValorAntigo"]); objPromocao.ValorAtual = Convert.ToDouble(retorno["ValorAtual"]); objPromocao.Ativo = Convert.ToBoolean(retorno["Ativo"]); listaPromocao.Add(objPromocao); objPromocao = null; } retorno.Close(); } return listaPromocao; } catch (DbException ex) { throw new ApplicationException("Erro ao listar os registros", ex); } catch (IndexOutOfRangeException ex) { throw new ApplicationException("Erro ao listar os registros", ex); } } public static void Homologar(int promocaoID) { Database conexao; DbCommand comando; try { conexao = DatabaseFactory.CreateDatabase(); using (comando = conexao.GetStoredProcCommand("[dbo].[HomologarPromocao]")) { conexao.AddInParameter(comando, "@PromocaoID", DbType.Int32, promocaoID); conexao.ExecuteNonQuery(comando); } } catch (DbException ex) { throw new ApplicationException("Erro ao excluir o registro", ex); } finally { comando = null; } } public static void Renovar(int promocaoID, DateTime dataFim, bool ativo) { Database conexao; DbCommand comando; try { conexao = DatabaseFactory.CreateDatabase(); using (comando = conexao.GetStoredProcCommand("[dbo].[RenovarPromocao]")) { conexao.AddInParameter(comando, "@PromocaoID", DbType.Int32, promocaoID); conexao.AddInParameter(comando, "@DataFim", DbType.DateTime, dataFim); conexao.AddInParameter(comando, "@Ativo", DbType.Boolean, ativo); conexao.ExecuteNonQuery(comando); } } catch (DbException ex) { throw new ApplicationException("Erro ao excluir o registro", ex); } finally { comando = null; } } } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ // Contributed by: Mitch Thompson using UnityEngine; using System; using System.Collections; namespace Spine.Unity { [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public abstract class SpineAttributeBase : PropertyAttribute { public string dataField = ""; public string startsWith = ""; public bool includeNone = true; } public class SpineSlot : SpineAttributeBase { public bool containsBoundingBoxes = false; /// <summary> /// Smart popup menu for Spine Slots /// </summary> /// <param name="startsWith">Filters popup results to elements that begin with supplied string.</param> /// <param name="containsBoundingBoxes">Disables popup results that don't contain bounding box attachments when true.</param> /// <param name = "includeNone">If true, the dropdown list will include a "none" option which stored as an empty string.</param> /// <param name="dataField">If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). /// If left empty and the script the attribute is applied to is derived from Component, GetComponent<SkeletonRenderer>() will be called as a fallback. /// </param> public SpineSlot(string startsWith = "", string dataField = "", bool containsBoundingBoxes = false, bool includeNone = true) { this.startsWith = startsWith; this.dataField = dataField; this.containsBoundingBoxes = containsBoundingBoxes; this.includeNone = includeNone; } } public class SpineEvent : SpineAttributeBase { /// <summary> /// Smart popup menu for Spine Events (Spine.EventData) /// </summary> /// <param name="startsWith">Filters popup results to elements that begin with supplied string.</param> /// <param name = "includeNone">If true, the dropdown list will include a "none" option which stored as an empty string.</param> /// <param name="dataField">If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). /// If left empty and the script the attribute is applied to is derived from Component, GetComponent<SkeletonRenderer>() will be called as a fallback. /// </param> public SpineEvent(string startsWith = "", string dataField = "", bool includeNone = true) { this.startsWith = startsWith; this.dataField = dataField; this.includeNone = includeNone; } } public class SpineIkConstraint : SpineAttributeBase { /// <summary> /// Smart popup menu for Spine IK Constraints (Spine.IkConstraint) /// </summary> /// <param name="startsWith">Filters popup results to elements that begin with supplied string.</param> /// <param name = "includeNone">If true, the dropdown list will include a "none" option which stored as an empty string.</param> /// <param name="dataField">If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). /// If left empty and the script the attribute is applied to is derived from Component, GetComponent<SkeletonRenderer>() will be called as a fallback. /// </param> public SpineIkConstraint(string startsWith = "", string dataField = "", bool includeNone = true) { this.startsWith = startsWith; this.dataField = dataField; this.includeNone = includeNone; } } public class SpinePathConstraint : SpineAttributeBase { /// <summary> /// Smart popup menu for Spine Events (Spine.PathConstraint) /// </summary> /// <param name="startsWith">Filters popup results to elements that begin with supplied string.</param> /// <param name = "includeNone">If true, the dropdown list will include a "none" option which stored as an empty string.</param> /// <param name="dataField">If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). /// If left empty and the script the attribute is applied to is derived from Component, GetComponent<SkeletonRenderer>() will be called as a fallback. /// </param> public SpinePathConstraint(string startsWith = "", string dataField = "", bool includeNone = true) { this.startsWith = startsWith; this.dataField = dataField; this.includeNone = includeNone; } } public class SpineTransformConstraint : SpineAttributeBase { /// <summary> /// Smart popup menu for Spine Transform Constraints (Spine.TransformConstraint) /// </summary> /// <param name="startsWith">Filters popup results to elements that begin with supplied string.</param> /// <param name = "includeNone">If true, the dropdown list will include a "none" option which stored as an empty string.</param> /// <param name="dataField">If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). /// If left empty and the script the attribute is applied to is derived from Component, GetComponent<SkeletonRenderer>() will be called as a fallback. /// </param> public SpineTransformConstraint(string startsWith = "", string dataField = "", bool includeNone = true) { this.startsWith = startsWith; this.dataField = dataField; this.includeNone = includeNone; } } public class SpineSkin : SpineAttributeBase { /// <summary> /// Smart popup menu for Spine Skins /// </summary> /// <param name="startsWith">Filters popup results to elements that begin with supplied string.</param> /// <param name = "includeNone">If true, the dropdown list will include a "none" option which stored as an empty string.</param> /// <param name="dataField">If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives) /// If left empty and the script the attribute is applied to is derived from Component, GetComponent<SkeletonRenderer>() will be called as a fallback. /// </param> public SpineSkin(string startsWith = "", string dataField = "", bool includeNone = true) { this.startsWith = startsWith; this.dataField = dataField; this.includeNone = includeNone; } } public class SpineAnimation : SpineAttributeBase { /// <summary> /// Smart popup menu for Spine Animations /// </summary> /// <param name="startsWith">Filters popup results to elements that begin with supplied string.</param> /// <param name="dataField">If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. /// <param name="includeNone">If true, the dropdown list will include a "none" option which stored as an empty string.</param> /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives) /// If left empty and the script the attribute is applied to is derived from Component, GetComponent<SkeletonRenderer>() will be called as a fallback. /// </param> public SpineAnimation(string startsWith = "", string dataField = "", bool includeNone = true) { this.startsWith = startsWith; this.dataField = dataField; this.includeNone = includeNone; } } public class SpineAttachment : SpineAttributeBase { public bool returnAttachmentPath = false; public bool currentSkinOnly = false; public bool placeholdersOnly = false; public string skinField = ""; public string slotField = ""; /// <summary> /// Smart popup menu for Spine Attachments /// </summary> /// <param name="currentSkinOnly">Filters popup results to only include the current Skin. Only valid when a SkeletonRenderer is the data source.</param> /// <param name="returnAttachmentPath">Returns a fully qualified path for an Attachment in the format "Skin/Slot/AttachmentName". This path format is only used by the SpineAttachment helper methods like SpineAttachment.GetAttachment and .GetHierarchy. Do not use full path anywhere else in Spine's system.</param> /// <param name="placeholdersOnly">Filters popup results to exclude attachments that are not children of Skin Placeholders</param> /// <param name="slotField">If specified, a locally scoped field with the name supplied by in slotField will be used to limit the popup results to children of a named slot</param> /// <param name="skinField">If specified, a locally scoped field with the name supplied by in skinField will be used to limit the popup results to entries of the named skin</param> /// <param name="includeNone">If true, the dropdown list will include a "none" option which stored as an empty string.</param> /// <param name="dataField">If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives) /// If left empty and the script the attribute is applied to is derived from Component, GetComponent<SkeletonRenderer>() will be called as a fallback. /// </param> public SpineAttachment (bool currentSkinOnly = true, bool returnAttachmentPath = false, bool placeholdersOnly = false, string slotField = "", string dataField = "", string skinField = "", bool includeNone = true) { this.currentSkinOnly = currentSkinOnly; this.returnAttachmentPath = returnAttachmentPath; this.placeholdersOnly = placeholdersOnly; this.slotField = slotField; this.dataField = dataField; this.skinField = skinField; this.includeNone = includeNone; } public static SpineAttachment.Hierarchy GetHierarchy (string fullPath) { return new SpineAttachment.Hierarchy(fullPath); } public static Spine.Attachment GetAttachment (string attachmentPath, Spine.SkeletonData skeletonData) { var hierarchy = SpineAttachment.GetHierarchy(attachmentPath); return string.IsNullOrEmpty(hierarchy.name) ? null : skeletonData.FindSkin(hierarchy.skin).GetAttachment(skeletonData.FindSlotIndex(hierarchy.slot), hierarchy.name); } public static Spine.Attachment GetAttachment (string attachmentPath, SkeletonDataAsset skeletonDataAsset) { return GetAttachment(attachmentPath, skeletonDataAsset.GetSkeletonData(true)); } /// <summary> /// A struct that represents 3 strings that help identify and locate an attachment in a skeleton.</summary> public struct Hierarchy { public string skin; public string slot; public string name; public Hierarchy (string fullPath) { string[] chunks = fullPath.Split(new char[]{'/'}, System.StringSplitOptions.RemoveEmptyEntries); if (chunks.Length == 0) { skin = ""; slot = ""; name = ""; return; } else if (chunks.Length < 2) { throw new System.Exception("Cannot generate Attachment Hierarchy from string! Not enough components! [" + fullPath + "]"); } skin = chunks[0]; slot = chunks[1]; name = ""; for (int i = 2; i < chunks.Length; i++) { name += chunks[i]; } } } } public class SpineBone : SpineAttributeBase { /// <summary> /// Smart popup menu for Spine Bones /// </summary> /// <param name="startsWith">Filters popup results to elements that begin with supplied string.</param> /// /// <param name="includeNone">If true, the dropdown list will include a "none" option which stored as an empty string.</param> /// <param name="dataField">If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives) /// If left empty and the script the attribute is applied to is derived from Component, GetComponent<SkeletonRenderer>() will be called as a fallback. /// </param> public SpineBone(string startsWith = "", string dataField = "", bool includeNone = true) { this.startsWith = startsWith; this.dataField = dataField; this.includeNone = includeNone; } public static Spine.Bone GetBone(string boneName, SkeletonRenderer renderer) { return renderer.skeleton == null ? null : renderer.skeleton.FindBone(boneName); } public static Spine.BoneData GetBoneData(string boneName, SkeletonDataAsset skeletonDataAsset) { var data = skeletonDataAsset.GetSkeletonData(true); return data.FindBone(boneName); } } public class SpineAtlasRegion : PropertyAttribute { public string atlasAssetField; public SpineAtlasRegion(string atlasAssetField = "") { this.atlasAssetField = atlasAssetField; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reactive.Linq; using Moq; using Avalonia.Controls; using Xunit; using System.Threading.Tasks; using Avalonia.Data.Converters; using Avalonia.Data; namespace Avalonia.Markup.UnitTests.Data { public class MultiBindingTests { [Fact] public async Task OneWay_Binding_Should_Be_Set_Up() { var source = new { A = 1, B = 2, C = 3 }; var binding = new MultiBinding { Converter = new ConcatConverter(), Bindings = new[] { new Binding { Path = "A" }, new Binding { Path = "B" }, new Binding { Path = "C" }, } }; var target = new Mock<IAvaloniaObject>().As<IControl>(); target.Setup(x => x.GetValue(Control.DataContextProperty)).Returns(source); var observable = binding.Initiate(target.Object, null).Observable; var result = await observable.Take(1); Assert.Equal("1,2,3", result); } [Fact] public async Task Nested_MultiBinding_Should_Be_Set_Up() { var source = new { A = 1, B = 2, C = 3 }; var binding = new MultiBinding { Converter = new ConcatConverter(), Bindings = { new Binding { Path = "A" }, new MultiBinding { Converter = new ConcatConverter(), Bindings = { new Binding { Path = "B"}, new Binding { Path = "C"} } } } }; var target = new Mock<IAvaloniaObject>().As<IControl>(); target.Setup(x => x.GetValue(Control.DataContextProperty)).Returns(source); var observable = binding.Initiate(target.Object, null).Observable; var result = await observable.Take(1); Assert.Equal("1,2,3", result); } [Fact] public void Should_Return_FallbackValue_When_Converter_Returns_UnsetValue() { var target = new TextBlock(); var source = new { A = 1, B = 2, C = 3 }; var binding = new MultiBinding { Converter = new UnsetValueConverter(), Bindings = new[] { new Binding { Path = "A" }, new Binding { Path = "B" }, new Binding { Path = "C" }, }, FallbackValue = "fallback", }; target.Bind(TextBlock.TextProperty, binding); Assert.Equal("fallback", target.Text); } [Fact] public void Should_Return_TargetNullValue_When_Value_Is_Null() { var target = new TextBlock(); var binding = new MultiBinding { Converter = new NullValueConverter(), Bindings = new[] { new Binding { Path = "A" }, new Binding { Path = "B" }, new Binding { Path = "C" }, }, TargetNullValue = "(null)", }; target.Bind(TextBlock.TextProperty, binding); Assert.Equal("(null)", target.Text); } [Fact] public void Should_Pass_UnsetValue_To_Converter_For_Broken_Binding() { var source = new { A = 1, B = 2, C = 3 }; var target = new TextBlock { DataContext = source }; var binding = new MultiBinding { Converter = new ConcatConverter(), Bindings = new[] { new Binding { Path = "A" }, new Binding { Path = "B" }, new Binding { Path = "Missing" }, }, }; target.Bind(TextBlock.TextProperty, binding); Assert.Equal("1,2,(unset)", target.Text); } [Fact] public void Should_Pass_FallbackValue_To_Converter_For_Broken_Binding() { var source = new { A = 1, B = 2, C = 3 }; var target = new TextBlock { DataContext = source }; var binding = new MultiBinding { Converter = new ConcatConverter(), Bindings = new[] { new Binding { Path = "A" }, new Binding { Path = "B" }, new Binding { Path = "Missing", FallbackValue = "Fallback" }, }, }; target.Bind(TextBlock.TextProperty, binding); Assert.Equal("1,2,Fallback", target.Text); } [Fact] public void MultiBinding_Without_StringFormat_And_Converter() { var source = new { A = 1, B = 2, C = 3 }; var target = new ItemsControl { }; var binding = new MultiBinding { Bindings = new[] { new Binding { Path = "A", Source = source }, new Binding { Path = "B", Source = source }, new Binding { Path = "C", Source = source }, }, }; target.Bind(ItemsControl.ItemsProperty, binding); Assert.Equal(target.ItemCount, 3); Assert.Equal(target.Items.ElementAt(0), source.A); Assert.Equal(target.Items.ElementAt(1), source.B); Assert.Equal(target.Items.ElementAt(2), source.C); } private class ConcatConverter : IMultiValueConverter { public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture) { return string.Join(",", values); } } private class UnsetValueConverter : IMultiValueConverter { public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture) { return AvaloniaProperty.UnsetValue; } } private class NullValueConverter : IMultiValueConverter { public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture) { return 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 log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.World.Land; using OpenSim.Region.DataSnapshot.Interfaces; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; using System.Xml; namespace OpenSim.Region.DataSnapshot.Providers { public class LandSnapshot : IDataSnapshotProvider { private Scene m_scene = null; private DataSnapshotManager m_parent = null; //private Dictionary<int, Land> m_landIndexed = new Dictionary<int, Land>(); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool m_stale = true; #region Dead code /* * David, I don't think we need this at all. When we do the snapshot, we can * simply look into the parcels that are marked for ShowDirectory -- see * conditional in RequestSnapshotData * //Revise this, look for more direct way of checking for change in land #region Client hooks public void OnNewClient(IClientAPI client) { //Land hooks client.OnParcelDivideRequest += ParcelSplitHook; client.OnParcelJoinRequest += ParcelSplitHook; client.OnParcelPropertiesUpdateRequest += ParcelPropsHook; } public void ParcelSplitHook(int west, int south, int east, int north, IClientAPI remote_client) { PrepareData(); } public void ParcelPropsHook(ParcelPropertiesUpdatePacket packet, IClientAPI remote_client) { PrepareData(); } #endregion public void PrepareData() { m_log.Info("[EXTERNALDATA]: Generating land data."); m_landIndexed.Clear(); //Index sim land foreach (KeyValuePair<int, Land> curLand in m_scene.LandManager.landList) { //if ((curLand.Value.LandData.landFlags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory) //{ m_landIndexed.Add(curLand.Key, curLand.Value.Copy()); //} } } public Dictionary<int,Land> IndexedLand { get { return m_landIndexed; } } */ #endregion #region IDataSnapshotProvider members public void Initialize(Scene scene, DataSnapshotManager parent) { m_scene = scene; m_parent = parent; //Brought back from the dead for staleness checks. m_scene.EventManager.OnNewClient += OnNewClient; } public Scene GetParentScene { get { return m_scene; } } public XmlNode RequestSnapshotData(XmlDocument nodeFactory) { ILandChannel landChannel = m_scene.LandChannel; List<ILandObject> parcels = landChannel.AllParcels(); IDwellModule dwellModule = m_scene.RequestModuleInterface<IDwellModule>(); XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "parceldata", ""); if (parcels != null) { //foreach (KeyValuePair<int, Land> curParcel in m_landIndexed) foreach (ILandObject parcel_interface in parcels) { // Play it safe if (!(parcel_interface is LandObject)) continue; LandObject land = (LandObject)parcel_interface; LandData parcel = land.LandData; if (m_parent.ExposureLevel.Equals("all") || (m_parent.ExposureLevel.Equals("minimum") && (parcel.Flags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory)) { //TODO: make better method of marshalling data from LandData to XmlNode XmlNode xmlparcel = nodeFactory.CreateNode(XmlNodeType.Element, "parcel", ""); // Attributes of the parcel node XmlAttribute scripts_attr = nodeFactory.CreateAttribute("scripts"); scripts_attr.Value = GetScriptsPermissions(parcel); XmlAttribute build_attr = nodeFactory.CreateAttribute("build"); build_attr.Value = GetBuildPermissions(parcel); XmlAttribute public_attr = nodeFactory.CreateAttribute("public"); public_attr.Value = GetPublicPermissions(parcel); // Check the category of the Parcel XmlAttribute category_attr = nodeFactory.CreateAttribute("category"); category_attr.Value = ((int)parcel.Category).ToString(); // Check if the parcel is for sale XmlAttribute forsale_attr = nodeFactory.CreateAttribute("forsale"); forsale_attr.Value = CheckForSale(parcel); XmlAttribute sales_attr = nodeFactory.CreateAttribute("salesprice"); sales_attr.Value = parcel.SalePrice.ToString(); XmlAttribute directory_attr = nodeFactory.CreateAttribute("showinsearch"); directory_attr.Value = GetShowInSearch(parcel); //XmlAttribute entities_attr = nodeFactory.CreateAttribute("entities"); //entities_attr.Value = land.primsOverMe.Count.ToString(); xmlparcel.Attributes.Append(directory_attr); xmlparcel.Attributes.Append(scripts_attr); xmlparcel.Attributes.Append(build_attr); xmlparcel.Attributes.Append(public_attr); xmlparcel.Attributes.Append(category_attr); xmlparcel.Attributes.Append(forsale_attr); xmlparcel.Attributes.Append(sales_attr); //xmlparcel.Attributes.Append(entities_attr); //name, description, area, and UUID XmlNode name = nodeFactory.CreateNode(XmlNodeType.Element, "name", ""); name.InnerText = parcel.Name; xmlparcel.AppendChild(name); XmlNode desc = nodeFactory.CreateNode(XmlNodeType.Element, "description", ""); desc.InnerText = parcel.Description; xmlparcel.AppendChild(desc); XmlNode uuid = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", ""); uuid.InnerText = parcel.GlobalID.ToString(); xmlparcel.AppendChild(uuid); XmlNode area = nodeFactory.CreateNode(XmlNodeType.Element, "area", ""); area.InnerText = parcel.Area.ToString(); xmlparcel.AppendChild(area); //default location XmlNode tpLocation = nodeFactory.CreateNode(XmlNodeType.Element, "location", ""); Vector3 loc = parcel.UserLocation; if (loc.Equals(Vector3.Zero)) // This test is moot at this point: the location is wrong by default loc = new Vector3((parcel.AABBMax.X + parcel.AABBMin.X) / 2, (parcel.AABBMax.Y + parcel.AABBMin.Y) / 2, (parcel.AABBMax.Z + parcel.AABBMin.Z) / 2); tpLocation.InnerText = loc.X.ToString() + "/" + loc.Y.ToString() + "/" + loc.Z.ToString(); xmlparcel.AppendChild(tpLocation); XmlNode infouuid = nodeFactory.CreateNode(XmlNodeType.Element, "infouuid", ""); uint x = (uint)loc.X, y = (uint)loc.Y; findPointInParcel(land, ref x, ref y); // find a suitable spot infouuid.InnerText = Util.BuildFakeParcelID( m_scene.RegionInfo.RegionHandle, x, y).ToString(); xmlparcel.AppendChild(infouuid); XmlNode dwell = nodeFactory.CreateNode(XmlNodeType.Element, "dwell", ""); if (dwellModule != null) dwell.InnerText = dwellModule.GetDwell(parcel.GlobalID).ToString(); else dwell.InnerText = "0"; xmlparcel.AppendChild(dwell); //TODO: figure how to figure out teleport system landData.landingType //land texture snapshot uuid if (parcel.SnapshotID != UUID.Zero) { XmlNode textureuuid = nodeFactory.CreateNode(XmlNodeType.Element, "image", ""); textureuuid.InnerText = parcel.SnapshotID.ToString(); xmlparcel.AppendChild(textureuuid); } string groupName = String.Empty; //attached user and group if (parcel.GroupID != UUID.Zero) { XmlNode groupblock = nodeFactory.CreateNode(XmlNodeType.Element, "group", ""); XmlNode groupuuid = nodeFactory.CreateNode(XmlNodeType.Element, "groupuuid", ""); groupuuid.InnerText = parcel.GroupID.ToString(); groupblock.AppendChild(groupuuid); IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>(); if (gm != null) { GroupRecord g = gm.GetGroupRecord(parcel.GroupID); if (g != null) groupName = g.GroupName; } XmlNode groupname = nodeFactory.CreateNode(XmlNodeType.Element, "groupname", ""); groupname.InnerText = groupName; groupblock.AppendChild(groupname); xmlparcel.AppendChild(groupblock); } XmlNode userblock = nodeFactory.CreateNode(XmlNodeType.Element, "owner", ""); UUID userOwnerUUID = parcel.OwnerID; XmlNode useruuid = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", ""); useruuid.InnerText = userOwnerUUID.ToString(); userblock.AppendChild(useruuid); if (!parcel.IsGroupOwned) { try { XmlNode username = nodeFactory.CreateNode(XmlNodeType.Element, "name", ""); UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, userOwnerUUID); username.InnerText = account.FirstName + " " + account.LastName; userblock.AppendChild(username); } catch (Exception) { //m_log.Info("[DATASNAPSHOT]: Cannot find owner name; ignoring this parcel"); } } else { XmlNode username = nodeFactory.CreateNode(XmlNodeType.Element, "name", ""); username.InnerText = groupName; userblock.AppendChild(username); } xmlparcel.AppendChild(userblock); parent.AppendChild(xmlparcel); } } //snap.AppendChild(parent); } this.Stale = false; return parent; } public String Name { get { return "LandSnapshot"; } } public bool Stale { get { return m_stale; } set { m_stale = value; if (m_stale) OnStale(this); } } public event ProviderStale OnStale; #endregion #region Helper functions private string GetScriptsPermissions(LandData parcel) { if ((parcel.Flags & (uint)ParcelFlags.AllowOtherScripts) == (uint)ParcelFlags.AllowOtherScripts) return "true"; else return "false"; } private string GetPublicPermissions(LandData parcel) { if ((parcel.Flags & (uint)ParcelFlags.UseAccessList) == (uint)ParcelFlags.UseAccessList) return "false"; else return "true"; } private string GetBuildPermissions(LandData parcel) { if ((parcel.Flags & (uint)ParcelFlags.CreateObjects) == (uint)ParcelFlags.CreateObjects) return "true"; else return "false"; } private string CheckForSale(LandData parcel) { if ((parcel.Flags & (uint)ParcelFlags.ForSale) == (uint)ParcelFlags.ForSale) return "true"; else return "false"; } private string GetShowInSearch(LandData parcel) { if ((parcel.Flags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory) return "true"; else return "false"; } #endregion #region Change detection hooks public void OnNewClient(IClientAPI client) { //Land hooks client.OnParcelDivideRequest += delegate(int west, int south, int east, int north, IClientAPI remote_client) { this.Stale = true; }; client.OnParcelJoinRequest += delegate(int west, int south, int east, int north, IClientAPI remote_client) { this.Stale = true; }; client.OnParcelPropertiesUpdateRequest += delegate(LandUpdateArgs args, int local_id, IClientAPI remote_client) { this.Stale = true; }; client.OnParcelBuy += delegate(UUID agentId, UUID groupId, bool final, bool groupOwned, bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated) { this.Stale = true; }; } public void ParcelSplitHook(int west, int south, int east, int north, IClientAPI remote_client) { this.Stale = true; } public void ParcelPropsHook(LandUpdateArgs args, int local_id, IClientAPI remote_client) { this.Stale = true; } #endregion // this is needed for non-convex parcels (example: rectangular parcel, and in the exact center // another, smaller rectangular parcel). Both will have the same initial coordinates. private void findPointInParcel(ILandObject land, ref uint refX, ref uint refY) { m_log.DebugFormat("[DATASNAPSHOT] trying {0}, {1}", refX, refY); // the point we started with already is in the parcel if (land.ContainsPoint((int)refX, (int)refY)) return; // ... otherwise, we have to search for a point within the parcel uint startX = (uint)land.LandData.AABBMin.X; uint startY = (uint)land.LandData.AABBMin.Y; uint endX = (uint)land.LandData.AABBMax.X; uint endY = (uint)land.LandData.AABBMax.Y; // default: center of the parcel refX = (startX + endX) / 2; refY = (startY + endY) / 2; // If the center point is within the parcel, take that one if (land.ContainsPoint((int)refX, (int)refY)) return; // otherwise, go the long way. for (uint y = startY; y <= endY; ++y) { for (uint x = startX; x <= endX; ++x) { if (land.ContainsPoint((int)x, (int)y)) { // found a point refX = x; refY = y; return; } } } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Management.Automation.Language; using Microsoft.PowerShell.EditorServices.Services.TextDocument; namespace Microsoft.PowerShell.EditorServices.Extensions { /// <summary> /// Provides context for a file that is open in the editor. /// </summary> public sealed class FileContext { #region Private Fields private readonly ScriptFile scriptFile; private readonly EditorContext editorContext; private readonly IEditorOperations editorOperations; #endregion #region Properties /// <summary> /// Gets the parsed abstract syntax tree for the file. /// </summary> public Ast Ast => this.scriptFile.ScriptAst; /// <summary> /// Gets a BufferRange which represents the entire content /// range of the file. /// </summary> public IFileRange FileRange => new BufferFileRange(this.scriptFile.FileRange); /// <summary> /// Gets the language of the file. /// </summary> public string Language { get; private set; } /// <summary> /// Gets the filesystem path of the file. /// </summary> public string Path => this.scriptFile.FilePath; /// <summary> /// Gets the URI of the file. /// </summary> public Uri Uri { get; } /// <summary> /// Gets the parsed token list for the file. /// </summary> public IReadOnlyList<Token> Tokens => this.scriptFile.ScriptTokens; /// <summary> /// Gets the workspace-relative path of the file. /// </summary> public string WorkspacePath { get { return this.editorOperations.GetWorkspaceRelativePath( this.scriptFile.FilePath); } } #endregion #region Constructors /// <summary> /// Creates a new instance of the FileContext class. /// </summary> /// <param name="scriptFile">The ScriptFile to which this file refers.</param> /// <param name="editorContext">The EditorContext to which this file relates.</param> /// <param name="editorOperations">An IEditorOperations implementation which performs operations in the editor.</param> /// <param name="language">Determines the language of the file.false If it is not specified, then it defaults to "Unknown"</param> internal FileContext( ScriptFile scriptFile, EditorContext editorContext, IEditorOperations editorOperations, string language = "Unknown") { if (string.IsNullOrWhiteSpace(language)) { language = "Unknown"; } this.scriptFile = scriptFile; this.editorContext = editorContext; this.editorOperations = editorOperations; this.Language = language; this.Uri = scriptFile.DocumentUri.ToUri(); } #endregion #region Text Accessors /// <summary> /// Gets the complete file content as a string. /// </summary> /// <returns>A string containing the complete file content.</returns> public string GetText() { return this.scriptFile.Contents; } /// <summary> /// Gets the file content in the specified range as a string. /// </summary> /// <param name="bufferRange">The buffer range for which content will be extracted.</param> /// <returns>A string with the specified range of content.</returns> public string GetText(FileRange bufferRange) { return string.Join( Environment.NewLine, this.GetTextLines(bufferRange)); } /// <summary> /// Gets the complete file content as an array of strings. /// </summary> /// <returns>An array of strings, each representing a line in the file.</returns> public string[] GetTextLines() { return this.scriptFile.FileLines.ToArray(); } /// <summary> /// Gets the file content in the specified range as an array of strings. /// </summary> /// <param name="bufferRange">The buffer range for which content will be extracted.</param> /// <returns>An array of strings, each representing a line in the file within the specified range.</returns> public string[] GetTextLines(FileRange fileRange) { return this.scriptFile.GetLinesInRange(fileRange.ToBufferRange()); } #endregion #region Text Manipulation /// <summary> /// Inserts a text string at the current cursor position represented by /// the parent EditorContext's CursorPosition property. /// </summary> /// <param name="textToInsert">The text string to insert.</param> public void InsertText(string textToInsert) { // Is there a selection? if (this.editorContext.SelectedRange.HasRange()) { this.InsertText( textToInsert, this.editorContext.SelectedRange); } else { this.InsertText( textToInsert, this.editorContext.CursorPosition); } } /// <summary> /// Inserts a text string at the specified buffer position. /// </summary> /// <param name="textToInsert">The text string to insert.</param> /// <param name="insertPosition">The position at which the text will be inserted.</param> public void InsertText(string textToInsert, IFilePosition insertPosition) { this.InsertText( textToInsert, new FileRange(insertPosition, insertPosition)); } /// <summary> /// Inserts a text string at the specified line and column numbers. /// </summary> /// <param name="textToInsert">The text string to insert.</param> /// <param name="insertLine">The 1-based line number at which the text will be inserted.</param> /// <param name="insertColumn">The 1-based column number at which the text will be inserted.</param> public void InsertText(string textToInsert, int insertLine, int insertColumn) { this.InsertText( textToInsert, new FilePosition(insertLine, insertColumn)); } /// <summary> /// Inserts a text string to replace the specified range, represented /// by starting and ending line and column numbers. Can be used to /// insert, replace, or delete text depending on the specified range /// and text to insert. /// </summary> /// <param name="textToInsert">The text string to insert.</param> /// <param name="startLine">The 1-based starting line number where text will be replaced.</param> /// <param name="startColumn">The 1-based starting column number where text will be replaced.</param> /// <param name="endLine">The 1-based ending line number where text will be replaced.</param> /// <param name="endColumn">The 1-based ending column number where text will be replaced.</param> public void InsertText( string textToInsert, int startLine, int startColumn, int endLine, int endColumn) { this.InsertText( textToInsert, new FileRange( new FilePosition(startLine, startColumn), new FilePosition(endLine, endColumn))); } /// <summary> /// Inserts a text string to replace the specified range. Can be /// used to insert, replace, or delete text depending on the specified /// range and text to insert. /// </summary> /// <param name="textToInsert">The text string to insert.</param> /// <param name="insertRange">The buffer range which will be replaced by the string.</param> public void InsertText(string textToInsert, IFileRange insertRange) { this.editorOperations .InsertTextAsync(this.scriptFile.DocumentUri.ToString(), textToInsert, insertRange.ToBufferRange()) .Wait(); } #endregion #region File Manipulation /// <summary> /// Saves this file. /// </summary> public void Save() { this.editorOperations.SaveFileAsync(this.scriptFile.FilePath); } /// <summary> /// Save this file under a new path and open a new editor window on that file. /// </summary> /// <param name="newFilePath"> /// the path where the file should be saved, /// including the file name with extension as the leaf /// </param> public void SaveAs(string newFilePath) { // Do some validation here so that we can provide a helpful error if the path won't work string absolutePath = System.IO.Path.IsPathRooted(newFilePath) ? newFilePath : System.IO.Path.GetFullPath(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.scriptFile.FilePath), newFilePath)); if (File.Exists(absolutePath)) { throw new IOException(String.Format("The file '{0}' already exists", absolutePath)); } this.editorOperations.SaveFileAsync(this.scriptFile.FilePath, newFilePath); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Security.Permissions; using System.Security.Principal; namespace System.DirectoryServices.AccountManagement { #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 [DirectoryRdnPrefix("CN")] public class UserPrincipal : AuthenticablePrincipal { // // Public constructors // public UserPrincipal(PrincipalContext context) : base(context) { if (context == null) throw new ArgumentException(StringResources.NullArguments); this.ContextRaw = context; this.unpersisted = true; } public UserPrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context) { if (samAccountName == null || password == null) throw new ArgumentException(StringResources.NullArguments); if (Context.ContextType != ContextType.ApplicationDirectory) this.SamAccountName = samAccountName; this.Name = samAccountName; this.SetPassword(password); this.Enabled = enabled; } // // Public properties // // GivenName private string _givenName = null; // the actual property value private LoadState _givenNameChanged = LoadState.NotSet; // change-tracking public string GivenName { get { return HandleGet<string>(ref _givenName, PropertyNames.UserGivenName, ref _givenNameChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserGivenName)) throw new InvalidOperationException(StringResources.InvalidPropertyForStore); HandleSet<string>(ref _givenName, value, ref _givenNameChanged, PropertyNames.UserGivenName); } } // MiddleName private string _middleName = null; // the actual property value private LoadState _middleNameChanged = LoadState.NotSet; // change-tracking public string MiddleName { get { return HandleGet<string>(ref _middleName, PropertyNames.UserMiddleName, ref _middleNameChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserMiddleName)) throw new InvalidOperationException(StringResources.InvalidPropertyForStore); HandleSet<string>(ref _middleName, value, ref _middleNameChanged, PropertyNames.UserMiddleName); } } // Surname private string _surname = null; // the actual property value private LoadState _surnameChanged = LoadState.NotSet; // change-tracking public string Surname { get { return HandleGet<string>(ref _surname, PropertyNames.UserSurname, ref _surnameChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserSurname)) throw new InvalidOperationException(StringResources.InvalidPropertyForStore); HandleSet<string>(ref _surname, value, ref _surnameChanged, PropertyNames.UserSurname); } } // EmailAddress private string _emailAddress = null; // the actual property value private LoadState _emailAddressChanged = LoadState.NotSet; // change-tracking public string EmailAddress { get { return HandleGet<string>(ref _emailAddress, PropertyNames.UserEmailAddress, ref _emailAddressChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmailAddress)) throw new InvalidOperationException(StringResources.InvalidPropertyForStore); HandleSet<string>(ref _emailAddress, value, ref _emailAddressChanged, PropertyNames.UserEmailAddress); } } // VoiceTelephoneNumber private string _voiceTelephoneNumber = null; // the actual property value private LoadState _voiceTelephoneNumberChanged = LoadState.NotSet; // change-tracking public string VoiceTelephoneNumber { get { return HandleGet<string>(ref _voiceTelephoneNumber, PropertyNames.UserVoiceTelephoneNumber, ref _voiceTelephoneNumberChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserVoiceTelephoneNumber)) throw new InvalidOperationException(StringResources.InvalidPropertyForStore); HandleSet<string>(ref _voiceTelephoneNumber, value, ref _voiceTelephoneNumberChanged, PropertyNames.UserVoiceTelephoneNumber); } } // EmployeeId private string _employeeID = null; // the actual property value private LoadState _employeeIDChanged = LoadState.NotSet; // change-tracking public string EmployeeId { get { return HandleGet<string>(ref _employeeID, PropertyNames.UserEmployeeID, ref _employeeIDChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmployeeID)) throw new InvalidOperationException(StringResources.InvalidPropertyForStore); HandleSet<string>(ref _employeeID, value, ref _employeeIDChanged, PropertyNames.UserEmployeeID); } } public override AdvancedFilters AdvancedSearchFilter { get { return rosf; } } public static UserPrincipal Current { [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)] get { PrincipalContext context; // Get the correct PrincipalContext to query against, depending on whether we're running // as a local or domain user if (Utils.IsSamUser()) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is local user"); #if PAPI_REGSAM context = new PrincipalContext(ContextType.Machine); #else // This implementation doesn't support Reg-SAM/MSAM (machine principals) throw new NotSupportedException(StringResources.UserLocalNotSupportedOnPlatform); #endif // PAPI_REGSAM } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is not local user"); #if PAPI_AD context = new PrincipalContext(ContextType.Domain); #else // This implementation doesn't support AD (domain principals) throw new NotSupportedException(StringResources.UserDomainNotSupportedOnPlatform); #endif // PAPI_AD } // Construct a query for the current user, using a SID IdentityClaim IntPtr pSid = IntPtr.Zero; UserPrincipal user = null; try { pSid = Utils.GetCurrentUserSid(); byte[] sid = Utils.ConvertNativeSidToByteArray(pSid); SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: using SID " + sidObj.ToString()); user = UserPrincipal.FindByIdentity(context, IdentityType.Sid, sidObj.ToString()); } finally { if (pSid != IntPtr.Zero) System.Runtime.InteropServices.Marshal.FreeHGlobal(pSid); } // We're running as the user, we know they must exist, but perhaps we don't have access // to their user object if (user == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "User", "Current: found no user"); throw new NoMatchingPrincipalException(StringResources.UserCouldNotFindCurrent); } return user; } } // // Public methods // public static new PrincipalSearchResult<UserPrincipal> FindByLockoutTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLockoutTime<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByLogonTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLogonTime<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByExpirationTime(PrincipalContext context, DateTime time, MatchType type) { return FindByExpirationTime<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByBadPasswordAttempt(PrincipalContext context, DateTime time, MatchType type) { return FindByBadPasswordAttempt<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByPasswordSetTime(PrincipalContext context, DateTime time, MatchType type) { return FindByPasswordSetTime<UserPrincipal>(context, time, type); } public static new UserPrincipal FindByIdentity(PrincipalContext context, string identityValue) { return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityValue); } public static new UserPrincipal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue) { return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityType, identityValue); } public PrincipalSearchResult<Principal> GetAuthorizationGroups() { return new PrincipalSearchResult<Principal>(GetAuthorizationGroupsHelper()); } // // Internal "constructor": Used for constructing Users returned by a query // static internal UserPrincipal MakeUser(PrincipalContext ctx) { UserPrincipal u = new UserPrincipal(ctx); u.unpersisted = false; return u; } // // Private implementation // private ResultSet GetAuthorizationGroupsHelper() { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); // Unpersisted principals are not members of any group if (this.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetAuthorizationGroupsHelper: unpersisted, using EmptySet"); return new EmptySet(); } StoreCtx storeCtx = GetStoreCtxToUse(); Debug.Assert(storeCtx != null); GlobalDebug.WriteLineIf( GlobalDebug.Info, "User", "GetAuthorizationGroupsHelper: retrieving AZ groups from StoreCtx of type=" + storeCtx.GetType().ToString() + ", base path=" + storeCtx.BasePath); ResultSet resultSet = storeCtx.GetGroupsMemberOfAZ(this); return resultSet; } // // Load/Store implementation // // // Loading with query results // internal override void LoadValueIntoProperty(string propertyName, object value) { if (value == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value= null"); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString()); } switch (propertyName) { case (PropertyNames.UserGivenName): _givenName = (string)value; _givenNameChanged = LoadState.Loaded; break; case (PropertyNames.UserMiddleName): _middleName = (string)value; _middleNameChanged = LoadState.Loaded; break; case (PropertyNames.UserSurname): _surname = (string)value; _surnameChanged = LoadState.Loaded; break; case (PropertyNames.UserEmailAddress): _emailAddress = (string)value; _emailAddressChanged = LoadState.Loaded; break; case (PropertyNames.UserVoiceTelephoneNumber): _voiceTelephoneNumber = (string)value; _voiceTelephoneNumberChanged = LoadState.Loaded; break; case (PropertyNames.UserEmployeeID): _employeeID = (string)value; _employeeIDChanged = LoadState.Loaded; break; default: base.LoadValueIntoProperty(propertyName, value); break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal override bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.UserGivenName): return _givenNameChanged == LoadState.Changed; case (PropertyNames.UserMiddleName): return _middleNameChanged == LoadState.Changed; case (PropertyNames.UserSurname): return _surnameChanged == LoadState.Changed; case (PropertyNames.UserEmailAddress): return _emailAddressChanged == LoadState.Changed; case (PropertyNames.UserVoiceTelephoneNumber): return _voiceTelephoneNumberChanged == LoadState.Changed; case (PropertyNames.UserEmployeeID): return _employeeIDChanged == LoadState.Changed; default: return base.GetChangeStatusForProperty(propertyName); } } // Given a property name, returns the current value for the property. internal override object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.UserGivenName): return _givenName; case (PropertyNames.UserMiddleName): return _middleName; case (PropertyNames.UserSurname): return _surname; case (PropertyNames.UserEmailAddress): return _emailAddress; case (PropertyNames.UserVoiceTelephoneNumber): return _voiceTelephoneNumber; case (PropertyNames.UserEmployeeID): return _employeeID; default: return base.GetValueForProperty(propertyName); } } // Reset all change-tracking status for all properties on the object to "unchanged". internal override void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "ResetAllChangeStatus"); _givenNameChanged = (_givenNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _middleNameChanged = (_middleNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _surnameChanged = (_surnameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _emailAddressChanged = (_emailAddressChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _voiceTelephoneNumberChanged = (_voiceTelephoneNumberChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _employeeIDChanged = (_employeeIDChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; base.ResetAllChangeStatus(); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.SS.Formula { using System; using System.Text; using System.Text.RegularExpressions; using NPOI.Util; using System.Globalization; /** * Formats sheet names for use in formula expressions. * * @author Josh Micich */ internal class SheetNameFormatter { private static String BIFF8_LAST_COLUMN = "IV"; private static int BIFF8_LAST_COLUMN_TEXT_LEN = BIFF8_LAST_COLUMN.Length; private static String BIFF8_LAST_ROW = (0x10000).ToString(CultureInfo.InvariantCulture); private static int BIFF8_LAST_ROW_TEXT_LEN = BIFF8_LAST_ROW.Length; private static char DELIMITER = '\''; private static string CELL_REF_PATTERN = "^([A-Za-z]+)([0-9]+)$"; private SheetNameFormatter() { // no instances of this class } /** * Used to format sheet names as they would appear in cell formula expressions. * @return the sheet name UnChanged if there is no need for delimiting. Otherwise the sheet * name is enclosed in single quotes ('). Any single quotes which were already present in the * sheet name will be converted to double single quotes (''). */ public static String Format(String rawSheetName) { StringBuilder sb = new StringBuilder(rawSheetName.Length + 2); AppendFormat(sb, rawSheetName); return sb.ToString(); } /** * Convenience method for when a StringBuilder is already available * * @param out - sheet name will be Appended here possibly with delimiting quotes */ public static void AppendFormat(StringBuilder out1, String rawSheetName) { bool needsQuotes = NeedsDelimiting(rawSheetName); if (needsQuotes) { out1.Append(DELIMITER); AppendAndEscape(out1, rawSheetName); out1.Append(DELIMITER); } else { out1.Append(rawSheetName); } } public static void AppendFormat(StringBuilder out1, String workbookName, String rawSheetName) { bool needsQuotes = NeedsDelimiting(workbookName) || NeedsDelimiting(rawSheetName); if (needsQuotes) { out1.Append(DELIMITER); out1.Append('['); AppendAndEscape(out1, workbookName.Replace('[', '(').Replace(']', ')')); out1.Append(']'); AppendAndEscape(out1, rawSheetName); out1.Append(DELIMITER); } else { out1.Append('['); out1.Append(workbookName); out1.Append(']'); out1.Append(rawSheetName); } } private static void AppendAndEscape(StringBuilder sb, String rawSheetName) { int len = rawSheetName.Length; for (int i = 0; i < len; i++) { char ch = rawSheetName[i]; if (ch == DELIMITER) { // single quotes (') are encoded as ('') sb.Append(DELIMITER); } sb.Append(ch); } } private static bool NeedsDelimiting(String rawSheetName) { int len = rawSheetName.Length; if (len < 1) { throw new Exception("Zero Length string is an invalid sheet name"); } if (Char.IsDigit(rawSheetName[0])) { // sheet name with digit in the first position always requires delimiting return true; } for (int i = 0; i < len; i++) { char ch = rawSheetName[i]; if (IsSpecialChar(ch)) { return true; } } if (Char.IsLetter(rawSheetName[0]) && Char.IsDigit(rawSheetName[len - 1])) { // note - values like "A$1:$C$20" don't Get this far if (NameLooksLikePlainCellReference(rawSheetName)) { return true; } } if (NameLooksLikeBooleanLiteral(rawSheetName)) { return true; } return false; } private static bool NameLooksLikeBooleanLiteral(String rawSheetName) { switch (rawSheetName[0]) { case 'T': case 't': return "TRUE".Equals(rawSheetName, StringComparison.OrdinalIgnoreCase); case 'F': case 'f': return "FALSE".Equals(rawSheetName, StringComparison.OrdinalIgnoreCase); } return false; } /** * @return <c>true</c> if the presence of the specified Char in a sheet name would * require the sheet name to be delimited in formulas. This includes every non-alphanumeric * Char besides Underscore '_'. */ /* package */ static bool IsSpecialChar(char ch) { // note - Char.IsJavaIdentifierPart() would allow dollars '$' if (Char.IsLetterOrDigit(ch)) { return false; } switch (ch) { case '.': // dot is OK case '_': // Underscore is ok return false; case '\n': case '\r': case '\t': throw new Exception("Illegal Char (0x" + StringUtil.ToHexString(ch) + ") found in sheet name"); } return true; } /** * Used to decide whether sheet names like 'AB123' need delimiting due to the fact that they * look like cell references. * <p/> * This code is currently being used for translating formulas represented with <code>Ptg</code> * tokens into human readable text form. In formula expressions, a sheet name always has a * trailing '!' so there is little chance for ambiguity. It doesn't matter too much what this * method returns but it is worth noting the likely consumers of these formula text strings: * <ol> * <li>POI's own formula parser</li> * <li>Visual reading by human</li> * <li>VBA automation entry into Excel cell contents e.g. ActiveCell.Formula = "=c64!A1"</li> * <li>Manual entry into Excel cell contents</li> * <li>Some third party formula parser</li> * </ol> * * At the time of writing, POI's formula parser tolerates cell-like sheet names in formulas * with or without delimiters. The same goes for Excel(2007), both manual and automated entry. * <p/> * For better or worse this implementation attempts to replicate Excel's formula renderer. * Excel uses range checking on the apparent 'row' and 'column' components. Note however that * the maximum sheet size varies across versions. * @see org.apache.poi.hssf.util.CellReference */ public static bool CellReferenceIsWithinRange(String lettersPrefix, String numbersSuffix) { return NPOI.SS.Util.CellReference.CellReferenceIsWithinRange(lettersPrefix, numbersSuffix, NPOI.SS.SpreadsheetVersion.EXCEL97); } /** * Note - this method assumes the specified rawSheetName has only letters and digits. It * cannot be used to match absolute or range references (using the dollar or colon char). * * Some notable cases: * <blockquote><table border="0" cellpAdding="1" cellspacing="0" * summary="Notable cases."> * <tr><th>Input </th><th>Result </th><th>Comments</th></tr> * <tr><td>"A1" </td><td>true</td><td> </td></tr> * <tr><td>"a111" </td><td>true</td><td> </td></tr> * <tr><td>"AA" </td><td>false</td><td> </td></tr> * <tr><td>"aa1" </td><td>true</td><td> </td></tr> * <tr><td>"A1A" </td><td>false</td><td> </td></tr> * <tr><td>"A1A1" </td><td>false</td><td> </td></tr> * <tr><td>"A$1:$C$20" </td><td>false</td><td>Not a plain cell reference</td></tr> * <tr><td>"SALES20080101" </td><td>true</td> * <td>Still needs delimiting even though well out of range</td></tr> * </table></blockquote> * * @return <c>true</c> if there is any possible ambiguity that the specified rawSheetName * could be interpreted as a valid cell name. */ public static bool NameLooksLikePlainCellReference(String rawSheetName) { Regex matcher = new Regex(CELL_REF_PATTERN); if (!matcher.IsMatch(rawSheetName)) { return false; } Match match = matcher.Matches(rawSheetName)[0]; // rawSheetName == "Sheet1" Gets this far. String lettersPrefix = match.Groups[1].Value; String numbersSuffix = match.Groups[2].Value; return CellReferenceIsWithinRange(lettersPrefix, numbersSuffix); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections; using System.Collections.Generic; using Encog.Util; namespace Encog.ML.Data.Basic { /// <summary> /// Basic implementation of the NeuralDataSet class. This class simply /// stores the neural data in an ArrayList. This class is memory based, /// so large enough datasets could cause memory issues. Many other dataset /// types extend this class. /// </summary> [Serializable] public class BasicMLDataSet : IMLDataSetAddable, IEnumerable<IMLDataPair> { /// <summary> /// The enumerator for the basic neural data set. /// </summary> [Serializable] public class BasicNeuralEnumerator : IEnumerator<IMLDataPair> { /// <summary> /// The current index. /// </summary> private int _current; /// <summary> /// The owner. /// </summary> private readonly BasicMLDataSet _owner; /// <summary> /// Construct an enumerator. /// </summary> /// <param name="owner">The owner of the enumerator.</param> public BasicNeuralEnumerator(BasicMLDataSet owner) { _current = -1; _owner = owner; } /// <summary> /// The current data item. /// </summary> public IMLDataPair Current { get { return _owner._data[_current]; } } /// <summary> /// Dispose of this object. /// </summary> public void Dispose() { // nothing needed } /// <summary> /// The current item. /// </summary> object IEnumerator.Current { get { if (_current < 0) { throw new InvalidOperationException("Must call MoveNext before reading Current."); } return _owner._data[_current]; } } /// <summary> /// Move to the next item. /// </summary> /// <returns>True if there is a next item.</returns> public bool MoveNext() { _current++; if (_current >= _owner._data.Count) return false; return true; } /// <summary> /// Reset to the beginning. /// </summary> public void Reset() { _current = -1; } } /// <summary> /// Access to the list of data items. /// </summary> public IList<IMLDataPair> Data { get { return _data; } set { _data = value; } } /// <summary> /// The data held by this object. /// </summary> private IList<IMLDataPair> _data = new List<IMLDataPair>(); /// <summary> /// Construct a data set from an already created list. Mostly used to /// duplicate this class. /// </summary> /// <param name="data">The data to use.</param> public BasicMLDataSet(IList<IMLDataPair> data) { _data = data; } /// <summary> /// Copy whatever dataset type is specified into a memory dataset. /// </summary> /// /// <param name="set">The dataset to copy.</param> public BasicMLDataSet(IMLDataSet set) { _data = new List<IMLDataPair>(); int inputCount = set.InputSize; int idealCount = set.IdealSize; foreach (IMLDataPair pair in set) { BasicMLData input = null; BasicMLData ideal = null; if (inputCount > 0) { input = new BasicMLData(inputCount); pair.Input.CopyTo(input.Data, 0, pair.Input.Count); } if (idealCount > 0) { ideal = new BasicMLData(idealCount); pair.Ideal.CopyTo(ideal.Data, 0, pair.Ideal.Count); } Add(new BasicMLDataPair(input, ideal)); // should we copy Significance here? } } /// <summary> /// Construct a data set from an input and idea array. /// </summary> /// <param name="input">The input into the neural network for training.</param> /// <param name="ideal">The idea into the neural network for training.</param> public BasicMLDataSet(double[][] input, double[][] ideal) { for (int i = 0; i < input.Length; i++) { var tempInput = new double[input[0].Length]; double[] tempIdeal; for (int j = 0; j < tempInput.Length; j++) { tempInput[j] = input[i][j]; } BasicMLData idealData = null; if (ideal != null) { tempIdeal = new double[ideal[0].Length]; for (int j = 0; j < tempIdeal.Length; j++) { tempIdeal[j] = ideal[i][j]; } idealData = new BasicMLData(tempIdeal); } var inputData = new BasicMLData(tempInput); Add(inputData, idealData); } } /// <summary> /// Construct a basic neural data set. /// </summary> public BasicMLDataSet() { } /// <summary> /// Get the ideal size, or zero for unsupervised. /// </summary> public virtual int IdealSize { get { if (_data == null || _data.Count <= 0) { return 0; } IMLDataPair pair = _data[0]; if (pair.Ideal == null) { return 0; } return pair.Ideal.Count; } } /// <summary> /// Get the input size. /// </summary> public virtual int InputSize { get { if (_data == null || _data.Count == 0) return 0; IMLDataPair pair = _data[0]; return pair.Input.Count; } } /// <summary> /// Add the specified data to the set. Add unsupervised data. /// </summary> /// <param name="data1">The data to add to the set.</param> public virtual void Add(IMLData data1) { IMLDataPair pair = new BasicMLDataPair(data1, null); _data.Add(pair); } /// <summary> /// Add supervised data to the set. /// </summary> /// <param name="inputData">The input data.</param> /// <param name="idealData">The ideal data.</param> public virtual void Add(IMLData inputData, IMLData idealData) { IMLDataPair pair = new BasicMLDataPair(inputData, idealData); _data.Add(pair); } /// <summary> /// Add a pair to the set. /// </summary> /// <param name="inputData">The pair to add to the set.</param> public virtual void Add(IMLDataPair inputData) { _data.Add(inputData); } /// <summary> /// Close the neural data set. /// </summary> public void Close() { // not needed } /// <summary> /// Get an enumerator to access the data with. /// </summary> /// <returns>An enumerator.</returns> public IEnumerator<IMLDataPair> GetEnumerator() { return new BasicNeuralEnumerator(this); } /// <summary> /// Get an enumerator to access the data with. /// </summary> /// <returns>An enumerator.</returns> IEnumerator IEnumerable.GetEnumerator() { return new BasicNeuralEnumerator(this); } /// <summary> /// Determine if the dataset is supervised. It is assumed that all pairs /// are either supervised or not. So we can determine the entire set by /// looking at the first item. If the set is empty then return false, or /// unsupervised. /// </summary> public bool IsSupervised { get { if (_data.Count == 0) return false; return (_data[0].Supervised); } } /// <summary> /// Clone this object. /// </summary> /// <returns>A clone of this object.</returns> public object Clone() { var result = new BasicMLDataSet(); foreach (IMLDataPair pair in Data) { result.Add((IMLDataPair) pair.Clone()); } return result; } /// <summary> /// The number of records in this data set. /// </summary> public int Count { get { return _data.Count; } } /// <summary> /// Open an additional instance of this dataset. /// </summary> /// <returns>The new instance of this dataset.</returns> public IMLDataSet OpenAdditional() { return new BasicMLDataSet(Data); } /// <summary> /// Return true if supervised. /// </summary> public bool Supervised { get { if (_data.Count == 0) { return false; } return _data[0].Supervised; } } public IMLDataPair this[int x] { get { return _data[x]; } } } }
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt // http://dead-code.org/redir.php?target=wme using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; namespace DeadCode.WME.Debugger { public class WatchProvider : ICustomTypeDescriptor { ////////////////////////////////////////////////////////////////////////// private class WatchItem : PropertyDescriptor { public WatchItem(string WatchName) : base(WatchName, null) { this.WatchName = WatchName; this.Value = null; } public string WatchName; public Variable Value; public override string DisplayName { get { return WatchName; } } public override bool CanResetValue(object component) { return false; } public override Type ComponentType { get { return this.GetType(); } } public override object GetValue(object component) { return "<variable name is not valid in current context>"; } public override bool IsReadOnly { get { return true; } } public override Type PropertyType { get { return this.GetType(); } } public override void ResetValue(object component) { } public override void SetValue(object component, object value) { } public override bool ShouldSerializeValue(object component) { return false; } }; List<WatchItem> Items = new List<WatchItem>(); ////////////////////////////////////////////////////////////////////////// public bool AddWatch(string Name) { foreach(WatchItem Item in Items) { if (Item.Name == Name) return true; } Items.Add(new WatchItem(Name)); Refresh(); return true; } ////////////////////////////////////////////////////////////////////////// public bool RemoveWatch(string Name) { foreach (WatchItem Item in Items) { if (Item.Name == Name) { Items.Remove(Item); return true; } } return false; } ////////////////////////////////////////////////////////////////////////// public string[] GetWatchNames() { List<string> Names = new List<string>(); foreach(WatchItem Item in Items) { Names.Add(Item.WatchName); } return Names.ToArray(); } private ScriptScope GlobalScope; private Script Script; ////////////////////////////////////////////////////////////////////////// public bool Refresh(ScriptScope GlobalScope) { this.GlobalScope = GlobalScope; return Refresh(); } ////////////////////////////////////////////////////////////////////////// public bool Refresh(Script Script) { this.Script = Script; return Refresh(); } ////////////////////////////////////////////////////////////////////////// public bool Refresh() { foreach(WatchItem Item in Items) { Variable Var = null; if (Script != null) { ScriptScope CurrScope = Script.GetCurrentScope(); if (CurrScope == null) CurrScope = Script.GlobalScope; Var = CurrScope.GetVarByName(Item.WatchName); } if (GlobalScope != null && Var == null) { Var = GlobalScope.GetVarByName(Item.WatchName); } Item.Value = Var; } return true; } #region ICustomTypeDescriptor implementation ////////////////////////////////////////////////////////////////////////// public String GetClassName() { return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public String GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return this; } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return GetProperties(); } public PropertyDescriptorCollection GetProperties() { PropertyDescriptorCollection NewProps = new PropertyDescriptorCollection(null); foreach(WatchItem Item in Items) { if(Item.Value==null) { NewProps.Add(Item); } else { VariablePropertyDescriptor pd = new VariablePropertyDescriptor(Item.Value); NewProps.Add(pd); } } return NewProps; } #endregion } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Google Inc. 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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using Grpc.Core.Internal; namespace Grpc.Core { /// <summary> /// Server is implemented only to be able to do /// in-process testing. /// </summary> public class Server { // TODO: make sure the delegate doesn't get garbage collected while // native callbacks are in the completion queue. readonly ServerShutdownCallbackDelegate serverShutdownHandler; readonly CompletionCallbackDelegate newServerRpcHandler; readonly BlockingCollection<NewRpcInfo> newRpcQueue = new BlockingCollection<NewRpcInfo>(); readonly ServerSafeHandle handle; readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>(); readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>(); public Server() { this.handle = ServerSafeHandle.NewServer(GetCompletionQueue(), IntPtr.Zero); this.newServerRpcHandler = HandleNewServerRpc; this.serverShutdownHandler = HandleServerShutdown; } // only call this before Start() public void AddServiceDefinition(ServerServiceDefinition serviceDefinition) { foreach(var entry in serviceDefinition.CallHandlers) { callHandlers.Add(entry.Key, entry.Value); } } // only call before Start() public int AddPort(string addr) { return handle.AddPort(addr); } public void Start() { handle.Start(); // TODO: this basically means the server is single threaded.... StartHandlingRpcs(); } /// <summary> /// Requests and handles single RPC call. /// </summary> internal void RunRpc() { AllowOneRpc(); try { var rpcInfo = newRpcQueue.Take(); //Console.WriteLine("Server received RPC " + rpcInfo.Method); IServerCallHandler callHandler; if (!callHandlers.TryGetValue(rpcInfo.Method, out callHandler)) { callHandler = new NoSuchMethodCallHandler(); } callHandler.StartCall(rpcInfo.Method, rpcInfo.Call, GetCompletionQueue()); } catch(Exception e) { Console.WriteLine("Exception while handling RPC: " + e); } } /// <summary> /// Requests server shutdown and when there are no more calls being serviced, /// cleans up used resources. /// </summary> /// <returns>The async.</returns> public async Task ShutdownAsync() { handle.ShutdownAndNotify(serverShutdownHandler); await shutdownTcs.Task; handle.Dispose(); } public void Kill() { handle.Dispose(); } private async Task StartHandlingRpcs() { while (true) { await Task.Factory.StartNew(RunRpc); } } private void AllowOneRpc() { AssertCallOk(handle.RequestCall(GetCompletionQueue(), newServerRpcHandler)); } private void HandleNewServerRpc(GRPCOpError error, IntPtr batchContextPtr) { try { var ctx = new BatchContextSafeHandleNotOwned(batchContextPtr); if (error != GRPCOpError.GRPC_OP_OK) { // TODO: handle error } var rpcInfo = new NewRpcInfo(ctx.GetServerRpcNewCall(), ctx.GetServerRpcNewMethod()); // after server shutdown, the callback returns with null call if (!rpcInfo.Call.IsInvalid) { newRpcQueue.Add(rpcInfo); } } catch(Exception e) { Console.WriteLine("Caught exception in a native handler: " + e); } } private void HandleServerShutdown(IntPtr eventPtr) { try { shutdownTcs.SetResult(null); } catch (Exception e) { Console.WriteLine("Caught exception in a native handler: " + e); } } private static void AssertCallOk(GRPCCallError callError) { Trace.Assert(callError == GRPCCallError.GRPC_CALL_OK, "Status not GRPC_CALL_OK"); } private static CompletionQueueSafeHandle GetCompletionQueue() { return GrpcEnvironment.ThreadPool.CompletionQueue; } private struct NewRpcInfo { private CallSafeHandle call; private string method; public NewRpcInfo(CallSafeHandle call, string method) { this.call = call; this.method = method; } public CallSafeHandle Call { get { return this.call; } } public string Method { get { return this.method; } } } } }
using System; using System.Diagnostics; using System.Text; namespace Core { public partial class Prepare { static void CorruptSchema(InitData data, string obj, string extra) { Context ctx = data.Ctx; if (!ctx.MallocFailed && (ctx.Flags & Context.FLAG.RecoveryMode) == 0) { if (obj == null) obj = "?"; C._setstring(ref data.ErrMsg, ctx, "malformed database schema (%s)", obj); if (extra == null) data.ErrMsg = C._mtagappendf(ctx, data.ErrMsg, "%s - %s", data.ErrMsg, extra); data.RC = (ctx.MallocFailed ? RC.NOMEM : SysEx.CORRUPT_BKPT()); } } public static bool InitCallback(object init, int argc, string[] argv, object notUsed1) { InitData data = (InitData)init; Context ctx = data.Ctx; int db = data.Db; Debug.Assert(argc == 3); Debug.Assert(MutexEx.Held(ctx.Mutex)); E.DbClearProperty(ctx, db, SCHEMA.Empty); if (ctx.MallocFailed) { CorruptSchema(data, argv[0], null); return true; } Debug.Assert(db >= 0 && db < ctx.DBs.length); if (argv == null) return false; // Might happen if EMPTY_RESULT_CALLBACKS are on */ if (argv[1] == null) CorruptSchema(data, argv[0], null); else if (!string.IsNullOrEmpty(argv[2])) { // Call the parser to process a CREATE TABLE, INDEX or VIEW. But because ctx->init.busy is set to 1, no VDBE code is generated // or executed. All the parser does is build the internal data structures that describe the table, index, or view. Debug.Assert(ctx.Init.Busy); ctx.Init.DB = (byte)db; ctx.Init.NewTid = ConvertEx.Atoi(argv[1]); ctx.Init.OrphanTrigger = false; Vdbe stmt = null; #if DEBUG int rcp = Prepare(ctx, argv[2], -1, ref stmt, null); #else Prepare(ctx, argv[2], -1, ref stmt, null); #endif RC rc = ctx.ErrCode; #if DEBUG Debug.Assert(((int)rc & 0xFF) == (rcp & 0xFF)); #endif ctx.Init.DB = 0; if (rc != RC.OK) { if (ctx.Init.OrphanTrigger) Debug.Assert(db == 1); else { data.RC = rc; if (rc == RC.NOMEM) ctx.MallocFailed = true; else if (rc != RC.INTERRUPT && (RC)((int)rc & 0xFF) != RC.LOCKED) CorruptSchema(data, argv[0], sqlite3_errmsg(ctx)); } } stmt.Finalize(); } else if (argv[0] == null) CorruptSchema(data, null, null); else { // If the SQL column is blank it means this is an index that was created to be the PRIMARY KEY or to fulfill a UNIQUE // constraint for a CREATE TABLE. The index should have already been created when we processed the CREATE TABLE. All we have // to do here is record the root page number for that index. Index index = Parse.FindIndex(ctx, argv[0], ctx.DBs[db].Name); if (index == null) { // This can occur if there exists an index on a TEMP table which has the same name as another index on a permanent index. Since // the permanent table is hidden by the TEMP table, we can also safely ignore the index on the permanent table. // Do Nothing } else if (!ConvertEx.Atoi(argv[1], ref index.Id)) CorruptSchema(data, argv[0], "invalid rootpage"); } return false; } // The master database table has a structure like this static readonly string master_schema = "CREATE TABLE sqlite_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")"; #if !OMIT_TEMPDB static readonly string temp_master_schema = "CREATE TEMP TABLE sqlite_temp_master(\n" + " type text,\n" + " name text,\n" + " tbl_name text,\n" + " rootpage integer,\n" + " sql text\n" + ")"; #else static readonly string temp_master_schema = null; #endif //ctx.pDfltColl = sqlite3FindCollSeq( ctx, SQLITE_UTF8, "BINARY", 0 ); public static RC InitOne(Context ctx, int db, ref string errMsg) { Debug.Assert(db >= 0 && db < ctx.DBs.length); Debug.Assert(ctx.DBs[db].Schema != null); Debug.Assert(MutexEx.Held(ctx.Mutex)); Debug.Assert(db == 1 || ctx.DBs[db].Bt.HoldsMutex()); RC rc; int i; // zMasterSchema and zInitScript are set to point at the master schema and initialisation script appropriate for the database being // initialized. zMasterName is the name of the master table. string masterSchema = (E.OMIT_TEMPDB == 0 && db == 1 ? temp_master_schema : master_schema); string masterName = E.SCHEMA_TABLE(db); // Construct the schema tables. string[] args = new string[4]; args[0] = masterName; args[1] = "1"; args[2] = masterSchema; args[3] = null; InitData initData = new InitData(); initData.Ctx = ctx; initData.Db = db; initData.RC = RC.OK; initData.ErrMsg = errMsg; InitCallback(initData, 3, args, null); if (initData.RC != 0) { rc = initData.RC; goto error_out; } Table table = Parse.FindTable(ctx, masterName, ctx.DBs[db].Name); if (C._ALWAYS(table != null)) table.TabFlags |= TF.Readonly; // Create a cursor to hold the database open Context.DB dbAsObj = ctx.DBs[db]; if (dbAsObj.Bt == null) { if (E.OMIT_TEMPDB == 0 && C._ALWAYS(db == 1)) E.DbSetProperty(ctx, 1, SCHEMA.SchemaLoaded); return RC.OK; } // If there is not already a read-only (or read-write) transaction opened on the b-tree database, open one now. If a transaction is opened, it // will be closed before this function returns. bool openedTransaction = false; dbAsObj.Bt.Enter(); if (!dbAsObj.Bt.IsInReadTrans()) { rc = dbAsObj.Bt.BeginTrans(0); if (rc != RC.OK) { C._setstring(ref errMsg, ctx, "%s", Main.ErrStr(rc)); goto initone_error_out; } openedTransaction = true; } // Get the database meta information. // Meta values are as follows: // meta[0] Schema cookie. Changes with each schema change. // meta[1] File format of schema layer. // meta[2] Size of the page cache. // meta[3] Largest rootpage (auto/incr_vacuum mode) // meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE // meta[5] User version // meta[6] Incremental vacuum mode // meta[7] unused // meta[8] unused // meta[9] unused // Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to the possible values of meta[4]. uint[] meta = new uint[5]; for (i = 0; i < meta.Length; i++) dbAsObj.Bt.GetMeta((Btree.META)i + 1, ref meta[i]); dbAsObj.Schema.SchemaCookie = (int)meta[(int)Btree.META.SCHEMA_VERSION - 1]; // If opening a non-empty database, check the text encoding. For the main database, set sqlite3.enc to the encoding of the main database. // For an attached ctx, it is an error if the encoding is not the same as sqlite3.enc. if (meta[(int)Btree.META.TEXT_ENCODING - 1] != 0) // text encoding { if (db == 0) { #if !OMIT_UTF16 // If opening the main database, set ENC(db). TEXTENCODE encoding = (TEXTENCODE)(meta[(int)Btree.META.TEXT_ENCODING - 1] & 3); if (encoding == 0) encoding = TEXTENCODE.UTF8; E.CTXENCODE(ctx, encoding); #else E.CTXENCODE(ctx, TEXTENCODE_UTF8); #endif } else { // If opening an attached database, the encoding much match ENC(db) if ((TEXTENCODE)meta[(int)Btree.META.TEXT_ENCODING - 1] != E.CTXENCODE(ctx)) { C._setstring(ref errMsg, ctx, "attached databases must use the same text encoding as main database"); rc = RC.ERROR; goto initone_error_out; } } } else E.DbSetProperty(ctx, db, SCHEMA.Empty); dbAsObj.Schema.Encode = E.CTXENCODE(ctx); if (dbAsObj.Schema.CacheSize == 0) { dbAsObj.Schema.CacheSize = DEFAULT_CACHE_SIZE; dbAsObj.Bt.SetCacheSize(dbAsObj.Schema.CacheSize); } // file_format==1 Version 3.0.0. // file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN // file_format==3 Version 3.1.4. // ditto but with non-NULL defaults // file_format==4 Version 3.3.0. // DESC indices. Boolean constants dbAsObj.Schema.FileFormat = (byte)meta[(int)Btree.META.FILE_FORMAT - 1]; if (dbAsObj.Schema.FileFormat == 0) dbAsObj.Schema.FileFormat = 1; if (dbAsObj.Schema.FileFormat > MAX_FILE_FORMAT) { C._setstring(ref errMsg, ctx, "unsupported file format"); rc = RC.ERROR; goto initone_error_out; } // Ticket #2804: When we open a database in the newer file format, clear the legacy_file_format pragma flag so that a VACUUM will // not downgrade the database and thus invalidate any descending indices that the user might have created. if (db == 0 && meta[(int)Btree.META.FILE_FORMAT - 1] >= 4) ctx.Flags &= ~Context.FLAG.LegacyFileFmt; // Read the schema information out of the schema tables Debug.Assert(ctx.Init.Busy); { string sql = C._mtagprintf(ctx, "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid", ctx.DBs[db].Name, masterName); #if !OMIT_AUTHORIZATION { Func<object, int, string, string, string, string, ARC> auth = ctx.Auth; ctx.Auth = null; #endif rc = sqlite3_exec(ctx, sql, InitCallback, initData, 0); //: errMsg = initData.ErrMsg; #if !OMIT_AUTHORIZATION ctx.Auth = auth; } #endif if (rc == RC.OK) rc = initData.RC; C._tagfree(ctx, ref sql); #if !OMIT_ANALYZE if (rc == RC.OK) sqlite3AnalysisLoad(ctx, db); #endif } if (ctx.MallocFailed) { rc = RC.NOMEM; Main.ResetAllSchemasOfConnection(ctx); } if (rc == RC.OK || (ctx.Flags & Context.FLAG.RecoveryMode) != 0) { // Black magic: If the SQLITE_RecoveryMode flag is set, then consider the schema loaded, even if errors occurred. In this situation the // current sqlite3_prepare() operation will fail, but the following one will attempt to compile the supplied statement against whatever subset // of the schema was loaded before the error occurred. The primary purpose of this is to allow access to the sqlite_master table // even when its contents have been corrupted. E.DbSetProperty(ctx, db, DB.SchemaLoaded); rc = RC.OK; } // Jump here for an error that occurs after successfully allocating curMain and calling sqlite3BtreeEnter(). For an error that occurs // before that point, jump to error_out. initone_error_out: if (openedTransaction) dbAsObj.Bt.Commit(); dbAsObj.Bt.Leave(); error_out: if (rc == RC.NOMEM || rc == RC.IOERR_NOMEM) ctx.MallocFailed = true; return rc; } public static RC Init(Context ctx, ref string errMsg) { Debug.Assert(MutexEx.Held(ctx.Mutex)); RC rc = RC.OK; ctx.Init.Busy = true; for (int i = 0; rc == RC.OK && i < ctx.DBs.length; i++) { if (E.DbHasProperty(ctx, i, SCHEMA.SchemaLoaded) || i == 1) continue; rc = InitOne(ctx, i, ref errMsg); if (rc != 0) ResetOneSchema(ctx, i); } // Once all the other databases have been initialized, load the schema for the TEMP database. This is loaded last, as the TEMP database // schema may contain references to objects in other databases. #if !OMIT_TEMPDB if (rc == RC.OK && C._ALWAYS(ctx.DBs.length > 1) && !E.DbHasProperty(ctx, 1, SCHEMA.SchemaLoaded)) { rc = InitOne(ctx, 1, ref errMsg); if (rc != 0) ResetOneSchema(ctx, 1); } #endif bool commitInternal = !((ctx.Flags & Context.FLAG.InternChanges) != 0); ctx.Init.Busy = false; if (rc == RC.OK && commitInternal) CommitInternalChanges(ctx); return rc; } public static RC ReadSchema(Parse parse) { RC rc = RC.OK; Context ctx = parse.Ctx; Debug.Assert(MutexEx.Held(ctx.Mutex)); if (!ctx.Init.Busy) rc = Init(ctx, ref parse.ErrMsg); if (rc != RC.OK) { parse.RC = rc; parse.Errs++; } return rc; } static void SchemaIsValid(Parse parse) { Context ctx = parse.Ctx; Debug.Assert(parse.CheckSchema != 0); Debug.Assert(MutexEx.Held(ctx.Mutex)); for (int db = 0; db < ctx.DBs.length; db++) { bool openedTransaction = false; // True if a transaction is opened Btree bt = ctx.DBs[db].Bt; // Btree database to read cookie from if (bt == null) continue; // If there is not already a read-only (or read-write) transaction opened on the b-tree database, open one now. If a transaction is opened, it // will be closed immediately after reading the meta-value. if (!bt.IsInReadTrans()) { RC rc = bt.BeginTrans(0); if (rc == RC.NOMEM || rc == RC.IOERR_NOMEM) ctx.MallocFailed = true; if (rc != RC.OK) return; openedTransaction = true; } // Read the schema cookie from the database. If it does not match the value stored as part of the in-memory schema representation, // set Parse.rc to SQLITE_SCHEMA. uint cookie; bt.GetMeta(Btree.META.SCHEMA_VERSION, ref cookie); Debug.Assert(Btree.SchemaMutexHeld(ctx, db, null)); if (cookie != ctx.DBs[db].Schema.SchemaCookie) { ResetOneSchema(ctx, db); parse.RC = RC.SCHEMA; } // Close the transaction, if one was opened. if (openedTransaction) bt.Commit(); } } public static int SchemaToIndex(Context ctx, Schema schema) { // If pSchema is NULL, then return -1000000. This happens when code in expr.c is trying to resolve a reference to a transient table (i.e. one // created by a sub-select). In this case the return value of this function should never be used. // // We return -1000000 instead of the more usual -1 simply because using -1000000 as the incorrect index into ctx->aDb[] is much // more likely to cause a segfault than -1 (of course there are assert() statements too, but it never hurts to play the odds). Debug.Assert(MutexEx.Held(ctx.Mutex)); int i = -1000000; if (schema != null) { for (i = 0; C._ALWAYS(i < ctx.DBs.length); i++) if (ctx.DBs[i].Schema == schema) break; Debug.Assert(i >= 0 && i < ctx.DBs.length); } return i; } #if !OMIT_EXPLAIN static readonly string[] _colName = new string[] { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", "selectid", "order", "from", "detail" }; #endif public static RC Prepare_(Context ctx, string sql, int bytes, bool isPrepareV2, Vdbe reprepare, ref Vdbe stmtOut, ref string tailOut) { stmtOut = null; tailOut = null; string errMsg = null; // Error message RC rc = RC.OK; int i; // Allocate the parsing context Parse parse = new Parse(); // Parsing context if (parse == null) { rc = RC.NOMEM; goto end_prepare; } parse.Reprepare = reprepare; parse.LastToken.data = null; //: C#? Debug.Assert(tailOut == null); Debug.Assert(!ctx.MallocFailed); Debug.Assert(MutexEx.Held(ctx.Mutex)); // Check to verify that it is possible to get a read lock on all database schemas. The inability to get a read lock indicates that // some other database connection is holding a write-lock, which in turn means that the other connection has made uncommitted changes // to the schema. // // Were we to proceed and prepare the statement against the uncommitted schema changes and if those schema changes are subsequently rolled // back and different changes are made in their place, then when this prepared statement goes to run the schema cookie would fail to detect // the schema change. Disaster would follow. // // This thread is currently holding mutexes on all Btrees (because of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it // is not possible for another thread to start a new schema change while this routine is running. Hence, we do not need to hold // locks on the schema, we just need to make sure nobody else is holding them. // // Note that setting READ_UNCOMMITTED overrides most lock detection, but it does *not* override schema lock detection, so this all still // works even if READ_UNCOMMITTED is set. for (i = 0; i < ctx.DBs.length; i++) { Btree bt = ctx.DBs[i].Bt; if (bt != null) { Debug.Assert(bt.HoldsMutex()); rc = bt.SchemaLocked(); if (rc != 0) { string dbName = ctx.DBs[i].Name; sqlite3Error(ctx, rc, "database schema is locked: %s", dbName); C.ASSERTCOVERAGE((ctx.Flags & Context.FLAG.ReadUncommitted) != 0); goto end_prepare; } } } VTable.UnlockList(ctx); parse.Ctx = ctx; parse.QueryLoops = (double)1; if (bytes >= 0 && (bytes == 0 || sql[bytes - 1] != 0)) { int maxLen = ctx.aLimit[SQLITE_LIMIT_SQL_LENGTH]; C.ASSERTCOVERAGE(bytes == maxLen); C.ASSERTCOVERAGE(bytes == maxLen + 1); if (bytes > maxLen) { sqlite3Error(ctx, RC.TOOBIG, "statement too long"); rc = SysEx.ApiExit(ctx, RC.TOOBIG); goto end_prepare; } string sqlCopy = sql.Substring(0, bytes); if (sqlCopy != null) { parse.RunParser(sqlCopy, ref errMsg); C._tagfree(ctx, ref sqlCopy); parse.Tail = null; //: &sql[parse->Tail - sqlCopy]; } else parse.Tail = null; //: &sql[bytes]; } else parse.RunParser(sql, ref errMsg); Debug.Assert((int)parse.QueryLoops == 1); if (ctx.MallocFailed) parse.RC = RC.NOMEM; if (parse.RC == RC.DONE) parse.RC = RC.OK; if (parse.CheckSchema != 0) SchemaIsValid(parse); if (ctx.MallocFailed) parse.RC = RC.NOMEM; tailOut = (parse.Tail == null ? null : parse.Tail.ToString()); rc = parse.RC; Vdbe v = parse.V; #if !OMIT_EXPLAIN if (rc == RC.OK && parse.V != null && parse.Explain != 0) { int first, max; if (parse.Explain == 2) { v.SetNumCols(4); first = 8; max = 12; } else { v.SetNumCols(8); first = 0; max = 8; } for (i = first; i < max; i++) v.SetColName(i - first, COLNAME_NAME, _colName[i], C.DESTRUCTOR_STATIC); } #endif Debug.Assert(!ctx.Init.Busy || !isPrepareV2); if (!ctx.Init.Busy) Vdbe.SetSql(v, sql, (int)(sql.Length - (parse.Tail == null ? 0 : parse.Tail.Length)), isPrepareV2); if (v != null && (rc != RC.OK || ctx.MallocFailed)) { v.Finalize(); Debug.Assert(stmtOut == null); } else stmtOut = v; if (errMsg != null) { sqlite3Error(ctx, rc, "%s", errMsg); C._tagfree(ctx, ref errMsg); } else sqlite3Error(ctx, rc, null); // Delete any TriggerPrg structures allocated while parsing this statement. while (parse.TriggerPrg != null) { TriggerPrg t = parse.TriggerPrg; parse.TriggerPrg = t.Next; C._tagfree(ctx, ref t); } end_prepare: //sqlite3StackFree( db, pParse ); rc = SysEx.ApiExit(ctx, rc); Debug.Assert((RC)((int)rc & ctx.ErrMask) == rc); return rc; } //C# Version w/o End of Parsed String public static RC LockAndPrepare(Context ctx, string sql, int bytes, bool isPrepareV2, Vdbe reprepare, ref Vdbe stmtOut, string dummy1) { string tailOut = null; return LockAndPrepare(ctx, sql, bytes, isPrepareV2, reprepare, ref stmtOut, ref tailOut); } public static RC LockAndPrepare(Context ctx, string sql, int bytes, bool isPrepareV2, Vdbe reprepare, ref Vdbe stmtOut, ref string tailOut) { if (!sqlite3SafetyCheckOk(ctx)) { stmtOut = null; tailOut = null; return SysEx.MISUSE_BKPT(); } MutexEx.Enter(ctx.Mutex); Btree.EnterAll(ctx); RC rc = Prepare_(ctx, sql, bytes, isPrepareV2, reprepare, ref stmtOut, ref tailOut); if (rc == RC.SCHEMA) { stmtOut.Finalize(); rc = Prepare_(ctx, sql, bytes, isPrepareV2, reprepare, ref stmtOut, ref tailOut); } Btree.LeaveAll(ctx); MutexEx.Leave(ctx.Mutex); Debug.Assert(rc == RC.OK || stmtOut == null); return rc; } public static RC Reprepare(Vdbe p) { Context ctx = p.Ctx; Debug.Assert(MutexEx.Held(ctx.Mutex)); string sql = Vdbe.Sql(p); Debug.Assert(sql != null); // Reprepare only called for prepare_v2() statements Vdbe newVdbe = new Vdbe(); RC rc = LockAndPrepare(ctx, sql, -1, false, p, ref newVdbe, null); if (rc != 0) { if (rc == RC.NOMEM) ctx.MallocFailed = true; Debug.Assert(newVdbe == null); return rc; } else Debug.Assert(newVdbe != null); Vdbe.Swap((Vdbe)newVdbe, p); Vdbe.TransferBindings(newVdbe, (Vdbe)p); newVdbe.ResetStepResult(); newVdbe.Finalize(); return RC.OK; } //C# Overload for ignore error out static public RC Prepare_(Context ctx, string sql, int bytes, ref Vdbe vdbeOut, string dummy1) { string tailOut = null; return Prepare_(ctx, sql, bytes, ref vdbeOut, ref tailOut); } static public RC Prepare_(Context ctx, StringBuilder sql, int bytes, ref Vdbe vdbeOut, string dummy1) { string tailOut = null; return Prepare_(ctx, sql.ToString(), bytes, ref vdbeOut, ref tailOut); } static public RC Prepare_(Context ctx, string sql, int bytes, ref Vdbe vdbeOut, ref string tailOut) { RC rc = LockAndPrepare(ctx, sql, bytes, false, null, ref vdbeOut, ref tailOut); Debug.Assert(rc == RC.OK || vdbeOut == null); // VERIFY: F13021 return rc; } public static RC Prepare_v2(Context ctx, string sql, int bytes, ref Vdbe stmtOut, string dummy1) { string tailOut = null; return Prepare_v2(ctx, sql, bytes, ref stmtOut, ref tailOut); } public static RC Prepare_v2(Context ctx, string sql, int bytes, ref Vdbe stmtOut, ref string tailOut) { RC rc = LockAndPrepare(ctx, sql, bytes, true, null, ref stmtOut, ref tailOut); Debug.Assert(rc == RC.OK || stmtOut == null); // VERIFY: F13021 return rc; } #if !OMIT_UTF16 public static RC Prepare16(Context ctx, string sql, int bytes, bool isPrepareV2, out Vdbe stmtOut, out string tailOut) { // This function currently works by first transforming the UTF-16 encoded string to UTF-8, then invoking sqlite3_prepare(). The // tricky bit is figuring out the pointer to return in *pzTail. stmtOut = null; if (!sqlite3SafetyCheckOk(ctx)) return SysEx.MISUSE_BKPT(); MutexEx.Enter(ctx.Mutex); RC rc = RC.OK; string tail8 = null; string sql8 = Vdbe.Utf16to8(ctx, sql, bytes, TEXTENCODE.UTF16NATIVE); if (sql8 != null) rc = LockAndPrepare(ctx, sql8, -1, isPrepareV2, null, ref stmtOut, ref tail8); if (tail8 != null && tailOut != null) { // If sqlite3_prepare returns a tail pointer, we calculate the equivalent pointer into the UTF-16 string by counting the unicode // characters between zSql8 and zTail8, and then returning a pointer the same number of characters into the UTF-16 string. Debugger.Break(); //: int charsParsed = Vdbe::Utf8CharLen(sql8, (int)(tail8 - sql8)); //: *tailOut = (uint8 *)sql + Vdbe::Utf16ByteLen(sql, charsParsed); } C._tagfree(ctx, ref sql8); rc = SysEx.ApiExit(ctx, rc); MutexEx.Leave(ctx.Mutex); return rc; } public static RC Prepare16(Context ctx, string sql, int bytes, out Vdbe stmtOut, out string tailOut) { RC rc = Prepare16(ctx, sql, bytes, false, out stmtOut, out tailOut); Debug.Assert(rc == RC.OK || stmtOut == null); // VERIFY: F13021 return rc; } public static RC Prepare16_v2(Context ctx, string sql, int bytes, out Vdbe stmtOut, out string tailOut) { RC rc = Prepare16(ctx, sql, bytes, true, out stmtOut, out tailOut); Debug.Assert(rc == RC.OK || stmtOut == null); // VERIFY: F13021 return rc; } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Net.Sockets; using System.Threading; namespace System.Net.NetworkInformation { public partial class NetworkChange { private static readonly object s_globalLock = new object(); public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { AvailabilityChangeListener.Start(value); } remove { AvailabilityChangeListener.Stop(value); } } public static event NetworkAddressChangedEventHandler NetworkAddressChanged { add { AddressChangeListener.Start(value); } remove { AddressChangeListener.Stop(value); } } internal static class AvailabilityChangeListener { private static readonly NetworkAddressChangedEventHandler s_addressChange = ChangedAddress; private static volatile bool s_isAvailable = false; private static void ChangedAddress(object sender, EventArgs eventArgs) { Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> availabilityChangedSubscribers = null; lock (s_globalLock) { bool isAvailableNow = SystemNetworkInterface.InternalGetIsNetworkAvailable(); // If there is an Availability Change, need to execute user callbacks. if (isAvailableNow != s_isAvailable) { s_isAvailable = isAvailableNow; if (s_availabilityChangedSubscribers.Count > 0) { availabilityChangedSubscribers = new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityChangedSubscribers); } } } // Executing user callbacks if Availability Change event occured. if (availabilityChangedSubscribers != null) { bool isAvailable = s_isAvailable; NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs; ContextCallback callbackContext = isAvailable ? s_runHandlerAvailable : s_runHandlerNotAvailable; foreach (KeyValuePair<NetworkAvailabilityChangedEventHandler, ExecutionContext> subscriber in availabilityChangedSubscribers) { NetworkAvailabilityChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, args); } else { ExecutionContext.Run(ec, callbackContext, handler); } } } } internal static void Start(NetworkAvailabilityChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { if (s_availabilityChangedSubscribers.Count == 0) { s_isAvailable = NetworkInterface.GetIsNetworkAvailable(); AddressChangeListener.UnsafeStart(s_addressChange); } s_availabilityChangedSubscribers.TryAdd(caller, ExecutionContext.Capture()); } } } internal static void Stop(NetworkAvailabilityChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { s_availabilityChangedSubscribers.Remove(caller); if (s_availabilityChangedSubscribers.Count == 0) { AddressChangeListener.Stop(s_addressChange); } } } } } // Helper class for detecting address change events. internal static unsafe class AddressChangeListener { private static RegisteredWaitHandle s_registeredWait; // Need to keep the reference so it isn't GC'd before the native call executes. private static bool s_isListening = false; private static bool s_isPending = false; private static SafeCloseSocketAndEvent s_ipv4Socket = null; private static SafeCloseSocketAndEvent s_ipv6Socket = null; private static WaitHandle s_ipv4WaitHandle = null; private static WaitHandle s_ipv6WaitHandle = null; // Callback fired when an address change occurs. private static void AddressChangedCallback(object stateObject, bool signaled) { Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> addressChangedSubscribers = null; lock (s_globalLock) { // The listener was canceled, which would only happen if we aren't listening for more events. s_isPending = false; if (!s_isListening) { return; } s_isListening = false; // Need to copy the array so the callback can call start and stop if (s_addressChangedSubscribers.Count > 0) { addressChangedSubscribers = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_addressChangedSubscribers); } try { //wait for the next address change StartHelper(null, false, (StartIPOptions)stateObject); } catch (NetworkInformationException nie) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, nie); } } // Release the lock before calling into user callback. if (addressChangedSubscribers != null) { foreach (KeyValuePair<NetworkAddressChangedEventHandler, ExecutionContext> subscriber in addressChangedSubscribers) { NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(ec, s_runAddressChangedHandler, handler); } } } } internal static void Start(NetworkAddressChangedEventHandler caller) { StartHelper(caller, true, StartIPOptions.Both); } internal static void UnsafeStart(NetworkAddressChangedEventHandler caller) { StartHelper(caller, false, StartIPOptions.Both); } private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions) { if (caller != null) { lock (s_globalLock) { // Setup changedEvent and native overlapped struct. if (s_ipv4Socket == null) { int blocking; // Sockets will be initialized by the call to OSSupportsIP*. if (Socket.OSSupportsIPv4) { blocking = -1; s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv4Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle(); } if (Socket.OSSupportsIPv6) { blocking = -1; s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv6Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle(); } } s_addressChangedSubscribers.TryAdd(caller, captureContext ? ExecutionContext.Capture() : null); if (s_isListening || s_addressChangedSubscribers.Count == 0) { return; } if (!s_isPending) { int length; SocketError errorCode; if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv4WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv4, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv4Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv4SocketGetEventHandleSafeWaitHandle = s_ipv4Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv4Socket, s_ipv4SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv6WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv6, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv6Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv6SocketGetEventHandleSafeWaitHandle = s_ipv6Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv6Socket, s_ipv6SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } } s_isListening = true; s_isPending = true; } } } internal static void Stop(NetworkAddressChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { s_addressChangedSubscribers.Remove(caller); if (s_addressChangedSubscribers.Count == 0 && s_isListening) { s_isListening = false; } } } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NuGet; using NuGet.Common; using NuGet.Configuration; using NuGet.Frameworks; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Packaging.Signing; using NuGet.Protocol; using NuGet.Protocol.Core.Types; using NuGet.DependencyResolver; using NuGet.Versioning; using NuGet.Repositories; using Sprache; using Versatile; using System.Text.RegularExpressions; namespace DevAudit.AuditLibrary { public class NetCorePackageSource : PackageSource, IDeveloperPackageSource { #region Constructors public NetCorePackageSource(Dictionary<string, object> package_source_options, EventHandler<EnvironmentEventArgs> message_handler = null) : base(package_source_options, message_handler) {} #endregion #region Overriden members public override string PackageManagerId { get { return "nuget"; } } public override string PackageManagerLabel { get { return ".NET Core"; } } public override string DefaultPackageManagerConfigurationFile { get { return string.Empty; } } public override IEnumerable<Package> GetPackages(params string[] o) { AuditFileInfo config_file = this.AuditEnvironment.ConstructFile(this.PackageManagerConfigurationFile); List<Package> packages = new List<Package>(); var isSnlSolution = config_file.Name.EndsWith(".sln"); var isCsProj = config_file.Name.EndsWith(".csproj"); var isBuildTargets = config_file.Name.EndsWith(".Build.targets"); var isDepsJson = config_file.Name.EndsWith(".deps.json"); if(isSnlSolution) { var Content = File.ReadAllText(this.PackageManagerConfigurationFile); Regex projReg = new Regex("Project\\(\"\\{[\\w-]*\\}\"\\) = \"([\\w _]*.*)\", \"(.*\\.(cs|vcx|vb)proj)\"", RegexOptions.Compiled); var matches = projReg.Matches(Content).Cast<Match>(); var Projects = matches.Select(x => x.Groups[2].Value).ToList(); for (int i = 0; i < Projects.Count; ++i) { if (!Path.IsPathRooted(Projects[i])) Projects[i] = Path.Combine(Path.GetDirectoryName(this.PackageManagerConfigurationFile), Projects[i]); Projects[i] = Path.GetFullPath(Projects[i]); } foreach(var project in Projects) { var tmpProject = GetPackagesFromProjectFile(project, true); if(tmpProject.Count != 0) { this.AuditEnvironment.Info($"Found {tmpProject.Count} packages in {project}"); foreach(var tmpPacket in tmpProject) { if(!packages.Contains(tmpPacket)) packages.Add(tmpPacket); } } } return packages; } if (isCsProj || isBuildTargets) { return GetPackagesFromProjectFile(this.PackageManagerConfigurationFile, isCsProj); } if (isDepsJson) { try { this.AuditEnvironment.Info("Reading packages from .NET Core dependencies manifest.."); JObject json = (JObject)JToken.Parse(config_file.ReadAsText()); JObject libraries = (JObject)json["libraries"]; if (libraries != null) { foreach (JProperty p in libraries.Properties()) { string[] name = p.Name.Split('/'); // Packages with version 0.0.0.0 can show up if the are part of .net framework. // Checking this version number is quite useless and might give a false positive. if (name[1] != "0.0.0.0") { packages.Add(new Package("nuget", name[0], name[1])); } } } return packages; } catch (Exception e) { this.AuditEnvironment.Error(e, "Error reading .NET Core dependencies manifest {0}.", config_file.FullName); return packages; } } this.AuditEnvironment.Error("Unknown .NET Core project file type: {0}.", config_file.FullName); return packages; } private List<Package> GetPackagesFromProjectFile(string filename, bool isCsProj) { List<Package> packages = new List<Package>(); AuditFileInfo config_file = this.AuditEnvironment.ConstructFile(filename); var fileType = isCsProj ? ".csproj" : "build targets"; this.AuditEnvironment.Info($"Reading packages from .NET Core C# {fileType} file."); string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); string xml = config_file.ReadAsText(); if (xml.StartsWith(_byteOrderMarkUtf8, StringComparison.Ordinal)) { var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length; xml = xml.Remove(0, lastIndexOfUtf8); } XElement root = XElement.Parse(xml); var package = isCsProj ? "Include" : "Update"; if (root.Name.LocalName == "Project") { packages = root .Descendants() .Where(x => x.Name.LocalName == "PackageReference" && x.Attribute(package) != null && x.Attribute("Version") != null) .SelectMany(r => GetDeveloperPackages(r.Attribute(package).Value, r.Attribute("Version").Value)) .ToList(); IEnumerable<string> skipped_packages = root .Descendants() .Where(x => x.Name.LocalName == "PackageReference" && x.Attribute(package) != null && x.Attribute("Version") == null) .Select(r => r.Attribute(package).Value); if (skipped_packages.Count() > 0) { this.AuditEnvironment.Warning("{0} package(s) do not have a version specified and will not be audited: {1}.", skipped_packages.Count(), skipped_packages.Aggregate((s1, s2) => s1 + "," + s2)); } var helper = new NuGetApiHelper(this.AuditEnvironment, config_file.DirectoryName); var nuGetFrameworks = helper.GetFrameworks(root); if (!nuGetFrameworks.Any()) { AuditEnvironment.Warning("Scanning from project file found 0 packages, checking for packages.config file. "); nuGetFrameworks = helper.GetFrameworks(); } if (!nuGetFrameworks.Any()) { AuditEnvironment.Warning("Scanning NuGet transitive dependencies failed because no target framework is found in {0}...", config_file.Name); } foreach (var framework in nuGetFrameworks) { AuditEnvironment.Info("Scanning NuGet transitive dependencies for {0}...", framework.GetFrameworkString()); var deps = helper.GetPackageDependencies(packages, framework); Task.WaitAll(deps); packages = helper.AddPackageDependencies(deps.Result, packages); } return packages; } else { this.AuditEnvironment.Error("{0} is not a .NET Core format .csproj file.", config_file.FullName); return packages; } } public override bool IsVulnerabilityVersionInPackageVersionRange(string vulnerability_version, string package_version) { string message = ""; bool r = NuGetv2.RangeIntersect(vulnerability_version, package_version, out message); if (!r && !string.IsNullOrEmpty(message)) { throw new Exception(message); } else return r; } #endregion #region Properties public string DefaultPackageSourceLockFile {get; } = ""; public string PackageSourceLockFile {get; set;} #endregion #region Methods public bool PackageVersionIsRange(string version) { var lcs = Versatile.SemanticVersion.Grammar.Range.Parse(version); if (lcs.Count > 1) { return true; } else if (lcs.Count == 1) { var cs = lcs.Single(); if (cs.Count == 1 && cs.Single().Operator == ExpressionType.Equal) { return false; } else { return true; } } else throw new ArgumentException($"Failed to parser {version} as a version."); } public List<string> GetMinimumPackageVersions(string version) { if (version.StartsWith("[")) version = version.Remove(0, 1); if (version.EndsWith("]")) version = version.Remove(version.Length -1, 1); var lcs = Versatile.SemanticVersion.Grammar.Range.Parse(version); List<string> minVersions = new List<string>(); foreach(ComparatorSet<Versatile.SemanticVersion> cs in lcs) { if (cs.Count == 1 && cs.Single().Operator == ExpressionType.Equal) { minVersions.Add(cs.Single().Version.ToNormalizedString()); } else { var gt = cs.Where(c => c.Operator == ExpressionType.GreaterThan || c.Operator == ExpressionType.GreaterThanOrEqual).Single(); if (gt.Operator == ExpressionType.GreaterThan) { var v = gt.Version; minVersions.Add((v++).ToNormalizedString()); this.AuditEnvironment.Info("Using {0} package version {1} which satisfies range {2}.", this.PackageManagerLabel, (v++).ToNormalizedString(), version); } else { minVersions.Add(gt.Version.ToNormalizedString()); this.AuditEnvironment.Info("Using {0} package version {1} which satisfies range {2}.", this.PackageManagerLabel, gt.Version.ToNormalizedString(), version); } } } return minVersions; } public List<Package> GetDeveloperPackages(string name, string version, string vendor = null, string group = null, string architecture=null) { return GetMinimumPackageVersions(version).Select(v => new Package(PackageManagerId, name, v, vendor, group, architecture)).ToList(); } public async Task GetDeps(XElement project, List<Package> packages) { IEnumerable<NuGetFramework> frameworks = project.Descendants() .Where(x => x.Name.LocalName == "TargetFramework" || x.Name.LocalName == "TargetFrameworks") .SingleOrDefault() .Value.Split(';') .Select(f => NuGetFramework.ParseFolder(f)); AuditEnvironment.Info("{0}", frameworks.First().Framework); var nugetPackages = packages.Select(p => new PackageIdentity(p.Name, NuGetVersion.Parse(p.Version))); var settings = Settings.LoadDefaultSettings(root: null); var sourceRepositoryProvider = new SourceRepositoryProvider(settings, Repository.Provider.GetCoreV3()); var logger = NullLogger.Instance; using (var cacheContext = new SourceCacheContext()) { foreach (var np in nugetPackages) { foreach (var sourceRepository in sourceRepositoryProvider.GetRepositories()) { var dependencyInfoResource = await sourceRepository.GetResourceAsync<DependencyInfoResource>(); var dependencyInfo = await dependencyInfoResource.ResolvePackage( np, frameworks.First(), cacheContext, logger, CancellationToken.None); if (dependencyInfo != null) { AuditEnvironment.Info("Dependency info: {0}.", dependencyInfo); } } } } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using MvxDemo.WebApi.Areas.HelpPage.Models; namespace MvxDemo.WebApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes { public class CodeFixServiceTests { [Fact] public void TestGetFirstDiagnosticWithFixAsync() { var diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); var fixers = CreateFixers(); var code = @" a "; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code)) { var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => workspace.Services.GetService<IErrorLoggerService>())); var fixService = new CodeFixService( diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>()); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); var document = project.Documents.Single(); var unused = fixService.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), considerSuppressionFixes: false, cancellationToken: CancellationToken.None).Result; var fixer1 = fixers.Single().Value as MockFixer; var fixer2 = reference.Fixer as MockFixer; // check to make sure both of them are called. Assert.True(fixer1.Called); Assert.True(fixer2.Called); } } [Fact] public void TestGetCodeFixWithExceptionInRegisterMethod() { GetFirstDiagnosticWithFix(new ErrorCases.ExceptionInRegisterMethod()); GetAddedFixes(new ErrorCases.ExceptionInRegisterMethod()); } [Fact] public void TestGetCodeFixWithExceptionInRegisterMethodAsync() { GetFirstDiagnosticWithFix(new ErrorCases.ExceptionInRegisterMethodAsync()); GetAddedFixes(new ErrorCases.ExceptionInRegisterMethodAsync()); } [Fact] public void TestGetCodeFixWithExceptionInFixableDiagnosticIds() { GetDefaultFixes(new ErrorCases.ExceptionInFixableDiagnosticIds()); GetAddedFixes(new ErrorCases.ExceptionInFixableDiagnosticIds()); } [Fact] public void TestGetCodeFixWithExceptionInGetFixAllProvider() { GetAddedFixes(new ErrorCases.ExceptionInGetFixAllProvider()); } public void GetDefaultFixes(CodeFixProvider codefix) { TestDiagnosticAnalyzerService diagnosticService; CodeFixService fixService; IErrorLoggerService errorLogger; using (var workspace = ServiceSetup(codefix, out diagnosticService, out fixService, out errorLogger)) { Document document; EditorLayerExtensionManager.ExtensionManager extensionManager; GetDocumentAndExtensionManager(diagnosticService, workspace, out document, out extensionManager); var fixes = fixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeSuppressionFixes: true, cancellationToken: CancellationToken.None).Result; Assert.True(((TestErrorLogger)errorLogger).Messages.Count == 1); string message; Assert.True(((TestErrorLogger)errorLogger).Messages.TryGetValue(codefix.GetType().Name, out message)); } } public void GetAddedFixes(CodeFixProvider codefix) { TestDiagnosticAnalyzerService diagnosticService; CodeFixService fixService; IErrorLoggerService errorLogger; using (var workspace = ServiceSetup(codefix, out diagnosticService, out fixService, out errorLogger)) { Document document; EditorLayerExtensionManager.ExtensionManager extensionManager; GetDocumentAndExtensionManager(diagnosticService, workspace, out document, out extensionManager); var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(codefix); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); document = project.Documents.Single(); var fixes = fixService.GetFixesAsync(document, TextSpan.FromBounds(0, 0), includeSuppressionFixes: true, cancellationToken: CancellationToken.None).Result; Assert.True(extensionManager.IsDisabled(codefix)); Assert.False(extensionManager.IsIgnored(codefix)); } } public void GetFirstDiagnosticWithFix(CodeFixProvider codefix) { TestDiagnosticAnalyzerService diagnosticService; CodeFixService fixService; IErrorLoggerService errorLogger; using (var workspace = ServiceSetup(codefix, out diagnosticService, out fixService, out errorLogger)) { Document document; EditorLayerExtensionManager.ExtensionManager extensionManager; GetDocumentAndExtensionManager(diagnosticService, workspace, out document, out extensionManager); var unused = fixService.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), considerSuppressionFixes: false, cancellationToken: CancellationToken.None).Result; Assert.True(extensionManager.IsDisabled(codefix)); Assert.False(extensionManager.IsIgnored(codefix)); } } private static TestWorkspace ServiceSetup(CodeFixProvider codefix, out TestDiagnosticAnalyzerService diagnosticService, out CodeFixService fixService, out IErrorLoggerService errorLogger) { diagnosticService = new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()); var fixers = SpecializedCollections.SingletonEnumerable( new Lazy<CodeFixProvider, CodeChangeProviderMetadata>( () => codefix, new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp))); var code = @"class Program { }"; var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code); var logger = SpecializedCollections.SingletonEnumerable(new Lazy<IErrorLoggerService>(() => new TestErrorLogger())); errorLogger = logger.First().Value; fixService = new CodeFixService( diagnosticService, logger, fixers, SpecializedCollections.EmptyEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>()); return workspace; } private static void GetDocumentAndExtensionManager(TestDiagnosticAnalyzerService diagnosticService, TestWorkspace workspace, out Document document, out EditorLayerExtensionManager.ExtensionManager extensionManager) { var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService; // register diagnostic engine to solution crawler var analyzer = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace); var reference = new MockAnalyzerReference(); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); document = project.Documents.Single(); extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>() as EditorLayerExtensionManager.ExtensionManager; } private IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> CreateFixers() { return SpecializedCollections.SingletonEnumerable( new Lazy<CodeFixProvider, CodeChangeProviderMetadata>(() => new MockFixer(), new CodeChangeProviderMetadata("Test", languages: LanguageNames.CSharp))); } internal class MockFixer : CodeFixProvider { public const string Id = "MyDiagnostic"; public bool Called = false; public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create(Id); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { Called = true; return SpecializedTasks.EmptyTask; } } private class MockAnalyzerReference : AnalyzerReference, ICodeFixProviderFactory { public readonly CodeFixProvider Fixer; public readonly MockDiagnosticAnalyzer Analyzer = new MockDiagnosticAnalyzer(); public MockAnalyzerReference() { Fixer = new MockFixer(); } public MockAnalyzerReference(CodeFixProvider codeFix) { Fixer = codeFix; } public override string Display { get { return "MockAnalyzerReference"; } } public override string FullPath { get { return string.Empty; } } public override object Id { get { return "MockAnalyzerReference"; } } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) { return ImmutableArray.Create<DiagnosticAnalyzer>(Analyzer); } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() { return ImmutableArray<DiagnosticAnalyzer>.Empty; } public ImmutableArray<CodeFixProvider> GetFixers() { return ImmutableArray.Create<CodeFixProvider>(Fixer); } public class MockDiagnosticAnalyzer : DiagnosticAnalyzer { private DiagnosticDescriptor _descriptor = new DiagnosticDescriptor(MockFixer.Id, "MockDiagnostic", "MockDiagnostic", "InternalCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxTreeAction(c => { c.ReportDiagnostic(Diagnostic.Create(_descriptor, c.Tree.GetLocation(TextSpan.FromBounds(0, 0)))); }); } } } internal class TestErrorLogger : IErrorLoggerService { public Dictionary<string, string> Messages = new Dictionary<string, string>(); public void LogException(object source, Exception exception) { Messages.Add(source.GetType().Name, ToLogFormat(exception)); } public bool TryLogException(object source, Exception exception) { try { Messages.Add(source.GetType().Name, ToLogFormat(exception)); return true; } catch (Exception) { return false; } } private static string ToLogFormat(Exception exception) { return exception.Message + Environment.NewLine + exception.StackTrace; } } } }
#if !ZEN_NOT_UNITY3D using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; using ModestTree; namespace Zenject { public static class ZenEditorUtil { public static DiContainer GetContainerForCurrentScene() { var compRoot = GameObject.FindObjectsOfType<SceneCompositionRoot>().OnlyOrDefault(); if (compRoot == null) { throw new ZenjectException( "Unable to find SceneCompositionRoot in current scene."); } return compRoot.Container; } public static List<ZenjectResolveException> ValidateAllActiveScenes(int maxErrors) { var activeScenes = UnityEditor.EditorBuildSettings.scenes.Where(x => x.enabled).Select(x => x.ToString()).ToList(); return ValidateScenes(activeScenes, maxErrors); } // This can be called by build scripts using batch mode unity for continuous integration testing public static void ValidateAllScenesFromScript() { var activeScenes = UnityEditor.EditorBuildSettings.scenes.Where(x => x.enabled).Select(x => x.ToString()).ToList(); ValidateScenes(activeScenes, 25, true); } public static List<ZenjectResolveException> ValidateScenes(List<string> sceneNames, int maxErrors) { return ValidateScenes(sceneNames, maxErrors, false); } public static List<ZenjectResolveException> ValidateScenes(List<string> sceneNames, int maxErrors, bool exitAfter) { var errors = new List<ZenjectResolveException>(); var activeScenes = sceneNames .Select(x => new { Name = x, Path = GetScenePath(x) }).ToList(); foreach (var sceneInfo in activeScenes) { Log.Trace("Validating Scene '{0}'", sceneInfo.Path); EditorApplication.OpenScene(sceneInfo.Path); errors.AddRange(ValidateCurrentScene().Take(maxErrors - errors.Count)); if (errors.Count >= maxErrors) { break; } } if (errors.IsEmpty()) { Log.Trace("Successfully validated all {0} scenes", activeScenes.Count); if (exitAfter) { // 0 = no errors EditorApplication.Exit(0); } } else { Log.Error("Zenject Validation failed! Found {0} errors.", errors.Count); foreach (var err in errors) { Log.ErrorException(err); } if (exitAfter) { // 1 = errors occurred EditorApplication.Exit(1); } } return errors; } static string GetScenePath(string sceneName) { var namesToPaths = UnityEditor.EditorBuildSettings.scenes.ToDictionary( x => Path.GetFileNameWithoutExtension(x.path), x => x.path); if (!namesToPaths.ContainsKey(sceneName)) { throw new Exception( "Could not find scene with name '" + sceneName + "'"); } return namesToPaths[sceneName]; } public static IEnumerable<ZenjectResolveException> ValidateCurrentScene() { var compRoot = GameObject.FindObjectsOfType<SceneCompositionRoot>().OnlyOrDefault(); if (compRoot == null || compRoot.Installers.IsEmpty()) { return Enumerable.Empty<ZenjectResolveException>(); } return ZenEditorUtil.ValidateInstallers(compRoot); } public static IEnumerable<ZenjectResolveException> ValidateInstallers(SceneCompositionRoot compRoot) { var globalContainer = GlobalCompositionRoot.CreateContainer(true, null); var container = compRoot.CreateContainer(true, globalContainer, new List<IInstaller>()); foreach (var error in container.ValidateResolve(new InjectContext(container, typeof(IDependencyRoot), null))) { yield return error; } // Also make sure we can fill in all the dependencies in the built-in scene foreach (var curTransform in compRoot.GetComponentsInChildren<Transform>()) { foreach (var monoBehaviour in curTransform.GetComponents<MonoBehaviour>()) { if (monoBehaviour == null) { Log.Warn("Found null MonoBehaviour on " + curTransform.name); continue; } foreach (var error in container.ValidateObjectGraph(monoBehaviour.GetType())) { yield return error; } } } foreach (var installer in globalContainer.InstalledInstallers.Concat(container.InstalledInstallers)) { if (installer is IValidatable) { foreach (var error in ((IValidatable)installer).Validate()) { yield return error; } } } foreach (var error in container.ValidateValidatables()) { yield return error; } } public static void OutputObjectGraphForCurrentScene( DiContainer container, IEnumerable<Type> ignoreTypes, IEnumerable<Type> contractTypes) { string dotFilePath = EditorUtility.SaveFilePanel("Choose the path to export the object graph", "", "ObjectGraph", "dot"); if (!dotFilePath.IsEmpty()) { ObjectGraphVisualizer.OutputObjectGraphToFile( container, dotFilePath, ignoreTypes, contractTypes); var dotExecPath = EditorPrefs.GetString("Zenject.GraphVizDotExePath", ""); if (dotExecPath.IsEmpty() || !File.Exists(dotExecPath)) { EditorUtility.DisplayDialog( "GraphViz", "Unable to locate GraphViz. Please select the graphviz 'dot.exe' file which can be found at [GraphVizInstallDirectory]/bin/dot.exe. If you do not have GraphViz you can download it at http://www.graphviz.org", "Ok"); dotExecPath = EditorUtility.OpenFilePanel("Please select dot.exe from GraphViz bin directory", "", "exe"); EditorPrefs.SetString("Zenject.GraphVizDotExePath", dotExecPath); } if (!dotExecPath.IsEmpty()) { RunDotExe(dotExecPath, dotFilePath); } } } static void RunDotExe(string dotExePath, string dotFileInputPath) { var outputDir = Path.GetDirectoryName(dotFileInputPath); var fileBaseName = Path.GetFileNameWithoutExtension(dotFileInputPath); var proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = dotExePath; proc.StartInfo.Arguments = "-Tpng {0}.dot -o{0}.png".Fmt(fileBaseName); proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.WorkingDirectory = outputDir; proc.Start(); proc.WaitForExit(); var errorMessage = proc.StandardError.ReadToEnd(); proc.WaitForExit(); if (errorMessage.IsEmpty()) { EditorUtility.DisplayDialog( "Success!", "Successfully created files {0}.dot and {0}.png".Fmt(fileBaseName), "Ok"); } else { EditorUtility.DisplayDialog( "Error", "Error occurred while generating {0}.png".Fmt(fileBaseName), "Ok"); Log.Error("Zenject error: Failure during object graph creation: " + errorMessage); // Do we care about STDOUT? //var outputMessage = proc.StandardOutput.ReadToEnd(); //Log.Error("outputMessage = " + outputMessage); } } } } #endif
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Text; using Mapsui.Extensions; using Mapsui.Layers; using Mapsui.Logging; using Mapsui.Providers; using Mapsui.Rendering; namespace Mapsui.ArcGIS.ImageServiceProvider { public class ArcGISImageServiceProvider : IProjectingProvider { private int _timeOut; private string _url = default!; public string? Token { get; set; } public ArcGISImageCapabilities ArcGisImageCapabilities { get; private set; } public ArcGISImageServiceProvider(ArcGISImageCapabilities capabilities, bool continueOnError = true, string? token = null) { Token = token; CRS = ""; TimeOut = 10000; ContinueOnError = continueOnError; ArcGisImageCapabilities = capabilities; Url = ArcGisImageCapabilities.ServiceUrl; } public ArcGISImageServiceProvider(string url, bool continueOnError = false, string format = "jpgpng", InterpolationType interpolation = InterpolationType.RSP_NearestNeighbor, long startTime = -1, long endTime = -1, string? token = null) { Token = token; Url = url; CRS = ""; TimeOut = 10000; ContinueOnError = continueOnError; ArcGisImageCapabilities = new ArcGISImageCapabilities(Url, startTime, endTime, format, interpolation) { fullExtent = new Extent { xmin = 0, xmax = 0, ymin = 0, ymax = 0 }, initialExtent = new Extent { xmin = 0, xmax = 0, ymin = 0, ymax = 0 } }; var capabilitiesHelper = new CapabilitiesHelper(); capabilitiesHelper.CapabilitiesReceived += CapabilitiesHelperCapabilitiesReceived; capabilitiesHelper.CapabilitiesFailed += CapabilitiesHelperCapabilitiesFailed; capabilitiesHelper.GetCapabilities(url, CapabilitiesType.DynamicServiceCapabilities, token); } public string Url { get => _url; set { _url = value; if (value[value.Length - 1].Equals('/')) _url = value.Remove(value.Length - 1); if (!_url.ToLower().Contains("exportimage")) _url += @"/ExportImage"; } } private static void CapabilitiesHelperCapabilitiesFailed(object? sender, EventArgs e) { throw new Exception("Unable to get ArcGISImage capbilities"); } private void CapabilitiesHelperCapabilitiesReceived(object? sender, EventArgs e) { var capabilities = sender as ArcGISImageCapabilities; if (capabilities == null) return; ArcGisImageCapabilities = capabilities; } public string? CRS { get; set; } public ICredentials? Credentials { get; set; } /// <summary> /// Timeout of webrequest in milliseconds. Default is 10 seconds /// </summary> public int TimeOut { get => _timeOut; set => _timeOut = value; } public IEnumerable<IFeature> GetFeatures(FetchInfo fetchInfo) { var features = new List<RasterFeature>(); var viewport = fetchInfo.ToViewport(); if (viewport != null && TryGetMap(viewport, out var raster)) features.Add(new RasterFeature(raster)); return features; } public bool TryGetMap(IViewport viewport, [NotNullWhen(true)] out MRaster? raster) { raster = null; int width; int height; try { width = Convert.ToInt32(viewport.Width); height = Convert.ToInt32(viewport.Height); } catch (OverflowException ex) { Logger.Log(LogLevel.Error, "Could not convert double to int (ExportMap size)", ex); raster = null; return false; } var uri = new Uri(GetRequestUrl(viewport.Extent, width, height)); var handler = new HttpClientHandler { Credentials = Credentials ?? CredentialCache.DefaultCredentials }; using var client = new HttpClient(handler) { Timeout = TimeSpan.FromMilliseconds(_timeOut) }; try { using var task = client.GetAsync(uri); using var response = task.Result; using (var dataStream = response.Content.ReadAsStreamAsync().Result) try { var bytes = BruTile.Utilities.ReadFully(dataStream); if (viewport.Extent != null) raster = new MRaster(bytes, viewport.Extent); else { raster = null; return false; } } catch (Exception ex) { Logger.Log(LogLevel.Error, ex.Message, ex); raster = null; return false; } return true; } catch (WebException ex) { Logger.Log(LogLevel.Warning, ex.Message, ex); if (!ContinueOnError) throw new RenderException( "There was a problem connecting to the ArcGISImage server", ex); Debug.WriteLine("There was a problem connecting to the WMS server: " + ex.Message); } catch (Exception ex) { if (!ContinueOnError) throw new RenderException("There was a problem while attempting to request the WMS", ex); Debug.WriteLine("There was a problem while attempting to request the WMS" + ex.Message); } raster = null; return false; } private string GetRequestUrl(MRect? boundingBox, int width, int height) { var url = new StringBuilder(Url); if (!ArcGisImageCapabilities.ServiceUrl?.Contains("?") ?? false) url.Append("?"); if (!url.ToString().EndsWith("&") && !url.ToString().EndsWith("?")) url.Append("&"); if (boundingBox != null) url.AppendFormat(CultureInfo.InvariantCulture, "bbox={0},{1},{2},{3}", boundingBox.Min.X, boundingBox.Min.Y, boundingBox.Max.X, boundingBox.Max.Y); url.AppendFormat("&size={0},{1}", width, height); url.AppendFormat("&interpolation={0}", ArcGisImageCapabilities.Interpolation); url.AppendFormat("&format={0}", ArcGisImageCapabilities.Format); url.AppendFormat("&f={0}", "image"); if (string.IsNullOrWhiteSpace(CRS)) throw new Exception("CRS not set"); url.AppendFormat("&imageSR={0}", CRS); url.AppendFormat("&bboxSR={0}", CRS); if (ArcGisImageCapabilities.StartTime == -1 && ArcGisImageCapabilities.EndTime == -1) if (ArcGisImageCapabilities.timeInfo == null || ArcGisImageCapabilities.timeInfo.timeExtent == null || ArcGisImageCapabilities.timeInfo.timeExtent.Length == 0) url.Append("&time=null, null"); else if (ArcGisImageCapabilities.timeInfo.timeExtent.Length == 1) url.AppendFormat("&time={0}, null", ArcGisImageCapabilities.timeInfo.timeExtent[0]); else if (ArcGisImageCapabilities.timeInfo.timeExtent.Length > 1) url.AppendFormat("&time={0}, {1}", ArcGisImageCapabilities.timeInfo.timeExtent[0], ArcGisImageCapabilities.timeInfo.timeExtent[ArcGisImageCapabilities.timeInfo.timeExtent.Length - 1]); else { if (ArcGisImageCapabilities.StartTime != -1 && ArcGisImageCapabilities.EndTime != -1) url.AppendFormat("&time={0}, {1}", ArcGisImageCapabilities.StartTime, ArcGisImageCapabilities.EndTime); if (ArcGisImageCapabilities.StartTime != -1 && ArcGisImageCapabilities.EndTime == -1) url.AppendFormat("&time={0}, null", ArcGisImageCapabilities.StartTime); if (ArcGisImageCapabilities.StartTime == -1 && ArcGisImageCapabilities.EndTime != -1) url.AppendFormat("&time=null, {0}", ArcGisImageCapabilities.EndTime); } if (!string.IsNullOrEmpty(Token)) url.AppendFormat("&token={0}", Token); return url.ToString(); } public MRect? GetExtent() { return null; } public bool ContinueOnError { get; set; } public bool? IsCrsSupported(string crs) { return true; // for now assuming ArcGISServer supports all CRSes } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ #define WSARECV namespace System.ServiceModel.Channels { using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Security.Principal; using System.Threading; using Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Text; using System.Transactions; using System.ServiceModel.Activation; using System.ServiceModel.Security; using System.EnterpriseServices; using SafeCloseHandle = System.ServiceModel.Activation.SafeCloseHandle; using TOKEN_INFORMATION_CLASS = System.ServiceModel.Activation.ListenerUnsafeNativeMethods.TOKEN_INFORMATION_CLASS; [SuppressUnmanagedCodeSecurity] internal static class UnsafeNativeMethods { public const string KERNEL32 = "kernel32.dll"; public const string ADVAPI32 = "advapi32.dll"; public const string BCRYPT = "bcrypt.dll"; public const string MQRT = "mqrt.dll"; public const string SECUR32 = "secur32.dll"; public const string USERENV = "userenv.dll"; #if WSARECV public const string WS2_32 = "ws2_32.dll"; #endif // public const int ERROR_SUCCESS = 0; public const int ERROR_FILE_NOT_FOUND = 2; public const int ERROR_ACCESS_DENIED = 5; public const int ERROR_INVALID_HANDLE = 6; public const int ERROR_NOT_ENOUGH_MEMORY = 8; public const int ERROR_OUTOFMEMORY = 14; public const int ERROR_SHARING_VIOLATION = 32; public const int ERROR_NETNAME_DELETED = 64; public const int ERROR_INVALID_PARAMETER = 87; public const int ERROR_BROKEN_PIPE = 109; public const int ERROR_ALREADY_EXISTS = 183; public const int ERROR_PIPE_BUSY = 231; public const int ERROR_NO_DATA = 232; public const int ERROR_MORE_DATA = 234; public const int WAIT_TIMEOUT = 258; public const int ERROR_PIPE_CONNECTED = 535; public const int ERROR_OPERATION_ABORTED = 995; public const int ERROR_IO_PENDING = 997; public const int ERROR_SERVICE_ALREADY_RUNNING = 1056; public const int ERROR_SERVICE_DISABLED = 1058; public const int ERROR_NO_TRACKING_SERVICE = 1172; public const int ERROR_ALLOTTED_SPACE_EXCEEDED = 1344; public const int ERROR_NO_SYSTEM_RESOURCES = 1450; // When querying for the token length const int ERROR_INSUFFICIENT_BUFFER = 122; public const int STATUS_PENDING = 0x103; // socket errors public const int WSAACCESS = 10013; public const int WSAEMFILE = 10024; public const int WSAEMSGSIZE = 10040; public const int WSAEADDRINUSE = 10048; public const int WSAEADDRNOTAVAIL = 10049; public const int WSAENETDOWN = 10050; public const int WSAENETUNREACH = 10051; public const int WSAENETRESET = 10052; public const int WSAECONNABORTED = 10053; public const int WSAECONNRESET = 10054; public const int WSAENOBUFS = 10055; public const int WSAESHUTDOWN = 10058; public const int WSAETIMEDOUT = 10060; public const int WSAECONNREFUSED = 10061; public const int WSAEHOSTDOWN = 10064; public const int WSAEHOSTUNREACH = 10065; public const int DUPLICATE_CLOSE_SOURCE = 0x00000001; public const int DUPLICATE_SAME_ACCESS = 0x00000002; public const int FILE_FLAG_OVERLAPPED = 0x40000000; public const int FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000; public const int GENERIC_ALL = 0x10000000; public const int GENERIC_READ = unchecked((int)0x80000000); public const int GENERIC_WRITE = 0x40000000; public const int FILE_CREATE_PIPE_INSTANCE = 0x00000004; public const int FILE_WRITE_ATTRIBUTES = 0x00000100; public const int FILE_WRITE_DATA = 0x00000002; public const int FILE_WRITE_EA = 0x00000010; public const int OPEN_EXISTING = 3; public const int PIPE_ACCESS_DUPLEX = 3; public const int PIPE_UNLIMITED_INSTANCES = 255; public const int PIPE_TYPE_BYTE = 0; public const int PIPE_TYPE_MESSAGE = 4; public const int PIPE_READMODE_BYTE = 0; public const int PIPE_READMODE_MESSAGE = 2; // VirtualAlloc constants public const uint MEM_COMMIT = 0x1000; public const uint MEM_DECOMMIT = 0x4000; public const int PAGE_READWRITE = 4; public const int FILE_MAP_WRITE = 2; public const int FILE_MAP_READ = 4; public const int SDDL_REVISION_1 = 1; public const int SECURITY_ANONYMOUS = 0x00000000; public const int SECURITY_QOS_PRESENT = 0x00100000; public const int SECURITY_IDENTIFICATION = 0x00010000; public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; public const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; public const int FORMAT_MESSAGE_FROM_STRING = 0x00000400; public const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; public const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; public const int FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; public const int MQ_RECEIVE_ACCESS = 0x00000001; public const int MQ_SEND_ACCESS = 0x00000002; public const int MQ_MOVE_ACCESS = 0x00000004; public const int MQ_DENY_NONE = 0x00000000; public const int MQ_DENY_RECEIVE_SHARE = 0x00000001; public const int MQ_ACTION_RECEIVE = 0x00000000; public const int MQ_ACTION_PEEK_CURRENT = unchecked((int)0x80000000); public const int MQ_ACTION_PEEK_NEXT = unchecked((int)0x80000001); public const int MQ_LOOKUP_RECEIVE_CURRENT = unchecked((int)0x40000020); public const int MQ_LOOKUP_PEEK_CURRENT = unchecked((int)0x40000010); public const int MQ_NO_TRANSACTION = 0; public const int MQ_MTS_TRANSACTION = 1; public const int MQ_SINGLE_MESSAGE = 3; public const int MQ_INFORMATION_PROPERTY = unchecked((int)0x400E0001); public const int MQ_INFORMATION_ILLEGAL_PROPERTY = unchecked((int)0x400E0002); public const int MQ_INFORMATION_PROPERTY_IGNORED = unchecked((int)0x400E0003); public const int MQ_INFORMATION_UNSUPPORTED_PROPERTY = unchecked((int)0x400E0004); public const int MQ_INFORMATION_DUPLICATE_PROPERTY = unchecked((int)0x400E0005); public const int MQ_INFORMATION_OPERATION_PENDING = unchecked((int)0x400E0006); public const int MQ_INFORMATION_FORMATNAME_BUFFER_TOO_SMALL = unchecked((int)0x400E0009); public const int MQ_INFORMATION_INTERNAL_USER_CERT_EXIST = unchecked((int)0x400E000A); public const int MQ_INFORMATION_OWNER_IGNORED = unchecked((int)0x400E000B); public const int MQ_ERROR = unchecked((int)0xC00E0001); public const int MQ_ERROR_PROPERTY = unchecked((int)0xC00E0002); public const int MQ_ERROR_QUEUE_NOT_FOUND = unchecked((int)0xC00E0003); public const int MQ_ERROR_QUEUE_NOT_ACTIVE = unchecked((int)0xC00E0004); public const int MQ_ERROR_QUEUE_EXISTS = unchecked((int)0xC00E0005); public const int MQ_ERROR_INVALID_PARAMETER = unchecked((int)0xC00E0006); public const int MQ_ERROR_INVALID_HANDLE = unchecked((int)0xC00E0007); public const int MQ_ERROR_OPERATION_CANCELLED = unchecked((int)0xC00E0008); public const int MQ_ERROR_SHARING_VIOLATION = unchecked((int)0xC00E0009); public const int MQ_ERROR_SERVICE_NOT_AVAILABLE = unchecked((int)0xC00E000B); public const int MQ_ERROR_MACHINE_NOT_FOUND = unchecked((int)0xC00E000D); public const int MQ_ERROR_ILLEGAL_SORT = unchecked((int)0xC00E0010); public const int MQ_ERROR_ILLEGAL_USER = unchecked((int)0xC00E0011); public const int MQ_ERROR_NO_DS = unchecked((int)0xC00E0013); public const int MQ_ERROR_ILLEGAL_QUEUE_PATHNAME = unchecked((int)0xC00E0014); public const int MQ_ERROR_ILLEGAL_PROPERTY_VALUE = unchecked((int)0xC00E0018); public const int MQ_ERROR_ILLEGAL_PROPERTY_VT = unchecked((int)0xC00E0019); public const int MQ_ERROR_BUFFER_OVERFLOW = unchecked((int)0xC00E001A); public const int MQ_ERROR_IO_TIMEOUT = unchecked((int)0xC00E001B); public const int MQ_ERROR_ILLEGAL_CURSOR_ACTION = unchecked((int)0xC00E001C); public const int MQ_ERROR_MESSAGE_ALREADY_RECEIVED = unchecked((int)0xC00E001D); public const int MQ_ERROR_ILLEGAL_FORMATNAME = unchecked((int)0xC00E001E); public const int MQ_ERROR_FORMATNAME_BUFFER_TOO_SMALL = unchecked((int)0xC00E001F); public const int MQ_ERROR_UNSUPPORTED_FORMATNAME_OPERATION = unchecked((int)0xC00E0020); public const int MQ_ERROR_ILLEGAL_SECURITY_DESCRIPTOR = unchecked((int)0xC00E0021); public const int MQ_ERROR_SENDERID_BUFFER_TOO_SMALL = unchecked((int)0xC00E0022); public const int MQ_ERROR_SECURITY_DESCRIPTOR_TOO_SMALL = unchecked((int)0xC00E0023); public const int MQ_ERROR_CANNOT_IMPERSONATE_CLIENT = unchecked((int)0xC00E0024); public const int MQ_ERROR_ACCESS_DENIED = unchecked((int)0xC00E0025); public const int MQ_ERROR_PRIVILEGE_NOT_HELD = unchecked((int)0xC00E0026); public const int MQ_ERROR_INSUFFICIENT_RESOURCES = unchecked((int)0xC00E0027); public const int MQ_ERROR_USER_BUFFER_TOO_SMALL = unchecked((int)0xC00E0028); public const int MQ_ERROR_MESSAGE_STORAGE_FAILED = unchecked((int)0xC00E002A); public const int MQ_ERROR_SENDER_CERT_BUFFER_TOO_SMALL = unchecked((int)0xC00E002B); public const int MQ_ERROR_INVALID_CERTIFICATE = unchecked((int)0xC00E002C); public const int MQ_ERROR_CORRUPTED_INTERNAL_CERTIFICATE = unchecked((int)0xC00E002D); public const int MQ_ERROR_INTERNAL_USER_CERT_EXIST = unchecked((int)0xC00E002E); public const int MQ_ERROR_NO_INTERNAL_USER_CERT = unchecked((int)0xC00E002F); public const int MQ_ERROR_CORRUPTED_SECURITY_DATA = unchecked((int)0xC00E0030); public const int MQ_ERROR_CORRUPTED_PERSONAL_CERT_STORE = unchecked((int)0xC00E0031); public const int MQ_ERROR_COMPUTER_DOES_NOT_SUPPORT_ENCRYPTION = unchecked((int)0xC00E0033); public const int MQ_ERROR_BAD_SECURITY_CONTEXT = unchecked((int)0xC00E0035); public const int MQ_ERROR_COULD_NOT_GET_USER_SID = unchecked((int)0xC00E0036); public const int MQ_ERROR_COULD_NOT_GET_ACCOUNT_INFO = unchecked((int)0xC00E0037); public const int MQ_ERROR_ILLEGAL_MQCOLUMNS = unchecked((int)0xC00E0038); public const int MQ_ERROR_ILLEGAL_PROPID = unchecked((int)0xC00E0039); public const int MQ_ERROR_ILLEGAL_RELATION = unchecked((int)0xC00E003A); public const int MQ_ERROR_ILLEGAL_PROPERTY_SIZE = unchecked((int)0xC00E003B); public const int MQ_ERROR_ILLEGAL_RESTRICTION_PROPID = unchecked((int)0xC00E003C); public const int MQ_ERROR_ILLEGAL_MQQUEUEPROPS = unchecked((int)0xC00E003D); public const int MQ_ERROR_PROPERTY_NOTALLOWED = unchecked((int)0xC00E003E); public const int MQ_ERROR_INSUFFICIENT_PROPERTIES = unchecked((int)0xC00E003F); public const int MQ_ERROR_MACHINE_EXISTS = unchecked((int)0xC00E0040); public const int MQ_ERROR_ILLEGAL_MQQMPROPS = unchecked((int)0xC00E0041); public const int MQ_ERROR_DS_IS_FULL = unchecked((int)0xC00E0042); public const int MQ_ERROR_DS_ERROR = unchecked((int)0xC00E0043); public const int MQ_ERROR_INVALID_OWNER = unchecked((int)0xC00E0044); public const int MQ_ERROR_UNSUPPORTED_ACCESS_MODE = unchecked((int)0xC00E0045); public const int MQ_ERROR_RESULT_BUFFER_TOO_SMALL = unchecked((int)0xC00E0046); public const int MQ_ERROR_DELETE_CN_IN_USE = unchecked((int)0xC00E0048); public const int MQ_ERROR_NO_RESPONSE_FROM_OBJECT_SERVER = unchecked((int)0xC00E0049); public const int MQ_ERROR_OBJECT_SERVER_NOT_AVAILABLE = unchecked((int)0xC00E004A); public const int MQ_ERROR_QUEUE_NOT_AVAILABLE = unchecked((int)0xC00E004B); public const int MQ_ERROR_DTC_CONNECT = unchecked((int)0xC00E004C); public const int MQ_ERROR_TRANSACTION_IMPORT = unchecked((int)0xC00E004E); public const int MQ_ERROR_TRANSACTION_USAGE = unchecked((int)0xC00E0050); public const int MQ_ERROR_TRANSACTION_SEQUENCE = unchecked((int)0xC00E0051); public const int MQ_ERROR_MISSING_CONNECTOR_TYPE = unchecked((int)0xC00E0055); public const int MQ_ERROR_STALE_HANDLE = unchecked((int)0xC00E0056); public const int MQ_ERROR_TRANSACTION_ENLIST = unchecked((int)0xC00E0058); public const int MQ_ERROR_QUEUE_DELETED = unchecked((int)0xC00E005A); public const int MQ_ERROR_ILLEGAL_CONTEXT = unchecked((int)0xC00E005B); public const int MQ_ERROR_ILLEGAL_SORT_PROPID = unchecked((int)0xC00E005C); public const int MQ_ERROR_LABEL_TOO_LONG = unchecked((int)0xC00E005D); public const int MQ_ERROR_LABEL_BUFFER_TOO_SMALL = unchecked((int)0xC00E005E); public const int MQ_ERROR_MQIS_SERVER_EMPTY = unchecked((int)0xC00E005F); public const int MQ_ERROR_MQIS_READONLY_MODE = unchecked((int)0xC00E0060); public const int MQ_ERROR_SYMM_KEY_BUFFER_TOO_SMALL = unchecked((int)0xC00E0061); public const int MQ_ERROR_SIGNATURE_BUFFER_TOO_SMALL = unchecked((int)0xC00E0062); public const int MQ_ERROR_PROV_NAME_BUFFER_TOO_SMALL = unchecked((int)0xC00E0063); public const int MQ_ERROR_ILLEGAL_OPERATION = unchecked((int)0xC00E0064); public const int MQ_ERROR_WRITE_NOT_ALLOWED = unchecked((int)0xC00E0065); public const int MQ_ERROR_WKS_CANT_SERVE_CLIENT = unchecked((int)0xC00E0066); public const int MQ_ERROR_DEPEND_WKS_LICENSE_OVERFLOW = unchecked((int)0xC00E0067); public const int MQ_ERROR_REMOTE_MACHINE_NOT_AVAILABLE = unchecked((int)0xC00E0069); public const int MQ_ERROR_UNSUPPORTED_OPERATION = unchecked((int)0xC00E006A); public const int MQ_ERROR_ENCRYPTION_PROVIDER_NOT_SUPPORTED = unchecked((int)0xC00E006B); public const int MQ_ERROR_CANNOT_SET_CRYPTO_SEC_DESCR = unchecked((int)0xC00E006C); public const int MQ_ERROR_CERTIFICATE_NOT_PROVIDED = unchecked((int)0xC00E006D); public const int MQ_ERROR_Q_DNS_PROPERTY_NOT_SUPPORTED = unchecked((int)0xC00E006E); public const int MQ_ERROR_CANNOT_CREATE_CERT_STORE = unchecked((int)0xC00E006F); public const int MQ_ERROR_CANNOT_OPEN_CERT_STORE = unchecked((int)0xC00E0070); public const int MQ_ERROR_ILLEGAL_ENTERPRISE_OPERATION = unchecked((int)0xC00E0071); public const int MQ_ERROR_CANNOT_GRANT_ADD_GUID = unchecked((int)0xC00E0072); public const int MQ_ERROR_CANNOT_LOAD_MSMQOCM = unchecked((int)0xC00E0073); public const int MQ_ERROR_NO_ENTRY_POINT_MSMQOCM = unchecked((int)0xC00E0074); public const int MQ_ERROR_NO_MSMQ_SERVERS_ON_DC = unchecked((int)0xC00E0075); public const int MQ_ERROR_CANNOT_JOIN_DOMAIN = unchecked((int)0xC00E0076); public const int MQ_ERROR_CANNOT_CREATE_ON_GC = unchecked((int)0xC00E0077); public const int MQ_ERROR_GUID_NOT_MATCHING = unchecked((int)0xC00E0078); public const int MQ_ERROR_PUBLIC_KEY_NOT_FOUND = unchecked((int)0xC00E0079); public const int MQ_ERROR_PUBLIC_KEY_DOES_NOT_EXIST = unchecked((int)0xC00E007A); public const int MQ_ERROR_ILLEGAL_MQPRIVATEPROPS = unchecked((int)0xC00E007B); public const int MQ_ERROR_NO_GC_IN_DOMAIN = unchecked((int)0xC00E007C); public const int MQ_ERROR_NO_MSMQ_SERVERS_ON_GC = unchecked((int)0xC00E007D); public const int MQ_ERROR_CANNOT_GET_DN = unchecked((int)0xC00E007E); public const int MQ_ERROR_CANNOT_HASH_DATA_EX = unchecked((int)0xC00E007F); public const int MQ_ERROR_CANNOT_SIGN_DATA_EX = unchecked((int)0xC00E0080); public const int MQ_ERROR_CANNOT_CREATE_HASH_EX = unchecked((int)0xC00E0081); public const int MQ_ERROR_FAIL_VERIFY_SIGNATURE_EX = unchecked((int)0xC00E0082); public const int MQ_ERROR_CANNOT_DELETE_PSC_OBJECTS = unchecked((int)0xC00E0083); public const int MQ_ERROR_NO_MQUSER_OU = unchecked((int)0xC00E0084); public const int MQ_ERROR_CANNOT_LOAD_MQAD = unchecked((int)0xC00E0085); public const int MQ_ERROR_CANNOT_LOAD_MQDSSRV = unchecked((int)0xC00E0086); public const int MQ_ERROR_PROPERTIES_CONFLICT = unchecked((int)0xC00E0087); public const int MQ_ERROR_MESSAGE_NOT_FOUND = unchecked((int)0xC00E0088); public const int MQ_ERROR_CANT_RESOLVE_SITES = unchecked((int)0xC00E0089); public const int MQ_ERROR_NOT_SUPPORTED_BY_DEPENDENT_CLIENTS = unchecked((int)0xC00E008A); public const int MQ_ERROR_OPERATION_NOT_SUPPORTED_BY_REMOTE_COMPUTER = unchecked((int)0xC00E008B); public const int MQ_ERROR_NOT_A_CORRECT_OBJECT_CLASS = unchecked((int)0xC00E008C); public const int MQ_ERROR_MULTI_SORT_KEYS = unchecked((int)0xC00E008D); public const int MQ_ERROR_GC_NEEDED = unchecked((int)0xC00E008E); public const int MQ_ERROR_DS_BIND_ROOT_FOREST = unchecked((int)0xC00E008F); public const int MQ_ERROR_DS_LOCAL_USER = unchecked((int)0xC00E0090); public const int MQ_ERROR_Q_ADS_PROPERTY_NOT_SUPPORTED = unchecked((int)0xC00E0091); public const int MQ_ERROR_BAD_XML_FORMAT = unchecked((int)0xC00E0092); public const int MQ_ERROR_UNSUPPORTED_CLASS = unchecked((int)0xC00E0093); public const int MQ_ERROR_UNINITIALIZED_OBJECT = unchecked((int)0xC00E0094); public const int MQ_ERROR_CANNOT_CREATE_PSC_OBJECTS = unchecked((int)0xC00E0095); public const int MQ_ERROR_CANNOT_UPDATE_PSC_OBJECTS = unchecked((int)0xC00E0096); public const int MQ_ERROR_MESSAGE_LOCKED_UNDER_TRANSACTION = unchecked((int)0xC00E009C); public const int MQMSG_DELIVERY_EXPRESS = 0; public const int MQMSG_DELIVERY_RECOVERABLE = 1; public const int PROPID_M_MSGID_SIZE = 20; public const int PROPID_M_CORRELATIONID_SIZE = 20; public const int MQ_MAX_MSG_LABEL_LEN = 250; public const int MQMSG_JOURNAL_NONE = 0; public const int MQMSG_DEADLETTER = 1; public const int MQMSG_JOURNAL = 2; public const int MQMSG_ACKNOWLEDGMENT_NONE = 0x00; public const int MQMSG_ACKNOWLEDGMENT_POS_ARRIVAL = 0x01; public const int MQMSG_ACKNOWLEDGMENT_POS_RECEIVE = 0x02; public const int MQMSG_ACKNOWLEDGMENT_NEG_ARRIVAL = 0x04; public const int MQMSG_ACKNOWLEDGMENT_NEG_RECEIVE = 0x08; public const int MQMSG_CLASS_NORMAL = 0x0; public const int MQMSG_CLASS_REPORT = 0x1; public const int MQMSG_SENDERID_TYPE_NONE = 0; public const int MQMSG_SENDERID_TYPE_SID = 1; public const int MQMSG_AUTH_LEVEL_NONE = 0; public const int MQMSG_AUTH_LEVEL_ALWAYS = 1; public const int MQMSG_PRIV_LEVEL_NONE = 0; public const int MQMSG_PRIV_LEVEL_BODY_BASE = 0x01; public const int MQMSG_PRIV_LEVEL_BODY_ENHANCED = 0x03; public const int MQMSG_TRACE_NONE = 0; public const int MQMSG_SEND_ROUTE_TO_REPORT_QUEUE = 1; public const int PROPID_M_BASE = 0; public const int PROPID_M_CLASS = (PROPID_M_BASE + 1); /* VT_UI2 */ public const int PROPID_M_MSGID = (PROPID_M_BASE + 2); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_CORRELATIONID = (PROPID_M_BASE + 3); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_PRIORITY = (PROPID_M_BASE + 4); /* VT_UI1 */ public const int PROPID_M_DELIVERY = (PROPID_M_BASE + 5); /* VT_UI1 */ public const int PROPID_M_ACKNOWLEDGE = (PROPID_M_BASE + 6); /* VT_UI1 */ public const int PROPID_M_JOURNAL = (PROPID_M_BASE + 7); /* VT_UI1 */ public const int PROPID_M_APPSPECIFIC = (PROPID_M_BASE + 8); /* VT_UI4 */ public const int PROPID_M_BODY = (PROPID_M_BASE + 9); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_BODY_SIZE = (PROPID_M_BASE + 10); /* VT_UI4 */ public const int PROPID_M_LABEL = (PROPID_M_BASE + 11); /* VT_LPWSTR */ public const int PROPID_M_LABEL_LEN = (PROPID_M_BASE + 12); /* VT_UI4 */ public const int PROPID_M_TIME_TO_REACH_QUEUE = (PROPID_M_BASE + 13); /* VT_UI4 */ public const int PROPID_M_TIME_TO_BE_RECEIVED = (PROPID_M_BASE + 14); /* VT_UI4 */ public const int PROPID_M_RESP_QUEUE = (PROPID_M_BASE + 15); /* VT_LPWSTR */ public const int PROPID_M_RESP_QUEUE_LEN = (PROPID_M_BASE + 16); /* VT_UI4 */ public const int PROPID_M_ADMIN_QUEUE = (PROPID_M_BASE + 17); /* VT_LPWSTR */ public const int PROPID_M_ADMIN_QUEUE_LEN = (PROPID_M_BASE + 18); /* VT_UI4 */ public const int PROPID_M_VERSION = (PROPID_M_BASE + 19); /* VT_UI4 */ public const int PROPID_M_SENDERID = (PROPID_M_BASE + 20); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_SENDERID_LEN = (PROPID_M_BASE + 21); /* VT_UI4 */ public const int PROPID_M_SENDERID_TYPE = (PROPID_M_BASE + 22); /* VT_UI4 */ public const int PROPID_M_PRIV_LEVEL = (PROPID_M_BASE + 23); /* VT_UI4 */ public const int PROPID_M_AUTH_LEVEL = (PROPID_M_BASE + 24); /* VT_UI4 */ public const int PROPID_M_AUTHENTICATED = (PROPID_M_BASE + 25); /* VT_UI1 */ public const int PROPID_M_HASH_ALG = (PROPID_M_BASE + 26); /* VT_UI4 */ public const int PROPID_M_ENCRYPTION_ALG = (PROPID_M_BASE + 27); /* VT_UI4 */ public const int PROPID_M_SENDER_CERT = (PROPID_M_BASE + 28); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_SENDER_CERT_LEN = (PROPID_M_BASE + 29); /* VT_UI4 */ public const int PROPID_M_SRC_MACHINE_ID = (PROPID_M_BASE + 30); /* VT_CLSID */ public const int PROPID_M_SENTTIME = (PROPID_M_BASE + 31); /* VT_UI4 */ public const int PROPID_M_ARRIVEDTIME = (PROPID_M_BASE + 32); /* VT_UI4 */ public const int PROPID_M_DEST_QUEUE = (PROPID_M_BASE + 33); /* VT_LPWSTR */ public const int PROPID_M_DEST_QUEUE_LEN = (PROPID_M_BASE + 34); /* VT_UI4 */ public const int PROPID_M_EXTENSION = (PROPID_M_BASE + 35); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_EXTENSION_LEN = (PROPID_M_BASE + 36); /* VT_UI4 */ public const int PROPID_M_SECURITY_CONTEXT = (PROPID_M_BASE + 37); /* VT_UI4 */ public const int PROPID_M_CONNECTOR_TYPE = (PROPID_M_BASE + 38); /* VT_CLSID */ public const int PROPID_M_XACT_STATUS_QUEUE = (PROPID_M_BASE + 39); /* VT_LPWSTR */ public const int PROPID_M_XACT_STATUS_QUEUE_LEN = (PROPID_M_BASE + 40); /* VT_UI4 */ public const int PROPID_M_TRACE = (PROPID_M_BASE + 41); /* VT_UI1 */ public const int PROPID_M_BODY_TYPE = (PROPID_M_BASE + 42); /* VT_UI4 */ public const int PROPID_M_DEST_SYMM_KEY = (PROPID_M_BASE + 43); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_DEST_SYMM_KEY_LEN = (PROPID_M_BASE + 44); /* VT_UI4 */ public const int PROPID_M_SIGNATURE = (PROPID_M_BASE + 45); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_SIGNATURE_LEN = (PROPID_M_BASE + 46); /* VT_UI4 */ public const int PROPID_M_PROV_TYPE = (PROPID_M_BASE + 47); /* VT_UI4 */ public const int PROPID_M_PROV_NAME = (PROPID_M_BASE + 48); /* VT_LPWSTR */ public const int PROPID_M_PROV_NAME_LEN = (PROPID_M_BASE + 49); /* VT_UI4 */ public const int PROPID_M_FIRST_IN_XACT = (PROPID_M_BASE + 50); /* VT_UI1 */ public const int PROPID_M_LAST_IN_XACT = (PROPID_M_BASE + 51); /* VT_UI1 */ public const int PROPID_M_XACTID = (PROPID_M_BASE + 52); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_AUTHENTICATED_EX = (PROPID_M_BASE + 53); /* VT_UI1 */ public const int PROPID_M_RESP_FORMAT_NAME = (PROPID_M_BASE + 54); /* VT_LPWSTR */ public const int PROPID_M_RESP_FORMAT_NAME_LEN = (PROPID_M_BASE + 55); /* VT_UI4 */ public const int PROPID_M_DEST_FORMAT_NAME = (PROPID_M_BASE + 58); /* VT_LPWSTR */ public const int PROPID_M_DEST_FORMAT_NAME_LEN = (PROPID_M_BASE + 59); /* VT_UI4 */ public const int PROPID_M_LOOKUPID = (PROPID_M_BASE + 60); /* VT_UI8 */ public const int PROPID_M_SOAP_ENVELOPE = (PROPID_M_BASE + 61); /* VT_LPWSTR */ public const int PROPID_M_SOAP_ENVELOPE_LEN = (PROPID_M_BASE + 62); /* VT_UI4 */ public const int PROPID_M_COMPOUND_MESSAGE = (PROPID_M_BASE + 63); /* VT_UI1|VT_VECTOR */ public const int PROPID_M_COMPOUND_MESSAGE_SIZE = (PROPID_M_BASE + 64); /* VT_UI4 */ public const int PROPID_M_SOAP_HEADER = (PROPID_M_BASE + 65); /* VT_LPWSTR */ public const int PROPID_M_SOAP_BODY = (PROPID_M_BASE + 66); /* VT_LPWSTR */ public const int PROPID_M_DEADLETTER_QUEUE = (PROPID_M_BASE + 67); /* VT_LPWSTR */ public const int PROPID_M_DEADLETTER_QUEUE_LEN = (PROPID_M_BASE + 68); /* VT_UI4 */ public const int PROPID_M_ABORT_COUNT = (PROPID_M_BASE + 69); /* VT_UI4 */ public const int PROPID_M_MOVE_COUNT = (PROPID_M_BASE + 70); /* VT_UI4 */ public const int PROPID_M_GROUP_ID = (PROPID_M_BASE + 71); /* VT_LPWSTR */ public const int PROPID_M_GROUP_ID_LEN = (PROPID_M_BASE + 72); /* VT_UI4 */ public const int PROPID_M_FIRST_IN_GROUP = (PROPID_M_BASE + 73); /* VT_UI1 */ public const int PROPID_M_LAST_IN_GROUP = (PROPID_M_BASE + 74); /* VT_UI1 */ public const int PROPID_M_LAST_MOVE_TIME = (PROPID_M_BASE + 75); /* VT_UI4 */ public const int PROPID_Q_BASE = 100; public const int PROPID_Q_INSTANCE = (PROPID_Q_BASE + 1); /* VT_CLSID */ public const int PROPID_Q_TYPE = (PROPID_Q_BASE + 2); /* VT_CLSID */ public const int PROPID_Q_PATHNAME = (PROPID_Q_BASE + 3); /* VT_LPWSTR */ public const int PROPID_Q_JOURNAL = (PROPID_Q_BASE + 4); /* VT_UI1 */ public const int PROPID_Q_QUOTA = (PROPID_Q_BASE + 5); /* VT_UI4 */ public const int PROPID_Q_BASEPRIORITY = (PROPID_Q_BASE + 6); /* VT_I2 */ public const int PROPID_Q_JOURNAL_QUOTA = (PROPID_Q_BASE + 7); /* VT_UI4 */ public const int PROPID_Q_LABEL = (PROPID_Q_BASE + 8); /* VT_LPWSTR */ public const int PROPID_Q_CREATE_TIME = (PROPID_Q_BASE + 9); /* VT_I4 */ public const int PROPID_Q_MODIFY_TIME = (PROPID_Q_BASE + 10); /* VT_I4 */ public const int PROPID_Q_AUTHENTICATE = (PROPID_Q_BASE + 11); /* VT_UI1 */ public const int PROPID_Q_PRIV_LEVEL = (PROPID_Q_BASE + 12); /* VT_UI4 */ public const int PROPID_Q_TRANSACTION = (PROPID_Q_BASE + 13); /* VT_UI1 */ public const int PROPID_Q_PATHNAME_DNS = (PROPID_Q_BASE + 24); /* VT_LPWSTR */ public const int PROPID_Q_MULTICAST_ADDRESS = (PROPID_Q_BASE + 25); /* VT_LPWSTR */ public const int PROPID_Q_ADS_PATH = (PROPID_Q_BASE + 26); /* VT_LPWSTR */ public const int PROPID_PC_BASE = 5800; public const int PROPID_PC_VERSION = (PROPID_PC_BASE + 1); /* VT_UI4 */ public const int PROPID_PC_DS_ENABLED = (PROPID_PC_BASE + 2); /* VT_BOOL */ public const int PROPID_MGMT_QUEUE_BASE = 0; public const int PROPID_MGMT_QUEUE_SUBQUEUE_NAMES = (PROPID_MGMT_QUEUE_BASE + 27); /* VT_LPWSTR|VT_VECTOR */ public const int MQ_TRANSACTIONAL_NONE = 0; public const int MQ_TRANSACTIONAL = 1; public const int ALG_CLASS_HASH = (4 << 13); public const int ALG_CLASS_DATA_ENCRYPT = (3 << 13); public const int ALG_TYPE_ANY = 0; public const int ALG_TYPE_STREAM = (4 << 9); public const int ALG_TYPE_BLOCK = (3 << 9); public const int ALG_SID_MD5 = 3; public const int ALG_SID_SHA1 = 4; public const int ALG_SID_SHA_256 = 12; public const int ALG_SID_SHA_512 = 14; public const int ALG_SID_RC4 = 1; public const int ALG_SID_AES = 17; public const int CALG_MD5 = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD5; public const int CALG_SHA1 = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA1; public const int CALG_SHA_256 = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256; public const int CALG_SHA_512 = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512; public const int CALG_RC4 = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | ALG_SID_RC4; public const int CALG_AES = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES; public const int PROV_RSA_AES = 24; public const string MS_ENH_RSA_AES_PROV = "Microsoft Enhanced RSA and AES Cryptographic Provider"; public const ushort VT_NULL = 1; public const ushort VT_BOOL = 11; public const ushort VT_UI1 = 17; public const ushort VT_UI2 = 18; public const ushort VT_UI4 = 19; public const ushort VT_UI8 = 21; public const ushort VT_LPWSTR = 31; public const ushort VT_VECTOR = 0x1000; public const uint MAX_PATH = 260; [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES { internal int nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); internal IntPtr lpSecurityDescriptor = IntPtr.Zero; internal bool bInheritHandle = false; } public unsafe delegate void MQReceiveCallback(int error, IntPtr handle, int timeout, int action, IntPtr props, NativeOverlapped* nativeOverlapped, IntPtr cursor); [DllImport(KERNEL32), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] internal static extern int CloseHandle ( IntPtr handle ); [DllImport(SECUR32), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] internal static extern int SspiFreeAuthIdentity( [In] IntPtr ppAuthIdentity ); [DllImport(SECUR32), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] internal static extern uint SspiExcludePackage( [In] IntPtr AuthIdentity, [MarshalAs(UnmanagedType.LPWStr)] [In] string pszPackageName, [Out] out IntPtr ppNewAuthIdentity); [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal unsafe static extern int ConnectNamedPipe ( PipeHandle handle, NativeOverlapped* lpOverlapped ); [DllImport(KERNEL32, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.Machine)] internal static extern PipeHandle CreateFile ( string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr lpSECURITY_ATTRIBUTES, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile ); [DllImport(KERNEL32, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern SafeFileMappingHandle CreateFileMapping( IntPtr fileHandle, SECURITY_ATTRIBUTES securityAttributes, int protect, int sizeHigh, int sizeLow, string name ); [DllImport(KERNEL32, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.Machine)] internal unsafe static extern PipeHandle CreateNamedPipe ( string name, int openMode, int pipeMode, int maxInstances, int outBufSize, int inBufSize, int timeout, SECURITY_ATTRIBUTES securityAttributes ); [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal unsafe static extern int DisconnectNamedPipe ( PipeHandle handle ); [DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool DuplicateHandle( IntPtr hSourceProcessHandle, PipeHandle hSourceHandle, SafeCloseHandle hTargetProcessHandle, out IntPtr lpTargetHandle, int dwDesiredAccess, bool bInheritHandle, int dwOptions ); [DllImport(KERNEL32, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] internal static extern int FormatMessage ( int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr arguments ); [DllImport(KERNEL32, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] internal static extern int FormatMessage ( int dwFlags, SafeLibraryHandle lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr arguments ); [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] unsafe internal static extern int GetOverlappedResult ( PipeHandle handle, NativeOverlapped* overlapped, out int bytesTransferred, int wait ); // This p/invoke is for perf-sensitive codepaths which can guarantee a valid handle via custom locking. [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] unsafe internal static extern int GetOverlappedResult ( IntPtr handle, NativeOverlapped* overlapped, out int bytesTransferred, int wait ); // NOTE: a macro in win32 [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical] internal unsafe static bool HasOverlappedIoCompleted( NativeOverlapped* overlapped) { return overlapped->InternalLow != (IntPtr)STATUS_PENDING; } [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.Machine)] internal static extern SafeFileMappingHandle OpenFileMapping ( int access, bool inheritHandle, string name ); [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern SafeViewOfFileHandle MapViewOfFile ( SafeFileMappingHandle handle, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, IntPtr dwNumberOfBytesToMap ); [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [SuppressUnmanagedCodeSecurity, HostProtection(SecurityAction.LinkDemand)] public static extern int QueryPerformanceCounter(out long time); // This p/invoke is for perf-sensitive codepaths which can guarantee a valid handle via custom locking. [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] unsafe internal static extern int ReadFile ( IntPtr handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped ); [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern int SetNamedPipeHandleState ( PipeHandle handle, ref int mode, IntPtr collectionCount, IntPtr collectionDataTimeout ); // This p/invoke is for perf-sensitive codepaths which can guarantee a valid handle via custom locking. [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static unsafe extern int WriteFile ( IntPtr handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped ); [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static unsafe extern bool GetNamedPipeClientProcessId(PipeHandle handle, out int id); [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static unsafe extern bool GetNamedPipeServerProcessId(PipeHandle handle, out int id); [DllImport(KERNEL32, ExactSpelling = true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] internal static extern int UnmapViewOfFile ( IntPtr lpBaseAddress ); [DllImport(KERNEL32, ExactSpelling = true)] [ResourceExposure(ResourceScope.None)] public static extern bool SetWaitableTimer(SafeWaitHandle handle, ref long dueTime, int period, IntPtr mustBeZero, IntPtr mustBeZeroAlso, bool resume); [DllImport(KERNEL32, BestFitMapping = false, CharSet = CharSet.Auto)] [ResourceExposure(ResourceScope.Machine)] public static extern SafeWaitHandle CreateWaitableTimer(IntPtr mustBeZero, bool manualReset, string timerName); #if WSARECV [DllImport(WS2_32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static unsafe extern int WSARecv ( IntPtr handle, WSABuffer* buffers, int bufferCount, out int bytesTransferred, ref int socketFlags, NativeOverlapped* nativeOverlapped, IntPtr completionRoutine ); [DllImport(WS2_32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static unsafe extern bool WSAGetOverlappedResult( IntPtr socketHandle, NativeOverlapped* overlapped, out int bytesTransferred, bool wait, out uint flags ); [StructLayout(LayoutKind.Sequential)] internal struct WSABuffer { public int length; public IntPtr buffer; } #endif internal static string GetComputerName(ComputerNameFormat nameType) { return System.Runtime.Interop.UnsafeNativeMethods.GetComputerName(nameType); } [DllImport(USERENV, SetLastError = true)] internal static extern int DeriveAppContainerSidFromAppContainerName ( [In, MarshalAs(UnmanagedType.LPWStr)] string appContainerName, out IntPtr appContainerSid ); [DllImport(ADVAPI32, SetLastError = true)] internal static extern IntPtr FreeSid ( IntPtr pSid ); // If the function succeeds, the return value is ERROR_SUCCESS and 'packageFamilyNameLength' contains the size of the data copied // to 'packageFamilyName' (in WCHARs, including the null-terminator). If the function fails, the return value is a Win32 error code. [DllImport(KERNEL32)] internal static extern int PackageFamilyNameFromFullName ( [In, MarshalAs(UnmanagedType.LPWStr)] string packageFullName, ref uint packageFamilyNameLength, [In, Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder packageFamilyName ); [DllImport(KERNEL32, SetLastError = true)] internal static extern bool GetAppContainerNamedObjectPath ( IntPtr token, IntPtr appContainerSid, uint objectPathLength, [In, Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder objectPath, ref uint returnLength ); [DllImport(KERNEL32, SetLastError = true)] internal static extern IntPtr GetCurrentProcess(); [DllImport(ADVAPI32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool OpenProcessToken ( IntPtr ProcessHandle, TokenAccessLevels DesiredAccess, out SafeCloseHandle TokenHandle ); // Token marshalled as byte[] [DllImport(ADVAPI32, SetLastError = true)] static extern unsafe bool GetTokenInformation ( SafeCloseHandle tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, byte[] tokenInformation, uint tokenInformationLength, out uint returnLength ); // Token marshalled as uint [DllImport(ADVAPI32, SetLastError = true)] static extern bool GetTokenInformation ( SafeCloseHandle tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, out uint tokenInformation, uint tokenInformationLength, out uint returnLength ); internal static unsafe SecurityIdentifier GetAppContainerSid(SafeCloseHandle tokenHandle) { // Get length of buffer needed for sid. uint returnLength = UnsafeNativeMethods.GetTokenInformationLength( tokenHandle, TOKEN_INFORMATION_CLASS.TokenAppContainerSid); byte[] tokenInformation = new byte[returnLength]; fixed (byte* pTokenInformation = tokenInformation) { if (!UnsafeNativeMethods.GetTokenInformation( tokenHandle, TOKEN_INFORMATION_CLASS.TokenAppContainerSid, tokenInformation, returnLength, out returnLength)) { int errorCode = Marshal.GetLastWin32Error(); throw FxTrace.Exception.AsError(new Win32Exception(errorCode)); } TokenAppContainerInfo* ptg = (TokenAppContainerInfo*)pTokenInformation; return new SecurityIdentifier(ptg->psid); } } [StructLayout(LayoutKind.Sequential)] struct TokenAppContainerInfo { public IntPtr psid; } static uint GetTokenInformationLength(SafeCloseHandle token, TOKEN_INFORMATION_CLASS tokenInformationClass) { uint lengthNeeded; bool success; if (!(success = GetTokenInformation( token, tokenInformationClass, null, 0, out lengthNeeded))) { int error = Marshal.GetLastWin32Error(); if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) { throw FxTrace.Exception.AsError(new Win32Exception(error)); } } Fx.Assert(!success, "Retreving the length should always fail."); return lengthNeeded; } internal static int GetSessionId(SafeCloseHandle tokenHandle) { uint sessionId; uint returnLength; if (!UnsafeNativeMethods.GetTokenInformation( tokenHandle, TOKEN_INFORMATION_CLASS.TokenSessionId, out sessionId, sizeof(uint), out returnLength)) { int errorCode = Marshal.GetLastWin32Error(); throw FxTrace.Exception.AsError(new Win32Exception(errorCode)); } return (int)sessionId; } internal static bool RunningInAppContainer(SafeCloseHandle tokenHandle) { uint runningInAppContainer; uint returnLength; if (!UnsafeNativeMethods.GetTokenInformation( tokenHandle, TOKEN_INFORMATION_CLASS.TokenIsAppContainer, out runningInAppContainer, sizeof(uint), out returnLength)) { int errorCode = Marshal.GetLastWin32Error(); throw FxTrace.Exception.AsError(new Win32Exception(errorCode)); } return runningInAppContainer == 1; } [StructLayout(LayoutKind.Sequential)] public class MQMSGPROPS { public int count; public IntPtr ids; public IntPtr variants; public IntPtr status; } [StructLayout(LayoutKind.Explicit)] public struct MQPROPVARIANT { [FieldOffset(0)] public ushort vt; [FieldOffset(2)] public ushort reserved1; [FieldOffset(4)] public ushort reserved2; [FieldOffset(6)] public ushort reserved3; [FieldOffset(8)] public byte byteValue; [FieldOffset(8)] public short shortValue; [FieldOffset(8)] public int intValue; [FieldOffset(8)] public long longValue; [FieldOffset(8)] public IntPtr intPtr; [FieldOffset(8)] public CAUI1 byteArrayValue; [FieldOffset(8)] public CALPWSTR stringArraysValue; [StructLayout(LayoutKind.Sequential)] public struct CAUI1 { public int size; public IntPtr intPtr; } [StructLayout(LayoutKind.Sequential)] public struct CALPWSTR { public int count; public IntPtr stringArrays; } } [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.Machine)] public static extern int MQOpenQueue(string formatName, int access, int shareMode, out MsmqQueueHandle handle); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public static extern int MQBeginTransaction(out ITransaction refTransaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] public static extern int MQCloseQueue(IntPtr handle); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public static extern int MQSendMessage(MsmqQueueHandle handle, IntPtr properties, IntPtr transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public static extern int MQSendMessage(MsmqQueueHandle handle, IntPtr properties, IDtcTransaction transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQReceiveMessage(MsmqQueueHandle handle, int timeout, int action, IntPtr properties, NativeOverlapped* nativeOverlapped, IntPtr receiveCallback, IntPtr cursorHandle, IntPtr transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQReceiveMessage(IntPtr handle, int timeout, int action, IntPtr properties, NativeOverlapped* nativeOverlapped, IntPtr receiveCallback, IntPtr cursorHandle, IntPtr transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQReceiveMessage(MsmqQueueHandle handle, int timeout, int action, IntPtr properties, NativeOverlapped* nativeOverlapped, IntPtr receiveCallback, IntPtr cursorHandle, IDtcTransaction transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQReceiveMessage(IntPtr handle, int timeout, int action, IntPtr properties, NativeOverlapped* nativeOverlapped, IntPtr receiveCallback, IntPtr cursorHandle, IDtcTransaction transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQReceiveMessage(MsmqQueueHandle handle, int timeout, int action, IntPtr properties, NativeOverlapped* nativeOverlapped, MQReceiveCallback receiveCallback, IntPtr cursorHandle, IntPtr transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQReceiveMessage(IntPtr handle, int timeout, int action, IntPtr properties, NativeOverlapped* nativeOverlapped, IntPtr receiveCallback, IntPtr cursorHandle, ITransaction transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQReceiveMessageByLookupId(MsmqQueueHandle handle, long lookupId, int action, IntPtr properties, NativeOverlapped* nativeOverlapped, IntPtr receiveCallback, IDtcTransaction transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQReceiveMessageByLookupId(MsmqQueueHandle handle, long lookupId, int action, IntPtr properties, NativeOverlapped* nativeOverlapped, IntPtr receiveCallback, IntPtr transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQReceiveMessageByLookupId(MsmqQueueHandle handle, long lookupId, int action, IntPtr properties, NativeOverlapped* nativeOverlapped, IntPtr receiveCallback, ITransaction transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQGetPrivateComputerInformation(string computerName, IntPtr properties); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQMarkMessageRejected(MsmqQueueHandle handle, long lookupId); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public static extern int MQMoveMessage(MsmqQueueHandle sourceQueueHandle, MsmqQueueHandle destinationQueueHandle, long lookupId, IntPtr transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public static extern int MQMoveMessage(MsmqQueueHandle sourceQueueHandle, MsmqQueueHandle destinationQueueHandle, long lookupId, IDtcTransaction transaction); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQGetOverlappedResult(NativeOverlapped* nativeOverlapped); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQGetQueueProperties(string formatName, IntPtr properties); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQPathNameToFormatName(string pathName, StringBuilder formatName, ref int count); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int MQMgmtGetInfo(string computerName, string objectName, IntPtr properties); [DllImport(MQRT, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.None)] public unsafe static extern void MQFreeMemory(IntPtr nativeBuffer); [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] public unsafe static extern int GetHandleInformation(MsmqQueueHandle handle, out int flags); [StructLayout(LayoutKind.Sequential)] public struct MEMORYSTATUSEX { public uint dwLength; public uint dwMemoryLoad; public ulong ullTotalPhys; public ulong ullAvailPhys; public ulong ullTotalPageFile; public ulong ullAvailPageFile; public ulong ullTotalVirtual; public ulong ullAvailVirtual; public ulong ullAvailExtendedVirtual; } [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] public static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [DllImport(KERNEL32, CallingConvention = CallingConvention.StdCall, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, uint flAllocationType, uint flProtect); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [DllImport(KERNEL32, CallingConvention = CallingConvention.StdCall, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize, uint dwFreeType); [DllImport(KERNEL32, CharSet = CharSet.Auto)] [ResourceExposure(ResourceScope.None)] internal static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, [In, MarshalAs(UnmanagedType.LPStr)]string lpProcName); [DllImport(KERNEL32, CharSet = CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.Process)] internal static extern SafeLibraryHandle LoadLibrary(string libFilename); // On Vista and higher, check the value of the machine FIPS policy [DllImport(BCRYPT, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal static extern int BCryptGetFipsAlgorithmMode( [MarshalAs(UnmanagedType.U1), Out] out bool pfEnabled ); // AppModel.h functions (Win8+) [DllImport(KERNEL32, CharSet = CharSet.None, EntryPoint = "GetCurrentPackageId")] [SecurityCritical] [return: MarshalAs(UnmanagedType.I4)] private static extern Int32 GetCurrentPackageId(ref Int32 pBufferLength, Byte[] pBuffer); [Fx.Tag.SecurityNote( Critical = "Critical because it calls the native function GetCurrentPackageId.", Safe = "Safe because it takes no user input and it doesn't leak security sensitive information.")] [SecuritySafeCritical] private static bool _IsTailoredApplication() { if (OSEnvironmentHelper.IsAtLeast(OSVersion.Win8)) { int bufLen = 0; // Will return ERROR_INSUFFICIENT_BUFFER when running within a tailored application, // and will return ERROR_NO_PACKAGE_IDENTITY otherwise. return GetCurrentPackageId(ref bufLen, null) == ERROR_INSUFFICIENT_BUFFER; } else { return false; } } /// <summary> /// Indicates weather the running application is an immersive (or modern) Windows 8 (or later) application. /// </summary> internal static Lazy<bool> IsTailoredApplication = new Lazy<bool>(() => _IsTailoredApplication()); } [SuppressUnmanagedCodeSecurity] class PipeHandle : SafeHandleMinusOneIsInvalid { internal PipeHandle() : base(true) { } // This is unsafe, but is useful for a duplicated handle, which is inherently unsafe already. internal PipeHandle(IntPtr handle) : base(true) { SetHandle(handle); } internal int GetClientPid() { int pid; #pragma warning suppress 56523 // [....], Win32Exception ctor calls Marshal.GetLastWin32Error() bool success = UnsafeNativeMethods.GetNamedPipeClientProcessId(this, out pid); if (!success) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception()); } return pid; } protected override bool ReleaseHandle() { return UnsafeNativeMethods.CloseHandle(handle) != 0; } } [SuppressUnmanagedCodeSecurityAttribute()] sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid { internal SafeFileMappingHandle() : base(true) { } override protected bool ReleaseHandle() { return UnsafeNativeMethods.CloseHandle(handle) != 0; } } [SuppressUnmanagedCodeSecurityAttribute] sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid { bool doNotfreeLibraryOnRelease; internal SafeLibraryHandle() : base(true) { doNotfreeLibraryOnRelease = false; } public void DoNotFreeLibraryOnRelease() { this.doNotfreeLibraryOnRelease = true; } [DllImport(UnsafeNativeMethods.KERNEL32, CharSet = CharSet.Unicode)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern bool FreeLibrary(IntPtr hModule); override protected bool ReleaseHandle() { if (doNotfreeLibraryOnRelease) { handle = IntPtr.Zero; return true; } return FreeLibrary(handle); } } [SuppressUnmanagedCodeSecurityAttribute] sealed class SafeViewOfFileHandle : SafeHandleZeroOrMinusOneIsInvalid { internal SafeViewOfFileHandle() : base(true) { } override protected bool ReleaseHandle() { if (UnsafeNativeMethods.UnmapViewOfFile(handle) != 0) { handle = IntPtr.Zero; return true; } return false; } } [SuppressUnmanagedCodeSecurity] sealed class MsmqQueueHandle : SafeHandleZeroOrMinusOneIsInvalid { internal MsmqQueueHandle() : base(true) { } protected override bool ReleaseHandle() { return UnsafeNativeMethods.MQCloseQueue(handle) >= 0; } } }
// // SeekableTrackInfoDisplay.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Hyena.Gui.Canvas; using Hyena.Gui.Theatrics; using Banshee.Collection; using Banshee.Sources; namespace Banshee.Gui.Widgets { public class SeekableTrackInfoDisplay : StackPanel { private static double text_opacity = 0.6; private CoverArtDisplay cover_art; private TextBlock title; private Slider seek_bar; private StackPanel time_bar; private TextBlock elapsed; private TextBlock seek_to; private TextBlock remaining; private DoubleAnimation transition_animation; private DoubleAnimation seek_to_animation; private uint transition_timeout; private int display_metadata_index; private int display_metadata_states = 3; public SeekableTrackInfoDisplay () { Spacing = 3; Children.Add (cover_art = new CoverArtDisplay ()); Children.Add (new StackPanel () { Orientation = Orientation.Vertical, Spacing = 4, Children = { (title = new TextBlock () { Opacity = text_opacity }), (seek_bar = new Slider ()), (time_bar = new StackPanel () { Spacing = 10, Children = { (elapsed = new TextBlock () { HorizontalAlignment = 0.0, Opacity = text_opacity + 0.25 }), (seek_to = new TextBlock () { HorizontalAlignment = 0.5, Opacity = text_opacity + 0.25 }), (remaining = new TextBlock () { HorizontalAlignment = 1.0, Opacity = text_opacity }) } }) } }); seek_to.Opacity = 0; seek_to_animation = new DoubleAnimation ("Opacity"); seek_to_animation.Repeat (1); seek_bar.PendingValueChanged += (o, e) => OnSeekPendingValueChanged (seek_bar.PendingValue); seek_bar.ValueChanged += (o, e) => OnSeekValueChanged (seek_bar.Value); UpdateMetadataDisplay (); BuildTransitionAnimation (); } private void BuildTransitionAnimation () { transition_animation = new DoubleAnimation ("Opacity"); transition_animation .Throttle (250) .Compose ((a, p) => { var opacity = a.StartState == 0 ? p : 1 - p; if (p == 1) { if (a.StartState == 1) { UpdateMetadataDisplay (); } if (a.ToValue == 1) { a.Expire (); } else { a.Reverse (); } } return opacity * text_opacity; }).Ease (Easing.QuadraticInOut); } public void ResetTransitionTimeout () { } public void StartTransitionTimeout () { if (transition_timeout > 0) { StopTransitionTimeout (); } transition_timeout = GLib.Timeout.Add (5000, OnTransitionTimeout); } public void StopTransitionTimeout () { if (transition_timeout > 0) { GLib.Source.Remove (transition_timeout); transition_timeout = 0; } } private bool OnTransitionTimeout () { title.Animate (transition_animation).From (1).To (0).Start (); return true; } public void UpdateMetadataDisplay () { if (CurrentTrack == null) { title.Text = String.Empty; return; } switch (display_metadata_index % display_metadata_states) { case 0: title.Text = CurrentTrack.DisplayTrackTitle; break; case 1: title.Text = CurrentTrack.DisplayArtistName; break; case 2: title.Text = CurrentTrack.DisplayAlbumTitle; break; } display_metadata_index++; } protected double TimeFromPercent (double percent) { return Duration * Math.Max (0, Math.Min (1, percent)); } private void UpdateTick () { seek_bar.InhibitValueChangeEvent (); seek_bar.Value = Math.Max (0, Math.Min (1, Duration > 0 ? Position / Duration : 0)); seek_bar.UninhibitValueChangeEvent (); TimeSpan duration = TimeSpan.FromMilliseconds (Duration); TimeSpan position = TimeSpan.FromMilliseconds (Position); elapsed.Text = DurationStatusFormatters.ConfusingPreciseFormatter (position); remaining.Text = "-" + DurationStatusFormatters.ConfusingPreciseFormatter (duration - position); } public override void Arrange () { base.Arrange (); time_bar.Margin = title.Margin = new Thickness (seek_bar.Margin.Left, 0, seek_bar.Margin.Right, 0); } public void UpdateCurrentTrack (TrackInfo track) { if (current_track != track) { current_track = track; } cover_art.UpdateCurrentTrack (track); display_metadata_index = 1; OnTransitionTimeout (); ResetTransitionTimeout (); } protected virtual void OnSeekPendingValueChanged (double value) { seek_to.Text = DurationStatusFormatters.ConfusingPreciseFormatter ( TimeSpan.FromMilliseconds (TimeFromPercent (value))); ShowSeekToLabel (); } protected virtual void OnSeekValueChanged (double value) { HideSeekToLabel (); } private void ShowSeekToLabel () { if (seek_bar.IsValueUpdatePending) { seek_to.Opacity = 1; } } private void HideSeekToLabel () { seek_to.Opacity = 0; } private TrackInfo current_track; public TrackInfo CurrentTrack { get { return current_track; } } private double duration; public double Duration { get { return duration; } set { duration = value; UpdateTick (); } } private double position; public double Position { get { return position; } set { position = value; UpdateTick (); } } } }
/* * Originally written by mAd_DaWg 4 November 2013 * * The Delta Project */ using System; using System.Text; using TheDeltaProject.Brain.NeuralNetwork; namespace TheDeltaProject.Tests { class NeuralNetTest { //set boolean standards //defines the difference between high and low in binary //this is done as the networks output is squashed between 0 and 1 private double high = .99; private double low = .01; private double mid = .5; public NeuralNetTest () { Console.Clear (); Console.WriteLine ("This is the neural net testing ground."); Console.WriteLine ("+++++++++++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine ("Currently there is only 1 test and only 1 neural net."); Console.WriteLine ("More neural networks and tests for each network will"); Console.WriteLine ("be added."); Console.WriteLine ("+++++++++++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine (); Console.WriteLine ("Choose a test to be done:"); Console.WriteLine ("Type in only the test Number."); Console.WriteLine ("---------------------------------------------------------"); Console.WriteLine ("1 XOR - Trains the network to a logic function"); Console.WriteLine (" Used to test network convergance and accuracy."); Console.WriteLine(); Console.WriteLine("2 NOR - Trains the network to a logic function"); Console.WriteLine(" Used to test network convergance and accuracy."); Console.WriteLine(); Console.WriteLine("3 XNOR - Trains the network to an advanced logic function"); Console.WriteLine(" Used to test network convergance and accuracy."); Console.WriteLine(" Currently broken, use ctrl+c to quit if 'non responsive'"); Console.WriteLine("---------------------------------------------------------"); while(true) { Console.Write("prompt> "); int testChoice = int.Parse(Console.ReadLine ().Trim()); if (testChoice == 1) { runXORtest (); break; } else if (testChoice == 2) { runNORtest(); break; } else if (testChoice == 3) { runXNORtest(); break; } else { Console.WriteLine(); Console.WriteLine("unknown option"); Console.WriteLine(); } } } //this function runs the XOR test on the Neural Network private void runXORtest () { Console.Clear (); Console.WriteLine ("This is the XOR test"); Console.WriteLine ("------------------------------------------"); Console.WriteLine ("First we need to train the network."); //instantiate variables needed for the test double ll, lh, hl, hh;//binary input combinations int count = 0; //keeps track of how many training sessions where needed to train the network to get an accurate result int iterations = 5;//how many time to iterate through the data for each training session. More iterations give more acurate outputs from the Neural network; double[][] input, output; StringBuilder bld = new StringBuilder (); //array of inputs for training. input = new double[4][]; input [0] = new double[] { high, high }; input [1] = new double[] { low, high }; input [2] = new double[] { high, low }; input [3] = new double[] { low, low }; //array of expected outputs. These outputs match the array of inputs. output = new double[4][]; output [0] = new double[] { low }; output [1] = new double[] { high }; output [2] = new double[] { high }; output [3] = new double[] { low }; NeuralNet net = new NeuralNet ();//create the NeuralNet object, The Neural Network still needs to be initialised. // initialize the Neural Network with // 2 perception neurons(number of inputs to the network) // 1 hidden layer (the number hidden layers to use[minimum of 1 is needed], // Currently using more than one layer will cause a convergance error // and training will loop infinitly in this example. This is a fault // in the Neural Network itself.) // 2 hidden layer neurons (the number of neurons in the hidden layer/each hidden layer // 1 output neuron (the number of outputs from the network) net.Initialize (1, 2, 1, 2, 1, true); Console.WriteLine (); Console.WriteLine ("Okay, all variables needed for the test have been accounted for!"); Console.WriteLine ("Now we will train the network to act like an XOR logic function..."); Console.WriteLine(); Console.Write("busy... "); double[] inputData = {0, 0}; do { count++;//increas the count of training sessions done by 1 net.LearningRate = 3;//set the rate that the neural network learns. By default the network has a learning rate of 0.5 net.Train (input, output, iterations);//do a training session! //get the results of training to see if more training is needed! Used by the while statement. //show the actual value for the output for a binary input of 0 0 inputData [0] = low; inputData [1] = low; ll = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 0 inputData [0] = high; inputData [1] = low; hl = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 0 1 inputData [0] = low; inputData [1] = high; lh = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 1 inputData [0] = high; inputData [1] = high; hh = net.CalculateOutput(inputData)[0]; } // really train this thing well... while (hh > (mid + low)/2 || lh < (mid + high)/2 || hl < (mid + low) /2 || ll > (mid + high)/2); //show the actual value for the output for a binary input of 0 0 inputData [0] = low; inputData [1] = low; ll = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 0 inputData [0] = high; inputData [1] = low; hl = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 0 1 inputData [0] = low; inputData [1] = high; lh = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 1 inputData [0] = high; inputData [1] = high; hh = net.CalculateOutput(inputData)[0]; Console.WriteLine ("Done!"); Console.WriteLine(); Console.WriteLine ("Training Complete!"); Console.WriteLine ("Here are the results of the networks learning"); Console.WriteLine ("=================================="); //print out training results bld.Remove (0, bld.Length); bld.Append ((count * iterations).ToString ()).Append (" iterations required for training\n"); bld.Append ("hh: ").Append (hh.ToString ()).Append (" < .5\n"); bld.Append ("ll: ").Append (ll.ToString ()).Append (" < .5\n"); bld.Append ("hl: ").Append (hl.ToString ()).Append (" > .5\n"); bld.Append ("lh: ").Append (lh.ToString ()).Append (" > .5\n"); Console.WriteLine (bld.ToString ()); Console.WriteLine ("=================================="); Console.WriteLine ("Press any key to continue..."); Console.ReadKey (); CalculateUserInput(net, "XOR"); } //this function runs the NOR test on the Neural Network private void runNORtest() { Console.Clear(); Console.WriteLine("This is the NOR test"); Console.WriteLine("------------------------------------------"); Console.WriteLine("First we need to train the network."); //instantiate variables needed for the test double ll, lh, hl, hh;//binary input combinations int count = 0; //keeps track of how many training sessions where needed to train the network to get an accurate result int iterations = 5;//how many time to iterate through the data for each training session. More iterations give more acurate outputs from the Neural network; double[][] input, output; StringBuilder bld = new StringBuilder(); //array of inputs for training. input = new double[4][]; input[0] = new double[] { high, high }; input[1] = new double[] { low, high }; input[2] = new double[] { high, low }; input[3] = new double[] { low, low }; //array of expected outputs. These outputs match the array of inputs. output = new double[4][]; output[0] = new double[] { low }; output[1] = new double[] { low }; output[2] = new double[] { low }; output[3] = new double[] { high }; NeuralNet net = new NeuralNet();//create the NeuralNet object, The Neural Network still needs to be initialised. // initialize the Neural Network with // 2 perception neurons(number of inputs to the network) // 1 hidden layer (the number hidden layers to use[minimum of 1 is needed], // Currently using more than one layer will cause a convergance error // and training will loop infinitly in this example. This is a fault // in the Neural Network itself.) // 4 hidden layer neurons (the number of neurons in the hidden layer/each hidden layer; requires a minimum of 4 neurons to converge on a NOR function // 1 output neuron (the number of outputs from the network) net.Initialize(1, 2, 1, 4, 1, true); Console.WriteLine(); Console.WriteLine("Okay, all variables needed for the test have been accounted for!"); Console.WriteLine("Now we will train the network to act like an NOR logic function..."); Console.WriteLine(); Console.Write("busy... "); double[] inputData = { 0, 0 }; do { count++;//increas the count of training sessions done by 1 net.LearningRate = 3;//set the rate that the neural network learns. By default the network has a learning rate of 0.5 net.Train(input, output, iterations);//do a training session! //get the results of training to see if more training is needed! Used by the while statement. //show the actual value for the output for a binary input of 0 0 inputData[0] = low; inputData[1] = low; ll = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 0 inputData[0] = high; inputData[1] = low; hl = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 0 1 inputData[0] = low; inputData[1] = high; lh = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 1 inputData[0] = high; inputData[1] = high; hh = net.CalculateOutput(inputData)[0]; } // really train this thing well... while (hh > (mid + low) / 2 || lh > (mid + low) / 2 || hl > (mid + low) / 2 || ll < (mid + high) / 2); //show the actual value for the output for a binary input of 0 0 inputData[0] = low; inputData[1] = low; ll = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 0 inputData[0] = high; inputData[1] = low; hl = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 0 1 inputData[0] = low; inputData[1] = high; lh = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 1 inputData[0] = high; inputData[1] = high; hh = net.CalculateOutput(inputData)[0]; Console.WriteLine("Done!"); Console.WriteLine(); Console.WriteLine("Training is Complete!"); Console.WriteLine("Here are the results of the networks learning"); Console.WriteLine("=================================="); //print out training results bld.Remove(0, bld.Length); bld.Append((count * iterations).ToString()).Append(" iterations required for training\n"); bld.Append("hh: ").Append(hh.ToString()).Append(" < .5\n"); bld.Append("hl: ").Append(hl.ToString()).Append(" < .5\n"); bld.Append("lh: ").Append(lh.ToString()).Append(" < .5\n"); bld.Append("ll: ").Append(ll.ToString()).Append(" > .5\n"); Console.WriteLine(bld.ToString()); Console.WriteLine("=================================="); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); CalculateUserInput(net, "NOR"); } //NEEDS MORE TESTING! this function runs the NOR test on the Neural Network. private void runXNORtest() { Console.Clear(); Console.WriteLine("This is the XNOR test"); Console.WriteLine("------------------------------------------"); Console.WriteLine("First we need to train the network."); //instantiate variables needed for the test double ll, lh, hl, hh;//binary input combinations int count = 0; //keeps track of how many training sessions where needed to train the network to get an accurate result int iterations = 5;//how many time to iterate through the data for each training session. More iterations give more acurate outputs from the Neural network; double[][] input, output; StringBuilder bld = new StringBuilder(); //array of inputs for training. input = new double[4][]; input[0] = new double[] { high, high }; input[1] = new double[] { low, high }; input[2] = new double[] { high, low }; input[3] = new double[] { low, low }; //array of expected outputs. These outputs match the array of inputs. output = new double[4][]; output[0] = new double[] { high }; output[1] = new double[] { low }; output[2] = new double[] { low }; output[3] = new double[] { high }; NeuralNet net = new NeuralNet();//create the NeuralNet object, The Neural Network still needs to be initialised. // initialize the Neural Network with // 2 perception neurons(number of inputs to the network) // 1 hidden layer (the number hidden layers to use[minimum of 1 is needed], // Currently using more than one layer will cause a convergance error // and training will loop infinitly in this example. This is a fault // in the Neural Network itself.) // 4 hidden layer neurons (the number of neurons in the hidden layer/each hidden layer; requires a minimum of 4 neurons to converge on a XNOR function // 1 output neuron (the number of outputs from the network) net.Initialize(1, 2, 1, 5, 1, true); Console.WriteLine(); Console.WriteLine("Okay, all variables needed for the test have been accounted for!"); Console.WriteLine("Now we will train the network to act like an XNOR logic function..."); Console.WriteLine(); Console.Write("busy... "); double[] inputData = { 0, 0 }; do { count++;//increas the count of training sessions done by 1 net.LearningRate = 0.5;//set the rate that the neural network learns. By default the network has a learning rate of 0.5 net.Train(input, output, iterations);//do a training session! //get the results of training to see if more training is needed! Used by the while statement. //show the actual value for the output for a binary input of 0 0 inputData[0] = low; inputData[1] = low; ll = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 0 inputData[0] = high; inputData[1] = low; hl = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 0 1 inputData[0] = low; inputData[1] = high; lh = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 1 inputData[0] = high; inputData[1] = high; hh = net.CalculateOutput(inputData)[0]; } // really train this thing well... while (hh < (mid + high) / 2 || lh > (mid + low) / 2 || hl > (mid + low) / 2 || ll < (mid + high) / 2); //show the actual value for the output for a binary input of 0 0 inputData[0] = low; inputData[1] = low; ll = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 0 inputData[0] = high; inputData[1] = low; hl = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 0 1 inputData[0] = low; inputData[1] = high; lh = net.CalculateOutput(inputData)[0]; //show the actual value for the output for a binary input of 1 1 inputData[0] = high; inputData[1] = high; hh = net.CalculateOutput(inputData)[0]; Console.WriteLine("Done!"); Console.WriteLine(); Console.WriteLine("Training is Complete!"); Console.WriteLine("Here are the results of the networks learning"); Console.WriteLine("=================================="); //print out training results bld.Remove(0, bld.Length); bld.Append((count * iterations).ToString()).Append(" iterations required for training\n"); bld.Append("hh: ").Append(hh.ToString()).Append(" > .5\n"); bld.Append("hl: ").Append(hl.ToString()).Append(" < .5\n"); bld.Append("lh: ").Append(lh.ToString()).Append(" < .5\n"); bld.Append("ll: ").Append(ll.ToString()).Append(" > .5\n"); Console.WriteLine(bld.ToString()); Console.WriteLine("=================================="); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); CalculateUserInput(net, "XNOR"); } //manages the users input for the test private void CalculateUserInput(NeuralNet net, string test) { Console.Clear(); Console.WriteLine("Now for the fun part!"); Console.WriteLine("-----------------------------------------------"); Console.WriteLine("To really get a feel for what the neural net"); Console.WriteLine("does, put in the binary for yourself(either "); Console.WriteLine("a 1 or a 0 only.) You will be asked for two "); Console.WriteLine("values, one at a time. The Neural Network will"); Console.WriteLine("then calculate the answer. I suggest you lookup"); Console.WriteLine("a \"" + test + "Truth Table\" to compare the answers"); Console.WriteLine("-----------------------------------------------"); bool quit = false; double[] inputData = { 0, 0 }; double[] outputData = { 0 };//used for values pertaining to network io string ans = ""; while (quit == false) { Console.WriteLine(); //get input for first input neuron aka input A while (true)//loop untill they give a valid input { Console.WriteLine(); Console.Write("Please enter a value for input A: "); ans = Console.ReadLine();//get value from console if (ans.Equals("0") || ans.ToLower().Equals("false") || ans.ToLower().Equals("f")) { inputData[0] = low; break;//end the loop } else if (ans.Equals("1") || ans.ToLower().Equals("true") || ans.ToLower().Equals("t")) { inputData[0] = high; break;//end the loop } else { Console.WriteLine(ans + " is not a valid input! Type in only a 0 or 1"); } } //get input for second input neuron aka input B while (true)//loop untill they give a valid input { Console.WriteLine(); Console.Write("Please enter a value for input B: "); ans = Console.ReadLine();//get value from console if (ans.Equals("0") || ans.ToLower().Equals("false") || ans.ToLower().Equals("f")) { inputData[1] = low; break;//end the loop } else if (ans.Equals("1") || ans.ToLower().Equals("true") || ans.ToLower().Equals("t")) { inputData[1] = high; break;//end the loop } else { Console.WriteLine(ans + " is not a valid input! Type in only a 0 or 1"); } } outputData = net.CalculateOutput(inputData);//calculate the output value for the users input printBinaryResult(test, inputData, outputData[0]); Console.Write("Do you want to try another input combination [Y or n]: "); ans = Console.ReadLine().ToLower();//get value from console if (ans.Equals("n") || ans.Equals("no")) { quit = true; Console.Clear(); //for asthetic sakes MainClass.printIntro(); } } } //print the results of a binary calculation private void printBinaryResult(string function, double[] input, double output) { Console.WriteLine(); Console.WriteLine(function + " result:"); Console.WriteLine("A B | Q"); Console.WriteLine("----------"); Console.WriteLine(ToBinaryString(input[0]) + " " + ToBinaryString(input[1]) + " | " + ToBinaryString(output)); Console.WriteLine("----------"); Console.WriteLine(); } //converts a double into a binary value returned as a string string ToBinaryString (double input) { if (input > 0.5) { return "1"; } else { return "0"; } } } }
#region license // Copyright (c) 2009 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 // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class Import : Node { protected Expression _expression; protected ReferenceExpression _assemblyReference; protected ReferenceExpression _alias; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Import CloneNode() { return (Import)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Import CleanClone() { return (Import)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.Import; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnImport(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( Import)node; if (!Node.Matches(_expression, other._expression)) return NoMatch("Import._expression"); if (!Node.Matches(_assemblyReference, other._assemblyReference)) return NoMatch("Import._assemblyReference"); if (!Node.Matches(_alias, other._alias)) return NoMatch("Import._alias"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_expression == existing) { this.Expression = (Expression)newNode; return true; } if (_assemblyReference == existing) { this.AssemblyReference = (ReferenceExpression)newNode; return true; } if (_alias == existing) { this.Alias = (ReferenceExpression)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { Import clone = new Import(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _expression) { clone._expression = _expression.Clone() as Expression; clone._expression.InitializeParent(clone); } if (null != _assemblyReference) { clone._assemblyReference = _assemblyReference.Clone() as ReferenceExpression; clone._assemblyReference.InitializeParent(clone); } if (null != _alias) { clone._alias = _alias.Clone() as ReferenceExpression; clone._alias.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _expression) { _expression.ClearTypeSystemBindings(); } if (null != _assemblyReference) { _assemblyReference.ClearTypeSystemBindings(); } if (null != _alias) { _alias.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Expression { get { return _expression; } set { if (_expression != value) { _expression = value; if (null != _expression) { _expression.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public ReferenceExpression AssemblyReference { get { return _assemblyReference; } set { if (_assemblyReference != value) { _assemblyReference = value; if (null != _assemblyReference) { _assemblyReference.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public ReferenceExpression Alias { get { return _alias; } set { if (_alias != value) { _alias = value; if (null != _alias) { _alias.InitializeParent(this); } } } } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Elixr.Api.ApiModels; using Elixr.Api.Models; using Elixr.Api.ViewModels; using Elixr.Api.ViewModels.Extensions; using Elixr.Api.Services; namespace Elixr.Api.Controllers { public class CreaturesController { ElixrDbContext dbContext; UserSession userSession; public CreaturesController(ElixrDbContext dbContext, UserSession userSession) { this.dbContext = dbContext; this.userSession = userSession; } private IQueryable<Creature> CreatureQuery { get { return this.dbContext.Creatures.Where(c => !c.Delisted) .Include(c => c.Race) .Include(c => c.Race).ThenInclude(r => r.FeatureInformation).ThenInclude(fi => fi.Feature).ThenInclude(f => f.RequiredFlaws) .Include(c => c.Race).ThenInclude(r => r.FeatureInformation).ThenInclude(fi => fi.Feature).ThenInclude(f => f.RequiredOaths) .Include(c => c.Race).ThenInclude(r => r.FlawInformation).ThenInclude(fi => fi.Flaw) .Include(c => c.OathInformation).ThenInclude(oi => oi.Oath).ThenInclude(o => o.Mods) .Include(c => c.FlawInformation).ThenInclude(fi => fi.Flaw).ThenInclude(f => f.Mods) .Include(c => c.FeatureInformation).ThenInclude(fi => fi.Feature).ThenInclude(f => f.Mods) .Include(c => c.SpellInformation).ThenInclude(si => si.Spell) .Include(c => c.SpellInformation).ThenInclude(si => si.FeaturesApplied).ThenInclude(fi => fi.Feature) .Include(c => c.ItemInformation).ThenInclude(ii => ii.Item) .Include(c => c.ItemInformation).ThenInclude(ii => ii.FeaturesApplied).ThenInclude(fi => fi.Feature) .Include(c => c.WeaponInformation).ThenInclude(wi => wi.Weapon) .Include(c => c.WeaponInformation).ThenInclude(wi => wi.FeaturesApplied).ThenInclude(fi => fi.Feature) .Include(c => c.ArmorInformation).ThenInclude(ai => ai.Armor) .Include(c => c.ArmorInformation).ThenInclude(ai => ai.FeaturesApplied).ThenInclude(fi => fi.Feature) .Include(c => c.Skills) .Include(c => c.BaseStats) .Include(c => c.Author) .AsQueryable(); } } [HttpGet("~/creatures/characters")] public async Task<List<CreatureViewModel>> GetPlayersCharacters() { var query = this.dbContext.Creatures.Where(c => !c.Delisted && c.IsPlayerCharacter && c.Author.Id == userSession.Player.Id) .OrderBy(c => c.Name); return await query.Select(r => r.ToViewModel()).ToListAsync(); } [HttpGet("~/creatures/delete/{creatureId}")] public async Task<List<CreatureViewModel>> DeleteCreature(int creatureId) { var creature = await dbContext.Creatures.FirstOrDefaultAsync(c => c.Id == creatureId && c.Author.Id == userSession.Player.Id); if (creature != null) { creature.Delisted = true; await dbContext.SaveChangesAsync(); } var query = this.dbContext.Creatures.Where(c => c.IsPlayerCharacter && c.Author.Id == userSession.Player.Id) .OrderBy(c => c.Name); return await query.Select(r => r.ToViewModel()).ToListAsync(); } [HttpPost("~/creatures/search")] public async Task<List<CreatureViewModel>> SearchCreatures([FromBody]SearchInput input) { if (input.Take > 100) { return null; } //For the search, not everything is needed var query = this.dbContext.Creatures.Where(c => !c.Delisted && !c.IsPlayerCharacter).Include(c => c.Author).AsQueryable(); if (!string.IsNullOrWhiteSpace(input.Name)) { query = query.Where(r => r.Name.ToLower() == input.Name.ToLower()); } bool orderByVotes = false; switch (input.SearchMode) { case SearchMode.JustCommunity: query = query.Where(f => f.Author.Id != Player.TheGameMasterId); orderByVotes = true; break; case SearchMode.JustOfficial: query = query.Where(f => f.Author.Id == Player.TheGameMasterId); orderByVotes = false; break; case SearchMode.All: default: orderByVotes = true; break; } if (orderByVotes) { query = query.OrderByVotes(); } else { query = query.OrderBy(f => f.Name); } query = query.Skip(input.Skip).Take(input.Take); var results = await query.ToListAsync(); return results.Select(r => r.ToViewModel()).ToList(); } [HttpGet("~/creatures/{creatureId}")] public async Task<CreatureViewModel> GetCreature(int creatureId) { var result = await this.CreatureQuery.SingleOrDefaultAsync(c => c.Id == creatureId); return result?.ToViewModel(); } [HttpPost("~/creatures/save")] public async Task<int> SaveCreature([FromBody]CreatureEditInput input) { if(input.IsPlayerCharacter && input.CreatureId == 0) { if(await dbContext.Creatures.CountAsync(c => !c.Delisted && c.IsPlayerCharacter && c.Author.Id == userSession.Player.Id) >= 6) { return 0; //they were warned client-side that the beta only allows six player characters } } Creature creature = null; if (input.CreatureId > 0) { creature = await this.CreatureQuery.Where(c => c.Author.Id == this.userSession.Player.Id) .SingleOrDefaultAsync(c => c.Id == input.CreatureId); } else { creature = new Creature(); creature.CreatedAtMS = System.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); dbContext.Entry(creature).State = EntityState.Added; dbContext.Attach(this.userSession.Player); creature.Author = this.userSession.Player; } if (!string.IsNullOrWhiteSpace(input.DescriptionChangedTo)) { creature.Description = input.DescriptionChangedTo; } if (!string.IsNullOrWhiteSpace(input.HairChangedTo)) { creature.Hair = input.HairChangedTo; } if (!string.IsNullOrWhiteSpace(input.AgeChangedTo)) { creature.Age = input.AgeChangedTo; } if (!string.IsNullOrWhiteSpace(input.WeightChangedTo)) { creature.Weight = input.WeightChangedTo; } if (!string.IsNullOrWhiteSpace(input.HeightChangedTo)) { creature.Height = input.HeightChangedTo; } if (!string.IsNullOrWhiteSpace(input.SkinChangedTo)) { creature.Skin = input.SkinChangedTo; } if (!string.IsNullOrWhiteSpace(input.EyesChangedTo)) { creature.Eyes = input.EyesChangedTo; } if (!string.IsNullOrWhiteSpace(input.NameChangedTo)) { creature.Name = input.NameChangedTo; } if (!string.IsNullOrWhiteSpace(input.GenderChangedTo)) { creature.Gender = input.GenderChangedTo; } if (input.RaceIdChangedTo > 0) { creature.Race = await dbContext.Races.SingleOrDefaultAsync(r => r.Id == input.RaceIdChangedTo); } else if(input.RaceIdChangedTo < 0) //-1 means remove Race { creature.Race = null; } creature.CurrentEnergyLedger = input.CurrentEnergyLedgerIs; creature.Level = input.LevelIs; creature.IsPlayerCharacter = input.IsPlayerCharacter; foreach (var oathInfoVM in input.NewOathInformation) { OathInfo oathInfo = new OathInfo { Broken = oathInfoVM.Broken, OathId = oathInfoVM.Oath.OathId, Notes = oathInfoVM.Notes }; creature.OathInformation.Add(oathInfo); } foreach (var featureInfoVM in input.NewFeatureInformation) { FeatureInfo featureInfo = new FeatureInfo { FeatureId = featureInfoVM.Feature.FeatureId, CostWhenTaken = featureInfoVM.CostWhenTaken, EnergySacrificedWhenTaken = featureInfoVM.EnergySacrificedWhenTaken, TakenAtLevel = featureInfoVM.TakenAtLevel, Notes = featureInfoVM.Notes }; if (featureInfoVM.FeatureInfoId > 0) { var existingFeatureInfo = creature.FeatureInformation.FirstOrDefault(fi => fi.Id == featureInfoVM.FeatureInfoId); if (existingFeatureInfo != null) { dbContext.Entry(existingFeatureInfo).State = EntityState.Detached; featureInfo.Id = featureInfoVM.FeatureInfoId; dbContext.Attach(featureInfo); dbContext.Entry(featureInfo).State = EntityState.Modified; } } else { creature.FeatureInformation.Add(featureInfo); } } foreach (var itemInfoVM in input.NewItemInformation) { ItemInfo itemInfo = new ItemInfo { ItemId = itemInfoVM.Item.EquipmentId, Notes = itemInfoVM.Notes }; if (itemInfoVM.ItemInfoId > 0) { // make sure this actually belongs to this here creature var existingItemInfo = creature.ItemInformation.FirstOrDefault(ii => ii.Id == itemInfoVM.ItemInfoId); if (existingItemInfo != null) { dbContext.Entry(existingItemInfo).State = EntityState.Detached; itemInfo.Id = itemInfoVM.ItemInfoId; dbContext.Attach(itemInfo); dbContext.Entry(itemInfo).State = EntityState.Modified; } } else { creature.ItemInformation.Add(itemInfo); } } foreach (var weaponInfoFeatureChange in input.WeaponFeatureChanges) { var weaponInfo = creature.WeaponInformation.FirstOrDefault(si => si.Id == weaponInfoFeatureChange.WeaponInfoId); if (weaponInfo == null) { continue; } foreach (var featureInfoVM in weaponInfoFeatureChange.NewFeatures) { var featureInfo = featureInfoVM.ToDomainModel(); featureInfo.Feature = null; weaponInfo.FeaturesApplied.Add(featureInfo); } weaponInfo.FeaturesApplied.RemoveAll(fi => weaponInfoFeatureChange.DeletedFeatureInfoIds.Contains(fi.Id)); } foreach (var weaponInfoVM in input.NewWeaponInformation) { WeaponInfo weaponInfo = new WeaponInfo { WeaponId = weaponInfoVM.Weapon.EquipmentId, Notes = weaponInfoVM.Notes }; if (weaponInfoVM.WeaponInfoId > 0) { // make sure this actually belongs to this here creature var existingWeaponInfo = creature.ItemInformation.FirstOrDefault(ii => ii.Id == weaponInfoVM.WeaponInfoId); if (existingWeaponInfo != null) { dbContext.Entry(existingWeaponInfo).State = EntityState.Detached; weaponInfo.Id = weaponInfoVM.WeaponInfoId; dbContext.Attach(weaponInfo); dbContext.Entry(weaponInfo).State = EntityState.Modified; } } else { foreach (var featureInfoVM in weaponInfoVM.FeaturesApplied) { var featureInfo = featureInfoVM.ToDomainModel(); featureInfo.Feature = null; weaponInfo.FeaturesApplied.Add(featureInfo); } creature.WeaponInformation.Add(weaponInfo); } } foreach (var armorInfoVM in input.NewArmorInformation) { ArmorInfo armorInfo = new ArmorInfo { ArmorId = armorInfoVM.Armor.EquipmentId, Notes = armorInfoVM.Notes }; if (armorInfoVM.ArmorInfoId > 0) { // make sure this actually belongs to this here creature var existingWeaponInfo = creature.ArmorInformation.FirstOrDefault(ii => ii.Id == armorInfoVM.ArmorInfoId); if (existingWeaponInfo != null) { dbContext.Entry(existingWeaponInfo).State = EntityState.Detached; armorInfo.Id = armorInfoVM.ArmorInfoId; dbContext.Attach(armorInfo); dbContext.Entry(armorInfo).State = EntityState.Modified; } } else { creature.ArmorInformation.Add(armorInfo); } } foreach (var flawInfoVM in input.NewFlawInformation) { FlawInfo flawInfo = new FlawInfo { FlawId = flawInfoVM.Flaw.FlawId, Notes = flawInfoVM.Notes }; if (flawInfoVM.FlawInfoId > 0) { // make sure this actually belongs to this here creature var existingFlawInfo = creature.FlawInformation.FirstOrDefault(fi => fi.Id == flawInfoVM.FlawInfoId); if (existingFlawInfo != null) { dbContext.Entry(existingFlawInfo).State = EntityState.Detached; flawInfo.Id = flawInfoVM.FlawInfoId; dbContext.Attach(flawInfo); dbContext.Entry(flawInfo).State = EntityState.Modified; } } else { creature.FlawInformation.Add(flawInfo); } } foreach (var spellInfoFeatureChange in input.SpellFeatureChanges) { var spellInfo = creature.SpellInformation.FirstOrDefault(si => si.Id == spellInfoFeatureChange.SpellInfoId); if (spellInfo == null) { continue; } foreach (var featureInfoVM in spellInfoFeatureChange.NewFeatures) { var featureInfo = featureInfoVM.ToDomainModel(); featureInfo.Feature = null; spellInfo.FeaturesApplied.Add(featureInfo); } spellInfo.FeaturesApplied.RemoveAll(fi => spellInfoFeatureChange.DeletedFeatureInfoIds.Contains(fi.Id)); } foreach (var spellInfoVM in input.NewSpellInformation) { SpellInfo spellInfo = new SpellInfo { SpellId = spellInfoVM.Spell.SpellId, Notes = spellInfoVM.Notes, FeaturesApplied = new List<FeatureInfo>() }; if (spellInfoVM.SpellInfoId > 0) { var existingSpellInfo = creature.SpellInformation.FirstOrDefault(si => si.Id == spellInfoVM.SpellInfoId); dbContext.Entry(existingSpellInfo).State = EntityState.Detached; spellInfo.Id = existingSpellInfo.Id; dbContext.Attach(spellInfo); dbContext.Entry(spellInfo).State = EntityState.Modified; } else { foreach (var featureInfoVM in spellInfoVM.FeaturesApplied) { var featureInfo = featureInfoVM.ToDomainModel(); featureInfo.Feature = null; spellInfo.FeaturesApplied.Add(featureInfo); } creature.SpellInformation.Add(spellInfo); } } foreach (var statModVM in input.NewStatMods) { var statMod = statModVM.ToDomainModel(); if (statModVM.StatModId > 0) { var existingStatMod = creature.BaseStats.SingleOrDefault(sm => sm.Id == statModVM.StatModId); if (existingStatMod != null) // make sure this stat belongs to this creature { dbContext.Entry(existingStatMod).State = EntityState.Detached; statMod.Id = statModVM.StatModId; dbContext.Attach(statMod); dbContext.Entry(statMod).State = EntityState.Modified; } } else { statMod.Id = 0; creature.BaseStats.Add(statMod); } } foreach (var skillVM in input.NewSkills) { var skill = new Skill { Name = skillVM.Name, Ranks = skillVM.Ranks, BelongsTo = skillVM.BelongsTo, HasDefense = skillVM.HasDefense }; if (skillVM.SkillId > 0) { var existingSkill = creature.Skills.SingleOrDefault(s => s.Id == skillVM.SkillId); if (existingSkill != null) //make sure this skill belongs to this creature { dbContext.Entry(existingSkill).State = EntityState.Detached; skill.Id = skillVM.SkillId; dbContext.Attach(skill); dbContext.Entry(skill).State = EntityState.Modified; } } else { creature.Skills.Add(skill); } } creature.FlawInformation.RemoveAll(fi => input.DeletedFlawInformationIds.Contains(fi.Id)); creature.OathInformation.RemoveAll(oi => input.DeletedOathInformationIds.Contains(oi.Id)); creature.FeatureInformation.RemoveAll(fi => input.DeletedFeatureInformationIds.Contains(fi.Id)); creature.WeaponInformation.RemoveAll(wi => input.DeletedWeaponInformationIds.Contains(wi.Id)); creature.ArmorInformation.RemoveAll(ai => input.DeletedArmorInformationIds.Contains(ai.Id)); creature.ItemInformation.RemoveAll(ii => input.DeletedArmorInformationIds.Contains(ii.Id)); creature.SpellInformation.RemoveAll(si => input.DeletedSpellInfoIds.Contains(si.Id)); creature.Skills.RemoveAll(s => input.DeletedSkillIds.Contains(s.Id)); creature.BaseStats.RemoveAll(sm => input.DeletedStatModIds.Contains(sm.Id)); await dbContext.SaveChangesAsync(); return creature.Id; } } }
#define REMOTE_CONSOLE using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using Microsoft.VisualBasic; // e.g. Interaction.InputBox, MsgBox, MsgBoxResult etc. using System.Diagnostics; #if NETCF using Microsoft.WindowsCE.Forms; #endif using System.IO; namespace DeviceMenuTesting { class FormMenu : ConsoleMenuTesting.MenuSystem { volatile bool _disposed; TextBox tb; Label labelPause; Menu parentMenu; MenuItem itemUnpause, itemClearConsole, itemDoException; #if !NETCF FormsMenuTesting.FormReadAddr _formReadAddress = new FormsMenuTesting.FormReadAddr(); #endif public FormMenu(TextBox tb, Menu parentMenu, Label labelPause) { this.tb = tb; this.tb.Disposed += new EventHandler(tb_Disposed); this.labelPause = labelPause; this.parentMenu = parentMenu; SetupPauseControls(); LoadKnownAddresses(); } void tb_Disposed(object sender, EventArgs e) { _disposed = true; SaveKnownAddresses(); } Dictionary<string, MenuItem> m_subMenus = new Dictionary<string, MenuItem>(); public override void RunMenu() { if (this.tb.InvokeRequired) throw new InvalidOperationException("Must be called from the main thread."); itemUnpause = new MenuItem(); itemUnpause.Enabled = false; itemUnpause.Text = "Un-pause"; itemUnpause.Click += Unpause_Click; this.parentMenu.MenuItems.Add(itemUnpause); // itemClearConsole = new MenuItem(); itemClearConsole.Text = "Clear console"; itemClearConsole.Click += ClearConsole_Click; this.parentMenu.MenuItems.Add(itemClearConsole); // #if NETCF && REMOTE_CONSOLE MenuItem itemX = new MenuItem(); itemX.Text = "Remote console"; itemX.Click += RemoteConsole_Click; this.parentMenu.MenuItems.Add(itemX); #else // Keep the compiler happy. _secondConsole = null; #endif // MenuItem itemY = new MenuItem(); itemY.Text = "Save text"; itemY.Click += SaveText_Click; this.parentMenu.MenuItems.Add(itemY); // itemDoException = new MenuItem(); itemDoException.Text = "Unhandled Exception"; itemDoException.Click += delegate { if (!this.ReadYesNo("Throw exception", false)) return; throw new RankException("DeviceMenuTesting manual exception."); }; this.parentMenu.MenuItems.Add(itemDoException); // foreach (ConsoleMenuTesting.Option cur in Options) { MenuItem item = new MenuItem(); var label = cur.name; label = label.Replace('_', '&'); item.Text = label; item.Click += cur.EventHandlerInvokeOnBackground; if (cur.SubMenu == null || cur.SubMenu == RootName) { this.parentMenu.MenuItems.Add(item); } else { if (!m_subMenus.ContainsKey(cur.SubMenu)) { MenuItem newSubMenu = new MenuItem(); newSubMenu.Text = cur.SubMenu; m_subMenus.Add(cur.SubMenu, newSubMenu); this.parentMenu.MenuItems.Add(newSubMenu); } MenuItem subMenu = m_subMenus[cur.SubMenu]; subMenu.MenuItems.Add(item); } }//for } //---- #if NETCF && REMOTE_CONSOLE void RemoteConsole_Click(object sender, EventArgs e) { if (!ReadYesNo("Connect to Remote console (port " + RemoteConsole.Port + ")", false)) return; if (_secondConsole != null) { var msg = "Remote Console already active!"; SafeMsgBox(msg, "Warning", MsgBoxStyle.Information); return; } _secondConsole = new RemoteConsole(this); } #endif void SaveText_Click(object sender, EventArgs e) { using (var f = System.IO.File.CreateText("output.txt")) { f.WriteLine(this.tb.Text); } } //-------- const string NewLine = "\r\n"; IAuxConsole _secondConsole; void SafeAppendText(string txt) { if (_secondConsole != null) { _secondConsole.AppendText(txt); } // EventHandler dlgt = delegate { tb.Text += txt; }; SafeInvoke(tb, dlgt); } void SafeSetText(string txt) { EventHandler dlgt = delegate { tb.Text = txt; }; SafeInvoke(tb, dlgt); } private void SafeInvoke(Control c, EventHandler dlgt) { if (_disposed) { return; } if (c.InvokeRequired) { c.Invoke(dlgt); } else { dlgt.Invoke(c, EventArgs.Empty); } } public /*override*/ void Clear() { SafeSetText(string.Empty); } public override void WriteLine(string msg) { SafeAppendText(msg + NewLine); } public override void Write(string msg) { SafeAppendText(msg); } public override void WriteLine(object arg0) { WriteLine(arg0.ToString()); } public override void WriteLine(string fmt, params object[] args) { WriteLine(string.Format(fmt, args)); } public override void Write(string fmt, params object[] args) { Write(string.Format(fmt, args)); } string SafeReadLine(string prompt, string title) { string txt = "eeeeeeh"; EventHandler dlgt = delegate { txt = Interaction.InputBox(prompt, title, null, -1, -1); }; SafeInvoke(this.tb, dlgt); return txt; } string SafeReadBluetoothAddress(string prompt, string title) { #if NETCF return SafeReadLine(prompt, title); #else string txt = "eeeeeeh"; EventHandler dlgt = delegate { _formReadAddress.SetPrompt(prompt, title); var rslt = _formReadAddress.ShowDialog(); if (rslt == DialogResult.OK) { txt = _formReadAddress.Line; } else { txt = null; } }; SafeInvoke(this.tb, dlgt); return txt; #endif } MsgBoxResult SafeMsgBox(string prompt, string title, MsgBoxStyle buttons) { MsgBoxResult result = MsgBoxResult.Cancel; EventHandler dlgt = delegate { result = Interaction.MsgBox(prompt, buttons, title); }; SafeInvoke(this.tb, dlgt); return result; } //-------- public override string ReadLine(string prompt) { return SafeReadLine(prompt, "ReadLine"); } public override int ReadInteger(string prompt) { while (true) { int value; string txt = SafeReadLine(prompt, "ReadInteger"); try { value = int.Parse(txt); } catch (FormatException) { continue; } return value; } } public override int? ReadOptionalInteger(string prompt) { while (true) { int value; string txt = SafeReadLine(prompt, "ReadOptionalInteger"); if (string.IsNullOrEmpty(txt)) { return null; } else { try { value = int.Parse(txt); } catch (FormatException) { continue; } return value; } } } public override int? ReadOptionalIntegerHexadecimal(string prompt) { while (true) { int value; string txt = SafeReadLine(prompt, "ReadOptionalIntegerHexadecimal"); if (string.IsNullOrEmpty(txt)) { return null; } else { try { value = int.Parse(txt, System.Globalization.NumberStyles.HexNumber); } catch (FormatException) { continue; } return value; } } } public override InTheHand.Net.BluetoothAddress ReadBluetoothAddress(string prompt) { return ReadBluetoothAddress(prompt, false); } public override InTheHand.Net.BluetoothAddress ReadOptionalBluetoothAddress(string prompt) { return ReadBluetoothAddress(prompt, true); } InTheHand.Net.BluetoothAddress ReadBluetoothAddress(string prompt, bool optional) { while (true) { InTheHand.Net.BluetoothAddress value; string txt = SafeReadBluetoothAddress(prompt, "ReadBluetoothAddress"); if (string.IsNullOrEmpty(txt) && optional) { return null; } if (InTheHand.Net.BluetoothAddress.TryParse(txt, out value)) { AddKnownAddress(value); return value; } }//while } public override string GetFilename() { return GetFilenameWinForms(this); } void ClearConsole_Click(object sender, EventArgs e) { Clear(); } System.Threading.ManualResetEvent m_pause = new System.Threading.ManualResetEvent(false); public override void Pause(string prompt) { m_pause.Reset(); ShowPause(true, prompt); bool x = m_pause.WaitOne(); } private void Unpause_Click(object sender, EventArgs e) { ShowPause(false, null); m_pause.Set(); } private void SetupPauseControls() { this.labelPause.SendToBack(); ShowPause(false, null); } private void ShowPause(bool pausing, string prompt) { System.Threading.ThreadStart dlgt = delegate { if (pausing) { WriteLine(prompt); this.labelPause.Text = "Menu->Un-pause: " + prompt; this.labelPause.Visible = true; Debug.Assert(itemUnpause != null, "init'd in RunMenu so should be valid!"); } else { this.labelPause.Visible = false; } if (itemUnpause != null) { itemUnpause.Enabled = pausing; } }; if (this.tb.InvokeRequired) { this.tb.BeginInvoke(dlgt); } else { dlgt(); } } void Pause__old() { //bool hc = this.tb.IsHandleCreated; bool ir = this.tb.InvokeRequired; if (ir) { //DEBUG } MessageBox.Show("Pause" + (ir ? " InvokeRequired!!" : " (is on UI thread)"), "Pause", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1); } public override bool ReadYesNo(string prompt, bool defaultYes) { MsgBoxStyle style = MsgBoxStyle.YesNo; style |= (defaultYes ? MsgBoxStyle.DefaultButton1 : MsgBoxStyle.DefaultButton2); while (true) { MsgBoxResult val = SafeMsgBox(prompt, "ReadYesNo", style); Debug.Assert(val == MsgBoxResult.Yes || val == MsgBoxResult.No); return (val == MsgBoxResult.Yes); // true==Yes, false==No } } public override bool? ReadYesNoCancel(string prompt, bool? defaultYes) { MsgBoxStyle style = MsgBoxStyle.YesNoCancel; style |= (defaultYes == true ? MsgBoxStyle.DefaultButton1 : defaultYes == false ? MsgBoxStyle.DefaultButton2 : MsgBoxStyle.DefaultButton3); var twoChoicesSupportedOnly = false; #if NETCF twoChoicesSupportedOnly = SystemSettings.Platform == WinCEPlatform.Smartphone; #endif if (twoChoicesSupportedOnly) { bool result; result = ReadYesNo("Choose Yes or No/Cancel -- " + prompt, defaultYes == null); if (result) return true; result = ReadYesNo("Choose No or Cancel -- " + prompt, defaultYes == null); if (result) return false; else return null; } while (true) { MsgBoxResult val = SafeMsgBox(prompt, "ReadYesNoCancel", style); Debug.Assert(val == MsgBoxResult.Yes || val == MsgBoxResult.No || val == MsgBoxResult.Cancel); // true==Yes, false==No if (val == MsgBoxResult.Yes) return true; else if (val == MsgBoxResult.No) return false; else return null; } } public override Guid? ReadOptionalBluetoothUuid(string prompt, Guid? promptDefault) { while (true) { Guid value; if (promptDefault != null) { prompt += " (default: " + promptDefault.ToString() + ")"; } string txt = SafeReadLine(prompt, "ReadOptionalIntegerHexadecimal"); if (string.IsNullOrEmpty(txt)) { return null; } else { if (base.BluetoothService_TryParseIncludingShortForm(txt, out value)) return value; // Continue to give user another chance to input a good value. } } } private void Log(string msg) { SafeAppendText(msg + "\r\n"); } //-- public override void UiInvoke(EventHandler dlgt) { SafeInvoke(tb, dlgt); } public override bool? InvokeRequired { get { return tb.InvokeRequired; } } public override object InvokeeControl { get { return tb; } } //---- #if !NETCF AutoCompleteStringCollection _knownAddresses; private string _knownAddressesPath { get { var dir = Path.GetDirectoryName(EntryAssemblyPath); return Path.Combine(dir, "knownAddresses.txt"); } } private string EntryAssemblyPath { get { var cb = System.Reflection.Assembly.GetEntryAssembly().CodeBase; var u = new Uri(cb); var dir = u.LocalPath; return dir; } } void LoadKnownAddresses() { _knownAddresses = new AutoCompleteStringCollection(); _formReadAddress.SetKnownAddressList(_knownAddresses); string[] lines; try { lines = File.ReadAllLines(_knownAddressesPath); } catch (FileNotFoundException) { return; } _knownAddresses.AddRange(lines); } void SaveKnownAddresses() { string[] arr = new string[_knownAddresses.Count]; _knownAddresses.CopyTo(arr, 0); System.IO.File.WriteAllLines(_knownAddressesPath, arr); } void AddKnownAddress(InTheHand.Net.BluetoothAddress value) { var text = value.ToString("C"); if (!_knownAddresses.Contains(text)) { _knownAddresses.Add(text); } } #else void LoadKnownAddresses() { } void SaveKnownAddresses() { } void AddKnownAddress(InTheHand.Net.BluetoothAddress value) { } #endif } }
using System; using EncompassRest.Loans.Enums; using EncompassRest.Schema; namespace EncompassRest.Loans { /// <summary> /// AdditionalRequests /// </summary> public sealed partial class AdditionalRequests : DirtyExtensibleObject, IIdentifiable { private DirtyValue<string?>? _appraisalContactCellPhone; private DirtyValue<string?>? _appraisalContactEmail; private DirtyValue<StringEnumValue<AppraisalContactForEntry>>? _appraisalContactForEntry; private DirtyValue<string?>? _appraisalContactHomePhone; private DirtyValue<string?>? _appraisalContactName; private DirtyValue<string?>? _appraisalContactWorkPhone; private DirtyValue<DateTime?>? _appraisalDateOrdered; private DirtyValue<string?>? _appraisalDescription1; private DirtyValue<string?>? _appraisalDescription2; private DirtyValue<string?>? _appraisalDescription3; private DirtyValue<bool?>? _appraisalKeyPickUp; private DirtyValue<bool?>? _appraisalLockBox; private DirtyValue<bool?>? _appraisalVacant; private DirtyValue<string?>? _floodDescription1; private DirtyValue<string?>? _floodDescription2; private DirtyValue<string?>? _floodDescription3; private DirtyValue<bool?>? _floodInsuranceEscrowed; private DirtyValue<string?>? _floodReplacementValue; private DirtyValue<string?>? _hazardDescription1; private DirtyValue<string?>? _hazardDescription2; private DirtyValue<string?>? _hazardDescription3; private DirtyValue<bool?>? _hazardInsuranceEscrowed; private DirtyValue<string?>? _hazardReplacementValue; private DirtyValue<string?>? _id; private DirtyValue<decimal?>? _maximumDeductibleFloodAmount; private DirtyValue<decimal?>? _maximumDeductibleFloodPercentage; private DirtyValue<decimal?>? _maximumDeductibleHazardAmount; private DirtyValue<decimal?>? _maximumDeductibleHazardPercentage; private DirtyValue<bool?>? _titleContract; private DirtyValue<string?>? _titleDescription1; private DirtyValue<string?>? _titleDescription2; private DirtyValue<string?>? _titleDescription3; private DirtyValue<bool?>? _titleInsRequirements; private DirtyValue<bool?>? _titleMailAway; private DirtyValue<bool?>? _titlePriorTitlePolicy; private DirtyValue<bool?>? _titleSurvey; private DirtyValue<string?>? _titleTypeOfProperty; private DirtyValue<bool?>? _titleWarrantyDeed; /// <summary> /// Request Appraisal Access Information Contact Cell Phone [REQUEST.X32] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? AppraisalContactCellPhone { get => _appraisalContactCellPhone; set => SetField(ref _appraisalContactCellPhone, value); } /// <summary> /// Request Appraisal Access Information Contact Email [REQUEST.X33] /// </summary> public string? AppraisalContactEmail { get => _appraisalContactEmail; set => SetField(ref _appraisalContactEmail, value); } /// <summary> /// Request Appraisal Contact for Entry [REQUEST.X25] /// </summary> public StringEnumValue<AppraisalContactForEntry> AppraisalContactForEntry { get => _appraisalContactForEntry; set => SetField(ref _appraisalContactForEntry, value); } /// <summary> /// Request Appraisal Access Information Contact Home Phone [REQUEST.X30] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? AppraisalContactHomePhone { get => _appraisalContactHomePhone; set => SetField(ref _appraisalContactHomePhone, value); } /// <summary> /// Request Appraisal Access Information Contact Name [REQUEST.X29] /// </summary> public string? AppraisalContactName { get => _appraisalContactName; set => SetField(ref _appraisalContactName, value); } /// <summary> /// Request Appraisal Access Information Contact Business Phone [REQUEST.X31] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? AppraisalContactWorkPhone { get => _appraisalContactWorkPhone; set => SetField(ref _appraisalContactWorkPhone, value); } /// <summary> /// Request Appraisal Date Ordered [REQUEST.X21] /// </summary> public DateTime? AppraisalDateOrdered { get => _appraisalDateOrdered; set => SetField(ref _appraisalDateOrdered, value); } /// <summary> /// Request Appraisal Comments 1 [REQUEST.X26] /// </summary> public string? AppraisalDescription1 { get => _appraisalDescription1; set => SetField(ref _appraisalDescription1, value); } /// <summary> /// Request Appraisal Comments 2 [REQUEST.X27] /// </summary> public string? AppraisalDescription2 { get => _appraisalDescription2; set => SetField(ref _appraisalDescription2, value); } /// <summary> /// Request Appraisal Comments 3 [REQUEST.X28] /// </summary> public string? AppraisalDescription3 { get => _appraisalDescription3; set => SetField(ref _appraisalDescription3, value); } /// <summary> /// Request Appraisal Prprty Access Key Pick Up [REQUEST.X24] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Key Pick Up\"}")] public bool? AppraisalKeyPickUp { get => _appraisalKeyPickUp; set => SetField(ref _appraisalKeyPickUp, value); } /// <summary> /// Request Appraisal Prprty Access Lockbox [REQUEST.X23] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Lock Box\"}")] public bool? AppraisalLockBox { get => _appraisalLockBox; set => SetField(ref _appraisalLockBox, value); } /// <summary> /// Request Appraisal Prprty Access Vacant [REQUEST.X22] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Vacant\"}")] public bool? AppraisalVacant { get => _appraisalVacant; set => SetField(ref _appraisalVacant, value); } /// <summary> /// Request Flood Ins Comments 1 [REQUEST.X8] /// </summary> public string? FloodDescription1 { get => _floodDescription1; set => SetField(ref _floodDescription1, value); } /// <summary> /// Request Flood Ins Comments 2 [REQUEST.X9] /// </summary> public string? FloodDescription2 { get => _floodDescription2; set => SetField(ref _floodDescription2, value); } /// <summary> /// Request Flood Ins Comments 3 [REQUEST.X10] /// </summary> public string? FloodDescription3 { get => _floodDescription3; set => SetField(ref _floodDescription3, value); } /// <summary> /// Request Flood Ins Escrowed Yes/No [REQUEST.X7] /// </summary> public bool? FloodInsuranceEscrowed { get => _floodInsuranceEscrowed; set => SetField(ref _floodInsuranceEscrowed, value); } /// <summary> /// Request Flood Ins Replacement Value [REQUEST.X6] /// </summary> public string? FloodReplacementValue { get => _floodReplacementValue; set => SetField(ref _floodReplacementValue, value); } /// <summary> /// Request Hazard Ins Comments 1 [REQUEST.X3] /// </summary> public string? HazardDescription1 { get => _hazardDescription1; set => SetField(ref _hazardDescription1, value); } /// <summary> /// Request Hazard Ins Comments 2 [REQUEST.X4] /// </summary> public string? HazardDescription2 { get => _hazardDescription2; set => SetField(ref _hazardDescription2, value); } /// <summary> /// Request Hazard Ins Comments 3 [REQUEST.X5] /// </summary> public string? HazardDescription3 { get => _hazardDescription3; set => SetField(ref _hazardDescription3, value); } /// <summary> /// Request Hazard Ins Escrowed Yes/No [REQUEST.X2] /// </summary> public bool? HazardInsuranceEscrowed { get => _hazardInsuranceEscrowed; set => SetField(ref _hazardInsuranceEscrowed, value); } /// <summary> /// Request Hazard Ins Replacement Value [REQUEST.X1] /// </summary> public string? HazardReplacementValue { get => _hazardReplacementValue; set => SetField(ref _hazardReplacementValue, value); } /// <summary> /// AdditionalRequests Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// Maximum Deductible Flood Amount [REQUEST.X37] /// </summary> public decimal? MaximumDeductibleFloodAmount { get => _maximumDeductibleFloodAmount; set => SetField(ref _maximumDeductibleFloodAmount, value); } /// <summary> /// Maximum Deductible Flood Percentage [REQUEST.X36] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? MaximumDeductibleFloodPercentage { get => _maximumDeductibleFloodPercentage; set => SetField(ref _maximumDeductibleFloodPercentage, value); } /// <summary> /// Maximum Deductible Hazard Amount [REQUEST.X35] /// </summary> public decimal? MaximumDeductibleHazardAmount { get => _maximumDeductibleHazardAmount; set => SetField(ref _maximumDeductibleHazardAmount, value); } /// <summary> /// Maximum Deductible Hazard Percentage [REQUEST.X34] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? MaximumDeductibleHazardPercentage { get => _maximumDeductibleHazardPercentage; set => SetField(ref _maximumDeductibleHazardPercentage, value); } /// <summary> /// Request Title Commit Attach Contract [REQUEST.X13] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Contract\"}")] public bool? TitleContract { get => _titleContract; set => SetField(ref _titleContract, value); } /// <summary> /// Request Title Commit Comments 1 [REQUEST.X18] /// </summary> public string? TitleDescription1 { get => _titleDescription1; set => SetField(ref _titleDescription1, value); } /// <summary> /// Request Title Commit Comments 2 [REQUEST.X19] /// </summary> public string? TitleDescription2 { get => _titleDescription2; set => SetField(ref _titleDescription2, value); } /// <summary> /// Request Title Commit Comments 3 [REQUEST.X20] /// </summary> public string? TitleDescription3 { get => _titleDescription3; set => SetField(ref _titleDescription3, value); } /// <summary> /// Request Title Commit Attach Title Ins Req [REQUEST.X12] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Title Insurance Requirements\"}")] public bool? TitleInsRequirements { get => _titleInsRequirements; set => SetField(ref _titleInsRequirements, value); } /// <summary> /// Request Title Commit Mail Yes/No [REQUEST.X17] /// </summary> public bool? TitleMailAway { get => _titleMailAway; set => SetField(ref _titleMailAway, value); } /// <summary> /// Request Title Commit Attach Prior Title Policy [REQUEST.X11] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Prior Title Policy\"}")] public bool? TitlePriorTitlePolicy { get => _titlePriorTitlePolicy; set => SetField(ref _titlePriorTitlePolicy, value); } /// <summary> /// Request Title Commit Attach Survey [REQUEST.X15] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Survey\"}")] public bool? TitleSurvey { get => _titleSurvey; set => SetField(ref _titleSurvey, value); } /// <summary> /// Request Title Commit Policy Type [REQUEST.X16] /// </summary> public string? TitleTypeOfProperty { get => _titleTypeOfProperty; set => SetField(ref _titleTypeOfProperty, value); } /// <summary> /// Request Title Commit Attach Warranty Deed [REQUEST.X14] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Warranty Deed\"}")] public bool? TitleWarrantyDeed { get => _titleWarrantyDeed; set => SetField(ref _titleWarrantyDeed, value); } } }
using System; namespace Bridge.jQuery2 { public partial class jQuery { /// <summary> /// Trigger the "click" JavaScript event on an element. /// </summary> /// <returns>The jQuery instance</returns> public virtual jQuery Click() { return null; } /// <summary> /// Bind an event handler to the "click" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Click(Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "click" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Click(Action handler) { return null; } /// <summary> /// Bind an event handler to the "click" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Click(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind an event handler to the "click" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Click(object eventData, Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "click" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Click(object eventData, Action handler) { return null; } /// <summary> /// Trigger the "dblclick" JavaScript event on an element. /// </summary> /// <returns>The jQuery instance</returns> [Template("dblclick()")] public virtual jQuery DblClick() { return null; } /// <summary> /// Bind an event handler to the "dblclick" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("dblclick({0})")] public virtual jQuery DblClick(Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "dblclick" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("dblclick({0})")] public virtual jQuery DblClick(Action handler) { return null; } /// <summary> /// Bind an event handler to the "dblclick" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("dblclick({0})")] public virtual jQuery DblClick(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind an event handler to the "dblclick" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("dblclick({0},{1})")] public virtual jQuery DblClick(object eventData, Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "dblclick" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("dblclick({0},{1})")] public virtual jQuery DblClick(object eventData, Action handler) { return null; } /// <summary> /// Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. /// </summary> /// <param name="handler">A function to execute when the mouse pointer enters or leaves the element.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Hover(Delegate handler) { return null; } /// <summary> /// Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. /// </summary> /// <param name="handler">A function to execute when the mouse pointer enters or leaves the element.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Hover(Action handler) { return null; } /// <summary> /// Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. /// </summary> /// <param name="handler">A function to execute when the mouse pointer enters or leaves the element.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Hover(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. /// </summary> /// <param name="handlerIn">A function to execute when the mouse pointer enters the element.</param> /// <param name="handlerOut">A function to execute when the mouse pointer leaves the element.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Hover(Delegate handlerIn, Delegate handlerOut) { return null; } /// <summary> /// Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. /// </summary> /// <param name="handlerIn">A function to execute when the mouse pointer enters the element.</param> /// <param name="handlerOut">A function to execute when the mouse pointer leaves the element.</param> /// <returns>The jQuery instance</returns> public virtual jQuery Hover(Action handlerIn, Action handlerOut) { return null; } /// <summary> /// Trigger the "mousedown" JavaScript event on an element. /// </summary> /// <returns>The jQuery instance</returns> [Template("mousedown()")] public virtual jQuery MouseDown() { return null; } /// <summary> /// Bind an event handler to the "mousedown" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousedown({0})")] public virtual jQuery MouseDown(Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mousedown" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousedown({0})")] public virtual jQuery MouseDown(Action handler) { return null; } /// <summary> /// Bind an event handler to the "mousedown" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousedown({0})")] public virtual jQuery MouseDown(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind an event handler to the "mousedown" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousedown({0},{1})")] public virtual jQuery MouseDown(object eventData, Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mousedown" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousedown({0},{1})")] public virtual jQuery MouseDown(object eventData, Action handler) { return null; } /// <summary> /// Trigger the "mouseenter" JavaScript event on an element. /// </summary> /// <returns>The jQuery instance</returns> [Template("mouseenter()")] public virtual jQuery MouseEnter() { return null; } /// <summary> /// Bind an event handler to the "mouseenter" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseenter({0})")] public virtual jQuery MouseEnter(Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseenter" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseenter({0})")] public virtual jQuery MouseEnter(Action handler) { return null; } /// <summary> /// Bind an event handler to the "mouseenter" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseenter({0})")] public virtual jQuery MouseEnter(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind an event handler to the "mouseenter" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseenter({0},{1})")] public virtual jQuery MouseEnter(object eventData, Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseenter" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseenter({0},{1})")] public virtual jQuery MouseEnter(object eventData, Action handler) { return null; } /// <summary> /// Trigger the "mouseleave" JavaScript event on an element. /// </summary> /// <returns>The jQuery instance</returns> [Template("mouseleave()")] public virtual jQuery MouseLeave() { return null; } /// <summary> /// Bind an event handler to the "mouseleave" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseleave({0})")] public virtual jQuery MouseLeave(Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseleave" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseleave({0})")] public virtual jQuery MouseLeave(Action handler) { return null; } /// <summary> /// Bind an event handler to the "mouseleave" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseleave({0})")] public virtual jQuery MouseLeave(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind an event handler to the "mouseleave" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseleave({0},{1})")] public virtual jQuery MouseLeave(object eventData, Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseleave" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseleave({0},{1})")] public virtual jQuery MouseLeave(object eventData, Action handler) { return null; } /// <summary> /// Trigger the "mousemove" JavaScript event on an element. /// </summary> /// <returns>The jQuery instance</returns> [Template("mousemove()")] public virtual jQuery MouseMove() { return null; } /// <summary> /// Bind an event handler to the "mousemove" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousemove({0})")] public virtual jQuery MouseMove(Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mousemove" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousemove({0})")] public virtual jQuery MouseMove(Action handler) { return null; } /// <summary> /// Bind an event handler to the "mousemove" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousemove({0})")] public virtual jQuery MouseMove(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind an event handler to the "mousemove" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousemove({0},{1})")] public virtual jQuery MouseMove(object eventData, Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mousemove" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mousemove({0},{1})")] public virtual jQuery MouseMove(object eventData, Action handler) { return null; } /// <summary> /// Trigger the "mouseout" JavaScript event on an element. /// </summary> /// <returns>The jQuery instance</returns> [Template("mouseout()")] public virtual jQuery MouseOut() { return null; } /// <summary> /// Bind an event handler to the "mouseout" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseout({0})")] public virtual jQuery MouseOut(Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseout" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseout({0})")] public virtual jQuery MouseOut(Action handler) { return null; } /// <summary> /// Bind an event handler to the "mouseout" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseout({0})")] public virtual jQuery MouseOut(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind an event handler to the "mouseout" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseout({0},{1})")] public virtual jQuery MouseOut(object eventData, Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseout" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseout({0},{1})")] public virtual jQuery MouseOut(object eventData, Action handler) { return null; } /// <summary> /// Trigger the "mouseover" JavaScript event on an element. /// </summary> /// <returns>The jQuery instance</returns> [Template("mouseover()")] public virtual jQuery MouseOver() { return null; } /// <summary> /// Bind an event handler to the "mouseover" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseover({0})")] public virtual jQuery MouseOver(Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseover" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseover({0})")] public virtual jQuery MouseOver(Action handler) { return null; } /// <summary> /// Bind an event handler to the "mouseover" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseover({0})")] public virtual jQuery MouseOver(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind an event handler to the "mouseover" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseover({0},{1})")] public virtual jQuery MouseOver(object eventData, Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseover" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseover({0},{1})")] public virtual jQuery MouseOver(object eventData, Action handler) { return null; } /// <summary> /// Trigger the "mouseup" JavaScript event on an element. /// </summary> /// <returns>The jQuery instance</returns> [Template("mouseup()")] public virtual jQuery MouseUp() { return null; } /// <summary> /// Bind an event handler to the "mouseup" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseup({0})")] public virtual jQuery MouseUp(Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseup" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseup({0})")] public virtual jQuery MouseUp(Action handler) { return null; } /// <summary> /// Bind an event handler to the "mouseup" JavaScript event. /// </summary> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseup({0})")] public virtual jQuery MouseUp(Action<jQueryMouseEvent> handler) { return null; } /// <summary> /// Bind an event handler to the "mouseup" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseup({0},{1})")] public virtual jQuery MouseUp(object eventData, Delegate handler) { return null; } /// <summary> /// Bind an event handler to the "mouseup" JavaScript event. /// </summary> /// <param name="eventData">An object containing data that will be passed to the event handler.</param> /// <param name="handler">A function to execute each time the event is triggered.</param> /// <returns>The jQuery instance</returns> [Template("mouseup({0},{1})")] public virtual jQuery MouseUp(object eventData, Action handler) { return null; } } }
//----------------------------------------------------------------------------- // Verve // Copyright (C) - Violent Tulip //----------------------------------------------------------------------------- $VerveEditor::HistoryManager = new UndoManager( VerveEditorHistoryManager ); $VerveEditor::UndoCount = 0; $VerveEditor::RedoCount = 0; //----------------------------------------------------------------------------- function VerveEditor::IsDirty() { if ( !isObject( VerveEditorHistoryManager ) ) { // Woops! return false; } return !( ( VerveEditorHistoryManager.getUndoCount() == $VerveEditor::UndoCount ) && ( VerveEditorHistoryManager.getRedoCount() == $VerveEditor::RedoCount ) ); } function VerveEditor::ClearDirty() { // Reset. $VerveEditor::UndoCount = VerveEditorHistoryManager.getUndoCount(); $VerveEditor::RedoCount = VerveEditorHistoryManager.getRedoCount(); } function VerveEditor::ClearHistory() { // Clear History. VerveEditorHistoryManager.clearAll(); // Clear Dirty. VerveEditor::ClearDirty(); } function VerveEditor::CanUndo() { return ( VerveEditorHistoryManager.getUndoCount() > 0 ); } function VerveEditor::Undo() { VerveEditorHistoryManager.Undo(); // Refresh. VerveEditor::Refresh(); } function VerveEditor::CanRedo() { return ( VerveEditorHistoryManager.getRedoCount() > 0 ); } function VerveEditor::Redo() { VerveEditorHistoryManager.Redo(); // Refresh. VerveEditor::Refresh(); } //------------------------------------------------------------------------- function VerveEditorHistoryObject::onAdd( %this ) { %historyManager = VerveEditorHistoryManager; if ( %historyManager.Locked ) { // Delete. %this.schedule( 0, delete ); return; } if ( isObject( %historyManager.HistoryGroup ) ) { // Add To Group. %historyManager.HistoryGroup.Group.add( %this ); return; } // Add To Manager. %this.addToManager( %historyManager ); // Update Window. VerveEditorWindow.UpdateWindowTitle(); } //------------------------------------------------------------------------- function VerveEditor::ToggleHistoryGroup() { %historyManager = VerveEditorHistoryManager; if ( isObject( %historyManager.HistoryGroup ) ) { // Clear. %historyManager.HistoryGroup = 0; // Update Window. VerveEditorWindow.UpdateWindowTitle(); return; } if ( VerveEditorHistoryManager.Locked ) { // Locked. return; } %historyManager.HistoryGroup = new UndoScriptAction() { Class = "VerveEditorHistoryGroup"; ActionName = "History Group"; // Store Object References. Group = new SimGroup(); }; // Add To Manager. %historyManager.HistoryGroup.addToManager( %historyManager ); } function VerveEditorHistoryGroup::onRemove( %this ) { if ( isObject( %this.Group ) ) { // Delete Group. %this.Group.delete(); } } function VerveEditorHistoryGroup::Undo( %this ) { // Undo In Reverse Order. %undoCount = %this.Group.getCount(); for ( %i = ( %undoCount - 1 ); %i >= 0; %i-- ) { %this.Group.getObject( %i ).Undo(); } } function VerveEditorHistoryGroup::Redo( %this ) { %undoCount = %this.Group.getCount(); for ( %i = 0; %i < %undoCount; %i++ ) { %this.Group.getObject( %i ).Redo(); } } //------------------------------------------------------------------------- function VerveEditorHistoryCreateObject::Undo( %this ) { // Undo Delete. %parentObject = %this.Parent; %object = %this.Object; // Detach Object. %parentObject.removeObject( %object ); } function VerveEditorHistoryCreateObject::Redo( %this ) { // Redo Delete. %parentObject = %this.Parent; %object = %this.Object; // Attach Object. %parentObject.addObject( %object ); } function VerveEditorHistoryCreateObject::onRemove( %this ) { /* if ( !isObject( %this.Object.getParent() ) || %this.Object.getParent().getId() != %this.Parent.getId() ) { SimObject::Delete( %this.Object ); } */ } //------------------------------------------------------------------------- function VerveEditorHistoryDeleteObject::Undo( %this ) { // Undo Delete. %parentObject = %this.Parent; %object = %this.Object; // Attach Object. %parentObject.addObject( %object ); } function VerveEditorHistoryDeleteObject::Redo( %this ) { // Redo Delete. %parentObject = %this.Parent; %object = %this.Object; // Detach Object. %parentObject.removeObject( %object ); } function VerveEditorHistoryDeleteObject::onRemove( %this ) { /* if ( !isObject( %this.Object.getParent() ) || %this.Object.getParent().getId() != %this.Parent.getId() ) { SimObject::Delete( %this.Object ); } */ } //------------------------------------------------------------------------- function VerveEditorHistoryChangeProperty::Undo( %this ) { // Undo Change. %object = %this.Object; %fieldName = %this.FieldName; %oldValue = %this.OldValue; // Lock History. VerveEditorHistoryManager.Locked = true; // Attach Object. %object.setFieldValue( %fieldName, %oldValue, false ); // Unlock History. VerveEditorHistoryManager.Locked = false; } function VerveEditorHistoryChangeProperty::Redo( %this ) { // Redo Change. %object = %this.Object; %fieldName = %this.FieldName; %newValue = %this.NewValue; // Lock History. VerveEditorHistoryManager.Locked = true; // Attach Object. %object.setFieldValue( %fieldName, %newValue, false ); // Unlock History. VerveEditorHistoryManager.Locked = false; } function VerveEditorHistoryManager::Lock( %this ) { %this.Locked = true; } function VerveEditorHistoryManager::UnLock( %this ) { %this.Locked = false; }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Palaso.BuildTasks.UnitTestTasks { /// <summary> /// Base class for both our Unitpp and NUnit tasks. /// </summary> /// <remarks> /// The NUnit task borrowed (and fixed slightly) from the network did not properly handle /// timeouts. In fact, anything based on ToolTask (at least in Mono 10.4) didn't handle /// timeouts properly in my testing. This code does handle timeouts properly. /// </remarks> public abstract class TestTask : Task { private StreamReader m_StdError; private StreamReader m_StdOut; protected List<string> m_TestLog = new List<string>(); /// <summary> /// Constructor /// </summary> public TestTask() { // more than 24 days should be a high enough value as default :-) Timeout = Int32.MaxValue; FudgeFactor = 1; } /// <summary> /// Used to ensure thread-safe operations. /// </summary> private static readonly object LockObject = new object(); /// <summary> /// Gets or sets the maximum amount of time the test is allowed to execute, /// expressed in milliseconds. The default is essentially no time-out. /// </summary> public int Timeout { get; set; } /// <summary> /// Factor the timeout will be multiplied by. /// </summary> public int FudgeFactor { get; set; } /// <summary> /// Contains the names of failed test suites /// </summary> [Output] public ITaskItem[] FailedSuites { get; protected set; } /// <summary> /// Contains the names of test suites that got a timeout or that crashed /// </summary> [Output] public ITaskItem[] AbandondedSuites { get; protected set; } public override bool Execute() { if (FudgeFactor >= 0 && Timeout < Int32.MaxValue) Timeout *= FudgeFactor; bool retVal = true; if (Timeout == Int32.MaxValue) Log.LogMessage(MessageImportance.Normal, "Running {0}", TestProgramName); else Log.LogMessage(MessageImportance.Normal, "Running {0} (timeout = {1} seconds)", TestProgramName, ((double)Timeout/1000.0).ToString("F1")); Thread outputThread = null; Thread errorThread = null; var dtStart = DateTime.Now; try { // Start the external process var process = StartProcess(); outputThread = new Thread(StreamReaderThread_Output); errorThread = new Thread(StreamReaderThread_Error); m_StdOut = process.StandardOutput; m_StdError = process.StandardError; outputThread.Start(); errorThread.Start(); // Wait for the process to terminate process.WaitForExit(Timeout); // Wait for the threads to terminate outputThread.Join(2000); errorThread.Join(2000); bool fTimedOut = !process.WaitForExit(0); // returns false immediately if still running. if (fTimedOut) { try { process.Kill(); } catch { // ignore possible exceptions that are thrown when the // process is terminated } } TimeSpan delta = DateTime.Now - dtStart; Log.LogMessage(MessageImportance.Normal, "Total time for running {0} = {1}", TestProgramName, delta); try { ProcessOutput(fTimedOut, delta); } catch //(Exception e) { //Console.WriteLine("CAUGHT EXCEPTION: {0}", e.Message); //Console.WriteLine("STACK: {0}", e.StackTrace); } // If the test timed out, it was killed and its ExitCode is not available. // So check for a timeout first. if (fTimedOut) { Log.LogError("The tests in {0} did not finish in {1} milliseconds.", TestProgramName, Timeout); FailedSuites = FailedSuiteNames; retVal = false; } else if (process.ExitCode != 0) { Log.LogWarning("{0} returned with exit code {1}", TestProgramName, process.ExitCode); FailedSuites = FailedSuiteNames; // Return true in this case - at least NUnit returns non-zero exit code when // a test fails, but we don't want to stop the build. } } catch (Exception e) { Log.LogErrorFromException(e, true); retVal = false; } finally { // ensure outputThread is always aborted if (outputThread != null && outputThread.IsAlive) { outputThread.Abort(); } // ensure errorThread is always aborted if (errorThread != null && errorThread.IsAlive) { errorThread.Abort(); } } // Return retVal instead of !Log.HasLoggedErrors - if we get test failures we log // those but don't want the build to fail. However, if we get an exception from the // test or if we get a timeout we want to fail the build. return retVal; } /// <summary> /// Starts the process and handles errors. /// </summary> protected virtual Process StartProcess() { var process = new Process { StartInfo = { FileName = ProgramName(), Arguments = ProgramArguments(), RedirectStandardOutput = true, RedirectStandardError = true, //required to allow redirects UseShellExecute = false, // do not start process in new window CreateNoWindow = true, WorkingDirectory = GetWorkingDirectory() } }; try { var msg = string.Format("Starting program: {1} ({2}) in {0}", process.StartInfo.WorkingDirectory, process.StartInfo.FileName, process.StartInfo.Arguments); Log.LogMessage(MessageImportance.Low, msg); process.Start(); return process; } catch (Exception ex) { throw new Exception(String.Format("Got exception starting {0}", process.StartInfo.FileName), ex); } } protected abstract string ProgramName(); protected abstract string ProgramArguments(); protected abstract void ProcessOutput(bool fTimedOut, TimeSpan delta); protected abstract string GetWorkingDirectory(); protected abstract string TestProgramName { get; } protected abstract ITaskItem[] FailedSuiteNames { get; } /// <summary> /// Reads from the standard output stream until the external program is ended. /// </summary> protected void StreamReaderThread_Output() { try { var reader = m_StdOut; while (true) { var logContents = reader.ReadLine(); if (logContents == null) { break; } // ensure only one thread writes to the log at any time lock (LockObject) { m_TestLog.Add(logContents); } } } catch (Exception) { // just ignore any errors } } /// <summary> /// Reads from the standard error stream until the external program is ended. /// </summary> protected void StreamReaderThread_Error() { try { var reader = m_StdError; while (true) { var logContents = reader.ReadLine(); if (logContents == null) { break; } // ensure only one thread writes to the log at any time lock (LockObject) { m_TestLog.Add(logContents); } } } catch (Exception) { // just ignore any errors } } } }
using IPFilter.Cli; namespace IPFilter.ViewModels { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Threading; using Apps; using ListProviders; using Microsoft.Win32; using Models; using Native; using Services; using Services.Deployment; using UI.Annotations; using Views; using Application = System.Windows.Application; using IPFilter.Formats; using IPFilter.Logging; public class MainWindowViewModel : INotifyPropertyChanged { IMirrorProvider selectedMirrorProvider; UpdateState state; IProgress<ProgressModel> progress; readonly ApplicationEnumerator applicationEnumerator; CancellationTokenSource cancellationToken; List<ApplicationDetectionResult> apps; readonly FilterDownloader downloader; int progressValue; string statusText; readonly StringBuilder log = new StringBuilder(500); readonly Dispatcher dispatcher; public MainWindowViewModel() { //Trace.TraceInformation("Initializing..."); //Trace.Listeners.Add(new DelegateTraceListener(null,LogLineAction )); dispatcher = Dispatcher.CurrentDispatcher; StatusText = "Ready"; State = UpdateState.Ready; ProgressMax = 100; Options = new OptionsViewModel(); Update = new UpdateModel(); MirrorProviders = MirrorProvidersFactory.Get(); LaunchHelpCommand = new DelegateCommand(LaunchHelp); ShowOptionsCommand = new DelegateCommand(ShowOptions); ShowLogCommand = new DelegateCommand(ShowLog); StartCommand = new DelegateCommand(Start, IsStartEnabled); applicationEnumerator = new ApplicationEnumerator(); downloader = new FilterDownloader(); cancellationToken = new CancellationTokenSource(); } void ShowLog(object obj) { try { var listener = Trace.Listeners["file"] as FileTraceListener; if (listener?.fileName == null) return; if (!File.Exists(listener.fileName)) return; Process.Start(listener.fileName); } catch (Exception ex) { Trace.TraceWarning("Couldn't launch support URL: " + ex); } } void ShowOptions(object obj) { var options = new OptionsWindow(); options.ShowDialog(); } void OnNotifyIconClick(object sender, EventArgs e) { Application.Current.MainWindow.Activate(); var helper = new WindowInteropHelper(Application.Current.MainWindow); Win32Api.BringToFront(helper.Handle); } bool IsStartEnabled(object arg) { return Update == null || !Update.IsUpdating; } void ProgressHandler(ProgressModel progressModel) { if (progressModel == null) return; ProgressValue = progressModel.Value; StatusText = progressModel.Caption; State = progressModel.State; } void LaunchHelp(object uri) { try { var url = (Uri) uri; Process.Start( url.ToString() ); } catch (Exception ex) { Trace.TraceWarning("Couldn't launch support URL: " + ex); } } void Start(object o) { switch (State) { case UpdateState.Done: case UpdateState.Ready: case UpdateState.Cancelled: cancellationToken.Dispose(); cancellationToken = new CancellationTokenSource(); Task.Run(StartAsync, cancellationToken.Token);//, TaskCreationOptions.None);//, TaskScheduler.FromCurrentSynchronizationContext()); break; case UpdateState.Downloading: case UpdateState.Decompressing: cancellationToken.Cancel(); break; } } internal async Task StartAsync() { var message = "Done"; progress.Report(UpdateState.Downloading, "Starting..."); try { if (SelectedMirrorProvider == null) { progress.Report(new ProgressModel(UpdateState.Cancelled, "Please select a filter source",0)); return; } var uri = SelectedMirrorProvider.GetUrlForMirror(); using (var filter = await downloader.DownloadFilter(new Uri(uri), cancellationToken.Token, progress)) { cancellationToken.Token.ThrowIfCancellationRequested(); if (filter == null) { progress.Report(new ProgressModel(UpdateState.Cancelled, "A filter wasn't downloaded successfully.", 0)); } else if (filter.Exception != null) { if (filter.Exception is OperationCanceledException) throw filter.Exception; Trace.TraceError("Problem when downloading: " + filter.Exception); progress.Report(new ProgressModel(UpdateState.Cancelled, "Problem when downloading: " + filter.Exception.Message, 0)); return; } else { filter.Stream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(filter.Stream, Encoding.Default, false, 65535, true)) { var line = await reader.ReadLineAsync(); while (line != null) { var entry = DatParser.ParseEntry(line); if( entry != null) filter.Entries.Add(entry); var percent = (int)Math.Floor( (double)filter.Stream.Position / filter.Stream.Length * 100); await Task.Yield(); if( percent > ProgressValue) progress.Report(new ProgressModel(UpdateState.Decompressing, "Parsed " + filter.Entries.Count + " entries", percent)); line = await reader.ReadLineAsync(); } } foreach (var application in apps) { Trace.TraceInformation("Updating app {0} {1}", application.Description, application.Version); await application.Application.UpdateFilterAsync(filter, cancellationToken.Token, progress); } } if (filter?.FilterTimestamp != null) { message = $"Done. List timestamp: {filter.FilterTimestamp.Value.ToLocalTime()}"; } } } catch (OperationCanceledException) { Trace.TraceWarning("Update was cancelled."); progress.Report(new ProgressModel(UpdateState.Cancelled, "Update was cancelled.", 0)); return; } catch (Exception ex) { Trace.TraceError("Problem when updating: " + ex); progress.Report(new ProgressModel(UpdateState.Cancelled, "Problem when updating: " + ex.Message, 0)); return; } progress.Report(UpdateState.Decompressing, "Cleaning up...", -1); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Trace.TraceInformation(message); progress.Report(new ProgressModel(UpdateState.Done, message, 100)); ShowNotification("Updated IP Filter", message, ToolTipIcon.Info); } public UpdateModel Update { get; set; } public IList<IMirrorProvider> MirrorProviders { get; set; } public OptionsViewModel Options { get; private set; } public IEnumerable<ApplicationDetectionResult> Providers { get; set; } public event PropertyChangedEventHandler PropertyChanged; public string StatusText { get { return statusText; } set { if (value == statusText) return; statusText = value; OnPropertyChanged(); } } public string ButtonText { get { switch (State) { case UpdateState.Downloading: case UpdateState.Decompressing: return "Cancel"; case UpdateState.Cancelling: return "Cancelling..."; default: return "Go"; } } } public int ProgressValue { get { return progressValue; } set { if (value == progressValue) return; ProgressIsIndeterminate = value < 0; progressValue = value; OnPropertyChanged(); } } public int ProgressMin { get; set; } public int ProgressMax { get; set; } public IMirrorProvider SelectedMirrorProvider { get { return selectedMirrorProvider; } set { if (Equals(value, selectedMirrorProvider)) return; selectedMirrorProvider = value; OnPropertyChanged(); } } public ICommand LaunchHelpCommand { get; private set; } public UpdateState State { get { return state; } set { if (value == state) return; state = value; OnPropertyChanged(); OnPropertyChanged(nameof(ButtonText)); } } public ICommand StartCommand { get; set; } public bool ProgressIsIndeterminate { get; set; } public Action<string, string, ToolTipIcon> ShowNotification { get; set; } public ICommand ShowOptionsCommand { get; private set; } public ICommand ShowLogCommand { get; private set; } public async Task Initialize() { progress = new Progress<ProgressModel>(ProgressHandler); // Check for updates await CheckForUpdates(); SelectedMirrorProvider = MirrorProviders.First(); apps = (await applicationEnumerator.GetInstalledApplications()).ToList(); if (!apps.Any()) { Trace.TraceWarning("No BitTorrent applications found."); return; } foreach (var result in apps) { Trace.TraceInformation("Found app {0} version {1} at {2}", result.Description, result.Version, result.InstallLocation); } } async Task ScheduledUpdate() { while (true) { await Task.Delay(TimeSpan.FromMinutes(1)); await StartAsync(); } } async Task CheckForUpdates() { try { if (Config.Default.settings.update.isDisabled) { Trace.TraceInformation("The software update check is disabled by the user; skipping check"); return; } // Remove any old ClickOnce installs try { var uninstallInfo = UninstallInfo.Find("IPFilter Updater"); if (uninstallInfo != null) { Trace.TraceWarning("Old ClickOnce app installed! Trying to remove..."); var uninstaller = new Uninstaller(); uninstaller.Uninstall(uninstallInfo); Trace.TraceInformation("Successfully removed ClickOnce app"); } } catch (Exception ex) { Trace.TraceError("Failed to remove old ClickOnce app: " + ex); } var applicationDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "IPFilter"); var installerDir = new DirectoryInfo(Path.Combine(applicationDirectory, "installer")); // Detect the current running version. The ProductVersion contains the informational, semantic version e.g. "3.0.0-beta" var versionInfo = Process.GetCurrentProcess().MainModule.FileVersionInfo; var currentVersion = new SemanticVersion(versionInfo.ProductVersion); // Remove any old installers try { if (!installerDir.Exists) { installerDir.Create(); } else if (!Config.Default.settings.update.isCleanupDisabled) { // Don't delete the MSI for the current installed version var currentMsiName = "IPFilter." + currentVersion.ToNormalizedString() + ".msi"; // Scan the directory for all installers foreach (var fileInfo in installerDir.GetFiles("IPFilter.*.msi")) { // Don't remove the installer for the installed version if (fileInfo.Name.Equals(currentMsiName, StringComparison.OrdinalIgnoreCase)) continue; Trace.TraceInformation("Removing cached installer: " + fileInfo.Name); fileInfo.SafeDelete(); } } } catch (Exception ex) { Trace.TraceError("Couldn't clean up old installers: " + ex); } Trace.TraceInformation("Checking for software updates..."); progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1)); var updater = new Updater(); var result = await updater.CheckForUpdateAsync(Config.Default.settings.update.isPreReleaseEnabled); if (result == null) return; var latestVersion = new SemanticVersion(result.Version); Update.IsUpdateAvailable = latestVersion > currentVersion; if (Update.IsUpdateAvailable) { Update.AvailableVersion = latestVersion; Update.IsUpdateRequired = true; Update.MinimumRequiredVersion = latestVersion; Update.UpdateSizeBytes = 2000000; } Trace.TraceInformation("Current version: {0}", Update.CurrentVersion); Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>"); if (!Update.IsUpdateAvailable ) return; if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes, "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes) { return; } Trace.TraceInformation("Starting application update..."); // If we're not "installed", then don't check for updates. This is so the // executable can be stand-alone. Stand-alone self-update to come later. using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter")) { var installPath = (string) key?.GetValue("InstallPath"); if (installPath == null) { using (var process = new Process()) { process.StartInfo = new ProcessStartInfo("https://www.ipfilter.app/") { UseShellExecute = true }; process.Start(); return; } } } // Download the MSI to the installer directory var msiPath = Path.Combine(installerDir.FullName, "IPFilter." + Update.AvailableVersion + ".msi"); // Download the installer using (var handler = new WebRequestHandler()) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}"); using (var httpClient = new HttpClient(handler)) using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token)) { if (cancellationToken.IsCancellationRequested) { progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100)); Update.IsUpdating = false; return; } var length = response.Content.Headers.ContentLength; double lengthInMb = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024; double bytesDownloaded = 0; using(var stream = await response.Content.ReadAsStreamAsync()) using(var msi = File.Open(msiPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { var buffer = new byte[65535 * 4]; int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token); while (bytesRead != 0) { await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token); bytesDownloaded += bytesRead; if (length.HasValue) { double downloadedMegs = bytesDownloaded / 1024 / 1024; var percent = (int)Math.Floor((bytesDownloaded / length.Value) * 100); var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb); Update.IsUpdating = true; Update.DownloadPercentage = percent; progress.Report(new ProgressModel(UpdateState.Downloading, status, percent)); } if (cancellationToken.IsCancellationRequested) { progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100)); Update.IsUpdating = false; return; } bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token); } } } } progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100)); Update.IsUpdating = false; // Now run the installer var sb = new StringBuilder("msiexec.exe "); // Enable logging for the installer var installLog = Path.Combine(applicationDirectory, "install.log"); sb.AppendFormat(" /l*v \"{0}\"", installLog); sb.AppendFormat(" /i \"{0}\"", msiPath); //sb.Append(" /passive"); ProcessInformation processInformation = new ProcessInformation(); StartupInfo startupInfo = new StartupInfo(); SecurityAttributes processSecurity = new SecurityAttributes(); SecurityAttributes threadSecurity = new SecurityAttributes(); processSecurity.nLength = Marshal.SizeOf(processSecurity); threadSecurity.nLength = Marshal.SizeOf(threadSecurity); const int NormalPriorityClass = 0x0020; if (!ProcessManager.CreateProcess(null, sb, processSecurity, threadSecurity, false, NormalPriorityClass, IntPtr.Zero, null, startupInfo, processInformation)) { throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); } try { //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown)); Application.Current.Shutdown(); } catch (Exception ex) { Trace.TraceError("Exception when shutting down app for update: " + ex); Update.ErrorMessage = "Couldn't shutdown the app to apply update."; } } catch (Exception ex) { Trace.TraceWarning("Application update check failed: " + ex); } finally { progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0)); } } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public void Shutdown() { } } }
// 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.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Globalization; using System.Text; using Microsoft.Extensions.Primitives; namespace Microsoft.Net.Http.Headers { /// <summary> /// Represents a <c>Content-Range</c> response HTTP header. /// </summary> public class ContentRangeHeaderValue { private static readonly HttpHeaderParser<ContentRangeHeaderValue> Parser = new GenericHeaderParser<ContentRangeHeaderValue>(false, GetContentRangeLength); private StringSegment _unit; private ContentRangeHeaderValue() { // Used by the parser to create a new instance of this type. } /// <summary> /// Initializes a new instance of <see cref="ContentRangeHeaderValue"/>. /// </summary> /// <param name="from">The start of the range.</param> /// <param name="to">The end of the range.</param> /// <param name="length">The total size of the document in bytes.</param> public ContentRangeHeaderValue(long from, long to, long length) { // Scenario: "Content-Range: bytes 12-34/5678" if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } if ((to < 0) || (to > length)) { throw new ArgumentOutOfRangeException(nameof(to)); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException(nameof(from)); } From = from; To = to; Length = length; _unit = HeaderUtilities.BytesUnit; } /// <summary> /// Initializes a new instance of <see cref="ContentRangeHeaderValue"/>. /// </summary> /// <param name="length">The total size of the document in bytes.</param> public ContentRangeHeaderValue(long length) { // Scenario: "Content-Range: bytes */1234" if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } Length = length; _unit = HeaderUtilities.BytesUnit; } /// <summary> /// Initializes a new instance of <see cref="ContentRangeHeaderValue"/>. /// </summary> /// <param name="from">The start of the range.</param> /// <param name="to">The end of the range.</param> public ContentRangeHeaderValue(long from, long to) { // Scenario: "Content-Range: bytes 12-34/*" if (to < 0) { throw new ArgumentOutOfRangeException(nameof(to)); } if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException(nameof(@from)); } From = from; To = to; _unit = HeaderUtilities.BytesUnit; } /// <summary> /// Gets or sets the unit in which ranges are specified. /// </summary> /// <value>Defaults to <c>bytes</c>.</value> public StringSegment Unit { get { return _unit; } set { HeaderUtilities.CheckValidToken(value, nameof(value)); _unit = value; } } /// <summary> /// Gets the start of the range. /// </summary> public long? From { get; private set; } /// <summary> /// Gets the end of the range. /// </summary> public long? To { get; private set; } /// <summary> /// Gets the total size of the document. /// </summary> [NotNullIfNotNull(nameof(Length))] public long? Length { get; private set; } /// <summary> /// Gets a value that determines if <see cref="Length"/> has been specified. /// </summary> [MemberNotNullWhen(true, nameof(Length))] public bool HasLength // e.g. "Content-Range: bytes 12-34/*" { get { return Length != null; } } /// <summary> /// Gets a value that determines if <see cref="From"/> and <see cref="To"/> have been specified. /// </summary> [MemberNotNullWhen(true, nameof(From), nameof(To))] public bool HasRange // e.g. "Content-Range: bytes */1234" { get { return From != null && To != null; } } /// <inheritdoc/> public override bool Equals(object? obj) { var other = obj as ContentRangeHeaderValue; if (other == null) { return false; } return ((From == other.From) && (To == other.To) && (Length == other.Length) && StringSegment.Equals(Unit, other.Unit, StringComparison.OrdinalIgnoreCase)); } /// <inheritdoc/> public override int GetHashCode() { var result = StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(Unit); if (HasRange) { result = result ^ From.GetHashCode() ^ To.GetHashCode(); } if (HasLength) { result = result ^ Length.GetHashCode(); } return result; } /// <inheritdoc/> public override string ToString() { var sb = new StringBuilder(); sb.Append(Unit.AsSpan()); sb.Append(' '); if (HasRange) { sb.Append(From.GetValueOrDefault().ToString(NumberFormatInfo.InvariantInfo)); sb.Append('-'); sb.Append(To.GetValueOrDefault().ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } sb.Append('/'); if (HasLength) { sb.Append(Length.GetValueOrDefault().ToString(NumberFormatInfo.InvariantInfo)); } else { sb.Append('*'); } return sb.ToString(); } /// <summary> /// Parses <paramref name="input"/> as a <see cref="ContentRangeHeaderValue"/> value. /// </summary> /// <param name="input">The values to parse.</param> /// <returns>The parsed values.</returns> public static ContentRangeHeaderValue Parse(StringSegment input) { var index = 0; return Parser.ParseValue(input, ref index)!; } /// <summary> /// Attempts to parse the specified <paramref name="input"/> as a <see cref="ContentRangeHeaderValue"/>. /// </summary> /// <param name="input">The value to parse.</param> /// <param name="parsedValue">The parsed value.</param> /// <returns><see langword="true"/> if input is a valid <see cref="ContentRangeHeaderValue"/>, otherwise <see langword="false"/>.</returns> public static bool TryParse(StringSegment input, [NotNullWhen(true)] out ContentRangeHeaderValue parsedValue) { var index = 0; return Parser.TryParseValue(input, ref index, out parsedValue!); } private static int GetContentRangeLength(StringSegment input, int startIndex, out ContentRangeHeaderValue? parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the unit string: <unit> in '<unit> <from>-<to>/<length>' var unitLength = HttpRuleParser.GetTokenLength(input, startIndex); if (unitLength == 0) { return 0; } var unit = input.Subsegment(startIndex, unitLength); var current = startIndex + unitLength; var separatorLength = HttpRuleParser.GetWhitespaceLength(input, current); if (separatorLength == 0) { return 0; } current = current + separatorLength; if (current == input.Length) { return 0; } // Read range values <from> and <to> in '<unit> <from>-<to>/<length>' var fromStartIndex = current; var fromLength = 0; var toStartIndex = 0; var toLength = 0; if (!TryGetRangeLength(input, ref current, out fromLength, out toStartIndex, out toLength)) { return 0; } // After the range is read we expect the length separator '/' if ((current == input.Length) || (input[current] != '/')) { return 0; } current++; // Skip '/' separator current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return 0; } // We may not have a length (e.g. 'bytes 1-2/*'). But if we do, parse the length now. var lengthStartIndex = current; var lengthLength = 0; if (!TryGetLengthLength(input, ref current, out lengthLength)) { return 0; } if (!TryCreateContentRange(input, unit, fromStartIndex, fromLength, toStartIndex, toLength, lengthStartIndex, lengthLength, out parsedValue)) { return 0; } return current - startIndex; } private static bool TryGetLengthLength(StringSegment input, ref int current, out int lengthLength) { lengthLength = 0; if (input[current] == '*') { current++; } else { // Parse length value: <length> in '<unit> <from>-<to>/<length>' lengthLength = HttpRuleParser.GetNumberLength(input, current, false); if ((lengthLength == 0) || (lengthLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + lengthLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryGetRangeLength(StringSegment input, ref int current, out int fromLength, out int toStartIndex, out int toLength) { fromLength = 0; toStartIndex = 0; toLength = 0; // Check if we have a value like 'bytes */133'. If yes, skip the range part and continue parsing the // length separator '/'. if (input[current] == '*') { current++; } else { // Parse first range value: <from> in '<unit> <from>-<to>/<length>' fromLength = HttpRuleParser.GetNumberLength(input, current, false); if ((fromLength == 0) || (fromLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + fromLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // After the first value, the '-' character must follow. if ((current == input.Length) || (input[current] != '-')) { // We need a '-' character otherwise this can't be a valid range. return false; } current++; // skip the '-' character current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (current == input.Length) { return false; } // Parse second range value: <to> in '<unit> <from>-<to>/<length>' toStartIndex = current; toLength = HttpRuleParser.GetNumberLength(input, current, false); if ((toLength == 0) || (toLength > HttpRuleParser.MaxInt64Digits)) { return false; } current = current + toLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return true; } private static bool TryCreateContentRange( StringSegment input, StringSegment unit, int fromStartIndex, int fromLength, int toStartIndex, int toLength, int lengthStartIndex, int lengthLength, [NotNullWhen(true)]out ContentRangeHeaderValue? parsedValue) { parsedValue = null; long from = 0; if ((fromLength > 0) && !HeaderUtilities.TryParseNonNegativeInt64(input.Subsegment(fromStartIndex, fromLength), out from)) { return false; } long to = 0; if ((toLength > 0) && !HeaderUtilities.TryParseNonNegativeInt64(input.Subsegment(toStartIndex, toLength), out to)) { return false; } // 'from' must not be greater than 'to' if ((fromLength > 0) && (toLength > 0) && (from > to)) { return false; } long length = 0; if ((lengthLength > 0) && !HeaderUtilities.TryParseNonNegativeInt64(input.Subsegment(lengthStartIndex, lengthLength), out length)) { return false; } // 'from' and 'to' must be less than 'length' if ((toLength > 0) && (lengthLength > 0) && (to >= length)) { return false; } var result = new ContentRangeHeaderValue(); result._unit = unit; if (fromLength > 0) { result.From = from; result.To = to; } if (lengthLength > 0) { result.Length = length; } parsedValue = result; return true; } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.Speech.V1; using Google.LongRunning; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Speech.V1.Snippets { /// <summary>Generated snippets</summary> public class GeneratedSpeechClientSnippets { /// <summary>Snippet for RecognizeAsync</summary> public async Task RecognizeAsync() { // Snippet: RecognizeAsync(RecognitionConfig,RecognitionAudio,CallSettings) // Additional: RecognizeAsync(RecognitionConfig,RecognitionAudio,CancellationToken) // Create client SpeechClient speechClient = await SpeechClient.CreateAsync(); // Initialize request argument(s) RecognitionConfig config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }; RecognitionAudio audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }; // Make the request RecognizeResponse response = await speechClient.RecognizeAsync(config, audio); // End snippet } /// <summary>Snippet for Recognize</summary> public void Recognize() { // Snippet: Recognize(RecognitionConfig,RecognitionAudio,CallSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize request argument(s) RecognitionConfig config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }; RecognitionAudio audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }; // Make the request RecognizeResponse response = speechClient.Recognize(config, audio); // End snippet } /// <summary>Snippet for RecognizeAsync</summary> public async Task RecognizeAsync_RequestObject() { // Snippet: RecognizeAsync(RecognizeRequest,CallSettings) // Create client SpeechClient speechClient = await SpeechClient.CreateAsync(); // Initialize request argument(s) RecognizeRequest request = new RecognizeRequest { Config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }, Audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }, }; // Make the request RecognizeResponse response = await speechClient.RecognizeAsync(request); // End snippet } /// <summary>Snippet for Recognize</summary> public void Recognize_RequestObject() { // Snippet: Recognize(RecognizeRequest,CallSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize request argument(s) RecognizeRequest request = new RecognizeRequest { Config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }, Audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }, }; // Make the request RecognizeResponse response = speechClient.Recognize(request); // End snippet } /// <summary>Snippet for LongRunningRecognizeAsync</summary> public async Task LongRunningRecognizeAsync() { // Snippet: LongRunningRecognizeAsync(RecognitionConfig,RecognitionAudio,CallSettings) // Additional: LongRunningRecognizeAsync(RecognitionConfig,RecognitionAudio,CancellationToken) // Create client SpeechClient speechClient = await SpeechClient.CreateAsync(); // Initialize request argument(s) RecognitionConfig config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }; RecognitionAudio audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }; // Make the request Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(config, audio); // Poll until the returned long-running operation is complete Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result LongRunningRecognizeResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for LongRunningRecognize</summary> public void LongRunningRecognize() { // Snippet: LongRunningRecognize(RecognitionConfig,RecognitionAudio,CallSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize request argument(s) RecognitionConfig config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }; RecognitionAudio audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }; // Make the request Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(config, audio); // Poll until the returned long-running operation is complete Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result LongRunningRecognizeResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for LongRunningRecognizeAsync</summary> public async Task LongRunningRecognizeAsync_RequestObject() { // Snippet: LongRunningRecognizeAsync(LongRunningRecognizeRequest,CallSettings) // Create client SpeechClient speechClient = await SpeechClient.CreateAsync(); // Initialize request argument(s) LongRunningRecognizeRequest request = new LongRunningRecognizeRequest { Config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }, Audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }, }; // Make the request Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(request); // Poll until the returned long-running operation is complete Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result LongRunningRecognizeResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for LongRunningRecognize</summary> public void LongRunningRecognize_RequestObject() { // Snippet: LongRunningRecognize(LongRunningRecognizeRequest,CallSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize request argument(s) LongRunningRecognizeRequest request = new LongRunningRecognizeRequest { Config = new RecognitionConfig { Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRateHertz = 44100, LanguageCode = "en-US", }, Audio = new RecognitionAudio { Uri = "gs://bucket_name/file_name.flac", }, }; // Make the request Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(request); // Poll until the returned long-running operation is complete Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result LongRunningRecognizeResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for StreamingRecognize</summary> public async Task StreamingRecognize() { // Snippet: StreamingRecognize(CallSettings,BidirectionalStreamingSettings) // Create client SpeechClient speechClient = SpeechClient.Create(); // Initialize streaming call, retrieving the stream object SpeechClient.StreamingRecognizeStream duplexStream = speechClient.StreamingRecognize(); // Sending requests and retrieving responses can be arbitrarily interleaved. // Exact sequence will depend on client/server behavior. // Create task to do something with responses from server Task responseHandlerTask = Task.Run(async () => { IAsyncEnumerator<StreamingRecognizeResponse> responseStream = duplexStream.ResponseStream; while (await responseStream.MoveNext()) { StreamingRecognizeResponse response = responseStream.Current; // Do something with streamed response } // The response stream has completed }); // Send requests to the server bool done = false; while (!done) { // Initialize a request StreamingRecognizeRequest request = new StreamingRecognizeRequest(); // Stream a request to the server await duplexStream.WriteAsync(request); // Set "done" to true when sending requests is complete } // Complete writing requests to the stream await duplexStream.WriteCompleteAsync(); // Await the response handler. // This will complete once all server responses have been processed. await responseHandlerTask; // End snippet } } }
#if ASYNC using System.Threading.Tasks; #endif using ZendeskApi_v2.Models.Macros; namespace ZendeskApi_v2.Requests { public interface IMacros : ICore { #if SYNC /// <summary> /// Lists all shared and personal macros available to the current user /// </summary> /// <returns></returns> GroupMacroResponse GetAllMacros(); IndividualMacroResponse GetMacroById(long id); /// <summary> /// Lists all active shared and personal macros available to the current user /// </summary> /// <returns></returns> GroupMacroResponse GetActiveMacros(); IndividualMacroResponse CreateMacro(Macro macro); IndividualMacroResponse UpdateMacro(Macro macro); bool DeleteMacro(long id); /// <summary> /// Applies a macro to all applicable tickets. /// </summary> /// <param name="macroId"></param> /// <returns></returns> ApplyMacroResponse ApplyMacro(long macroId); /// <summary> /// Applies a macro to a specific ticket /// </summary> /// <param name="ticketId"></param> /// <param name="macroId"></param> /// <returns></returns> ApplyMacroResponse ApplyMacroToTicket(long ticketId, long macroId); #endif #if ASYNC /// <summary> /// Lists all shared and personal macros available to the current user /// </summary> /// <returns></returns> Task<GroupMacroResponse> GetAllMacrosAsync(); Task<IndividualMacroResponse> GetMacroByIdAsync(long id); /// <summary> /// Lists all active shared and personal macros available to the current user /// </summary> /// <returns></returns> Task<GroupMacroResponse> GetActiveMacrosAsync(); Task<IndividualMacroResponse> CreateMacroAsync(Macro macro); Task<IndividualMacroResponse> UpdateMacroAsync(Macro macro); Task<bool> DeleteMacroAsync(long id); /// <summary> /// Applies a macro to all applicable tickets. /// </summary> /// <param name="macroId"></param> /// <returns></returns> Task<ApplyMacroResponse> ApplyMacroAsync(long macroId); /// <summary> /// Applies a macro to a specific ticket /// </summary> /// <param name="ticketId"></param> /// <param name="macroId"></param> /// <returns></returns> Task<ApplyMacroResponse> ApplyMacroToTicketAsync(long ticketId, long macroId); #endif } public class Macros : Core, IMacros { public Macros(string yourZendeskUrl, string user, string password, string apiToken, string p_OAuthToken) : base(yourZendeskUrl, user, password, apiToken, p_OAuthToken) { } #if SYNC /// <summary> /// Lists all shared and personal macros available to the current user /// </summary> /// <returns></returns> public GroupMacroResponse GetAllMacros() { return GenericGet<GroupMacroResponse>(string.Format("macros.json")); } public IndividualMacroResponse GetMacroById(long id) { return GenericGet<IndividualMacroResponse>(string.Format("macros/{0}.json", id)); } /// <summary> /// Lists all active shared and personal macros available to the current user /// </summary> /// <returns></returns> public GroupMacroResponse GetActiveMacros() { return GenericGet<GroupMacroResponse>(string.Format("macros/active.json")); } public IndividualMacroResponse CreateMacro(Macro macro) { var body = new {macro}; return GenericPost<IndividualMacroResponse>("macros.json", body); } public IndividualMacroResponse UpdateMacro(Macro macro) { var body = new { macro }; return GenericPut<IndividualMacroResponse>(string.Format("macros/{0}.json", macro.Id), body); } public bool DeleteMacro(long id) { return GenericDelete(string.Format("macros/{0}.json", id)); } /// <summary> /// Applies a macro to all applicable tickets. /// </summary> /// <param name="macroId"></param> /// <returns></returns> public ApplyMacroResponse ApplyMacro(long macroId) { return GenericGet<ApplyMacroResponse>(string.Format("macros/{0}/apply.json", macroId)); } /// <summary> /// Applies a macro to a specific ticket /// </summary> /// <param name="ticketId"></param> /// <param name="macroId"></param> /// <returns></returns> public ApplyMacroResponse ApplyMacroToTicket(long ticketId, long macroId) { return GenericGet<ApplyMacroResponse>(string.Format("tickets/{0}/macros/{1}/apply.json", ticketId, macroId)); } #endif #if ASYNC /// <summary> /// Lists all shared and personal macros available to the current user /// </summary> /// <returns></returns> public async Task<GroupMacroResponse> GetAllMacrosAsync() { return await GenericGetAsync<GroupMacroResponse>(string.Format("macros.json")); } public async Task<IndividualMacroResponse> GetMacroByIdAsync(long id) { return await GenericGetAsync<IndividualMacroResponse>(string.Format("macros/{0}.json", id)); } /// <summary> /// Lists all active shared and personal macros available to the current user /// </summary> /// <returns></returns> public async Task<GroupMacroResponse> GetActiveMacrosAsync() { return await GenericGetAsync<GroupMacroResponse>(string.Format("macros/active.json")); } public async Task<IndividualMacroResponse> CreateMacroAsync(Macro macro) { var body = new { macro }; return await GenericPostAsync<IndividualMacroResponse>("macros.json", body); } public async Task<IndividualMacroResponse> UpdateMacroAsync(Macro macro) { var body = new { macro }; return await GenericPutAsync<IndividualMacroResponse>(string.Format("macros/{0}.json", macro.Id), body); } public async Task<bool> DeleteMacroAsync(long id) { return await GenericDeleteAsync(string.Format("macros/{0}.json", id)); } /// <summary> /// Applies a macro to all applicable tickets. /// </summary> /// <param name="macroId"></param> /// <returns></returns> public async Task<ApplyMacroResponse> ApplyMacroAsync(long macroId) { return await GenericGetAsync<ApplyMacroResponse>(string.Format("macros/{0}/apply.json", macroId)); } /// <summary> /// Applies a macro to a specific ticket /// </summary> /// <param name="ticketId"></param> /// <param name="macroId"></param> /// <returns></returns> public async Task<ApplyMacroResponse> ApplyMacroToTicketAsync(long ticketId, long macroId) { return await GenericGetAsync<ApplyMacroResponse>(string.Format("tickets/{0}/macros/{1}/apply.json", ticketId, macroId)); } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class FirstTests { public class First003 { private static int First001() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; var rst1 = q.First<int>(); var rst2 = q.First<int>(); return ((rst1 == rst2) ? 0 : 1); } private static int First002() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x; var rst1 = q.First<string>(); var rst2 = q.First<string>(); return ((rst1 == rst2) ? 0 : 1); } public static int Main() { int ret = RunTest(First001) + RunTest(First002); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First1a { // source is of type IList, source is empty public static int Test1a() { int[] source = { }; IList<int> list = source as IList<int>; if (list == null) return 1; try { var actual = source.First(); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test1a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First1b { // source is of type IList, source has one element public static int Test1b() { int[] source = { 5 }; int expected = 5; IList<int> list = source as IList<int>; if (list == null) return 1; var actual = source.First(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First1c { // source is of type IList, source has > 1 element public static int Test1c() { int?[] source = { null, -10, 2, 4, 3, 0, 2 }; int? expected = null; IList<int?> list = source as IList<int?>; if (list == null) return 1; var actual = source.First(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1c(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First1d { // source is NOT of type IList, source is empty public static int Test1d() { IEnumerable<int> source = Functions.NumList(0, 0); IList<int> list = source as IList<int>; if (list != null) return 1; try { var actual = source.First(); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test1d(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First1e { // source is NOT of type IList, source has one element public static int Test1e() { IEnumerable<int> source = Functions.NumList(-5, 1); int expected = -5; IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.First(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1e(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First1f { // source is NOT of type IList, source has > 1 element public static int Test1f() { IEnumerable<int> source = Functions.NumList(3, 10); int expected = 3; IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.First(); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1f(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First2a { // source is empty public static int Test2a() { int[] source = { }; Func<int, bool> predicate = Functions.IsEven; try { var actual = source.First(predicate); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test2a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First2b { // source has one element, predicate is true public static int Test2b() { int[] source = { 4 }; Func<int, bool> predicate = Functions.IsEven; int expected = 4; var actual = source.First(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First2c { // source has > one element, predicate is false for all public static int Test2c() { int[] source = { 9, 5, 1, 3, 17, 21 }; Func<int, bool> predicate = Functions.IsEven; try { var actual = source.First(predicate); return 1; } catch (InvalidOperationException) { return 0; } } public static int Main() { return Test2c(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First2d { // source has > one element, predicate is true only for last element public static int Test2d() { int[] source = { 9, 5, 1, 3, 17, 21, 50 }; Func<int, bool> predicate = Functions.IsEven; int expected = 50; var actual = source.First(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2d(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class First2e { // source has > one element, predicate is true for 3rd, 6th and last element public static int Test2e() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 17, 13, 8 }; Func<int, bool> predicate = Functions.IsEven; int expected = 10; var actual = source.First(predicate); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2e(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
using System; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class PageLoadingTest : DriverTestFixture { [Test] public void ShouldWaitForDocumentToBeLoaded() { driver.Url = simpleTestPage; Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldFollowRedirectsSentInTheHttpResponseHeaders() { driver.Url = redirectPage; Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldFollowMetaRedirects() { driver.Url = metaRedirectPage; WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [IgnoreBrowser(Browser.Chrome)] public void ShouldBeAbleToGetAFragmentOnTheCurrentPage() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Marionette doesn't see subsequent navigation to a fragment as a new navigation."); } driver.Url = xhtmlTestPage; driver.Url = xhtmlTestPage + "#text"; driver.FindElement(By.Id("id1")); } [Test] public void ShouldReturnWhenGettingAUrlThatDoesNotResolve() { try { // Of course, we're up the creek if this ever does get registered driver.Url = "http://www.thisurldoesnotexist.comx/"; } catch (Exception e) { if (!IsIeDriverTimedOutException(e)) { throw e; } } } [Test] [IgnoreBrowser(Browser.IE, "IE happily will navigate to invalid URLs")] [IgnoreBrowser(Browser.IPhone)] public void ShouldThrowIfUrlIsMalformed() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Browser hangs when executed via Marionette"); } driver.Url = "www.test.com"; } [Test] [IgnoreBrowser(Browser.IPhone)] public void ShouldReturnWhenGettingAUrlThatDoesNotConnect() { // Here's hoping that there's nothing here. There shouldn't be driver.Url = "http://localhost:3001"; } [Test] public void ShouldReturnUrlOnNotExistedPage() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("not_existed_page.html"); driver.Url = url; Assert.AreEqual(url, driver.Url); } [Test] public void ShouldBeAbleToLoadAPageWithFramesetsAndWaitUntilAllFramesAreLoaded() { driver.Url = framesetPage; driver.SwitchTo().Frame(0); IWebElement pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "1"); driver.SwitchTo().DefaultContent().SwitchTo().Frame(1); pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "2"); } [Test] [IgnoreBrowser(Browser.IPhone)] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldDoNothingIfThereIsNothingToGoBackTo() { string originalTitle = driver.Title; driver.Url = formsPage; driver.Navigate().Back(); // We may have returned to the browser's home page string currentTitle = driver.Title; Assert.IsTrue(currentTitle == originalTitle || currentTitle == "We Leave From Here", "title is " + currentTitle); if (driver.Title == originalTitle) { driver.Navigate().Back(); Assert.AreEqual(originalTitle, driver.Title); } } [Test] [IgnoreBrowser(Browser.Android)] public void ShouldBeAbleToNavigateBackInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); } [Test] public void ShouldBeAbleToNavigateBackInTheBrowserHistoryInPresenceOfIframes() { driver.Url = xhtmlTestPage; driver.FindElement(By.Name("sameWindow")).Click(); WaitFor(TitleToBeEqualTo("This page has iframes"), "Browser title was not 'This page has iframes'"); Assert.AreEqual(driver.Title, "This page has iframes"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Browser title was not 'XHTML Test Page'"); Assert.AreEqual(driver.Title, "XHTML Test Page"); } [Test] [IgnoreBrowser(Browser.Android)] public void ShouldBeAbleToNavigateForwardsInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); driver.Navigate().Forward(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } //TODO (jimevan): Implement SSL secure http function //[Test] //[IgnoreBrowser(Browser.Chrome)] //[IgnoreBrowser(Browser.IE)] //public void ShouldBeAbleToAccessPagesWithAnInsecureSslCertificate() //{ // String url = GlobalTestEnvironment.get().getAppServer().whereIsSecure("simpleTest.html"); // driver.Url = url; // // This should work // Assert.AreEqual(driver.Title, "Hello WebDriver"); //} [Test] public void ShouldBeAbleToRefreshAPage() { driver.Url = xhtmlTestPage; driver.Navigate().Refresh(); Assert.AreEqual(driver.Title, "XHTML Test Page"); } /// <summary> /// see <a href="http://code.google.com/p/selenium/issues/detail?id=208">Issue 208</a> /// </summary> [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IE, "Browser does, in fact, hang in this case.")] [IgnoreBrowser(Browser.IPhone, "Untested user-agent")] public void ShouldNotHangIfDocumentOpenCallIsNeverFollowedByDocumentCloseCall() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Browser hangs when executed via Marionette"); } driver.Url = documentWrite; // If this command succeeds, then all is well. driver.FindElement(By.XPath("//body")); } [Test] [IgnoreBrowser(Browser.Android, "Not implemented for browser")] [IgnoreBrowser(Browser.Chrome, "Not implemented for browser")] [IgnoreBrowser(Browser.HtmlUnit, "Not implemented for browser")] [IgnoreBrowser(Browser.IPhone, "Not implemented for browser")] [IgnoreBrowser(Browser.PhantomJS, "Not implemented for browser")] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] public void ShouldTimeoutIfAPageTakesTooLongToLoad() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Driver does not return control from timeout wait when executed via Marionette"); } driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); try { // Get the sleeping servlet with a pause of 5 seconds string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); driver.Url = slowPage; Assert.Fail("I should have timed out"); } catch (WebDriverTimeoutException) { } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.MinValue; } } private Func<bool> TitleToBeEqualTo(string expectedTitle) { return () => { return driver.Title == expectedTitle; }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftLeftLogical128BitLaneInt161() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int16); private const int RetElementCount = VectorSize / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Vector128<Int16> _clsVar; private Vector128<Int16> _fld; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftLeftLogical128BitLane( Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftLeftLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt161(); var result = Sse2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int16> firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { if (result[0] != 2048) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 2048) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical128BitLane)}<Int16>(Vector128<Int16><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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.Linq; using System.Runtime.Serialization; using Microsoft.Extensions.Logging; using NakedFramework.Architecture.Adapter; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.Menu; using NakedFramework.Architecture.Reflect; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Core.Util; using NakedFramework.Metamodel.Spec; using NakedFramework.Metamodel.Utils; namespace NakedFramework.Metamodel.SpecImmutable; [Serializable] public abstract class TypeSpecImmutable : Specification, ITypeSpecBuilder { private IIdentifier identifier; private Type[] services; private ImmutableList<ITypeSpecImmutable> subclasses; private List<IActionSpecImmutable> unorderedCollectionContributedActions = new(); private List<IActionSpecImmutable> unorderedContributedActions = new(); private List<IAssociationSpecImmutable> unorderedFields; private List<IActionSpecImmutable> unorderedFinderActions = new(); private List<IActionSpecImmutable> unorderedObjectActions; protected TypeSpecImmutable(Type type, bool isRecognized) { Type = type.IsGenericType && CollectionUtils.IsCollection(type) ? type.GetGenericTypeDefinition() : type; Interfaces = ImmutableList<ITypeSpecImmutable>.Empty; subclasses = ImmutableList<ITypeSpecImmutable>.Empty; ReflectionStatus = isRecognized ? ReflectionStatus.PlaceHolder : ReflectionStatus.PendingIntrospection; } private ReflectionStatus ReflectionStatus { get; set; } public void AddContributedFunctions(IList<IActionSpecImmutable> contributedFunctions) => unorderedContributedActions.AddRange(contributedFunctions); public void AddContributedFields(IList<IAssociationSpecImmutable> addedFields) => unorderedFields.AddRange(addedFields); public bool IsPlaceHolder => ReflectionStatus == ReflectionStatus.PlaceHolder; public bool IsPendingIntrospection => ReflectionStatus == ReflectionStatus.PendingIntrospection; public void RemoveAction(IActionSpecImmutable action, ILogger logger) { if (!UnorderedObjectActions.Remove(action)) { logger.LogWarning($"Failed to find and remove {action} from {identifier}"); } } private static bool IsAssignableToGenericType(Type givenType, Type genericType) { var interfaceTypes = givenType.GetInterfaces(); if (interfaceTypes.Any(it => it.IsGenericType && it.GetGenericTypeDefinition() == genericType)) { return true; } if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType) { return true; } var baseType = givenType.BaseType; return baseType != null && IsAssignableToGenericType(baseType, genericType); } public void AddContributedActions(IList<IActionSpecImmutable> contributedActions, Type[] services) { unorderedContributedActions = contributedActions.ToList(); this.services = services; } public void AddCollectionContributedActions(IList<IActionSpecImmutable> collectionContributedActions) => unorderedCollectionContributedActions.AddRange(collectionContributedActions); public void AddFinderActions(IList<IActionSpecImmutable> finderActions) => unorderedFinderActions.AddRange(finderActions); private void DecorateAllFacets(IFacetDecoratorSet decorator) { decorator.DecorateAllHoldersFacets(this); UnorderedFields.ForEach(decorator.DecorateAllHoldersFacets); UnorderedObjectActions.Where(s => s != null).ForEach(action => DecorateAction(decorator, action)); } private static void DecorateAction(IFacetDecoratorSet decorator, IActionSpecImmutable action) { decorator.DecorateAllHoldersFacets(action); action.Parameters.ForEach(decorator.DecorateAllHoldersFacets); } public override string ToString() => $"{GetType().Name} for {Type.Name}"; #region ITypeSpecBuilder Members public IImmutableDictionary<string, ITypeSpecBuilder> Introspect(IFacetDecoratorSet decorator, IIntrospector introspector, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) { metamodel = introspector.IntrospectType(Type, this, metamodel); identifier = introspector.Identifier; FullName = introspector.FullName; ShortName = introspector.ShortName; Superclass = introspector.Superclass; Interfaces = introspector.Interfaces.Cast<ITypeSpecImmutable>().ToImmutableList(); unorderedFields = introspector.UnorderedFields.ToList(); unorderedObjectActions = introspector.UnorderedObjectActions.ToList(); DecorateAllFacets(decorator); Type = introspector.SpecificationType; ReflectionStatus = ReflectionStatus.Introspected; return metamodel; } public void AddSubclass(ITypeSpecImmutable subclass) { lock (subclasses) { subclasses = subclasses.Add(subclass); } } public ITypeSpecImmutable Superclass { get; private set; } public override IIdentifier Identifier => identifier; public Type Type { get; private set; } public string FullName { get; private set; } public string ShortName { get; private set; } public IMenuImmutable ObjectMenu => GetFacet<IMenuFacet>()?.GetMenu(); public IReadOnlyList<IActionSpecImmutable> OrderedObjectActions { get; private set; } public IReadOnlyList<IActionSpecImmutable> OrderedContributedActions { get; private set; } public IReadOnlyList<IActionSpecImmutable> OrderedCollectionContributedActions { get; private set; } public IReadOnlyList<IActionSpecImmutable> OrderedFinderActions { get; private set; } public IReadOnlyList<IAssociationSpecImmutable> OrderedFields { get; private set; } public IReadOnlyList<ITypeSpecImmutable> Interfaces { get; private set; } public IReadOnlyList<ITypeSpecImmutable> Subclasses => subclasses; public override IFacet GetFacet(Type facetType) { var facet = base.GetFacet(facetType); if (FacetUtils.IsNotANoopFacet(facet)) { return facet; } var noopFacet = facet; if (Superclass != null) { var superClassFacet = Superclass.GetFacet(facetType); if (FacetUtils.IsNotANoopFacet(superClassFacet)) { return superClassFacet; } noopFacet ??= superClassFacet; } foreach (var interfaceSpec in Interfaces) { var interfaceFacet = interfaceSpec.GetFacet(facetType); if (FacetUtils.IsNotANoopFacet(interfaceFacet)) { return interfaceFacet; } noopFacet ??= interfaceFacet; } return noopFacet; } public virtual bool IsCollection => ContainsFacet(typeof(ICollectionFacet)); public bool IsQueryable => GetFacet<ICollectionFacet>()?.IsQueryable == true; public virtual bool IsParseable => ContainsFacet(typeof(IParseableFacet)); public virtual bool IsObject => !IsCollection; public IList<IAssociationSpecImmutable> UnorderedFields => unorderedFields; public IList<IActionSpecImmutable> UnorderedObjectActions => unorderedObjectActions; public bool IsOfType(ITypeSpecImmutable otherSpecification) { if (otherSpecification == this) { return true; } var otherType = otherSpecification.Type; if (otherType.IsAssignableFrom(Type)) { return true; } // match generic types if (Type.IsGenericType && IsCollection && otherType.IsGenericType && otherSpecification.IsCollection) { var thisGenericType = Type.GetGenericTypeDefinition(); var otherGenericType = Type.GetGenericTypeDefinition(); return thisGenericType == otherGenericType || IsAssignableToGenericType(otherType, thisGenericType); } return false; } #endregion #region ISerializable private readonly IList<IActionSpecImmutable> tempContributedActions; private readonly IList<IActionSpecImmutable> tempCollectionContributedActions; private readonly IList<IActionSpecImmutable> tempFinderActions; private readonly IList<IAssociationSpecImmutable> tempFields; private readonly IList<ITypeSpecImmutable> tempInterfaces; private readonly IList<IActionSpecImmutable> tempObjectActions; private readonly IList<ITypeSpecImmutable> tempSubclasses; // The special constructor is used to deserialize values. protected TypeSpecImmutable(SerializationInfo info, StreamingContext context) : base(info, context) { Type = info.GetValue<Type>("Type"); FullName = info.GetValue<string>("FullName"); ShortName = info.GetValue<string>("ShortName"); identifier = info.GetValue<IIdentifier>("identifier"); Superclass = info.GetValue<ITypeSpecImmutable>("Superclass"); tempFields = info.GetValue<IList<IAssociationSpecImmutable>>("Fields"); tempInterfaces = info.GetValue<IList<ITypeSpecImmutable>>("Interfaces"); tempSubclasses = info.GetValue<IList<ITypeSpecImmutable>>("subclasses"); tempObjectActions = info.GetValue<IList<IActionSpecImmutable>>("ObjectActions"); tempContributedActions = info.GetValue<IList<IActionSpecImmutable>>("OrderedContributedActions"); tempCollectionContributedActions = info.GetValue<IList<IActionSpecImmutable>>("OrderedCollectionContributedActions"); tempFinderActions = info.GetValue<IList<IActionSpecImmutable>>("OrderedFinderActions"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue<Type>("Type", Type); info.AddValue<string>("FullName", FullName); info.AddValue<string>("ShortName", ShortName); info.AddValue<IIdentifier>("identifier", identifier); info.AddValue<IList<IAssociationSpecImmutable>>("Fields", OrderedFields.ToList()); info.AddValue<IList<ITypeSpecImmutable>>("Interfaces", Interfaces.ToList()); info.AddValue<ITypeSpecImmutable>("Superclass", Superclass); info.AddValue<IList<ITypeSpecImmutable>>("subclasses", subclasses.ToList()); info.AddValue<IList<IActionSpecImmutable>>("ObjectActions", OrderedObjectActions.ToList()); info.AddValue<IList<IActionSpecImmutable>>("OrderedContributedActions", OrderedContributedActions.ToList()); info.AddValue<IList<IActionSpecImmutable>>("OrderedCollectionContributedActions", OrderedCollectionContributedActions.ToList()); info.AddValue<IList<IActionSpecImmutable>>("OrderedFinderActions", OrderedFinderActions.ToList()); base.GetObjectData(info, context); } public override void OnDeserialization(object sender) { OrderedFields = tempFields.ToImmutableList(); Interfaces = tempInterfaces.ToImmutableList(); subclasses = tempSubclasses.ToImmutableList(); OrderedObjectActions = tempObjectActions.ToImmutableList(); OrderedContributedActions = tempContributedActions.ToImmutableList(); OrderedCollectionContributedActions = tempCollectionContributedActions.ToImmutableList(); OrderedFinderActions = tempFinderActions.ToImmutableList(); base.OnDeserialization(sender); } private static IReadOnlyList<T> CreateOrderedImmutableList<T>(IEnumerable<T> members) where T : IMemberSpecImmutable => Order(members).ToImmutableList(); private static IEnumerable<T> Order<T>(IEnumerable<T> members) where T : IMemberSpecImmutable => members.OrderBy(m => m, new MemberOrderComparator<T>()); private void ClearUnorderedCollections() { unorderedFields = null; unorderedObjectActions = null; unorderedContributedActions = null; unorderedCollectionContributedActions = null; unorderedFinderActions = null; } public void CompleteIntegration() { OrderedFields = CreateOrderedImmutableList(UnorderedFields); OrderedFields.Select(a => new FacetUtils.ActionHolder(a)).ToList().ErrorOnDuplicates(); OrderedObjectActions = CreateOrderedImmutableList(UnorderedObjectActions); OrderedContributedActions = Order(unorderedContributedActions).GroupBy(i => i.OwnerSpec.Type, i => i, (service, actions) => new { service, actions }).OrderBy(a => Array.IndexOf(services, a.service)).SelectMany(a => a.actions).ToImmutableList(); OrderedCollectionContributedActions = CreateOrderedImmutableList(unorderedCollectionContributedActions); OrderedFinderActions = CreateOrderedImmutableList(unorderedFinderActions); ClearUnorderedCollections(); } #endregion }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.TeamFoundation.Server; using Microsoft.TeamFoundation.VersionControl.Client; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Core.TfsInterop; using Sep.Git.Tfs.Util; namespace Sep.Git.Tfs.VsCommon { public class WrapperForVersionControlServer : WrapperFor<VersionControlServer>, IVersionControlServer { private readonly TfsApiBridge _bridge; private readonly VersionControlServer _versionControlServer; public WrapperForVersionControlServer(TfsApiBridge bridge, VersionControlServer versionControlServer) : base(versionControlServer) { _bridge = bridge; _versionControlServer = versionControlServer; } public IItem GetItem(int itemId, int changesetNumber) { return _bridge.Wrap<WrapperForItem, Item>(_versionControlServer.GetItem(itemId, changesetNumber)); } public IItem GetItem(string itemPath, int changesetNumber) { return _bridge.Wrap<WrapperForItem, Item>(_versionControlServer.GetItem(itemPath, new ChangesetVersionSpec(changesetNumber))); } public IItem[] GetItems(string itemPath, int changesetNumber, TfsRecursionType recursionType) { var itemSet = _versionControlServer.GetItems( new ItemSpec(itemPath, _bridge.Convert<RecursionType>(recursionType), 0), new ChangesetVersionSpec(changesetNumber), DeletedState.NonDeleted, ItemType.Any, true ); return _bridge.Wrap<WrapperForItem, Item>(itemSet.Items); } public IEnumerable<IChangeset> QueryHistory(string path, int version, int deletionId, TfsRecursionType recursion, string user, int versionFrom, int versionTo, int maxCount, bool includeChanges, bool slotMode, bool includeDownloadInfo) { var history = _versionControlServer.QueryHistory(path, new ChangesetVersionSpec(version), deletionId, _bridge.Convert<RecursionType>(recursion), user, new ChangesetVersionSpec(versionFrom), new ChangesetVersionSpec(versionTo), maxCount, includeChanges, slotMode, includeDownloadInfo); return _bridge.Wrap<WrapperForChangeset, Changeset>(history); } } public class WrapperForChangeset : WrapperFor<Changeset>, IChangeset { private readonly TfsApiBridge _bridge; private readonly Changeset _changeset; public WrapperForChangeset(TfsApiBridge bridge, Changeset changeset) : base(changeset) { _bridge = bridge; _changeset = changeset; } public IChange[] Changes { get { return _bridge.Wrap<WrapperForChange, Change>(_changeset.Changes); } } public string Committer { get { var committer = _changeset.Committer; var owner = _changeset.Owner; // Sometimes TFS itself commits the changeset if (owner != committer) return owner; return committer; } } public DateTime CreationDate { get { return _changeset.CreationDate; } } public string Comment { get { return _changeset.Comment; } } public int ChangesetId { get { return _changeset.ChangesetId; } } public IVersionControlServer VersionControlServer { get { return _bridge.Wrap<WrapperForVersionControlServer, VersionControlServer>(_changeset.VersionControlServer); } } public void Get(IWorkspace workspace) { workspace.GetSpecificVersion(this); } } public class WrapperForChange : WrapperFor<Change>, IChange { private readonly TfsApiBridge _bridge; private readonly Change _change; public WrapperForChange(TfsApiBridge bridge, Change change) : base(change) { _bridge = bridge; _change = change; } public TfsChangeType ChangeType { get { return _bridge.Convert<TfsChangeType>(_change.ChangeType); } } public IItem Item { get { return _bridge.Wrap<WrapperForItem, Item>(_change.Item); } } } public class WrapperForItem : WrapperFor<Item>, IItem { private readonly IItemDownloadStrategy _downloadStrategy; private readonly TfsApiBridge _bridge; private readonly Item _item; public WrapperForItem(IItemDownloadStrategy downloadStrategy, TfsApiBridge bridge, Item item) : base(item) { _downloadStrategy = downloadStrategy; _bridge = bridge; _item = item; } public IVersionControlServer VersionControlServer { get { return _bridge.Wrap<WrapperForVersionControlServer, VersionControlServer>(_item.VersionControlServer); } } public int ChangesetId { get { return _item.ChangesetId; } } public string ServerItem { get { return _item.ServerItem; } } public int DeletionId { get { return _item.DeletionId; } } public TfsItemType ItemType { get { return _bridge.Convert<TfsItemType>(_item.ItemType); } } public int ItemId { get { return _item.ItemId; } } public long ContentLength { get { return _item.ContentLength; } } public TemporaryFile DownloadFile() { return _downloadStrategy.DownloadFile(this); } } public class WrapperForIdentity : WrapperFor<Identity>, IIdentity { private readonly Identity _identity; public WrapperForIdentity(Identity identity) : base(identity) { Debug.Assert(identity != null, "wrapped property must not be null."); _identity = identity; } public string MailAddress { get { return _identity.MailAddress; } } public string DisplayName { get { return _identity.DisplayName; } } } public class WrapperForShelveset : WrapperFor<Shelveset>, IShelveset { private readonly Shelveset _shelveset; private readonly TfsApiBridge _bridge; public WrapperForShelveset(TfsApiBridge bridge, Shelveset shelveset) : base(shelveset) { _shelveset = shelveset; _bridge = bridge; } public string Comment { get { return _shelveset.Comment; } set { _shelveset.Comment = value; } } public IWorkItemCheckinInfo[] WorkItemInfo { get { return _bridge.Wrap<WrapperForWorkItemCheckinInfo, WorkItemCheckinInfo>(_shelveset.WorkItemInfo); } set { _shelveset.WorkItemInfo = _bridge.Unwrap<WorkItemCheckinInfo>(value); } } } public class WrapperForWorkItemCheckinInfo : WrapperFor<WorkItemCheckinInfo>, IWorkItemCheckinInfo { public WrapperForWorkItemCheckinInfo(WorkItemCheckinInfo workItemCheckinInfo) : base(workItemCheckinInfo) { } } public class WrapperForWorkItemCheckedInfo : WrapperFor<WorkItemCheckedInfo>, IWorkItemCheckedInfo { public WrapperForWorkItemCheckedInfo(WorkItemCheckedInfo workItemCheckinInfo) : base(workItemCheckinInfo) { } } public class WrapperForPendingChange : WrapperFor<PendingChange>, IPendingChange { public WrapperForPendingChange(PendingChange pendingChange) : base(pendingChange) { } } public class WrapperForCheckinNote : WrapperFor<CheckinNote>, ICheckinNote { public WrapperForCheckinNote(CheckinNote checkiNote) : base(checkiNote) { } } public class WrapperForCheckinEvaluationResult : WrapperFor<CheckinEvaluationResult>, ICheckinEvaluationResult { private readonly TfsApiBridge _bridge; private readonly CheckinEvaluationResult _result; public WrapperForCheckinEvaluationResult(TfsApiBridge bridge, CheckinEvaluationResult result) : base(result) { _bridge = bridge; _result = result; } public ICheckinConflict[] Conflicts { get { return _bridge.Wrap<WrapperForCheckinConflict, CheckinConflict>(_result.Conflicts); } } public ICheckinNoteFailure[] NoteFailures { get { return _bridge.Wrap<WrapperForCheckinNoteFailure, CheckinNoteFailure>(_result.NoteFailures); } } public IPolicyFailure[] PolicyFailures { get { return _bridge.Wrap<WrapperForPolicyFailure, PolicyFailure>(_result.PolicyFailures); } } public Exception PolicyEvaluationException { get { return _result.PolicyEvaluationException; } } } public class WrapperForCheckinConflict : WrapperFor<CheckinConflict>, ICheckinConflict { private readonly CheckinConflict _conflict; public WrapperForCheckinConflict(CheckinConflict conflict) : base(conflict) { _conflict = conflict; } public string ServerItem { get { return _conflict.ServerItem; } } public string Message { get { return _conflict.Message; } } public bool Resolvable { get { return _conflict.Resolvable; } } } public class WrapperForCheckinNoteFailure : WrapperFor<CheckinNoteFailure>, ICheckinNoteFailure { private readonly TfsApiBridge _bridge; private readonly CheckinNoteFailure _failure; public WrapperForCheckinNoteFailure(TfsApiBridge bridge, CheckinNoteFailure failure) : base(failure) { _bridge = bridge; _failure = failure; } public ICheckinNoteFieldDefinition Definition { get { return _bridge.Wrap<WrapperForCheckinNoteFieldDefinition, CheckinNoteFieldDefinition>(_failure.Definition); } } public string Message { get { return _failure.Message; } } } public class WrapperForCheckinNoteFieldDefinition : WrapperFor<CheckinNoteFieldDefinition>, ICheckinNoteFieldDefinition { private readonly CheckinNoteFieldDefinition _fieldDefinition; public WrapperForCheckinNoteFieldDefinition(CheckinNoteFieldDefinition fieldDefinition) : base(fieldDefinition) { _fieldDefinition = fieldDefinition; } public string ServerItem { get { return _fieldDefinition.ServerItem; } } public string Name { get { return _fieldDefinition.Name; } } public bool Required { get { return _fieldDefinition.Required; } } public int DisplayOrder { get { return _fieldDefinition.DisplayOrder; } } } public class WrapperForPolicyFailure : WrapperFor<PolicyFailure>, IPolicyFailure { private readonly PolicyFailure _failure; public WrapperForPolicyFailure(PolicyFailure failure) : base(failure) { _failure = failure; } public string Message { get { return _failure.Message; } } } public partial class WrapperForWorkspace : WrapperFor<Workspace>, IWorkspace { private readonly TfsApiBridge _bridge; private readonly Workspace _workspace; public WrapperForWorkspace(TfsApiBridge bridge, Workspace workspace) : base(workspace) { _bridge = bridge; _workspace = workspace; } public IPendingChange[] GetPendingChanges() { return _bridge.Wrap<WrapperForPendingChange, PendingChange>(_workspace.GetPendingChanges()); } public void Shelve(IShelveset shelveset, IPendingChange[] changes, TfsShelvingOptions options) { _workspace.Shelve(_bridge.Unwrap<Shelveset>(shelveset), _bridge.Unwrap<PendingChange>(changes), _bridge.Convert<ShelvingOptions>(options)); } private PolicyOverrideInfo ToTfs(TfsPolicyOverrideInfo policyOverrideInfo) { if (policyOverrideInfo == null) return null; return new PolicyOverrideInfo(policyOverrideInfo.Comment, _bridge.Unwrap<PolicyFailure>(policyOverrideInfo.Failures)); } public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes, string comment, string author, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges) { return _bridge.Wrap<WrapperForCheckinEvaluationResult, CheckinEvaluationResult>(_workspace.EvaluateCheckin( _bridge.Convert<CheckinEvaluationOptions>(options), _bridge.Unwrap<PendingChange>(allChanges), _bridge.Unwrap<PendingChange>(changes), comment, _bridge.Unwrap<CheckinNote>(checkinNote), _bridge.Unwrap<WorkItemCheckinInfo>(workItemChanges))); } public int PendAdd(string path) { return _workspace.PendAdd(path); } public int PendEdit(string path) { return _workspace.PendEdit(path); } public int PendDelete(string path) { return _workspace.PendDelete(path); } public int PendRename(string pathFrom, string pathTo) { FileInfo info = new FileInfo(pathTo); if (info.Exists) info.Delete(); return _workspace.PendRename(pathFrom, pathTo); } public void ForceGetFile(string path, int changeset) { var item = new ItemSpec(path, RecursionType.None); _workspace.Get(new GetRequest(item, changeset), GetOptions.Overwrite | GetOptions.GetAll); } public void GetSpecificVersion(int changeset) { _workspace.Get(new ChangesetVersionSpec(changeset), GetOptions.Overwrite | GetOptions.GetAll); } public void GetSpecificVersion(IChangeset changeset) { var requests = from change in changeset.Changes select new GetRequest(new ItemSpec(change.Item.ServerItem, RecursionType.None, change.Item.DeletionId), changeset.ChangesetId); _workspace.Get(requests.ToArray(), GetOptions.Overwrite); } public string GetLocalItemForServerItem(string serverItem) { return _workspace.GetLocalItemForServerItem(serverItem); } public string GetServerItemForLocalItem(string localItem) { return _workspace.GetServerItemForLocalItem(localItem); } public string OwnerName { get { return _workspace.OwnerName; } } public void Merge(string sourceTfsPath, string targetTfsPath) { var status = _workspace.Merge(sourceTfsPath, targetTfsPath, null, null, LockLevel.None, RecursionType.Full, MergeOptions.AlwaysAcceptMine); var conflicts = _workspace.QueryConflicts(null, true); foreach (var conflict in conflicts) { conflict.Resolution = Resolution.AcceptYours; _workspace.ResolveConflict(conflict); } } } }
#region License //*****************************************************************************/ // Copyright (c) 2010 - 2012 Luigi Grilli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //*****************************************************************************/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; namespace Grillisoft.ImmutableArray { internal class ImmutableArrayInternal<T> where T : struct, IComparable, IEquatable<T>, IConvertible { private static readonly IBufferManager<T> _bufferManager = new BufferManager<T>(); private static readonly T[] EmptyArray = new T[0]; /// <summary> /// Separator used between array items when converting an immutable array to string /// </summary> internal const string SEPARATOR = "-"; /// <summary> /// Maximum number of elements used to calculate hash code /// </summary> internal const int HASH_MAX_ELEMENTS = 10; private int _offset = 0; private T[] _data = EmptyArray; private int _length = 0; private int _references = 0; private readonly ImmutableArrayInternal<T> _source; #region Constructors public static IEnumerable<ImmutableArrayInternal<T>> Create(int sourceIndex, T[] data, int length) { if (sourceIndex < 0) throw new IndexOutOfRangeException("Index cannot be less than zero"); if (data == null) throw new ArgumentNullException("data", "Array cannot be null"); if ((sourceIndex + length) > data.Length) throw new ArgumentOutOfRangeException("The sourceIndex and length specified overcome the source ByteArray length"); foreach (var buffer in _bufferManager.Allocate(length)) { var part = Math.Min(buffer.Length, length); Array.Copy(data, sourceIndex, buffer, 0, part); yield return new ImmutableArrayInternal<T>(sourceIndex, buffer, part); sourceIndex += part; length -= part; } } private ImmutableArrayInternal(int sourceIndex, T[] data, int length) { _offset = 0; _data = data; _length = length; } public ImmutableArrayInternal(ImmutableArrayInternal<T> data) : this(data, data.Length) { } public ImmutableArrayInternal(ImmutableArrayInternal<T> data, int length) : this(0, data, length) { } public ImmutableArrayInternal(int sourceIndex, ImmutableArrayInternal<T> data, int length) { if ((sourceIndex < 0) || (sourceIndex >= data.Length)) throw new IndexOutOfRangeException("Index must be between 0 and upper array bound"); if (data == null) throw new ArgumentNullException("data", "Array cannot be null"); if ((sourceIndex + length) > data.Length) throw new ArgumentOutOfRangeException("The sourceIndex and length specified overcome the source ByteArray length"); _offset = data.Offset + sourceIndex; _data = data.Data; _length = length; _source = data; } #endregion #region Public methods public T this[int index] { get { return _data[_offset + index]; } } public int Length { get { return _length; } } public ImmutableArrayInternal<T> SubArrayInternal(int sourceIndex) { return this.SubArrayInternal(sourceIndex, _length - sourceIndex); } public ImmutableArrayInternal<T> SubArrayInternal(int sourceIndex, int length) { if ((sourceIndex == 0) && (length == _length)) return this; return new ImmutableArrayInternal<T>(sourceIndex, this, length); } public void CopyTo(Array array, int index) { this.CopyTo(array, index, _length); } public void CopyTo(Array array, int index, int length) { Array.Copy(_data, _offset, array, index, length); } #endregion #region References count /// <summary> /// Increase the references count /// </summary> public int IncreaseReferences() { if (_source != null) return _source.IncreaseReferences(); return Interlocked.Increment(ref _references); } /// <summary> /// Decrease the references count /// </summary> public int DecreaseReferences() { if (_source != null) return _source.DecreaseReferences(); return this.DecreaseReferenceInternal(); } private int DecreaseReferenceInternal() { var ret = Interlocked.Decrement(ref _references); if (ret == 0 && !object.ReferenceEquals(_data, EmptyArray)) { _bufferManager.Free(_data); _data = null; } return ret; } #endregion #region Protected and Private method/properties protected int Offset { get { return _offset; } set { _offset = value; } } protected T[] Data { get { return _data; } set { _data = value; } } #endregion #region Object overrides public override bool Equals(object obj) { if (obj == null) throw new ArgumentNullException("Cannot compare object with a null instance"); if (typeof(T[]).IsInstanceOfType(obj)) return this.EqualsTo((T[])obj); if (typeof(ImmutableArrayInternal<T>).IsInstanceOfType(obj)) return this.EqualsTo((ImmutableArrayInternal<T>)obj); return base.Equals(obj); } public override int GetHashCode() { int step = _length / ImmutableArrayInternal<T>.HASH_MAX_ELEMENTS; if (step <= 0) step = 1; int hash = 0; for (int i = 0; i < _length; i += step) hash += this[i].GetHashCode(); return hash; } public override string ToString() { if (_length <= 0) return String.Empty; StringBuilder builder = new StringBuilder(); for (int i = 0; i < (_length - 1); i++) { builder.Append(this[i].ToString()); builder.Append(ImmutableArrayInternal<T>.SEPARATOR); } builder.Append(this[_length - 1].ToString()); return builder.ToString(); } #endregion #region EqualsTo methods protected bool EqualsTo(T[] array) { if (_length != array.Length) return false; for (int i = 0; i < _length; i++) if (!this[i].Equals(array[i])) return false; return true; } protected bool EqualsTo(ImmutableArrayInternal<T> array) { if (_length != array.Length) return false; //fast compare if (this.GetHashCode() != array.GetHashCode()) return false; //slow compare for (int i = 0; i < _length; i++) if (!this[i].Equals(array[i])) return false; return true; } #endregion } }
using System; using System.Collections.Concurrent; using System.IO; using System.Net; using System.Threading.Tasks; using LoginRadiusSDK.V2.Common; using LoginRadiusSDK.V2.Exception; using Newtonsoft.Json; namespace LoginRadiusSDK.V2.Http { /// <summary> /// Stores details related to an HTTP request. /// </summary> public class RequestDetails { /// <summary> /// Gets or sets the URL for the request. /// </summary> public string Url { get; set; } /// <summary> /// Gets or sets the HTTP method verb used for the request. /// </summary> public string Method { get; set; } /// <summary> /// Gets or sets the headers used in the request. /// </summary> public WebHeaderCollection Headers { get; set; } /// <summary> /// Gets or sets the request body. /// </summary> public string Body { get; set; } /// <summary> /// Gets or sets the number of retry attempts for sending an HTTP request. /// </summary> public int RetryAttempts { get; set; } /// <summary> /// Resets the state of this object and clears its properties. /// </summary> public void Reset() { Url = string.Empty; Headers = null; Body = string.Empty; RetryAttempts = 0; } } /// <summary> /// Stores details related to an HTTP response. /// </summary> public class ResponseDetails { /// <summary> /// Gets or sets the headers used in the response. /// </summary> public WebHeaderCollection Headers { get; set; } /// <summary> /// Gets or sets the response body. /// </summary> public string Body { get; set; } /// <summary> /// Gets or sets the response HTTP status code. /// </summary> public HttpStatusCode? StatusCode { get; set; } /// <summary> /// Gets or sets an exception related to the response. /// </summary> public ConnectionException Exception { get; set; } /// <summary> /// Resets the state of this object and clears its properties. /// </summary> public void Reset() { Headers = null; Body = string.Empty; StatusCode = null; Exception = null; } } /// <summary> /// Helper class for sending HTTP requests. /// </summary> internal class HttpConnection { private readonly ConcurrentDictionary<string, string> _config; /// <summary> /// Gets the HTTP request details. /// </summary> public RequestDetails RequestDetails { get; private set; } /// <summary> /// Gets the HTTP response details. /// </summary> public ResponseDetails ResponseDetails { get; private set; } /// <summary> /// Initializes a new instance of <seealso cref="HttpConnection"/> using the given _config. /// </summary> /// <param name="config">The _config to use when making HTTP requests.</param> public HttpConnection(ConcurrentDictionary<string, string> config) { _config = config; RequestDetails = new RequestDetails(); ResponseDetails = new ResponseDetails(); } /// <summary> /// Copying existing HttpWebRequest parameters to newly created HttpWebRequest, can't reuse the same HttpWebRequest for retries. /// </summary> /// <param name="httpRequest"></param> /// <param name="config"></param> /// <param name="url"></param> /// <returns>HttpWebRequest</returns> private HttpWebRequest CopyRequest(HttpWebRequest httpRequest, ConcurrentDictionary<string, string> config, string url) { ConnectionManager connMngr = ConnectionManager.Instance; HttpWebRequest newHttpRequest = connMngr.GetConnection(config, url); newHttpRequest.Method = httpRequest.Method; newHttpRequest.Accept = httpRequest.Accept; newHttpRequest.ContentType = httpRequest.ContentType; #if !NETSTANDARD1_3 if (httpRequest.ContentLength > 0) { newHttpRequest.ContentLength = httpRequest.ContentLength; } newHttpRequest.UserAgent = httpRequest.UserAgent; newHttpRequest.ClientCertificates = httpRequest.ClientCertificates; newHttpRequest.AutomaticDecompression = DecompressionMethods.GZip; #endif newHttpRequest = CopyHttpWebRequestHeaders(httpRequest, newHttpRequest); return newHttpRequest; } /// <summary> /// Copying existing HttpWebRequest headers into newly created HttpWebRequest /// </summary> /// <param name="httpRequest"></param> /// <param name="newHttpRequest"></param> /// <returns>HttpWebRequest</returns> private HttpWebRequest CopyHttpWebRequestHeaders(HttpWebRequest httpRequest, HttpWebRequest newHttpRequest) { string[] allKeys = httpRequest.Headers.AllKeys; foreach (string key in allKeys) { switch (key.ToLower()) { case "accept": case "connection": case "content-length": case "content-type": case "date": case "expect": case "host": case "if-modified-since": case "range": case "referer": case "transfer-encoding": case "user-agent": case "proxy-connection": break; default: newHttpRequest.Headers[key] = httpRequest.Headers[key]; break; } } return newHttpRequest; } /// <summary> /// Executing API calls /// </summary> /// <param name="payLoad"></param> /// <param name="httpRequest"></param> /// <param name="contentLength"></param> /// <returns>A string containing the response from the remote host.</returns> public async Task<string> Execute(string payLoad, HttpWebRequest httpRequest, int contentLength) { int retriesConfigured = _config.ContainsKey(LRConfigConstants.HttpConnectionRetryConfig) && int.TryParse(_config[LRConfigConstants.HttpConnectionRetryConfig], out int retriesInt) ? retriesInt : 0; int retries = 0; // Reset the request & response details RequestDetails.Reset(); ResponseDetails.Reset(); // Store the request details RequestDetails.Body = payLoad; RequestDetails.Headers = httpRequest.Headers; RequestDetails.Url = httpRequest.RequestUri.AbsoluteUri; RequestDetails.Method = httpRequest.Method; #if !NETSTANDARD1_3 if (contentLength == 0) httpRequest.ContentLength = contentLength; #endif try { do { if (retries > 0) { httpRequest = CopyRequest(httpRequest, _config, httpRequest.RequestUri.ToString()); RequestDetails.RetryAttempts++; } try { switch (httpRequest.Method.ToUpper()) { case "POST": case "PUT": case "DELETE": if (!string.IsNullOrEmpty(payLoad)) { Stream stream = null; #if NetFramework stream = httpRequest.GetRequestStream(); #else stream = await httpRequest.GetRequestStreamAsync(); #endif using (StreamWriter writerStream = new StreamWriter(stream)) { writerStream.Write(payLoad); writerStream.Flush(); #if NetFramework writerStream.Close(); #endif } } break; } WebResponse webResponse = null; #if !NetFramework webResponse = await httpRequest.GetResponseAsync(); #else webResponse = httpRequest.GetResponse(); #endif using (WebResponse responseWeb = webResponse) { // Store the response information ResponseDetails.Headers = responseWeb.Headers; if (responseWeb is HttpWebResponse httpWebResponse) { ResponseDetails.StatusCode = httpWebResponse.StatusCode; } using (StreamReader readerStream = new StreamReader(responseWeb.GetResponseStream())) { #if NET40 ResponseDetails.Body = readerStream.ReadToEnd().Trim(); #else ResponseDetails.Body = await readerStream.ReadToEndAsync(); #endif return ResponseDetails.Body; } } } catch (WebException ex) { CatchException(ex, httpRequest); } #if NETSTANDARD catch (System.Exception ex) { if (ex.InnerException is WebException webException) { CatchException(webException, httpRequest); } else { throw new LoginRadiusException(ex.Message, ex); } } #endif } while (retries++ < retriesConfigured); } catch (LoginRadiusException) { // Rethrow any LoginRadiusExceptions since they already contain the // details of the exception. throw; } catch (System.Exception ex) { // Repackage any other exceptions to give a bit more context to // the caller. throw new LoginRadiusException("Exception in LoginRadius.HttpConnection.Execute(): " + ex.Message, ex); } // If we've gotten this far, it means all attempts at sending the // request resulted in a failed attempt. throw new LoginRadiusException("Retried " + retriesConfigured + " times.... Exception in LoginRadius.HttpConnection.Execute()."); } private void CatchException(WebException ex, HttpWebRequest httpRequest) { // If provided, get and log the response from the remote host. var response = string.Empty; if (ex.Response != null) { using (var readerStream = new StreamReader(ex.Response.GetResponseStream())) { response = readerStream.ReadToEnd().Trim(); } } ConnectionException rethrowEx; // Protocol errors indicate the remote host received the // request, but responded with an error (usually a 4xx or // 5xx error). if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response is HttpWebResponse httpWebResponse) { if (httpWebResponse.StatusCode.Equals((HttpStatusCode)429)) { throw new LoginRadiusException("Too many request in particular time frame", ex, response, (HttpStatusCode)429); } // If the HTTP status code is flagged as one where we // should continue retrying, then ignore the exception // and continue with the retry attempt. if (httpWebResponse.StatusCode == HttpStatusCode.GatewayTimeout || httpWebResponse.StatusCode == HttpStatusCode.RequestTimeout || httpWebResponse.StatusCode == HttpStatusCode.BadGateway) { return; } // If the httpWebResponse.StatusCode is defined in the HttpStatusCode then throw the LoginRadiusException if (Enum.IsDefined(typeof(HttpStatusCode), httpWebResponse.StatusCode)) { throw new LoginRadiusException(ex.Message, ex, response, (HttpStatusCode)httpWebResponse.StatusCode); } rethrowEx = new HttpException(ex.Message, response, httpWebResponse.StatusCode, ex.Status, httpWebResponse.Headers, httpRequest); } else if (ex.Status == WebExceptionStatus.Timeout) { string message; // For connection timeout errors, include the connection timeout value that was used. #if NetFramework message = $"{ex.Message} (HTTP request timeout was set to {httpRequest.Timeout}ms)"; #else message = ex.Message; #endif rethrowEx = new ConnectionException(message, response, ex.Status, httpRequest); } else { // Non-protocol errors indicate something happened with the underlying connection to the server. rethrowEx = new ConnectionException("Invalid HTTP response: " + ex.Message, response, ex.Status, httpRequest); } if (ex.Response is HttpWebResponse httpWebResponse1) { ResponseDetails.StatusCode = httpWebResponse1.StatusCode; ResponseDetails.Headers = httpWebResponse1.Headers; } ResponseDetails.Exception = rethrowEx; throw rethrowEx; } } }
/* * CID0001.cs - ar culture handler. * * Copyright (c) 2003 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ar.txt". namespace I18N.MidEast { using System; using System.Globalization; using I18N.Common; public class CID0001 : RootCulture { public CID0001() : base(0x0001) {} public CID0001(int culture) : base(culture) {} public override String Name { get { return "ar"; } } public override String ThreeLetterISOLanguageName { get { return "ara"; } } public override String ThreeLetterWindowsLanguageName { get { return "ARA"; } } public override String TwoLetterISOLanguageName { get { return "ar"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AMDesignator = "\u0635"; dfi.PMDesignator = "\u0645"; dfi.AbbreviatedDayNames = new String[] {"\u062D", "\u0646", "\u062B", "\u0631", "\u062E", "\u062C", "\u0633"}; dfi.DayNames = new String[] {"\u0627\u0644\u0623\u062D\u062F", "\u0627\u0644\u0627\u062B\u0646\u064A\u0646", "\u0627\u0644\u062B\u0644\u0627\u062B\u0627\u0621", "\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621", "\u0627\u0644\u062E\u0645\u064A\u0633", "\u0627\u0644\u062C\u0645\u0639\u0629", "\u0627\u0644\u0633\u0628\u062A"}; dfi.AbbreviatedMonthNames = new String[] {"\u064A\u0646\u0627", "\u0641\u0628\u0631", "\u0645\u0627\u0631", "\u0623\u0628\u0631", "\u0645\u0627\u064A", "\u064A\u0648\u0646", "\u064A\u0648\u0644", "\u0623\u063A\u0633", "\u0633\u0628\u062A", "\u0623\u0643\u062A", "\u0646\u0648\u0641", "\u062F\u064A\u0633", ""}; dfi.MonthNames = new String[] {"\u064A\u0646\u0627\u064A\u0631", "\u0641\u0628\u0631\u0627\u064A\u0631", "\u0645\u0627\u0631\u0633", "\u0623\u0628\u0631\u064A\u0644", "\u0645\u0627\u064A\u0648", "\u064A\u0648\u0646\u064A\u0648", "\u064A\u0648\u0644\u064A\u0648", "\u0623\u063A\u0633\u0637\u0633", "\u0633\u0628\u062A\u0645\u0628\u0631", "\u0623\u0643\u062A\u0648\u0628\u0631", "\u0646\u0648\u0641\u0645\u0628\u0631", "\u062F\u064A\u0633\u0645\u0628\u0631", ""}; dfi.DateSeparator = "/"; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "d MMMM, yyyy"; dfi.LongTimePattern = "z h:mm:ss tt"; dfi.ShortDatePattern = "dd/MM/yy"; dfi.ShortTimePattern = "h:mm tt"; dfi.FullDateTimePattern = "dddd, d MMMM, yyyy z h:mm:ss tt"; dfi.I18NSetDateTimePatterns(new String[] { "d:dd/MM/yy", "D:dddd, d MMMM, yyyy", "f:dddd, d MMMM, yyyy z h:mm:ss tt", "f:dddd, d MMMM, yyyy z h:mm:ss tt", "f:dddd, d MMMM, yyyy h:mm:ss tt", "f:dddd, d MMMM, yyyy h:mm tt", "F:dddd, d MMMM, yyyy HH:mm:ss", "g:dd/MM/yy z h:mm:ss tt", "g:dd/MM/yy z h:mm:ss tt", "g:dd/MM/yy h:mm:ss tt", "g:dd/MM/yy h:mm tt", "G:dd/MM/yy HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:z h:mm:ss tt", "t:z h:mm:ss tt", "t:h:mm:ss tt", "t:h:mm tt", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "ar": return "\u0627\u0644\u0639\u0631\u0628\u064A\u0629"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "AE": return "\u0627\u0644\u0625\u0645\u0627\u0631\u0627\u062A"; case "BH": return "\u0627\u0644\u0628\u062D\u0631\u064A\u0646"; case "DZ": return "\u0627\u0644\u062C\u0632\u0627\u0626\u0631"; case "EG": return "\u0645\u0635\u0631"; case "IQ": return "\u0627\u0644\u0639\u0631\u0627\u0642"; case "IN": return "\u0627\u0644\u0647\u0646\u062F"; case "JO": return "\u0627\u0644\u0623\u0631\u062F\u0646"; case "KW": return "\u0627\u0644\u0643\u0648\u064A\u062A"; case "LB": return "\u0644\u0628\u0646\u0627\u0646"; case "LY": return "\u0644\u064A\u0628\u064A\u0627"; case "MA": return "\u0627\u0644\u0645\u063A\u0631\u0628"; case "OM": return "\u0633\u0644\u0637\u0646\u0629 \u0639\u0645\u0627\u0646"; case "QA": return "\u0642\u0637\u0631"; case "SA": return "\u0627\u0644\u0633\u0639\u0648\u062F\u064A\u0629"; case "SD": return "\u0627\u0644\u0633\u0648\u062F\u0627\u0646"; case "SY": return "\u0633\u0648\u0631\u064A\u0627"; case "TN": return "\u062A\u0648\u0646\u0633"; case "YE": return "\u0627\u0644\u064A\u0645\u0646"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int ANSICodePage { get { return 1256; } } public override int EBCDICCodePage { get { return 20420; } } public override int MacCodePage { get { return 10004; } } public override int OEMCodePage { get { return 720; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID0001 public class CNar : CID0001 { public CNar() : base() {} }; // class CNar }; // namespace I18N.MidEast
using System; using ModestTree; using ModestTree.Util; #if !ZEN_NOT_UNITY3D using UnityEngine; #endif namespace Zenject { ////////////////////////////// Zero parameters ////////////////////////////// [System.Diagnostics.DebuggerStepThrough] public class IFactoryBinder<TContract> { readonly DiContainer _container; readonly string _identifier; public IFactoryBinder(DiContainer container, string identifier) { _container = container; _identifier = identifier; } public BindingConditionSetter ToInstance(TContract instance) { return ToMethod((c) => instance); } public BindingConditionSetter ToMethod( Func<DiContainer, TContract> method) { return _container.Bind<IFactory<TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<FactoryMethod<TContract>>(method)); } public BindingConditionSetter ToFactory() { Assert.That(!typeof(TContract).IsAbstract, "Unable to create abstract type '{0}' in Factory", typeof(TContract).Name()); return _container.Bind<IFactory<TContract>>(_identifier) .ToTransient<Factory<TContract>>(); } public BindingConditionSetter ToFactory<TConcrete>() where TConcrete : TContract { return ToCustomFactory<TConcrete, Factory<TConcrete>>(); } // Note that we assume here that IFactory<TConcrete> is bound somewhere else public BindingConditionSetter ToIFactory<TConcrete>() where TConcrete : TContract { return _container.Bind<IFactory<TContract>>(_identifier) .ToMethod(c => new FactoryNested<TContract, TConcrete>(c.Container.Resolve<IFactory<TConcrete>>())); } public BindingConditionSetter ToCustomFactory<TFactory>() where TFactory : IFactory<TContract> { return _container.Bind<IFactory<TContract>>(_identifier).ToTransient<TFactory>(); } public BindingConditionSetter ToCustomFactory<TConcrete, TFactory>() where TFactory : IFactory<TConcrete> where TConcrete : TContract { return _container.Bind<IFactory<TContract>>(_identifier) .ToMethod(c => new FactoryNested<TContract, TConcrete>(c.Container.Instantiate<TFactory>())); } #if !ZEN_NOT_UNITY3D public BindingConditionSetter ToPrefab(GameObject prefab) { Assert.That(typeof(TContract).DerivesFrom<Component>()); if (prefab == null) { throw new ZenjectBindException( "Null prefab provided to BindIFactory<{0}>().ToPrefab".Fmt(typeof(TContract).Name())); } return _container.Bind<IFactory<TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<GameObjectFactory<TContract>>(prefab)); } #endif } ////////////////////////////// One parameter ////////////////////////////// [System.Diagnostics.DebuggerStepThrough] public class IFactoryBinder<TParam1, TContract> { readonly DiContainer _container; readonly string _identifier; public IFactoryBinder(DiContainer container, string identifier) { _container = container; _identifier = identifier; } public BindingConditionSetter ToMethod( Func<DiContainer, TParam1, TContract> method) { return _container.Bind<IFactory<TParam1, TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<FactoryMethod<TParam1, TContract>>(method)); } public BindingConditionSetter ToFactory() { Assert.That(!typeof(TContract).IsAbstract); return _container.Bind<IFactory<TParam1, TContract>>(_identifier) .ToTransient<Factory<TParam1, TContract>>(); } public BindingConditionSetter ToFactory<TConcrete>() where TConcrete : TContract { return ToCustomFactory<TConcrete, Factory<TParam1, TConcrete>>(); } // Note that we assume here that IFactory<TConcrete> is bound somewhere else public BindingConditionSetter ToIFactory<TConcrete>() where TConcrete : TContract { return _container.Bind<IFactory<TParam1, TContract>>(_identifier) .ToMethod(c => new FactoryNested<TParam1, TContract, TConcrete>( c.Container.Resolve<IFactory<TParam1, TConcrete>>())); } public BindingConditionSetter ToCustomFactory<TFactory>() where TFactory : IFactory<TParam1, TContract> { return _container.Bind<IFactory<TParam1, TContract>>(_identifier).ToTransient<TFactory>(); } public BindingConditionSetter ToCustomFactory<TConcrete, TFactory>() where TFactory : IFactory<TParam1, TConcrete> where TConcrete : TContract { return _container.Bind<IFactory<TParam1, TContract>>(_identifier) .ToMethod(c => new FactoryNested<TParam1, TContract, TConcrete>( c.Container.Instantiate<TFactory>())); } #if !ZEN_NOT_UNITY3D public BindingConditionSetter ToPrefab(GameObject prefab) { Assert.That(typeof(TContract).DerivesFrom<Component>()); if (prefab == null) { throw new ZenjectBindException( "Null prefab provided to BindIFactory<{0}>().ToPrefab".Fmt(typeof(TContract).Name())); } return _container.Bind<IFactory<TParam1, TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<GameObjectFactory<TParam1, TContract>>(prefab)); } #endif } ////////////////////////////// Two parameters ////////////////////////////// [System.Diagnostics.DebuggerStepThrough] public class IFactoryBinder<TParam1, TParam2, TContract> { readonly DiContainer _container; readonly string _identifier; public IFactoryBinder(DiContainer container, string identifier) { _container = container; _identifier = identifier; } public BindingConditionSetter ToMethod( Func<DiContainer, TParam1, TParam2, TContract> method) { return _container.Bind<IFactory<TParam1, TParam2, TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<FactoryMethod<TParam1, TParam2, TContract>>(method)); } public BindingConditionSetter ToFactory() { Assert.That(!typeof(TContract).IsAbstract); return _container.Bind<IFactory<TParam1, TParam2, TContract>>(_identifier) .ToTransient<Factory<TParam1, TParam2, TContract>>(); } public BindingConditionSetter ToFactory<TConcrete>() where TConcrete : TContract { return ToCustomFactory<TConcrete, Factory<TParam1, TParam2, TConcrete>>(); } // Note that we assume here that IFactory<TConcrete> is bound somewhere else public BindingConditionSetter ToIFactory<TConcrete>() where TConcrete : TContract { return _container.Bind<IFactory<TParam1, TParam2, TContract>>(_identifier) .ToMethod(c => new FactoryNested<TParam1, TParam2, TContract, TConcrete>( c.Container.Resolve<IFactory<TParam1, TParam2, TConcrete>>())); } public BindingConditionSetter ToCustomFactory<TFactory>() where TFactory : IFactory<TParam1, TParam2, TContract> { return _container.Bind<IFactory<TParam1, TParam2, TContract>>(_identifier).ToTransient<TFactory>(); } public BindingConditionSetter ToCustomFactory<TConcrete, TFactory>() where TFactory : IFactory<TParam1, TParam2, TConcrete> where TConcrete : TContract { return _container.Bind<IFactory<TParam1, TParam2, TContract>>(_identifier) .ToMethod(c => new FactoryNested<TParam1, TParam2, TContract, TConcrete>( c.Container.Instantiate<TFactory>())); } #if !ZEN_NOT_UNITY3D public BindingConditionSetter ToPrefab(GameObject prefab) { Assert.That(typeof(TContract).DerivesFrom<Component>()); if (prefab == null) { throw new ZenjectBindException( "Null prefab provided to BindIFactory<{0}>().ToPrefab".Fmt(typeof(TContract).Name())); } return _container.Bind<IFactory<TParam1, TParam2, TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<GameObjectFactory<TParam1, TParam2, TContract>>(prefab)); } #endif } ////////////////////////////// Three parameters ////////////////////////////// [System.Diagnostics.DebuggerStepThrough] public class IFactoryBinder<TParam1, TParam2, TParam3, TContract> { readonly DiContainer _container; readonly string _identifier; public IFactoryBinder(DiContainer container, string identifier) { _container = container; _identifier = identifier; } public BindingConditionSetter ToMethod( Func<DiContainer, TParam1, TParam2, TParam3, TContract> method) { return _container.Bind<IFactory<TParam1, TParam2, TParam3, TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<FactoryMethod<TParam1, TParam2, TParam3, TContract>>(method)); } public BindingConditionSetter ToFactory() { Assert.That(!typeof(TContract).IsAbstract); return _container.Bind<IFactory<TParam1, TParam2, TParam3, TContract>>(_identifier) .ToTransient<Factory<TParam1, TParam2, TParam3, TContract>>(); } public BindingConditionSetter ToFactory<TConcrete>() where TConcrete : TContract { return ToCustomFactory<TConcrete, Factory<TParam1, TParam2, TParam3, TConcrete>>(); } // Note that we assume here that IFactory<TConcrete> is bound somewhere else public BindingConditionSetter ToIFactory<TConcrete>() where TConcrete : TContract { return _container.Bind<IFactory<TParam1, TParam2, TParam3, TContract>>(_identifier) .ToMethod(c => new FactoryNested<TParam1, TParam2, TParam3, TContract, TConcrete>( c.Container.Resolve<IFactory<TParam1, TParam2, TParam3, TConcrete>>())); } public BindingConditionSetter ToCustomFactory<TFactory>() where TFactory : IFactory<TParam1, TParam2, TParam3, TContract> { return _container.Bind<IFactory<TParam1, TParam2, TParam3, TContract>>(_identifier).ToTransient<TFactory>(); } public BindingConditionSetter ToCustomFactory<TConcrete, TFactory>() where TFactory : IFactory<TParam1, TParam2, TParam3, TConcrete> where TConcrete : TContract { return _container.Bind<IFactory<TParam1, TParam2, TParam3, TContract>>(_identifier) .ToMethod(c => new FactoryNested<TParam1, TParam2, TParam3, TContract, TConcrete>( c.Container.Instantiate<TFactory>())); } #if !ZEN_NOT_UNITY3D public BindingConditionSetter ToPrefab(GameObject prefab) { Assert.That(typeof(TContract).DerivesFrom<Component>()); if (prefab == null) { throw new ZenjectBindException( "Null prefab provided to BindIFactory<{0}>().ToPrefab".Fmt(typeof(TContract).Name())); } return _container.Bind<IFactory<TParam1, TParam2, TParam3, TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<GameObjectFactory<TParam1, TParam2, TParam3, TContract>>(prefab)); } #endif } ////////////////////////////// Four parameters ////////////////////////////// [System.Diagnostics.DebuggerStepThrough] public class IFactoryBinder<TParam1, TParam2, TParam3, TParam4, TContract> { readonly DiContainer _container; readonly string _identifier; public IFactoryBinder(DiContainer container, string identifier) { _container = container; _identifier = identifier; } public BindingConditionSetter ToMethod( Func<DiContainer, TParam1, TParam2, TParam3, TParam4, TContract> method) { return _container.Bind<IFactory<TParam1, TParam2, TParam3, TParam4, TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<FactoryMethod<TParam1, TParam2, TParam3, TParam4, TContract>>(method)); } public BindingConditionSetter ToFactory() { Assert.That(!typeof(TContract).IsAbstract); return _container.Bind<IFactory<TParam1, TParam2, TParam3, TParam4, TContract>>(_identifier) .ToTransient<Factory<TParam1, TParam2, TParam3, TParam4, TContract>>(); } public BindingConditionSetter ToFactory<TConcrete>() where TConcrete : TContract { return ToCustomFactory<TConcrete, Factory<TParam1, TParam2, TParam3, TParam4, TConcrete>>(); } // Note that we assume here that IFactory<TConcrete> is bound somewhere else public BindingConditionSetter ToIFactory<TConcrete>() where TConcrete : TContract { return _container.Bind<IFactory<TParam1, TParam2, TParam3, TParam4, TContract>>(_identifier) .ToMethod(c => new FactoryNested<TParam1, TParam2, TParam3, TParam4, TContract, TConcrete>( c.Container.Resolve<IFactory<TParam1, TParam2, TParam3, TParam4, TConcrete>>())); } public BindingConditionSetter ToCustomFactory<TFactory>() where TFactory : IFactory<TParam1, TParam2, TParam3, TParam4, TContract> { return _container.Bind<IFactory<TParam1, TParam2, TParam3, TParam4, TContract>>(_identifier).ToTransient<TFactory>(); } public BindingConditionSetter ToCustomFactory<TConcrete, TFactory>() where TFactory : IFactory<TParam1, TParam2, TParam3, TParam4, TConcrete> where TConcrete : TContract { return _container.Bind<IFactory<TParam1, TParam2, TParam3, TParam4, TContract>>(_identifier) .ToMethod(c => new FactoryNested<TParam1, TParam2, TParam3, TParam4, TContract, TConcrete>( c.Container.Instantiate<TFactory>())); } #if !ZEN_NOT_UNITY3D public BindingConditionSetter ToPrefab(GameObject prefab) { Assert.That(typeof(TContract).DerivesFrom<Component>()); if (prefab == null) { throw new ZenjectBindException( "Null prefab provided to BindIFactory<{0}>().ToPrefab".Fmt(typeof(TContract).Name())); } return _container.Bind<IFactory<TParam1, TParam2, TParam3, TParam4, TContract>>(_identifier) .ToMethod((ctx) => ctx.Container.Instantiate<GameObjectFactory<TParam1, TParam2, TParam3, TParam4, TContract>>(prefab)); } #endif } }
// 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.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Encryption.Des.Tests { public static class DesCipherTests { // These are the expected output of many decryptions. Changing these values requires re-generating test input. private static readonly string s_multiBlockString = new ASCIIEncoding().GetBytes( "This is a sentence that is longer than a block, it ensures that multi-block functions work.").ByteArrayToHex(); private static readonly string s_multiBlockStringPaddedZeros = "5468697320697320612073656E74656E63652074686174206973206C6F6E676572207468616E206120626C6F636B2C20" + "697420656E73757265732074686174206D756C74692D626C6F636B2066756E6374696F6E7320776F726B2E0000000000"; private static readonly string s_multiBlockString_8 = new ASCIIEncoding().GetBytes( "This is a sentence that is longer than a block,but exactly an even block multiplier of 8").ByteArrayToHex(); private static readonly string s_randomKey_64 = "87FF0737F868378F"; private static readonly string s_randomIv_64 = "E531E789E3E1BB6F"; public static IEnumerable<object[]> DesTestData { get { // FIPS81 ECB with plaintext "Now is the time for all " yield return new object[] { CipherMode.ECB, PaddingMode.None, "0123456789abcdef", null, "4e6f77206973207468652074696d6520666f7220616c6c20", null, "3fa40e8a984d48156a271787ab8883f9893d51ec4b563b53" }; yield return new object[] { CipherMode.ECB, PaddingMode.None, s_randomKey_64, null, s_multiBlockString_8, null, "4E42A439ED50C7998CD626B8BE1ECC0A82B985EA772030E87C96BFAE1B97A7666505B8AE96745DE2921F6868897C20F2" + "BC8C7B284FD1E9A0A2E49DDAB7A3978233423377C88177CB2D92475EE4DC1FF9E6DFA135DE648E1B" }; yield return new object[] { CipherMode.ECB, PaddingMode.PKCS7, s_randomKey_64, null, s_multiBlockString, null, "4E42A439ED50C7998CD626B8BE1ECC0A82B985EA772030E87C96BFAE1B97A7666505B8AE96745DE249C1EC3338BBAD41" + "93A9B792205F345E22D45A9A996F21CE24697E5A45F600E8C6E71FC7114A3E96EC4EACC9F652DEBC679D22DE7141F67F" }; yield return new object[] { CipherMode.ECB, PaddingMode.Zeros, s_randomKey_64, null, s_multiBlockString, s_multiBlockStringPaddedZeros, "4E42A439ED50C7998CD626B8BE1ECC0A82B985EA772030E87C96BFAE1B97A7666505B8AE96745DE249C1EC3338BBAD41" + "93A9B792205F345E22D45A9A996F21CE24697E5A45F600E8C6E71FC7114A3E96EC4EACC9F652DEBC471DF9564F29C738" }; // FIPS81 CBC with plaintext "Now is the time for all " yield return new object[] { CipherMode.CBC, PaddingMode.None, "0123456789abcdef", "1234567890abcdef", "4e6f77206973207468652074696d6520666f7220616c6c20", null, "e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6" }; yield return new object[] { CipherMode.CBC, PaddingMode.None, s_randomKey_64, s_randomIv_64, s_multiBlockString_8, null, "7264319AE3C504148CD4A19B4FDC7D2ACCCB0A08D60CBE2B885DCB2C1A86ED9CA51006E33859B03EEB61CF5219D769C1" + "ABF1A1FDE0EF87D3B3C4D567D9C8960DDA55DBE13341928FEF38B938E1F62FAD1D05E355E440E012" }; yield return new object[] { CipherMode.CBC, PaddingMode.Zeros, s_randomKey_64, s_randomIv_64, s_multiBlockString, s_multiBlockStringPaddedZeros, "7264319AE3C504148CD4A19B4FDC7D2ACCCB0A08D60CBE2B885DCB2C1A86ED9CA51006E33859B03E00F5B57801EFF745" + "F7A577842461CF39AC143505EC326233E66343A46FEADE9E8456D8AC6A84A1C32E6792857F062400740CB21A333D334D" }; yield return new object[] { CipherMode.CBC, PaddingMode.PKCS7, s_randomKey_64, s_randomIv_64, s_multiBlockString, null, "7264319AE3C504148CD4A19B4FDC7D2ACCCB0A08D60CBE2B885DCB2C1A86ED9CA51006E33859B03E00F5B57801EFF745" + "F7A577842461CF39AC143505EC326233E66343A46FEADE9E8456D8AC6A84A1C32E6792857F062400EA9053D17AD3C35D" }; } } [Theory, MemberData(nameof(DesTestData))] public static void DesRoundTrip(CipherMode cipherMode, PaddingMode paddingMode, string key, string iv, string textHex, string expectedDecrypted, string expectedEncrypted) { byte[] expectedDecryptedBytes = expectedDecrypted == null ? textHex.HexToByteArray() : expectedDecrypted.HexToByteArray(); byte[] expectedEncryptedBytes = expectedEncrypted.HexToByteArray(); byte[] keyBytes = key.HexToByteArray(); using (DES alg = DESFactory.Create()) { alg.Key = keyBytes; alg.Padding = paddingMode; alg.Mode = cipherMode; if (iv != null) alg.IV = iv.HexToByteArray(); byte[] cipher = alg.Encrypt(textHex.HexToByteArray()); Assert.Equal<byte>(expectedEncryptedBytes, cipher); byte[] decrypted = alg.Decrypt(cipher); Assert.Equal<byte>(expectedDecryptedBytes, decrypted); } } [Fact] public static void DesReuseEncryptorDecryptor() { using (DES alg = DESFactory.Create()) { alg.Key = s_randomKey_64.HexToByteArray(); alg.IV = s_randomIv_64.HexToByteArray(); alg.Padding = PaddingMode.PKCS7; alg.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = alg.CreateEncryptor()) using (ICryptoTransform decryptor = alg.CreateDecryptor()) { for (int i = 0; i < 2; i++) { byte[] plainText1 = s_multiBlockString.HexToByteArray(); byte[] cipher1 = encryptor.Transform(plainText1); byte[] expectedCipher1 = ( "7264319AE3C504148CD4A19B4FDC7D2ACCCB0A08D60CBE2B885DCB2C1A86ED9CA51006E33859B03E00F5B57801EFF745" + "F7A577842461CF39AC143505EC326233E66343A46FEADE9E8456D8AC6A84A1C32E6792857F062400EA9053D17AD3C35D").HexToByteArray(); Assert.Equal<byte>(expectedCipher1, cipher1); byte[] decrypted1 = decryptor.Transform(cipher1); byte[] expectedDecrypted1 = s_multiBlockString.HexToByteArray(); Assert.Equal<byte>(expectedDecrypted1, decrypted1); byte[] plainText2 = s_multiBlockString_8.HexToByteArray(); byte[] cipher2 = encryptor.Transform(plainText2); byte[] expectedCipher2 = ( "7264319AE3C504148CD4A19B4FDC7D2ACCCB0A08D60CBE2B885DCB2C1A86ED9CA51006E33859B03EEB61CF5219D769C1" + "ABF1A1FDE0EF87D3B3C4D567D9C8960DDA55DBE13341928FEF38B938E1F62FAD1D05E355E440E012A0FFAB00B7AEE64D").HexToByteArray(); Assert.Equal<byte>(expectedCipher2, cipher2); byte[] decrypted2 = decryptor.Transform(cipher2); byte[] expectedDecrypted2 = s_multiBlockString_8.HexToByteArray(); Assert.Equal<byte>(expectedDecrypted2, decrypted2); } } } } [Fact] public static void DesExplicitEncryptorDecryptor_WithIV() { using (DES alg = DESFactory.Create()) { alg.Padding = PaddingMode.PKCS7; alg.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = alg.CreateEncryptor(s_randomKey_64.HexToByteArray(), s_randomIv_64.HexToByteArray())) { byte[] plainText1 = s_multiBlockString.HexToByteArray(); byte[] cipher1 = encryptor.Transform(plainText1); byte[] expectedCipher1 = ( "7264319AE3C504148CD4A19B4FDC7D2ACCCB0A08D60CBE2B885DCB2C1A86ED9CA51006E33859B03E00F5B57801EFF745" + "F7A577842461CF39AC143505EC326233E66343A46FEADE9E8456D8AC6A84A1C32E6792857F062400EA9053D17AD3C35D").HexToByteArray(); Assert.Equal<byte>(expectedCipher1, cipher1); } } } [Fact] public static void DesExplicitEncryptorDecryptor_NoIV() { using (DES alg = DESFactory.Create()) { alg.Padding = PaddingMode.PKCS7; alg.Mode = CipherMode.ECB; using (ICryptoTransform encryptor = alg.CreateEncryptor(s_randomKey_64.HexToByteArray(), null)) { byte[] plainText1 = s_multiBlockString.HexToByteArray(); byte[] cipher1 = encryptor.Transform(plainText1); byte[] expectedCipher1 = ( "4E42A439ED50C7998CD626B8BE1ECC0A82B985EA772030E87C96BFAE1B97A7666505B8AE96745DE249C1EC3338BBAD41" + "93A9B792205F345E22D45A9A996F21CE24697E5A45F600E8C6E71FC7114A3E96EC4EACC9F652DEBC679D22DE7141F67F").HexToByteArray(); Assert.Equal<byte>(expectedCipher1, cipher1); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.Serialization.Json { using System.Runtime.Serialization; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Text; using System.Xml; using System.Collections; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Globalization; using System.Reflection; using System.Security; public sealed class DataContractJsonSerializer { private const char BACK_SLASH = '\\'; private const char FORWARD_SLASH = '/'; private const char HIGH_SURROGATE_START = (char)0xd800; private const char LOW_SURROGATE_END = (char)0xdfff; private const char MAX_CHAR = (char)0xfffe; private const char WHITESPACE = ' '; internal IList<Type> knownTypeList; internal DataContractDictionary knownDataContracts; private EmitTypeInformation _emitTypeInformation; private ReadOnlyCollection<Type> _knownTypeCollection; private int _maxItemsInObjectGraph; private bool _serializeReadOnlyTypes; private DateTimeFormat _dateTimeFormat; private bool _useSimpleDictionaryFormat; private DataContractJsonSerializerImpl _serializer; public DataContractJsonSerializer(Type type) { _serializer = new DataContractJsonSerializerImpl(type); } public DataContractJsonSerializer(Type type, IEnumerable<Type> knownTypes) { _serializer = new DataContractJsonSerializerImpl(type, knownTypes); } public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings) { _serializer = new DataContractJsonSerializerImpl(type, settings); } public ReadOnlyCollection<Type> KnownTypes { get { if (_knownTypeCollection == null) { if (knownTypeList != null) { _knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList); } else { _knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>()); } } return _knownTypeCollection; } } internal DataContractDictionary KnownDataContracts { get { if (this.knownDataContracts == null && this.knownTypeList != null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of // data contracts will be created and re-assigned to this field. Introduction // of a lock here could lead to deadlocks. this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList); } return this.knownDataContracts; } } public int MaxItemsInObjectGraph { get { return _maxItemsInObjectGraph; } } internal bool AlwaysEmitTypeInformation { get { return _emitTypeInformation == EmitTypeInformation.Always; } } public DateTimeFormat DateTimeFormat { get { return _dateTimeFormat; } } public EmitTypeInformation EmitTypeInformation { get { return _emitTypeInformation; } } public bool SerializeReadOnlyTypes { get { return _serializeReadOnlyTypes; } } public bool UseSimpleDictionaryFormat { get { return _useSimpleDictionaryFormat; } } internal static void CheckIfTypeIsReference(DataContract dataContract) { if (dataContract.IsReference) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException(SR.Format( SR.JsonUnsupportedForIsReference, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.IsReference))); } } internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) { DataContract contract = DataContractSerializer.GetDataContract(declaredTypeContract, declaredType, objectType); CheckIfTypeIsReference(contract); return contract; } public void WriteObject(Stream stream, object graph) { _serializer.WriteObject(stream, graph); } internal object ConvertDataContractToObject(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context, bool writeServerType, RuntimeTypeHandle declaredTypeHandle) { if (context != null) { context.OnHandleReference(null /*XmlWriter*/, value, true); // canContainReferences } try { if (contract is ObjectDataContract) { Type valueType = value.GetType(); if (valueType != Globals.TypeOfObject) return ConvertDataContractToObject(value, DataContract.GetDataContract(valueType), context, true, contract.UnderlyingType.TypeHandle); else return value; } else if (contract is TimeSpanDataContract) { return XmlConvert.ToString((TimeSpan)value); } else if (contract is QNameDataContract) { XmlQualifiedName qname = (XmlQualifiedName)value; return (qname.IsEmpty) ? string.Empty : (qname.Name + ":" + qname.Namespace); } else if (contract is PrimitiveDataContract) { return value; } else if (contract is CollectionDataContract) { CollectionDataContract collectionContract = contract as CollectionDataContract; switch (collectionContract.Kind) { case CollectionKind.GenericDictionary: case CollectionKind.Dictionary: return DataContractToObjectConverter.ConvertGenericDictionaryToArray(this, (IEnumerable)value, collectionContract, context, writeServerType); default: return DataContractToObjectConverter.ConvertGenericListToArray(this, (IEnumerable)value, collectionContract, context, writeServerType); } } else if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (Globals.TypeOfScriptObject_IsAssignableFrom(classContract.UnderlyingType)) { return ConvertScriptObjectToObject(value); } return DataContractToObjectConverter.ConvertClassDataContractToDictionary(this, (ClassDataContract)contract, value, context, writeServerType); } else if (contract is EnumDataContract) { if (((EnumDataContract)contract).IsULong) return Convert.ToUInt64(value, null); else return Convert.ToInt64(value, null); } else if (contract is XmlDataContract) { DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle), GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList)); MemoryStream memoryStream = new MemoryStream(); dataContractSerializer.WriteObject(memoryStream, value); memoryStream.Position = 0; return new StreamReader(memoryStream, Encoding.UTF8).ReadToEnd(); } } finally { if (context != null) { context.OnEndHandleReference(null /*XmlWriter*/, value, true); // canContainReferences } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownDataContract, contract.Name))); } private object ConvertScriptObjectToObject(object value) { string jsonValue = Globals.ScriptObjectJsonSerialize(value); using (MemoryStream jsonStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonValue))) { JavaScriptDeserializer jsDeserializer = new JavaScriptDeserializer(jsonStream); return jsDeserializer.DeserializeObject(); } } public object ReadObject(Stream stream) { return _serializer.ReadObject(stream); } private object ConvertObjectToPrimitiveDataContract(DataContract contract, object value, XmlObjectSerializerReadContextComplexJson context) { // Taking the right deserialized value for datetime string based on contract information var tuple = value as Tuple<DateTime, string>; if (tuple != null) { if (contract is StringDataContract || contract.UnderlyingType == typeof(object)) { value = tuple.Item2; } else { value = tuple.Item1; } } if (contract is TimeSpanDataContract) { return XmlConvert.ToTimeSpan(String.Format(CultureInfo.InvariantCulture, "{0}", value)); } else if (contract is ByteArrayDataContract) { return ObjectToDataContractConverter.ConvertToArray(typeof(Byte), (IList)value); } else if (contract is GuidDataContract) { return new Guid(String.Format(CultureInfo.InvariantCulture, "{0}", value)); } else if (contract is ObjectDataContract) { if (value is ICollection) { return ConvertObjectToDataContract(DataContract.GetDataContract(Globals.TypeOfObjectArray), value, context); } return TryParseJsonNumber(value); } else if (contract is QNameDataContract) { return XmlObjectSerializerReadContextComplexJson.ParseQualifiedName(value.ToString()); } else if (contract is StringDataContract) { if (value is bool) { return ((bool)value) ? Globals.True : Globals.False; } return value.ToString(); } else if (contract is UriDataContract) { return new Uri(value.ToString(), UriKind.RelativeOrAbsolute); } else if (contract is DoubleDataContract) { if (value is float) { return (double)(float)value; } if (value is double) { return (double)value; } return double.Parse(String.Format(CultureInfo.InvariantCulture, "{0}", value), NumberStyles.Float, CultureInfo.InvariantCulture); } else if (contract is DecimalDataContract) { return decimal.Parse(String.Format(CultureInfo.InvariantCulture, "{0}", value), NumberStyles.Float, CultureInfo.InvariantCulture); } return Convert.ChangeType(value, contract.UnderlyingType, CultureInfo.InvariantCulture); } internal object ConvertObjectToDataContract(DataContract contract, object value, XmlObjectSerializerReadContextComplexJson context) { if (value == null) { return value; } else if (contract is PrimitiveDataContract) { return ConvertObjectToPrimitiveDataContract(contract, value, context); } else if (contract is CollectionDataContract) { return ObjectToDataContractConverter.ConvertICollectionToCollectionDataContract(this, (CollectionDataContract)contract, value, context); } else if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (Globals.TypeOfScriptObject_IsAssignableFrom(classContract.UnderlyingType)) { return ConvertObjectToScriptObject(value); } return ObjectToDataContractConverter.ConvertDictionaryToClassDataContract(this, classContract, (Dictionary<string, object>)value, context); } else if (contract is EnumDataContract) { return Enum.ToObject(contract.UnderlyingType, ((EnumDataContract)contract).IsULong ? ulong.Parse(String.Format(CultureInfo.InvariantCulture, "{0}", value), NumberStyles.Float, NumberFormatInfo.InvariantInfo) : value); } else if (contract is XmlDataContract) { DataContractSerializer dataContractSerializer = new DataContractSerializer(contract.UnderlyingType, GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList)); MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes((string)value)); return dataContractSerializer.ReadObject(XmlDictionaryReader.CreateTextReader(memoryStream, XmlDictionaryReaderQuotas.Max)); } return value; } private object ConvertObjectToScriptObject(object deserialzedValue) { MemoryStream memStream = new MemoryStream(); JavaScriptSerializer jsSerializer = new JavaScriptSerializer(memStream); jsSerializer.SerializeObject(deserialzedValue); memStream.Flush(); memStream.Position = 0; return Globals.ScriptObjectJsonDeserialize(new StreamReader(memStream).ReadToEnd()); } private object TryParseJsonNumber(object value) { string input = value as string; if (input != null && input.IndexOfAny(JsonGlobals.FloatingPointCharacters) >= 0) { return JavaScriptObjectDeserializer.ParseJsonNumberAsDoubleOrDecimal(input); } return value; } private List<Type> GetKnownTypesFromContext(XmlObjectSerializerContext context, IList<Type> serializerKnownTypeList) { List<Type> knownTypesList = new List<Type>(); if (context != null) { List<XmlQualifiedName> stableNames = new List<XmlQualifiedName>(); Dictionary<XmlQualifiedName, DataContract>[] entries = context.scopedKnownTypes.dataContractDictionaries; if (entries != null) { for (int i = 0; i < entries.Length; i++) { Dictionary<XmlQualifiedName, DataContract> entry = entries[i]; if (entry != null) { foreach (KeyValuePair<XmlQualifiedName, DataContract> pair in entry) { if (!stableNames.Contains(pair.Key)) { stableNames.Add(pair.Key); knownTypesList.Add(pair.Value.UnderlyingType); } } } } } if (serializerKnownTypeList != null) { knownTypesList.AddRange(serializerKnownTypeList); } } return knownTypesList; } static internal void InvokeOnSerializing(Object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context) { if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (classContract.BaseContract != null) InvokeOnSerializing(value, classContract.BaseContract, context); if (classContract.OnSerializing != null) { bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try { classContract.OnSerializing.Invoke(value, new object[] { context.GetStreamingContext() }); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } catch (TargetInvocationException targetInvocationException) { if (targetInvocationException.InnerException == null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers throw targetInvocationException.InnerException; } } } } static internal void InvokeOnSerialized(Object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context) { if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (classContract.BaseContract != null) InvokeOnSerialized(value, classContract.BaseContract, context); if (classContract.OnSerialized != null) { bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try { classContract.OnSerialized.Invoke(value, new object[] { context.GetStreamingContext() }); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } catch (TargetInvocationException targetInvocationException) { if (targetInvocationException.InnerException == null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers throw targetInvocationException.InnerException; } } } } static internal void InvokeOnDeserializing(Object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context) { if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (classContract.BaseContract != null) InvokeOnDeserializing(value, classContract.BaseContract, context); if (classContract.OnDeserializing != null) { bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { classContract.OnDeserializing.Invoke(value, new object[] { context.GetStreamingContext() }); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForRead(securityException); } else { throw; } } catch (TargetInvocationException targetInvocationException) { if (targetInvocationException.InnerException == null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers throw targetInvocationException.InnerException; } } } } static internal void InvokeOnDeserialized(object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context) { if (contract is ClassDataContract) { ClassDataContract classContract = contract as ClassDataContract; if (classContract.BaseContract != null) InvokeOnDeserialized(value, classContract.BaseContract, context); if (classContract.OnDeserialized != null) { bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { classContract.OnDeserialized.Invoke(value, new object[] { context.GetStreamingContext() }); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForRead(securityException); } else { throw; } } catch (TargetInvocationException targetInvocationException) { if (targetInvocationException.InnerException == null) throw; //We are catching the TIE here and throws the inner exception only, //this is needed to have a consistent exception story in all serializers throw targetInvocationException.InnerException; } } } } internal static bool CharacterNeedsEscaping(char ch) { return (ch == FORWARD_SLASH || ch == JsonGlobals.QuoteChar || ch < WHITESPACE || ch == BACK_SLASH || (ch >= HIGH_SURROGATE_START && (ch <= LOW_SURROGATE_END || ch >= MAX_CHAR))); } internal static bool CheckIfJsonNameRequiresMapping(string jsonName) { if (jsonName != null) { if (!DataContract.IsValidNCName(jsonName)) { return true; } for (int i = 0; i < jsonName.Length; i++) { if (CharacterNeedsEscaping(jsonName[i])) { return true; } } } return false; } internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName) { return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value); } internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString name, XmlDictionaryString ns, DataContract contract) { if (name == null) return false; if (contract.IsBuiltInDataContract || !contract.CanContainReferences) return false; string contractNs = XmlDictionaryString.GetString(contract.Namespace); if (string.IsNullOrEmpty(contractNs) || contractNs == XmlDictionaryString.GetString(ns)) return false; return true; } internal static void CheckNull(object obj, string name) { if (obj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(name)); } internal static string ConvertXmlNameToJsonName(string xmlName) { return XmlConvert.DecodeName(xmlName); } internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName) { return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); } internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context) { return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context); } internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { contract.WriteJsonValue(writer, graph, context, declaredTypeHandle); } } internal sealed class DataContractJsonSerializerImpl : XmlObjectSerializer { internal IList<Type> knownTypeList; internal DataContractDictionary knownDataContracts; private EmitTypeInformation _emitTypeInformation; private bool _ignoreExtensionDataObject; private ReadOnlyCollection<Type> _knownTypeCollection; private int _maxItemsInObjectGraph; private DataContract _rootContract; // post-surrogate private XmlDictionaryString _rootName; private bool _rootNameRequiresMapping; private Type _rootType; private bool _serializeReadOnlyTypes; private DateTimeFormat _dateTimeFormat; private bool _useSimpleDictionaryFormat; public DataContractJsonSerializerImpl(Type type) : this(type, (IEnumerable<Type>)null) { } public DataContractJsonSerializerImpl(Type type, IEnumerable<Type> knownTypes) : this(type, knownTypes, int.MaxValue, false, false) { } internal DataContractJsonSerializerImpl(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool alwaysEmitTypeInformation) { EmitTypeInformation emitTypeInformation = alwaysEmitTypeInformation ? EmitTypeInformation.Always : EmitTypeInformation.AsNeeded; Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, false, null, false); } public DataContractJsonSerializerImpl(Type type, DataContractJsonSerializerSettings settings) { if (settings == null) { settings = new DataContractJsonSerializerSettings(); } XmlDictionaryString rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName); Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.EmitTypeInformation, settings.SerializeReadOnlyTypes, settings.DateTimeFormat, settings.UseSimpleDictionaryFormat); } public ReadOnlyCollection<Type> KnownTypes { get { if (_knownTypeCollection == null) { if (knownTypeList != null) { _knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList); } else { _knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>()); } } return _knownTypeCollection; } } internal override DataContractDictionary KnownDataContracts { get { if (this.knownDataContracts == null && this.knownTypeList != null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of // data contracts will be created and re-assigned to this field. Introduction // of a lock here could lead to deadlocks. this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList); } return this.knownDataContracts; } } internal int MaxItemsInObjectGraph { get { return _maxItemsInObjectGraph; } } internal bool AlwaysEmitTypeInformation { get { return _emitTypeInformation == EmitTypeInformation.Always; } } public EmitTypeInformation EmitTypeInformation { get { return _emitTypeInformation; } } public bool SerializeReadOnlyTypes { get { return _serializeReadOnlyTypes; } } public DateTimeFormat DateTimeFormat { get { return _dateTimeFormat; } } public bool UseSimpleDictionaryFormat { get { return _useSimpleDictionaryFormat; } } private DataContract RootContract { get { if (_rootContract == null) { _rootContract = DataContract.GetDataContract(_rootType); CheckIfTypeIsReference(_rootContract); } return _rootContract; } } private XmlDictionaryString RootName { get { return _rootName ?? JsonGlobals.rootDictionaryString; } } public override bool IsStartObject(XmlReader reader) { // No need to pass in DateTimeFormat to JsonReaderDelegator: no DateTimes will be read in IsStartObject return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader)); } public override bool IsStartObject(XmlDictionaryReader reader) { // No need to pass in DateTimeFormat to JsonReaderDelegator: no DateTimes will be read in IsStartObject return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader)); } public override object ReadObject(Stream stream) { CheckNull(stream, "stream"); return ReadObject(JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max)); } public override object ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName); } public override object ReadObject(XmlDictionaryReader reader) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true); // verifyObjectName } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName); } public override void WriteEndObject(XmlWriter writer) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in end object WriteEndObjectHandleExceptions(new JsonWriterDelegator(writer)); } public override void WriteEndObject(XmlDictionaryWriter writer) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in end object WriteEndObjectHandleExceptions(new JsonWriterDelegator(writer)); } public override void WriteObject(Stream stream, object graph) { CheckNull(stream, "stream"); XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, false); // ownsStream WriteObject(jsonWriter, graph); jsonWriter.Flush(); } public override void WriteObject(XmlWriter writer, object graph) { WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } public override void WriteObject(XmlDictionaryWriter writer, object graph) { WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } public override void WriteStartObject(XmlWriter writer, object graph) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph); } internal static bool CheckIfJsonNameRequiresMapping(string jsonName) { if (jsonName != null) { if (!DataContract.IsValidNCName(jsonName)) { return true; } for (int i = 0; i < jsonName.Length; i++) { if (XmlJsonWriter.CharacterNeedsEscaping(jsonName[i])) { return true; } } } return false; } internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName) { return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value); } internal static bool CheckIfXmlNameRequiresMapping(string xmlName) { return (xmlName == null) ? false : CheckIfJsonNameRequiresMapping(ConvertXmlNameToJsonName(xmlName)); } internal static bool CheckIfXmlNameRequiresMapping(XmlDictionaryString xmlName) { return (xmlName == null) ? false : CheckIfXmlNameRequiresMapping(xmlName.Value); } internal static string ConvertXmlNameToJsonName(string xmlName) { return XmlConvert.DecodeName(xmlName); } internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName) { return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); } internal static bool IsJsonLocalName(XmlReaderDelegator reader, string elementName) { string name; if (XmlObjectSerializerReadContextComplexJson.TryGetJsonLocalName(reader, out name)) { return (elementName == name); } return false; } internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context) { return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context); } internal static void WriteJsonNull(XmlWriterDelegator writer) { writer.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.nullString); // prefix // namespace } internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { contract.WriteJsonValue(writer, graph, context, declaredTypeHandle); } internal override Type GetDeserializeType() { return _rootType; } internal override Type GetSerializeType(object graph) { return (graph == null) ? _rootType : graph.GetType(); } internal override bool InternalIsStartObject(XmlReaderDelegator reader) { if (IsRootElement(reader, RootContract, RootName, XmlDictionaryString.Empty)) { return true; } return IsJsonLocalName(reader, RootName.Value); } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { if (MaxItemsInObjectGraph == 0) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)); } if (verifyObjectName) { if (!InternalIsStartObject(xmlReader)) { throw XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElement, XmlDictionaryString.Empty, RootName), xmlReader); } } else if (!IsStartElement(xmlReader)) { throw XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader); } DataContract contract = RootContract; if (contract.IsPrimitive && object.ReferenceEquals(contract.UnderlyingType, _rootType))// handle Nullable<T> differently { return DataContractJsonSerializerImpl.ReadJsonValue(contract, xmlReader, null); } XmlObjectSerializerReadContextComplexJson context = XmlObjectSerializerReadContextComplexJson.CreateContext(this, contract); return context.InternalDeserialize(xmlReader, _rootType, contract, null, null); } internal override void InternalWriteEndObject(XmlWriterDelegator writer) { writer.WriteEndElement(); } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) { InternalWriteStartObject(writer, graph); InternalWriteObjectContent(writer, graph); InternalWriteEndObject(writer); } internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { if (MaxItemsInObjectGraph == 0) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)); } DataContract contract = RootContract; Type declaredType = contract.UnderlyingType; Type graphType = (graph == null) ? declaredType : graph.GetType(); //if (dataContractSurrogate != null) //{ // graph = DataContractSerializer.SurrogateToDataContractType(dataContractSurrogate, graph, declaredType, ref graphType); //} if (graph == null) { WriteJsonNull(writer); } else { if (declaredType == graphType) { if (contract.CanContainReferences) { XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, contract); context.OnHandleReference(writer, graph, true); // canContainReferences context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle); } else { DataContractJsonSerializerImpl.WriteJsonValue(JsonDataContract.GetJsonDataContract(contract), writer, graph, null, declaredType.TypeHandle); // XmlObjectSerializerWriteContextComplexJson } } else { XmlObjectSerializerWriteContextComplexJson context = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, RootContract); contract = DataContractJsonSerializerImpl.GetDataContract(contract, declaredType, graphType); if (contract.CanContainReferences) { context.OnHandleReference(writer, graph, true); // canContainCyclicReference context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType); } else { context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle); } } } } internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { if (_rootNameRequiresMapping) { writer.WriteStartElement("a", JsonGlobals.itemString, JsonGlobals.itemString); writer.WriteAttributeString(null, JsonGlobals.itemString, null, RootName.Value); } else { writer.WriteStartElement(RootName, XmlDictionaryString.Empty); } } private void AddCollectionItemTypeToKnownTypes(Type knownType) { Type itemType; Type typeToCheck = knownType; while (CollectionDataContract.IsCollection(typeToCheck, out itemType)) { if (itemType.GetTypeInfo().IsGenericType && (itemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue)) { itemType = Globals.TypeOfKeyValuePair.MakeGenericType(itemType.GetTypeInfo().GenericTypeArguments); } this.knownTypeList.Add(itemType); typeToCheck = itemType; } } private void Initialize(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, EmitTypeInformation emitTypeInformation, bool serializeReadOnlyTypes, DateTimeFormat dateTimeFormat, bool useSimpleDictionaryFormat) { CheckNull(type, "type"); _rootType = type; if (knownTypes != null) { this.knownTypeList = new List<Type>(); foreach (Type knownType in knownTypes) { this.knownTypeList.Add(knownType); if (knownType != null) { AddCollectionItemTypeToKnownTypes(knownType); } } } if (maxItemsInObjectGraph < 0) { throw new ArgumentOutOfRangeException("maxItemsInObjectGraph", SR.ValueMustBeNonNegative); } _maxItemsInObjectGraph = maxItemsInObjectGraph; _ignoreExtensionDataObject = ignoreExtensionDataObject; _emitTypeInformation = emitTypeInformation; _serializeReadOnlyTypes = serializeReadOnlyTypes; _dateTimeFormat = dateTimeFormat; _useSimpleDictionaryFormat = useSimpleDictionaryFormat; } private void Initialize(Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, EmitTypeInformation emitTypeInformation, bool serializeReadOnlyTypes, DateTimeFormat dateTimeFormat, bool useSimpleDictionaryFormat) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, serializeReadOnlyTypes, dateTimeFormat, useSimpleDictionaryFormat); _rootName = ConvertXmlNameToJsonName(rootName); _rootNameRequiresMapping = CheckIfJsonNameRequiresMapping(_rootName); } internal static void CheckIfTypeIsReference(DataContract dataContract) { if (dataContract.IsReference) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonUnsupportedForIsReference, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.IsReference)); } } internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) { DataContract contract = DataContractSerializer.GetDataContract(declaredTypeContract, declaredType, objectType); CheckIfTypeIsReference(contract); return contract; } } }
using System; using System.Collections.Generic; using System.IO; using System.Reactive.Disposables; using System.Threading.Tasks; using Avalonia.Automation.Peers; using Avalonia.Controls; using Avalonia.Controls.Platform; using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Input.Raw; using Avalonia.Platform; using Avalonia.Rendering; namespace Avalonia.DesignerSupport.Remote { class WindowStub : IWindowImpl, IPopupImpl { public Action Deactivated { get; set; } public Action Activated { get; set; } public IPlatformHandle Handle { get; } public Size MaxAutoSizeHint { get; } public Size ClientSize { get; } public Size? FrameSize => null; public double RenderScaling { get; } = 1.0; public double DesktopScaling => 1.0; public IEnumerable<object> Surfaces { get; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size, PlatformResizeReason> Resized { get; set; } public Action<double> ScalingChanged { get; set; } public Func<bool> Closing { get; set; } public Action Closed { get; set; } public Action LostFocus { get; set; } public IMouseDevice MouseDevice { get; } = new MouseDevice(); public IPopupImpl CreatePopup() => new WindowStub(this); public PixelPoint Position { get; set; } public Action<PixelPoint> PositionChanged { get; set; } public WindowState WindowState { get; set; } public Action<WindowState> WindowStateChanged { get; set; } public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; } public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; } public Thickness ExtendedMargins { get; } = new Thickness(); public Thickness OffScreenMargin { get; } = new Thickness(); public WindowStub(IWindowImpl parent = null) { if (parent != null) PopupPositioner = new ManagedPopupPositioner(new ManagedPopupPositionerPopupImplHelper(parent, (_, size, __) => { Resize(size, PlatformResizeReason.Unspecified); })); } public IRenderer CreateRenderer(IRenderRoot root) => new ImmediateRenderer(root); public void Dispose() { } public void Invalidate(Rect rect) { } public void SetInputRoot(IInputRoot inputRoot) { } public Point PointToClient(PixelPoint p) => p.ToPoint(1); public PixelPoint PointToScreen(Point p) => PixelPoint.FromPoint(p, 1); public void SetCursor(ICursorImpl cursor) { } public void Show(bool activate, bool isDialog) { } public void Hide() { } public void BeginMoveDrag(PointerPressedEventArgs e) { } public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e) { } public void Activate() { } public void Resize(Size clientSize, PlatformResizeReason reason) { } public void Move(PixelPoint point) { } public IScreenImpl Screen { get; } = new ScreenStub(); public void SetMinMaxSize(Size minSize, Size maxSize) { } public void SetTitle(string title) { } public void ShowDialog(IWindowImpl parent) { } public void SetSystemDecorations(SystemDecorations enabled) { } public void SetIcon(IWindowIconImpl icon) { } public void ShowTaskbarIcon(bool value) { } public void CanResize(bool value) { } public void SetTopmost(bool value) { } public void SetParent(IWindowImpl parent) { } public void SetEnabled(bool enable) { } public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint) { } public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints) { } public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight) { } public IPopupPositioner PopupPositioner { get; } public Action GotInputWhenDisabled { get; set; } public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel) { } public void SetWindowManagerAddShadowHint(bool enabled) { } public WindowTransparencyLevel TransparencyLevel { get; private set; } public bool IsClientAreaExtendedToDecorations { get; } public bool NeedsManagedDecorations => false; public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 1, 1); } class ClipboardStub : IClipboard { public Task<string> GetTextAsync() => Task.FromResult(""); public Task SetTextAsync(string text) => Task.CompletedTask; public Task ClearAsync() => Task.CompletedTask; public Task SetDataObjectAsync(IDataObject data) => Task.CompletedTask; public Task<string[]> GetFormatsAsync() => Task.FromResult(new string[0]); public Task<object> GetDataAsync(string format) => Task.FromResult((object)null); } class CursorFactoryStub : ICursorFactory { public ICursorImpl GetCursor(StandardCursorType cursorType) => new CursorStub(); public ICursorImpl CreateCursor(IBitmapImpl cursor, PixelPoint hotSpot) => new CursorStub(); private class CursorStub : ICursorImpl { public void Dispose() { } } } class IconLoaderStub : IPlatformIconLoader { class IconStub : IWindowIconImpl { public void Save(Stream outputStream) { } } public IWindowIconImpl LoadIcon(string fileName) => new IconStub(); public IWindowIconImpl LoadIcon(Stream stream) => new IconStub(); public IWindowIconImpl LoadIcon(IBitmapImpl bitmap) => new IconStub(); } class SystemDialogsStub : ISystemDialogImpl { public Task<string[]> ShowFileDialogAsync(FileDialog dialog, Window parent) => Task.FromResult((string[])null); public Task<string> ShowFolderDialogAsync(OpenFolderDialog dialog, Window parent) => Task.FromResult((string)null); } class ScreenStub : IScreenImpl { public int ScreenCount => 1; public IReadOnlyList<Screen> AllScreens { get; } = new Screen[] { new Screen(1, new PixelRect(0, 0, 4000, 4000), new PixelRect(0, 0, 4000, 4000), true) }; } }
// 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.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.ParameterInfos; using Internal.Reflection.Core.Execution; namespace System.Reflection.Runtime.MethodInfos { // // These methods implement the Get/Set methods on array types. // internal sealed partial class RuntimeSyntheticMethodInfo : RuntimeMethodInfo { private RuntimeSyntheticMethodInfo(SyntheticMethodId syntheticMethodId, String name, RuntimeTypeInfo declaringType, RuntimeTypeInfo[] parameterTypes, RuntimeTypeInfo returnType, InvokerOptions options, Func<Object, Object[], Object> invoker) { _syntheticMethodId = syntheticMethodId; _name = name; _declaringType = declaringType; _options = options; _invoker = invoker; _runtimeParameterTypes = parameterTypes; _returnType = returnType; } public sealed override MethodAttributes Attributes { get { return MethodAttributes.Public | MethodAttributes.PrivateScope; } } public sealed override CallingConventions CallingConvention { get { return CallingConventions.Standard | CallingConventions.HasThis; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { return Empty<CustomAttributeData>.Enumerable; } } public sealed override bool Equals(Object obj) { RuntimeSyntheticMethodInfo other = obj as RuntimeSyntheticMethodInfo; if (other == null) return false; if (_syntheticMethodId != other._syntheticMethodId) return false; if (!(_declaringType.Equals(other._declaringType))) return false; return true; } public sealed override MethodInfo GetGenericMethodDefinition() { throw new InvalidOperationException(); } public sealed override int GetHashCode() { return _declaringType.GetHashCode(); } public sealed override bool IsGenericMethod { get { return false; } } public sealed override bool IsGenericMethodDefinition { get { return false; } } public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this)); } public sealed override MethodImplAttributes MethodImplementationFlags { get { return MethodImplAttributes.IL; } } public sealed override Module Module { get { return this.DeclaringType.Assembly.ManifestModule; } } public sealed override int MetadataToken { get { throw new InvalidOperationException(SR.NoMetadataTokenAvailable); } } public sealed override Type ReflectedType { get { // The only synthetic methods come from array types which can never be inherited from. So unless that changes, // we don't provide a way to specify the ReflectedType. return DeclaringType; } } public sealed override String ToString() { return RuntimeMethodHelpers.ComputeToString(this, Array.Empty<RuntimeTypeInfo>(), RuntimeParameters, RuntimeReturnParameter); } public sealed override RuntimeMethodHandle MethodHandle { get { throw new PlatformNotSupportedException(); } } protected sealed override MethodInvoker UncachedMethodInvoker { get { RuntimeTypeInfo[] runtimeParameterTypes = _runtimeParameterTypes; RuntimeTypeHandle[] runtimeParameterTypeHandles = new RuntimeTypeHandle[runtimeParameterTypes.Length]; for (int i = 0; i < runtimeParameterTypes.Length; i++) runtimeParameterTypeHandles[i] = runtimeParameterTypes[i].TypeHandle; return ReflectionCoreExecution.ExecutionEnvironment.GetSyntheticMethodInvoker( _declaringType.TypeHandle, runtimeParameterTypeHandles, _options, _invoker); } } internal sealed override RuntimeTypeInfo[] RuntimeGenericArgumentsOrParameters { get { return Array.Empty<RuntimeTypeInfo>(); } } internal sealed override RuntimeTypeInfo RuntimeDeclaringType { get { return _declaringType; } } internal sealed override String RuntimeName { get { return _name; } } internal sealed override RuntimeParameterInfo[] GetRuntimeParameters(RuntimeMethodInfo contextMethod, out RuntimeParameterInfo returnParameter) { RuntimeTypeInfo[] runtimeParameterTypes = _runtimeParameterTypes; RuntimeParameterInfo[] parameters = new RuntimeParameterInfo[runtimeParameterTypes.Length]; for (int i = 0; i < parameters.Length; i++) { parameters[i] = RuntimeSyntheticParameterInfo.GetRuntimeSyntheticParameterInfo(this, i, runtimeParameterTypes[i]); } returnParameter = RuntimeSyntheticParameterInfo.GetRuntimeSyntheticParameterInfo(this, -1, _returnType); return parameters; } private readonly String _name; private readonly SyntheticMethodId _syntheticMethodId; private readonly RuntimeTypeInfo _declaringType; private readonly RuntimeTypeInfo[] _runtimeParameterTypes; private readonly RuntimeTypeInfo _returnType; private readonly InvokerOptions _options; private readonly Func<Object, Object[], Object> _invoker; } }
using NPOI.OpenXml4Net.Util; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; namespace NPOI.OpenXmlFormats.Dml { [Serializable] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=false)] public enum ST_TextAnchoringType { t, ctr, b, just, dist, } [Serializable] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=false)] public enum ST_TextVertOverflowType { overflow, ellipsis, clip, } [Serializable] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=false)] public enum ST_TextHorzOverflowType { overflow, clip, } [Serializable] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=false)] public enum ST_TextVerticalType { horz, vert, vert270, wordArtVert, eaVert, mongolianVert, wordArtVertRtl, } [Serializable] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=false)] public enum ST_TextWrappingType { none, square, } [Serializable] [System.ComponentModel.DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=true)] public class CT_TextListStyle { private CT_TextParagraphProperties defPPrField; private CT_TextParagraphProperties lvl1pPrField; private CT_TextParagraphProperties lvl2pPrField; private CT_TextParagraphProperties lvl3pPrField; private CT_TextParagraphProperties lvl4pPrField; private CT_TextParagraphProperties lvl5pPrField; private CT_TextParagraphProperties lvl6pPrField; private CT_TextParagraphProperties lvl7pPrField; private CT_TextParagraphProperties lvl8pPrField; private CT_TextParagraphProperties lvl9pPrField; private CT_OfficeArtExtensionList extLstField; public static CT_TextListStyle Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) return null; CT_TextListStyle ctObj = new CT_TextListStyle(); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "defPPr") ctObj.defPPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lvl1pPr") ctObj.lvl1pPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lvl2pPr") ctObj.lvl2pPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lvl3pPr") ctObj.lvl3pPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lvl4pPr") ctObj.lvl4pPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lvl5pPr") ctObj.lvl5pPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lvl6pPr") ctObj.lvl6pPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lvl7pPr") ctObj.lvl7pPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lvl8pPr") ctObj.lvl8pPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lvl9pPr") ctObj.lvl9pPr = CT_TextParagraphProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "extLst") ctObj.extLst = CT_OfficeArtExtensionList.Parse(childNode, namespaceManager); } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<a:{0}", nodeName)); sw.Write(">"); if (this.defPPr != null) this.defPPr.Write(sw, "defPPr"); if (this.lvl1pPr != null) this.lvl1pPr.Write(sw, "lvl1pPr"); if (this.lvl2pPr != null) this.lvl2pPr.Write(sw, "lvl2pPr"); if (this.lvl3pPr != null) this.lvl3pPr.Write(sw, "lvl3pPr"); if (this.lvl4pPr != null) this.lvl4pPr.Write(sw, "lvl4pPr"); if (this.lvl5pPr != null) this.lvl5pPr.Write(sw, "lvl5pPr"); if (this.lvl6pPr != null) this.lvl6pPr.Write(sw, "lvl6pPr"); if (this.lvl7pPr != null) this.lvl7pPr.Write(sw, "lvl7pPr"); if (this.lvl8pPr != null) this.lvl8pPr.Write(sw, "lvl8pPr"); if (this.lvl9pPr != null) this.lvl9pPr.Write(sw, "lvl9pPr"); if (this.extLst != null) this.extLst.Write(sw, "extLst"); sw.Write(string.Format("</a:{0}>", nodeName)); } public CT_TextParagraphProperties defPPr { get { return this.defPPrField; } set { this.defPPrField = value; } } public CT_TextParagraphProperties lvl1pPr { get { return this.lvl1pPrField; } set { this.lvl1pPrField = value; } } public CT_TextParagraphProperties lvl2pPr { get { return this.lvl2pPrField; } set { this.lvl2pPrField = value; } } public CT_TextParagraphProperties lvl3pPr { get { return this.lvl3pPrField; } set { this.lvl3pPrField = value; } } public CT_TextParagraphProperties lvl4pPr { get { return this.lvl4pPrField; } set { this.lvl4pPrField = value; } } public CT_TextParagraphProperties lvl5pPr { get { return this.lvl5pPrField; } set { this.lvl5pPrField = value; } } public CT_TextParagraphProperties lvl6pPr { get { return this.lvl6pPrField; } set { this.lvl6pPrField = value; } } public CT_TextParagraphProperties lvl7pPr { get { return this.lvl7pPrField; } set { this.lvl7pPrField = value; } } public CT_TextParagraphProperties lvl8pPr { get { return this.lvl8pPrField; } set { this.lvl8pPrField = value; } } public CT_TextParagraphProperties lvl9pPr { get { return this.lvl9pPrField; } set { this.lvl9pPrField = value; } } public CT_OfficeArtExtensionList extLst { get { return this.extLstField; } set { this.extLstField = value; } } } [Serializable] [System.ComponentModel.DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=true)] public class CT_TextNormalAutofit { private int fontScaleField; private int lnSpcReductionField; public CT_TextNormalAutofit() { this.fontScaleField = 100000; this.lnSpcReductionField = 0; } public static CT_TextNormalAutofit Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) return null; CT_TextNormalAutofit ctObj = new CT_TextNormalAutofit(); ctObj.fontScale = XmlHelper.ReadInt(node.Attributes["fontScale"]); ctObj.lnSpcReduction = XmlHelper.ReadInt(node.Attributes["lnSpcReduction"]); return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<a:{0}", nodeName)); XmlHelper.WriteAttribute(sw, "fontScale", this.fontScale); XmlHelper.WriteAttribute(sw, "lnSpcReduction", this.lnSpcReduction); sw.Write(">"); sw.Write(string.Format("</a:{0}>", nodeName)); } [XmlAttribute] [DefaultValue(100000)] public int fontScale { get { return this.fontScaleField; } set { this.fontScaleField = value; } } [XmlAttribute] [DefaultValue(0)] public int lnSpcReduction { get { return this.lnSpcReductionField; } set { this.lnSpcReductionField = value; } } } [Serializable] [System.ComponentModel.DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=true)] public class CT_TextShapeAutofit { } [Serializable] [System.ComponentModel.DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=true)] public class CT_TextNoAutofit { } [Serializable] [System.ComponentModel.DesignerCategory("code")] [XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)] public class CT_TextBodyProperties { private CT_PresetTextShape prstTxWarpField; private CT_TextNoAutofit noAutofitField; private CT_TextNormalAutofit normAutofitField; private CT_TextShapeAutofit spAutoFitField; private CT_Scene3D scene3dField; private CT_Shape3D sp3dField; private CT_FlatText flatTxField; private CT_OfficeArtExtensionList extLstField; private int rotField; private bool rotFieldSpecified; private bool spcFirstLastParaField; private bool spcFirstLastParaFieldSpecified; private ST_TextVertOverflowType vertOverflowField; private bool vertOverflowFieldSpecified; private ST_TextHorzOverflowType horzOverflowField; private bool horzOverflowFieldSpecified; private ST_TextVerticalType vertField; private bool vertFieldSpecified; private ST_TextWrappingType wrapField; private bool wrapFieldSpecified; private int lInsField; private bool lInsFieldSpecified; private int tInsField; private bool tInsFieldSpecified; private int rInsField; private bool rInsFieldSpecified; private int bInsField; private bool bInsFieldSpecified; private int numColField; private bool numColFieldSpecified; private int spcColField; private bool spcColFieldSpecified; private bool rtlColField; private bool rtlColFieldSpecified; private bool fromWordArtField; private bool fromWordArtFieldSpecified; private ST_TextAnchoringType anchorField; private bool anchorFieldSpecified; private bool anchorCtrField; private bool anchorCtrFieldSpecified; private bool forceAAField; private bool forceAAFieldSpecified; private bool uprightField; private bool compatLnSpcField; private bool compatLnSpcFieldSpecified; public CT_TextBodyProperties() { this.uprightField = false; this.vert = ST_TextVerticalType.horz; this.wrap = ST_TextWrappingType.none; this.spcFirstLastPara = false; } public static CT_TextBodyProperties Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) return null; CT_TextBodyProperties ctObj = new CT_TextBodyProperties(); ctObj.rot = XmlHelper.ReadInt(node.Attributes["rot"]); ctObj.spcFirstLastPara = XmlHelper.ReadBool(node.Attributes["spcFirstLastPara"]); if (node.Attributes["vertOverflow"] != null) ctObj.vertOverflow = (ST_TextVertOverflowType)Enum.Parse(typeof(ST_TextVertOverflowType), node.Attributes["vertOverflow"].Value); if (node.Attributes["horzOverflow"] != null) ctObj.horzOverflow = (ST_TextHorzOverflowType)Enum.Parse(typeof(ST_TextHorzOverflowType), node.Attributes["horzOverflow"].Value); if (node.Attributes["vert"] != null) ctObj.vert = (ST_TextVerticalType)Enum.Parse(typeof(ST_TextVerticalType), node.Attributes["vert"].Value); if (node.Attributes["wrap"] != null) ctObj.wrap = (ST_TextWrappingType)Enum.Parse(typeof(ST_TextWrappingType), node.Attributes["wrap"].Value); ctObj.lIns = XmlHelper.ReadInt(node.Attributes["lIns"]); ctObj.tIns = XmlHelper.ReadInt(node.Attributes["tIns"]); ctObj.rIns = XmlHelper.ReadInt(node.Attributes["rIns"]); ctObj.bIns = XmlHelper.ReadInt(node.Attributes["bIns"]); ctObj.numCol = XmlHelper.ReadInt(node.Attributes["numCol"]); ctObj.spcCol = XmlHelper.ReadInt(node.Attributes["spcCol"]); ctObj.rtlCol = XmlHelper.ReadBool(node.Attributes["rtlCol"]); ctObj.fromWordArt = XmlHelper.ReadBool(node.Attributes["fromWordArt"]); if (node.Attributes["anchor"] != null) ctObj.anchor = (ST_TextAnchoringType)Enum.Parse(typeof(ST_TextAnchoringType), node.Attributes["anchor"].Value); ctObj.anchorCtr = XmlHelper.ReadBool(node.Attributes["anchorCtr"]); ctObj.forceAA = XmlHelper.ReadBool(node.Attributes["forceAA"]); ctObj.upright = XmlHelper.ReadBool(node.Attributes["upright"]); ctObj.compatLnSpc = XmlHelper.ReadBool(node.Attributes["compatLnSpc"]); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "prstTxWarp") ctObj.prstTxWarp = CT_PresetTextShape.Parse(childNode, namespaceManager); else if (childNode.LocalName == "noAutofit") ctObj.noAutofit = new CT_TextNoAutofit(); else if (childNode.LocalName == "normAutofit") ctObj.normAutofit = CT_TextNormalAutofit.Parse(childNode, namespaceManager); else if (childNode.LocalName == "spAutoFit") ctObj.spAutoFit = new CT_TextShapeAutofit(); else if (childNode.LocalName == "scene3d") ctObj.scene3d = CT_Scene3D.Parse(childNode, namespaceManager); else if (childNode.LocalName == "sp3d") ctObj.sp3d = CT_Shape3D.Parse(childNode, namespaceManager); else if (childNode.LocalName == "flatTx") ctObj.flatTx = CT_FlatText.Parse(childNode, namespaceManager); else if (childNode.LocalName == "extLst") ctObj.extLst = CT_OfficeArtExtensionList.Parse(childNode, namespaceManager); } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<a:{0}", nodeName)); XmlHelper.WriteAttribute(sw, "rot", this.rot); if(spcFirstLastPara) XmlHelper.WriteAttribute(sw, "spcFirstLastPara", this.spcFirstLastPara); XmlHelper.WriteAttribute(sw, "vertOverflow", this.vertOverflow.ToString()); XmlHelper.WriteAttribute(sw, "horzOverflow", this.horzOverflow.ToString()); if(this.vert!= ST_TextVerticalType.horz) XmlHelper.WriteAttribute(sw, "vert", this.vert.ToString()); if(this.wrap!= ST_TextWrappingType.none) XmlHelper.WriteAttribute(sw, "wrap", this.wrap.ToString()); XmlHelper.WriteAttribute(sw, "lIns", this.lIns,true); XmlHelper.WriteAttribute(sw, "tIns", this.tIns, true); XmlHelper.WriteAttribute(sw, "rIns", this.rIns, true); XmlHelper.WriteAttribute(sw, "bIns", this.bIns, true); XmlHelper.WriteAttribute(sw, "numCol", this.numCol); XmlHelper.WriteAttribute(sw, "spcCol", this.spcCol); XmlHelper.WriteAttribute(sw, "rtlCol", this.rtlCol); XmlHelper.WriteAttribute(sw, "fromWordArt", this.fromWordArt, false); XmlHelper.WriteAttribute(sw, "anchor", this.anchor.ToString()); XmlHelper.WriteAttribute(sw, "anchorCtr", this.anchorCtr, false); XmlHelper.WriteAttribute(sw, "forceAA", this.forceAA, false); if(upright) XmlHelper.WriteAttribute(sw, "upright", this.upright); if (compatLnSpc) XmlHelper.WriteAttribute(sw, "compatLnSpc", this.compatLnSpc); sw.Write(">"); if (this.prstTxWarp != null) this.prstTxWarp.Write(sw, "prstTxWarp"); if (this.noAutofit != null) sw.Write("<a:noAutofit/>"); if (this.normAutofit != null) this.normAutofit.Write(sw, "normAutofit"); if (this.spAutoFit != null) sw.Write("<a:spAutoFit/>"); if (this.scene3d != null) this.scene3d.Write(sw, "scene3d"); if (this.sp3d != null) this.sp3d.Write(sw, "sp3d"); if (this.flatTx != null) this.flatTx.Write(sw, "flatTx"); if (this.extLst != null) this.extLst.Write(sw, "extLst"); sw.Write(string.Format("</a:{0}>", nodeName)); } public CT_PresetTextShape prstTxWarp { get { return this.prstTxWarpField; } set { this.prstTxWarpField = value; } } public CT_TextNoAutofit noAutofit { get { return this.noAutofitField; } set { this.noAutofitField = value; } } public CT_TextNormalAutofit normAutofit { get { return this.normAutofitField; } set { this.normAutofitField = value; } } public CT_TextShapeAutofit spAutoFit { get { return this.spAutoFitField; } set { this.spAutoFitField = value; } } public CT_Scene3D scene3d { get { return this.scene3dField; } set { this.scene3dField = value; } } public CT_Shape3D sp3d { get { return this.sp3dField; } set { this.sp3dField = value; } } public CT_FlatText flatTx { get { return this.flatTxField; } set { this.flatTxField = value; } } public CT_OfficeArtExtensionList extLst { get { return this.extLstField; } set { this.extLstField = value; } } [XmlAttribute] public int rot { get { return this.rotField; } set { this.rotField = value; } } [XmlIgnore] public bool rotSpecified { get { return this.rotFieldSpecified; } set { this.rotFieldSpecified = value; } } [XmlAttribute] public bool spcFirstLastPara { get { return this.spcFirstLastParaField; } set { this.spcFirstLastParaField = value; } } [XmlIgnore] public bool spcFirstLastParaSpecified { get { return this.spcFirstLastParaFieldSpecified; } set { this.spcFirstLastParaFieldSpecified = value; } } [XmlAttribute] public ST_TextVertOverflowType vertOverflow { get { return this.vertOverflowField; } set { this.vertOverflowField = value; } } [XmlIgnore] public bool vertOverflowSpecified { get { return this.vertOverflowFieldSpecified; } set { this.vertOverflowFieldSpecified = value; } } [XmlAttribute] public ST_TextHorzOverflowType horzOverflow { get { return this.horzOverflowField; } set { this.horzOverflowField = value; } } [XmlIgnore] public bool horzOverflowSpecified { get { return this.horzOverflowFieldSpecified; } set { this.horzOverflowFieldSpecified = value; } } [XmlAttribute] public ST_TextVerticalType vert { get { return this.vertField; } set { this.vertField = value; } } [XmlIgnore] public bool vertSpecified { get { return this.vertFieldSpecified; } set { this.vertFieldSpecified = value; } } [XmlAttribute] public ST_TextWrappingType wrap { get { return this.wrapField; } set { this.wrapField = value; } } [XmlIgnore] public bool wrapSpecified { get { return this.wrapFieldSpecified; } set { this.wrapFieldSpecified = value; } } [XmlAttribute] public int lIns { get { return this.lInsField; } set { this.lInsField = value; } } [XmlIgnore] public bool lInsSpecified { get { return this.lInsFieldSpecified; } set { this.lInsFieldSpecified = value; } } [XmlAttribute] public int tIns { get { return this.tInsField; } set { this.tInsField = value; } } [XmlIgnore] public bool tInsSpecified { get { return this.tInsFieldSpecified; } set { this.tInsFieldSpecified = value; } } [XmlAttribute] public int rIns { get { return this.rInsField; } set { this.rInsField = value; } } [XmlIgnore] public bool rInsSpecified { get { return this.rInsFieldSpecified; } set { this.rInsFieldSpecified = value; } } [XmlAttribute] public int bIns { get { return this.bInsField; } set { this.bInsField = value; } } [XmlIgnore] public bool bInsSpecified { get { return this.bInsFieldSpecified; } set { this.bInsFieldSpecified = value; } } [XmlAttribute] public int numCol { get { return this.numColField; } set { this.numColField = value; } } [XmlIgnore] public bool numColSpecified { get { return this.numColFieldSpecified; } set { this.numColFieldSpecified = value; } } [XmlAttribute] public int spcCol { get { return this.spcColField; } set { this.spcColField = value; } } [XmlIgnore] public bool spcColSpecified { get { return this.spcColFieldSpecified; } set { this.spcColFieldSpecified = value; } } [XmlAttribute] public bool rtlCol { get { return this.rtlColField; } set { this.rtlColField = value; } } [XmlIgnore] public bool rtlColSpecified { get { return this.rtlColFieldSpecified; } set { this.rtlColFieldSpecified = value; } } [XmlAttribute] public bool fromWordArt { get { return this.fromWordArtField; } set { this.fromWordArtField = value; } } [XmlIgnore] public bool fromWordArtSpecified { get { return this.fromWordArtFieldSpecified; } set { this.fromWordArtFieldSpecified = value; } } [XmlAttribute] public ST_TextAnchoringType anchor { get { return this.anchorField; } set { this.anchorField = value; } } [XmlIgnore] public bool anchorSpecified { get { return this.anchorFieldSpecified; } set { this.anchorFieldSpecified = value; } } [XmlAttribute] public bool anchorCtr { get { return this.anchorCtrField; } set { this.anchorCtrField = value; } } [XmlIgnore] public bool anchorCtrSpecified { get { return this.anchorCtrFieldSpecified; } set { this.anchorCtrFieldSpecified = value; } } [XmlAttribute] public bool forceAA { get { return this.forceAAField; } set { this.forceAAField = value; } } [XmlIgnore] public bool forceAASpecified { get { return this.forceAAFieldSpecified; } set { this.forceAAFieldSpecified = value; } } [XmlAttribute] [DefaultValue(false)] public bool upright { get { return this.uprightField; } set { this.uprightField = value; } } [XmlAttribute] public bool compatLnSpc { get { return this.compatLnSpcField; } set { this.compatLnSpcField = value; } } [XmlIgnore] public bool compatLnSpcSpecified { get { return this.compatLnSpcFieldSpecified; } set { this.compatLnSpcFieldSpecified = value; } } } [Serializable] [System.ComponentModel.DesignerCategory("code")] [XmlType(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace="http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable=true)] public class CT_TextBody { private CT_TextBodyProperties bodyPrField; private CT_TextListStyle lstStyleField; private List<CT_TextParagraph> pField; public static CT_TextBody Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) return null; CT_TextBody ctObj = new CT_TextBody(); ctObj.p = new List<CT_TextParagraph>(); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "bodyPr") ctObj.bodyPr = CT_TextBodyProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "lstStyle") ctObj.lstStyle = CT_TextListStyle.Parse(childNode, namespaceManager); else if (childNode.LocalName == "p") ctObj.p.Add(CT_TextParagraph.Parse(childNode, namespaceManager)); } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<a:{0}", nodeName)); sw.Write(">"); if (this.bodyPr != null) this.bodyPr.Write(sw, "bodyPr"); if (this.lstStyle != null) this.lstStyle.Write(sw, "lstStyle"); foreach (CT_TextParagraph x in this.p) { x.Write(sw, "p"); } sw.Write(string.Format("</a:{0}>", nodeName)); } public void SetPArray(CT_TextParagraph[] array) { pField = new List<CT_TextParagraph>(array); } public CT_TextParagraph AddNewP() { if (this.pField == null) pField = new List<CT_TextParagraph>(); CT_TextParagraph tp = new CT_TextParagraph(); pField.Add(tp); return tp; } public CT_TextBodyProperties AddNewBodyPr() { this.bodyPrField = new CT_TextBodyProperties(); return this.bodyPrField; } public CT_TextListStyle AddNewLstStyle() { this.lstStyleField=new CT_TextListStyle(); return this.lstStyleField; } public CT_TextBodyProperties bodyPr { get { return this.bodyPrField; } set { this.bodyPrField = value; } } public CT_TextListStyle lstStyle { get { return this.lstStyleField; } set { this.lstStyleField = value; } } public override string ToString() { if (p == null||p.Count==0) return string.Empty; StringBuilder sb = new StringBuilder(); foreach (CT_TextParagraph tp in p) { foreach (CT_RegularTextRun tr in tp.r) { sb.Append(tr.t); } } return sb.ToString(); } [XmlElement("p")] public List<CT_TextParagraph> p { get { return this.pField; } set { this.pField = value; } } } }
using System; using System.Text; using System.Linq; using System.Globalization; using System.ComponentModel; using System.Collections.Generic; using System.Reflection; namespace Eto.Forms { /// <summary> /// Masked text provider for numeric input of the specified type. /// </summary> public class NumericMaskedTextProvider<T> : NumericMaskedTextProvider, IMaskedTextProvider<T> { Func<string, T> parse; class Info { public bool AllowSign; public bool AllowDecimal; public Func<string, object> Parse; } // use dictionary instead of reflection for Xamarin.Mac linking Dictionary<Type, Info> numericTypes = new Dictionary<Type, Info> { { typeof(decimal), new Info { Parse = s => { decimal d; return decimal.TryParse(s, out d) ? (object)d : null; }, AllowSign = true, AllowDecimal = true } }, { typeof(double), new Info { Parse = s => { double d; return double.TryParse(s, out d) ? (object)d : null; }, AllowSign = true, AllowDecimal = true } }, { typeof(float), new Info { Parse = s => { float d; return float.TryParse(s, out d) ? (object)d : null; }, AllowSign = true, AllowDecimal = true } }, { typeof(int), new Info { Parse = s => { int d; return int.TryParse(s, out d) ? (object)d : null; }, AllowSign = true } }, { typeof(uint), new Info { Parse = s => { uint d; return uint.TryParse(s, out d) ? (object)d : null; } } }, { typeof(long), new Info { Parse = s => { long d; return long.TryParse(s, out d) ? (object)d : null; }, AllowSign = true } }, { typeof(ulong), new Info { Parse = s => { ulong d; return ulong.TryParse(s, out d) ? (object)d : null; } } }, { typeof(short), new Info { Parse = s => { short d; return short.TryParse(s, out d) ? (object)d : null; }, AllowSign = true } }, { typeof(ushort), new Info { Parse = s => { ushort d; return ushort.TryParse(s, out d) ? (object)d : null; } } }, { typeof(byte), new Info { Parse = s => { byte d; return byte.TryParse(s, out d) ? (object)d : null; } } }, { typeof(sbyte), new Info { Parse = s => { sbyte d; return sbyte.TryParse(s, out d) ? (object)d : null; }, AllowSign = true } } }; /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.NumericMaskedTextProvider{T}"/> class. /// </summary> public NumericMaskedTextProvider() { var type = typeof(T); var underlyingType = Nullable.GetUnderlyingType(type) ?? type; Info info; if (numericTypes.TryGetValue(underlyingType, out info)) { AllowSign = info.AllowSign; AllowDecimal = info.AllowDecimal; parse = text => { var val = info.Parse(text); return val == null ? default(T) : (T)val; }; Validate = text => info.Parse(text) != null; } else { // use reflection for other types AllowSign = Convert.ToBoolean(underlyingType.GetRuntimeField("MinValue").GetValue(null)); AllowDecimal = underlyingType == typeof(decimal) || underlyingType == typeof(double) || underlyingType == typeof(float); var tryParseMethod = underlyingType.GetRuntimeMethod("TryParse", new [] { typeof(string), underlyingType.MakeByRefType() }); if (tryParseMethod == null || tryParseMethod.ReturnType != typeof(bool)) throw new ArgumentException(string.Format("Type of T ({0}) must implement a static bool TryParse(string, out T) method", typeof(T))); parse = text => { var parameters = new object[] { Text, null }; if ((bool)tryParseMethod.Invoke(null, parameters)) { return (T)parameters[1]; } return default(T); }; Validate = text => { var parameters = new object[] { text, null }; return (bool)tryParseMethod.Invoke(null, parameters); }; } } /// <summary> /// Gets or sets the translated value of the mask. /// </summary> /// <value>The value of the mask.</value> public T Value { get { return parse(Text); } set { Text = Convert.ToString(value); } } } /// <summary> /// Masked text provider for numeric input. /// </summary> public class NumericMaskedTextProvider : VariableMaskedTextProvider { /// <summary> /// Gets or sets a value indicating that the mask can optionally include a decimal, as specified by the <see cref="DecimalCharacter"/>. /// </summary> /// <value><c>true</c> to allow the decimal; otherwise, <c>false</c>.</value> public bool AllowDecimal { get; set; } /// <summary> /// Gets or sets a value indicating that the mask can optionally include the sign, as specified by <see cref="SignCharacters"/>. /// </summary> /// <value><c>true</c> to allow a sign character; otherwise, <c>false</c>.</value> public bool AllowSign { get; set; } /// <summary> /// Gets or sets the sign characters when <see cref="AllowSign"/> is <c>true</c>. Default is '+' and '-'. /// </summary> /// <value>The sign characters.</value> public char[] SignCharacters { get; set; } /// <summary> /// Gets or sets a delegate used to validate the mask. /// </summary> /// <value>The validation delegate.</value> public Func<string, bool> Validate { get; set; } /// <summary> /// Gets or sets the decimal character when <see cref="AllowDecimal"/> is <c>true</c>. Default is '.'. /// </summary> /// <value>The decimal character.</value> [DefaultValue('.')] public char DecimalCharacter { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.NumericMaskedTextProvider"/> class. /// </summary> public NumericMaskedTextProvider() { DecimalCharacter = '.'; SignCharacters = new [] { '+', '-' }; } /// <summary> /// Gets a value indicating whether the mask has all required text to pass its validation. /// </summary> /// <value><c>true</c> if mask is completed; otherwise, <c>false</c>.</value> public override bool MaskCompleted { get { return base.MaskCompleted && Text.ToCharArray().Any(char.IsDigit); } } /// <summary> /// Called to replace a character at the specified position in the masked text. /// </summary> /// <param name="character">Character to insert.</param> /// <param name="position">Position to insert at.</param> /// <returns><c>true</c> when the replacement was successful, or <c>false</c> if it failed.</returns> public override bool Replace(char character, ref int position) { var allow = Allow(character, ref position); return allow && base.Replace(character, ref position); } bool Allow(char character, ref int position) { bool allow = false; if (!allow && AllowDecimal && character == DecimalCharacter) { var val = Text; if (val.IndexOf(DecimalCharacter) == -1) { allow = true; if (position < val.Length && !char.IsDigit(val[position])) { // insert at correct location and move cursor int idx; for (idx = 0; idx < val.Length; idx++) { if (char.IsDigit(val[idx])) { break; } } position = idx; allow = true; } } } if (!allow && AllowSign && SignCharacters.Contains(character)) { var val = Text; if (val.IndexOfAny(SignCharacters) == 0) { Builder.Remove(0, 1); if (position == 0) position++; } else position++; Builder.Insert(0, character); return false; } allow |= char.IsDigit(character); return allow; } /// <summary> /// Called to insert a character at the specified position in the masked text. /// </summary> /// <param name="character">Character to insert.</param> /// <param name="position">Position to insert at.</param> /// <returns><c>true</c> when the insertion was successful, or <c>false</c> if it failed.</returns> public override bool Insert(char character, ref int position) { int pos = position; var allow = Allow(character, ref position); var ret = allow && base.Insert(character, ref position); if (ret && Validate != null && MaskCompleted && !Validate(Text)) { Builder.Remove(pos, 1); position = pos; ret = false; } return ret; } } }
using System; using System.Collections; using System.Globalization; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Engines { /** * implementation of GOST 28147-89 */ public class Gost28147Engine : IBlockCipher { private const int BlockSize = 8; private int[] workingKey = null; private bool forEncryption; // these are the S-boxes given in Applied Cryptography 2nd Ed., p. 333 // This is default S-box! private readonly byte[] S = { 0x4,0xA,0x9,0x2,0xD,0x8,0x0,0xE,0x6,0xB,0x1,0xC,0x7,0xF,0x5,0x3, 0xE,0xB,0x4,0xC,0x6,0xD,0xF,0xA,0x2,0x3,0x8,0x1,0x0,0x7,0x5,0x9, 0x5,0x8,0x1,0xD,0xA,0x3,0x4,0x2,0xE,0xF,0xC,0x7,0x6,0x0,0x9,0xB, 0x7,0xD,0xA,0x1,0x0,0x8,0x9,0xF,0xE,0x4,0x6,0xC,0xB,0x2,0x5,0x3, 0x6,0xC,0x7,0x1,0x5,0xF,0xD,0x8,0x4,0xA,0x9,0xE,0x0,0x3,0xB,0x2, 0x4,0xB,0xA,0x0,0x7,0x2,0x1,0xD,0x3,0x6,0x8,0x5,0x9,0xC,0xF,0xE, 0xD,0xB,0x4,0x1,0x3,0xF,0x5,0x9,0x0,0xA,0xE,0x7,0x6,0x8,0x2,0xC, 0x1,0xF,0xD,0x0,0x5,0x7,0xA,0x4,0x9,0x2,0x3,0xE,0x6,0xB,0x8,0xC }; /* * class content S-box parameters for encrypting * getting from, see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt * http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-02.txt */ private static readonly byte[] ESbox_Test = { 0x4,0x2,0xF,0x5,0x9,0x1,0x0,0x8,0xE,0x3,0xB,0xC,0xD,0x7,0xA,0x6, 0xC,0x9,0xF,0xE,0x8,0x1,0x3,0xA,0x2,0x7,0x4,0xD,0x6,0x0,0xB,0x5, 0xD,0x8,0xE,0xC,0x7,0x3,0x9,0xA,0x1,0x5,0x2,0x4,0x6,0xF,0x0,0xB, 0xE,0x9,0xB,0x2,0x5,0xF,0x7,0x1,0x0,0xD,0xC,0x6,0xA,0x4,0x3,0x8, 0x3,0xE,0x5,0x9,0x6,0x8,0x0,0xD,0xA,0xB,0x7,0xC,0x2,0x1,0xF,0x4, 0x8,0xF,0x6,0xB,0x1,0x9,0xC,0x5,0xD,0x3,0x7,0xA,0x0,0xE,0x2,0x4, 0x9,0xB,0xC,0x0,0x3,0x6,0x7,0x5,0x4,0x8,0xE,0xF,0x1,0xA,0x2,0xD, 0xC,0x6,0x5,0x2,0xB,0x0,0x9,0xD,0x3,0xE,0x7,0xA,0xF,0x4,0x1,0x8 }; private static readonly byte[] ESbox_A = { 0x9,0x6,0x3,0x2,0x8,0xB,0x1,0x7,0xA,0x4,0xE,0xF,0xC,0x0,0xD,0x5, 0x3,0x7,0xE,0x9,0x8,0xA,0xF,0x0,0x5,0x2,0x6,0xC,0xB,0x4,0xD,0x1, 0xE,0x4,0x6,0x2,0xB,0x3,0xD,0x8,0xC,0xF,0x5,0xA,0x0,0x7,0x1,0x9, 0xE,0x7,0xA,0xC,0xD,0x1,0x3,0x9,0x0,0x2,0xB,0x4,0xF,0x8,0x5,0x6, 0xB,0x5,0x1,0x9,0x8,0xD,0xF,0x0,0xE,0x4,0x2,0x3,0xC,0x7,0xA,0x6, 0x3,0xA,0xD,0xC,0x1,0x2,0x0,0xB,0x7,0x5,0x9,0x4,0x8,0xF,0xE,0x6, 0x1,0xD,0x2,0x9,0x7,0xA,0x6,0x0,0x8,0xC,0x4,0x5,0xF,0x3,0xB,0xE, 0xB,0xA,0xF,0x5,0x0,0xC,0xE,0x8,0x6,0x2,0x3,0x9,0x1,0x7,0xD,0x4 }; private static readonly byte[] ESbox_B = { 0x8,0x4,0xB,0x1,0x3,0x5,0x0,0x9,0x2,0xE,0xA,0xC,0xD,0x6,0x7,0xF, 0x0,0x1,0x2,0xA,0x4,0xD,0x5,0xC,0x9,0x7,0x3,0xF,0xB,0x8,0x6,0xE, 0xE,0xC,0x0,0xA,0x9,0x2,0xD,0xB,0x7,0x5,0x8,0xF,0x3,0x6,0x1,0x4, 0x7,0x5,0x0,0xD,0xB,0x6,0x1,0x2,0x3,0xA,0xC,0xF,0x4,0xE,0x9,0x8, 0x2,0x7,0xC,0xF,0x9,0x5,0xA,0xB,0x1,0x4,0x0,0xD,0x6,0x8,0xE,0x3, 0x8,0x3,0x2,0x6,0x4,0xD,0xE,0xB,0xC,0x1,0x7,0xF,0xA,0x0,0x9,0x5, 0x5,0x2,0xA,0xB,0x9,0x1,0xC,0x3,0x7,0x4,0xD,0x0,0x6,0xF,0x8,0xE, 0x0,0x4,0xB,0xE,0x8,0x3,0x7,0x1,0xA,0x2,0x9,0x6,0xF,0xD,0x5,0xC }; private static readonly byte[] ESbox_C = { 0x1,0xB,0xC,0x2,0x9,0xD,0x0,0xF,0x4,0x5,0x8,0xE,0xA,0x7,0x6,0x3, 0x0,0x1,0x7,0xD,0xB,0x4,0x5,0x2,0x8,0xE,0xF,0xC,0x9,0xA,0x6,0x3, 0x8,0x2,0x5,0x0,0x4,0x9,0xF,0xA,0x3,0x7,0xC,0xD,0x6,0xE,0x1,0xB, 0x3,0x6,0x0,0x1,0x5,0xD,0xA,0x8,0xB,0x2,0x9,0x7,0xE,0xF,0xC,0x4, 0x8,0xD,0xB,0x0,0x4,0x5,0x1,0x2,0x9,0x3,0xC,0xE,0x6,0xF,0xA,0x7, 0xC,0x9,0xB,0x1,0x8,0xE,0x2,0x4,0x7,0x3,0x6,0x5,0xA,0x0,0xF,0xD, 0xA,0x9,0x6,0x8,0xD,0xE,0x2,0x0,0xF,0x3,0x5,0xB,0x4,0x1,0xC,0x7, 0x7,0x4,0x0,0x5,0xA,0x2,0xF,0xE,0xC,0x6,0x1,0xB,0xD,0x9,0x3,0x8 }; private static readonly byte[] ESbox_D = { 0xF,0xC,0x2,0xA,0x6,0x4,0x5,0x0,0x7,0x9,0xE,0xD,0x1,0xB,0x8,0x3, 0xB,0x6,0x3,0x4,0xC,0xF,0xE,0x2,0x7,0xD,0x8,0x0,0x5,0xA,0x9,0x1, 0x1,0xC,0xB,0x0,0xF,0xE,0x6,0x5,0xA,0xD,0x4,0x8,0x9,0x3,0x7,0x2, 0x1,0x5,0xE,0xC,0xA,0x7,0x0,0xD,0x6,0x2,0xB,0x4,0x9,0x3,0xF,0x8, 0x0,0xC,0x8,0x9,0xD,0x2,0xA,0xB,0x7,0x3,0x6,0x5,0x4,0xE,0xF,0x1, 0x8,0x0,0xF,0x3,0x2,0x5,0xE,0xB,0x1,0xA,0x4,0x7,0xC,0x9,0xD,0x6, 0x3,0x0,0x6,0xF,0x1,0xE,0x9,0x2,0xD,0x8,0xC,0x4,0xB,0xA,0x5,0x7, 0x1,0xA,0x6,0x8,0xF,0xB,0x0,0x4,0xC,0x3,0x5,0x9,0x7,0xD,0x2,0xE }; //S-box for digest private static readonly byte[] DSbox_Test = { 0x4,0xA,0x9,0x2,0xD,0x8,0x0,0xE,0x6,0xB,0x1,0xC,0x7,0xF,0x5,0x3, 0xE,0xB,0x4,0xC,0x6,0xD,0xF,0xA,0x2,0x3,0x8,0x1,0x0,0x7,0x5,0x9, 0x5,0x8,0x1,0xD,0xA,0x3,0x4,0x2,0xE,0xF,0xC,0x7,0x6,0x0,0x9,0xB, 0x7,0xD,0xA,0x1,0x0,0x8,0x9,0xF,0xE,0x4,0x6,0xC,0xB,0x2,0x5,0x3, 0x6,0xC,0x7,0x1,0x5,0xF,0xD,0x8,0x4,0xA,0x9,0xE,0x0,0x3,0xB,0x2, 0x4,0xB,0xA,0x0,0x7,0x2,0x1,0xD,0x3,0x6,0x8,0x5,0x9,0xC,0xF,0xE, 0xD,0xB,0x4,0x1,0x3,0xF,0x5,0x9,0x0,0xA,0xE,0x7,0x6,0x8,0x2,0xC, 0x1,0xF,0xD,0x0,0x5,0x7,0xA,0x4,0x9,0x2,0x3,0xE,0x6,0xB,0x8,0xC }; private static readonly byte[] DSbox_A = { 0xA,0x4,0x5,0x6,0x8,0x1,0x3,0x7,0xD,0xC,0xE,0x0,0x9,0x2,0xB,0xF, 0x5,0xF,0x4,0x0,0x2,0xD,0xB,0x9,0x1,0x7,0x6,0x3,0xC,0xE,0xA,0x8, 0x7,0xF,0xC,0xE,0x9,0x4,0x1,0x0,0x3,0xB,0x5,0x2,0x6,0xA,0x8,0xD, 0x4,0xA,0x7,0xC,0x0,0xF,0x2,0x8,0xE,0x1,0x6,0x5,0xD,0xB,0x9,0x3, 0x7,0x6,0x4,0xB,0x9,0xC,0x2,0xA,0x1,0x8,0x0,0xE,0xF,0xD,0x3,0x5, 0x7,0x6,0x2,0x4,0xD,0x9,0xF,0x0,0xA,0x1,0x5,0xB,0x8,0xE,0xC,0x3, 0xD,0xE,0x4,0x1,0x7,0x0,0x5,0xA,0x3,0xC,0x8,0xF,0x6,0x2,0x9,0xB, 0x1,0x3,0xA,0x9,0x5,0xB,0x4,0xF,0x8,0x6,0x7,0xE,0xD,0x0,0x2,0xC }; // // pre-defined sbox table // private static readonly Hashtable sBoxes = new Hashtable(); static Gost28147Engine() { sBoxes.Add("E-TEST", ESbox_Test); sBoxes.Add("E-A", ESbox_A); sBoxes.Add("E-B", ESbox_B); sBoxes.Add("E-C", ESbox_C); sBoxes.Add("E-D", ESbox_D); sBoxes.Add("D-TEST", DSbox_Test); sBoxes.Add("D-A", DSbox_A); } /** * standard constructor. */ public Gost28147Engine() { } /** * initialise an Gost28147 cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (parameters is ParametersWithSBox) { ParametersWithSBox param = (ParametersWithSBox)parameters; // // Set the S-Box // Array.Copy(param.GetSBox(), 0, this.S, 0, param.GetSBox().Length); // // set key if there is one // if (param.Parameters != null) { workingKey = generateWorkingKey(forEncryption, ((KeyParameter)param.Parameters).GetKey()); } } else if (parameters is KeyParameter) { workingKey = generateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); } else { throw new ArgumentException("invalid parameter passed to Gost28147 init - " + parameters.GetType().Name); } } public string AlgorithmName { get { return "Gost28147"; } } public bool IsPartialBlockOkay { get { return false; } } public int GetBlockSize() { return BlockSize; } public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) { throw new InvalidOperationException("Gost28147 engine not initialised"); } if ((inOff + BlockSize) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + BlockSize) > output.Length) { throw new DataLengthException("output buffer too short"); } Gost28147Func(workingKey, input, inOff, output, outOff); return BlockSize; } public void Reset() { } private int[] generateWorkingKey( bool forEncryption, byte[] userKey) { this.forEncryption = forEncryption; if (userKey.Length != 32) { throw new ArgumentException("Key length invalid. Key needs to be 32 byte - 256 bit!!!"); } int[] key = new int[8]; for(int i=0; i!=8; i++) { key[i] = bytesToint(userKey,i*4); } return key; } private int Gost28147_mainStep(int n1, int key) { int cm = (key + n1); // CM1 // S-box replacing int om = S[ 0 + ((cm >> (0 * 4)) & 0xF)] << (0 * 4); om += S[ 16 + ((cm >> (1 * 4)) & 0xF)] << (1 * 4); om += S[ 32 + ((cm >> (2 * 4)) & 0xF)] << (2 * 4); om += S[ 48 + ((cm >> (3 * 4)) & 0xF)] << (3 * 4); om += S[ 64 + ((cm >> (4 * 4)) & 0xF)] << (4 * 4); om += S[ 80 + ((cm >> (5 * 4)) & 0xF)] << (5 * 4); om += S[ 96 + ((cm >> (6 * 4)) & 0xF)] << (6 * 4); om += S[112 + ((cm >> (7 * 4)) & 0xF)] << (7 * 4); // return om << 11 | om >>> (32-11); // 11-leftshift int omLeft = om << 11; int omRight = (int)(((uint) om) >> (32 - 11)); // Note: Casts required to get unsigned bit rotation return omLeft | omRight; } private void Gost28147Func( int[] workingKey, byte[] inBytes, int inOff, byte[] outBytes, int outOff) { int N1, N2, tmp; //tmp -> for saving N1 N1 = bytesToint(inBytes, inOff); N2 = bytesToint(inBytes, inOff + 4); if (this.forEncryption) { for(int k = 0; k < 3; k++) // 1-24 steps { for(int j = 0; j < 8; j++) { tmp = N1; int step = Gost28147_mainStep(N1, workingKey[j]); N1 = N2 ^ step; // CM2 N2 = tmp; } } for(int j = 7; j > 0; j--) // 25-31 steps { tmp = N1; N1 = N2 ^ Gost28147_mainStep(N1, workingKey[j]); // CM2 N2 = tmp; } } else //decrypt { for(int j = 0; j < 8; j++) // 1-8 steps { tmp = N1; N1 = N2 ^ Gost28147_mainStep(N1, workingKey[j]); // CM2 N2 = tmp; } for(int k = 0; k < 3; k++) //9-31 steps { for(int j = 7; j >= 0; j--) { if ((k == 2) && (j==0)) { break; // break 32 step } tmp = N1; N1 = N2 ^ Gost28147_mainStep(N1, workingKey[j]); // CM2 N2 = tmp; } } } N2 = N2 ^ Gost28147_mainStep(N1, workingKey[0]); // 32 step (N1=N1) intTobytes(N1, outBytes, outOff); intTobytes(N2, outBytes, outOff + 4); } //array of bytes to type int private static int bytesToint( byte[] inBytes, int inOff) { return (int)((inBytes[inOff + 3] << 24) & 0xff000000) + ((inBytes[inOff + 2] << 16) & 0xff0000) + ((inBytes[inOff + 1] << 8) & 0xff00) + (inBytes[inOff] & 0xff); } //int to array of bytes private static void intTobytes( int num, byte[] outBytes, int outOff) { outBytes[outOff + 3] = (byte)(num >> 24); outBytes[outOff + 2] = (byte)(num >> 16); outBytes[outOff + 1] = (byte)(num >> 8); outBytes[outOff] = (byte)num; } /** * Return the S-Box associated with SBoxName * @param sBoxName name of the S-Box * @return byte array representing the S-Box */ public static byte[] GetSBox( string sBoxName) { byte[] namedSBox = (byte[])sBoxes[sBoxName.ToUpper(CultureInfo.InvariantCulture)]; if (namedSBox == null) { throw new ArgumentException("Unknown S-Box - possible types: " + "\"E-Test\", \"E-A\", \"E-B\", \"E-C\", \"E-D\", \"D-Test\", \"D-A\"."); } return (byte[]) namedSBox.Clone(); } } }
namespace AutoMapper { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Impl; using Internal; /// <summary> /// Main configuration object holding all mapping configuration for a source and destination type /// </summary> [DebuggerDisplay("{_sourceType.Type.Name} -> {_destinationType.Type.Name}")] public class TypeMap { private readonly IList<Action<object, object>> _afterMapActions = new List<Action<object, object>>(); private readonly IList<Action<object, object>> _beforeMapActions = new List<Action<object, object>>(); private readonly TypeInfo _destinationType; private readonly ISet<TypePair> _includedDerivedTypes = new HashSet<TypePair>(); private readonly ThreadSafeList<PropertyMap> _propertyMaps = new ThreadSafeList<PropertyMap>(); private readonly ThreadSafeList<SourceMemberConfig> _sourceMemberConfigs = new ThreadSafeList<SourceMemberConfig>(); private readonly IList<PropertyMap> _inheritedMaps = new List<PropertyMap>(); private PropertyMap[] _orderedPropertyMaps; private readonly TypeInfo _sourceType; private bool _sealed; private Func<ResolutionContext, bool> _condition; private int _maxDepth = Int32.MaxValue; private IList<TypeMap> _inheritedTypeMaps = new List<TypeMap>(); public TypeMap(TypeInfo sourceType, TypeInfo destinationType, MemberList memberList) { _sourceType = sourceType; _destinationType = destinationType; Profile = ConfigurationStore.DefaultProfileName; ConfiguredMemberList = memberList; } public ConstructorMap ConstructorMap { get; private set; } public Type SourceType => _sourceType.Type; public Type DestinationType => _destinationType.Type; public string Profile { get; set; } public Func<ResolutionContext, object> CustomMapper { get; private set; } public LambdaExpression CustomProjection { get; private set; } public Action<object, object> BeforeMap { get { return (src, dest) => { foreach (var action in _beforeMapActions) action(src, dest); }; } } public Action<object, object> AfterMap { get { return (src, dest) => { foreach (var action in _afterMapActions) action(src, dest); }; } } public Func<ResolutionContext, object> DestinationCtor { get; set; } public List<string> IgnorePropertiesStartingWith { get; set; } public Type DestinationTypeOverride { get; set; } public bool ConstructDestinationUsingServiceLocator { get; set; } public MemberList ConfiguredMemberList { get; } public IEnumerable<TypePair> IncludedDerivedTypes => _includedDerivedTypes; public int MaxDepth { get { return _maxDepth; } set { _maxDepth = value; SetCondition(o => PassesDepthCheck(o, value)); } } public Func<object, object> Substitution { get; set; } public LambdaExpression ConstructExpression { get; set; } public IEnumerable<PropertyMap> GetPropertyMaps() { return _sealed ? _orderedPropertyMaps : _propertyMaps.Concat(_inheritedMaps); } public void AddPropertyMap(PropertyMap propertyMap) { _propertyMaps.Add(propertyMap); } protected void AddInheritedMap(PropertyMap propertyMap) { _inheritedMaps.Add(propertyMap); } public void AddPropertyMap(IMemberAccessor destProperty, IEnumerable<IValueResolver> resolvers) { var propertyMap = new PropertyMap(destProperty); resolvers.Each(propertyMap.ChainResolver); AddPropertyMap(propertyMap); } public string[] GetUnmappedPropertyNames() { var autoMappedProperties = _propertyMaps.Where(pm => pm.IsMapped()) .Select(pm => pm.DestinationProperty.Name); var inheritedProperties = _inheritedMaps.Where(pm => pm.IsMapped()) .Select(pm => pm.DestinationProperty.Name); IEnumerable<string> properties; if (ConfiguredMemberList == MemberList.Destination) properties = _destinationType.PublicWriteAccessors .Select(p => p.Name) .Except(autoMappedProperties) .Except(inheritedProperties); else { var redirectedSourceMembers = _propertyMaps .Where(pm => pm.IsMapped()) .Where(pm => pm.CustomExpression != null) .Where(pm => pm.SourceMember != null) .Select(pm => pm.SourceMember.Name); var ignoredSourceMembers = _sourceMemberConfigs .Where(smc => smc.IsIgnored()) .Select(pm => pm.SourceMember.Name); properties = _sourceType.PublicReadAccessors .Select(p => p.Name) .Except(autoMappedProperties) .Except(inheritedProperties) .Except(redirectedSourceMembers) .Except(ignoredSourceMembers) ; } return properties.Where(memberName => !IgnorePropertiesStartingWith.Any(memberName.StartsWith)).ToArray(); } public PropertyMap FindOrCreatePropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = GetExistingPropertyMapFor(destinationProperty); if (propertyMap != null) return propertyMap; propertyMap = new PropertyMap(destinationProperty); AddPropertyMap(propertyMap); return propertyMap; } public void IncludeDerivedTypes(Type derivedSourceType, Type derivedDestinationType) { _includedDerivedTypes.Add(new TypePair(derivedSourceType, derivedDestinationType)); } public Type GetDerivedTypeFor(Type derivedSourceType) { // This might need to be fixed for multiple derived source types to different dest types var match = _includedDerivedTypes.FirstOrDefault(tp => tp.SourceType == derivedSourceType); return match == null ? DestinationType : match.DestinationType; } public bool TypeHasBeenIncluded(Type derivedSourceType, Type derivedDestinationType) { return _includedDerivedTypes.Contains(new TypePair(derivedSourceType, derivedDestinationType)); } public bool HasDerivedTypesToInclude() { return _includedDerivedTypes.Any(); } public void UseCustomMapper(Func<ResolutionContext, object> customMapper) { CustomMapper = customMapper; _propertyMaps.Clear(); } public void AddBeforeMapAction(Action<object, object> beforeMap) { _beforeMapActions.Add(beforeMap); } public void AddAfterMapAction(Action<object, object> afterMap) { _afterMapActions.Add(afterMap); } public void Seal() { if (_sealed) return; foreach (var inheritedTypeMap in _inheritedTypeMaps) { inheritedTypeMap.Seal(); ApplyInheritedTypeMap(inheritedTypeMap); } _orderedPropertyMaps = _propertyMaps .Union(_inheritedMaps) .OrderBy(map => map.GetMappingOrder()).ToArray(); _orderedPropertyMaps.Each(pm => pm.Seal()); foreach (var inheritedMap in _inheritedMaps) inheritedMap.Seal(); _sealed = true; } public bool Equals(TypeMap other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other._sourceType, _sourceType) && Equals(other._destinationType, _destinationType); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (TypeMap)) return false; return Equals((TypeMap) obj); } public override int GetHashCode() { unchecked { return (_sourceType.GetHashCode()*397) ^ _destinationType.GetHashCode(); } } public PropertyMap GetExistingPropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = _propertyMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name)); if (propertyMap != null) return propertyMap; propertyMap = _inheritedMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name)); if (propertyMap == null) return null; var propertyInfo = propertyMap.DestinationProperty.MemberInfo as PropertyInfo; if (propertyInfo == null) return propertyMap; var baseAccessor = propertyInfo.GetAccessors()[0]; if (baseAccessor.IsAbstract || baseAccessor.IsVirtual) return propertyMap; var accessor = ((PropertyInfo) destinationProperty.MemberInfo).GetAccessors()[0]; if (baseAccessor.DeclaringType == accessor.DeclaringType) return propertyMap; return null; } public void AddInheritedPropertyMap(PropertyMap mappedProperty) { _inheritedMaps.Add(mappedProperty); } public void InheritTypes(TypeMap inheritedTypeMap) { foreach (var includedDerivedType in inheritedTypeMap._includedDerivedTypes .Where(includedDerivedType => !_includedDerivedTypes.Contains(includedDerivedType))) { _includedDerivedTypes.Add(includedDerivedType); } } public void SetCondition(Func<ResolutionContext, bool> condition) { _condition = condition; } public bool ShouldAssignValue(ResolutionContext resolutionContext) { return _condition == null || _condition(resolutionContext); } public void AddConstructorMap(ConstructorInfo constructorInfo, IEnumerable<ConstructorParameterMap> parameters) { var ctorMap = new ConstructorMap(constructorInfo, parameters); ConstructorMap = ctorMap; } public SourceMemberConfig FindOrCreateSourceMemberConfigFor(MemberInfo sourceMember) { var config = _sourceMemberConfigs.FirstOrDefault(smc => smc.SourceMember == sourceMember); if (config == null) { config = new SourceMemberConfig(sourceMember); _sourceMemberConfigs.Add(config); } return config; } private static bool PassesDepthCheck(ResolutionContext context, int maxDepth) { if (context.InstanceCache.ContainsKey(context)) { // return true if we already mapped this value and it's in the cache return true; } ResolutionContext contextCopy = context; int currentDepth = 1; // walk parents to determine current depth while (contextCopy.Parent != null) { if (contextCopy.SourceType == context.TypeMap.SourceType && contextCopy.DestinationType == context.TypeMap.DestinationType) { // same source and destination types appear higher up in the hierarchy currentDepth++; } contextCopy = contextCopy.Parent; } return currentDepth <= maxDepth; } public void UseCustomProjection(LambdaExpression projectionExpression) { CustomProjection = projectionExpression; _propertyMaps.Clear(); } public void ApplyInheritedMap(TypeMap inheritedTypeMap) { _inheritedTypeMaps.Add(inheritedTypeMap); } private void ApplyInheritedTypeMap(TypeMap inheritedTypeMap) { foreach (var inheritedMappedProperty in inheritedTypeMap.GetPropertyMaps().Where(m => m.IsMapped())) { var conventionPropertyMap = GetPropertyMaps() .SingleOrDefault(m => m.DestinationProperty.Name == inheritedMappedProperty.DestinationProperty.Name); if (conventionPropertyMap != null && inheritedMappedProperty.HasCustomValueResolver && !conventionPropertyMap.HasCustomValueResolver) { conventionPropertyMap.AssignCustomValueResolver( inheritedMappedProperty.GetSourceValueResolvers().First()); conventionPropertyMap.AssignCustomExpression(inheritedMappedProperty.CustomExpression); } else if (conventionPropertyMap == null) { var propertyMap = new PropertyMap(inheritedMappedProperty); AddInheritedPropertyMap(propertyMap); } } //Include BeforeMap if (inheritedTypeMap.BeforeMap != null) AddBeforeMapAction(inheritedTypeMap.BeforeMap); //Include AfterMap if (inheritedTypeMap.AfterMap != null) AddAfterMapAction(inheritedTypeMap.AfterMap); } internal LambdaExpression DestinationConstructorExpression(Expression instanceParameter) { var ctorExpr = ConstructExpression; if(ctorExpr != null) { return ctorExpr; } Expression newExpression; if(ConstructorMap != null && ConstructorMap.CtorParams.All(p => p.CanResolve)) { newExpression = ConstructorMap.NewExpression(instanceParameter); } else { newExpression = Expression.New(DestinationType); } return Expression.Lambda(newExpression); } } }
/****************************************************************************** * 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.Utilclass.RDN.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap.Utilclass { /// <summary> A RDN encapsulates a single object's name of a Distinguished Name(DN). /// The object name represented by this class contains no context. Thus a /// Relative Distinguished Name (RDN) could be relative to anywhere in the /// Directories tree. /// /// For example, of following DN, 'cn=admin, ou=marketing, o=corporation', all /// possible RDNs are 'cn=admin', 'ou=marketing', and 'o=corporation'. /// /// Multivalued attributes are encapsulated in this class. For example the /// following could be represented by an RDN: 'cn=john + l=US', or /// 'cn=juan + l=ES' /// /// </summary> /// <seealso cref="DN"> /// </seealso> public class RDN:System.Object { /// <summary> Returns the actually Raw String before Normalization /// /// </summary> /// <returns> The raw string /// </returns> virtual protected internal System.String RawValue { get { return rawValue; } } /// <summary> Returns the type of this RDN. This method assumes that only one value /// is used, If multivalues attributes are used only the first Type is /// returned. Use GetTypes. /// </summary> /// <returns> Type of attribute /// </returns> virtual public System.String Type { get { return (System.String) types[0]; } } /// <summary> Returns all the types for this RDN.</summary> /// <returns> list of types /// </returns> virtual public System.String[] Types { get { System.String[] toReturn = new System.String[types.Count]; for (int i = 0; i < types.Count; i++) toReturn[i] = ((System.String) types[i]); return toReturn; } } /// <summary> Returns the values of this RDN. If multivalues attributes are used only /// the first Type is returned. Use GetTypes. /// /// </summary> /// <returns> Type of attribute /// </returns> virtual public System.String Value { get { return (System.String) values[0]; } } /// <summary> Returns all the types for this RDN.</summary> /// <returns> list of types /// </returns> virtual public System.String[] Values { get { System.String[] toReturn = new System.String[values.Count]; for (int i = 0; i < values.Count; i++) toReturn[i] = ((System.String) values[i]); return toReturn; } } /// <summary> Determines if this RDN is multivalued or not</summary> /// <returns> true if this RDN is multivalued /// </returns> virtual public bool Multivalued { get { return (values.Count > 1)?true:false; } } private System.Collections.ArrayList types; //list of Type strings private System.Collections.ArrayList values; //list of Value strings private System.String rawValue; //the unnormalized value /// <summary> Creates an RDN object from the DN component specified in the string RDN /// /// </summary> /// <param name="rdn">the DN component /// </param> public RDN(System.String rdn) { rawValue = rdn; DN dn = new DN(rdn); System.Collections.ArrayList rdns = dn.RDNs; //there should only be one rdn if (rdns.Count != 1) throw new System.ArgumentException("Invalid RDN: see API " + "documentation"); RDN thisRDN = (RDN) (rdns[0]); this.types = thisRDN.types; this.values = thisRDN.values; this.rawValue = thisRDN.rawValue; return ; } public RDN() { types = new System.Collections.ArrayList(); values = new System.Collections.ArrayList(); rawValue = ""; return ; } /// <summary> Compares the RDN to the rdn passed. Note: If an there exist any /// mulivalues in one RDN they must all be present in the other. /// /// </summary> /// <param name="rdn">the RDN to compare to /// /// @throws IllegalArgumentException if the application compares a name /// with an OID. /// </param> [CLSCompliantAttribute(false)] public virtual bool equals(RDN rdn) { if (this.values.Count != rdn.values.Count) { return false; } int j, i; for (i = 0; i < this.values.Count; i++) { //verify that the current value and type exists in the other list j = 0; //May need a more intellegent compare while (j < values.Count && (!((System.String) this.values[i]).ToUpper().Equals(((System.String) rdn.values[j]).ToUpper()) || !equalAttrType((System.String) this.types[i], (System.String) rdn.types[j]))) { j++; } if (j >= rdn.values.Count) //couldn't find first value return false; } return true; } /// <summary> Internal function used by equal to compare Attribute types. Because /// attribute types could either be an OID or a name. There needs to be a /// Translation mechanism. This function will absract this functionality. /// /// Currently if types differ (Oid and number) then UnsupportedOperation is /// thrown, either one or the other must used. In the future an OID to name /// translation can be used. /// /// /// </summary> private bool equalAttrType(System.String attr1, System.String attr2) { if (System.Char.IsDigit(attr1[0]) ^ System.Char.IsDigit(attr2[0])) //isDigit tests if it is an OID throw new System.ArgumentException("OID numbers are not " + "currently compared to attribute names"); return attr1.ToUpper().Equals(attr2.ToUpper()); } /// <summary> Adds another value to the RDN. Only one attribute type is allowed for /// the RDN. /// </summary> /// <param name="attrType">Attribute type, could be an OID or String /// </param> /// <param name="attrValue">Attribute Value, must be normalized and escaped /// </param> /// <param name="rawValue">or text before normalization, can be Null /// </param> public virtual void add(System.String attrType, System.String attrValue, System.String rawValue) { types.Add(attrType); values.Add(attrValue); this.rawValue += rawValue; } /// <summary> Creates a string that represents this RDN, according to RFC 2253 /// /// </summary> /// <returns> An RDN string /// </returns> public override System.String ToString() { return toString(false); } /// <summary> Creates a string that represents this RDN. /// /// If noTypes is true then Atribute types will be ommited. /// /// </summary> /// <param name="noTypes">true if attribute types will be omitted. /// /// </param> /// <returns> An RDN string /// </returns> [CLSCompliantAttribute(false)] public virtual System.String toString(bool noTypes) { int length = types.Count; System.String toReturn = ""; if (length < 1) return null; if (!noTypes) { toReturn = types[0] + "="; } toReturn += values[0]; for (int i = 1; i < length; i++) { toReturn += "+"; if (!noTypes) { toReturn += (types[i] + "="); } toReturn += values[i]; } return toReturn; } /// <summary> Returns each multivalued name in the current RDN as an array of Strings. /// /// </summary> /// <param name="noTypes">Specifies whether Attribute types are included. The attribute /// type names will be ommitted if the parameter noTypes is true. /// /// </param> /// <returns> List of multivalued Attributes /// </returns> public virtual System.String[] explodeRDN(bool noTypes) { int length = types.Count; if (length < 1) return null; System.String[] toReturn = new System.String[types.Count]; if (!noTypes) { toReturn[0] = types[0] + "="; } toReturn[0] += values[0]; for (int i = 1; i < length; i++) { if (!noTypes) { toReturn[i] += (types[i] + "="); } toReturn[i] += values[i]; } return toReturn; } } //end class RDN }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using DeleteFileLine.Properties; namespace DeleteFileLine { /// <summary> /// Class of the main program. /// </summary> public static class Program { /// <summary> /// Entry point of the program. /// </summary> /// <param name="arguments"> /// All the arguments separated by a white space. /// </param> private static void Main(string[] arguments) { Action<string> display = Console.WriteLine; var argumentDictionary = new Dictionary<string, string> { // Initialization of the dictionary with default values {"filename", string.Empty}, {"separator", ";" }, {"hasheader", "false" }, {"hasfooter", "false"}, {"deleteheader", "false"}, {"deletefooter", "false"}, {"deletefirstcolumn", "false"}, {"samename", "true"}, {"newname", string.Empty}, {"log", "false" }, {"removeemptylines", "true" }, {"countlines", "false" }, {"verifyheaderandfooter", "false" } }; // the variable numberOfInitialDictionaryItems is used for the log to list all non-standard arguments passed in. int numberOfInitialDictionaryItems = 13; var fileContent = new List<string>(); var fileTransformed = new List<string>(); int numberOfLineInfile = 0; bool hasExtraArguments = false; bool fileHasHeader = false; bool fileHasFooter = false; string datedLogFileName = string.Empty; byte returnCode = 1; Stopwatch chrono = new Stopwatch(); if (arguments.Length == 0 || arguments[0].ToLower().Contains("help") || arguments[0].Contains("?")) { Usage(); return; } chrono.Start(); // we split arguments into the dictionary foreach (string argument in arguments) { string argumentKey = string.Empty; string argumentValue = string.Empty; if (argument.IndexOf(':') != -1) { argumentKey = argument.Substring(1, argument.IndexOf(':') - 1).ToLower(); argumentValue = argument.Substring(argument.IndexOf(':') + 1, argument.Length - (argument.IndexOf(':') + 1)); } else { // If we have an argument without the colon sign (:) then we add it to the dictionary argumentKey = argument; argumentValue = "The argument passed in does not have any value. The colon sign (:) is missing."; } if (argumentDictionary.ContainsKey(argumentKey)) { // set the value of the argument argumentDictionary[argumentKey] = argumentValue; } else { // we add any other or new argument into the dictionary to look at them in the log argumentDictionary.Add(argumentKey, argumentValue); hasExtraArguments = true; } } // We check if countlines is true then removeemptyline = true if (argumentDictionary["countlines"] == "true") { argumentDictionary["removeemptylines"] = "true"; } // check that filename doesn't any Windows forbidden characters and trim all space characters at the start of the name. argumentDictionary["filename"] = RemoveWindowsForbiddenCharacters(argumentDictionary["filename"]).TrimStart(); // if log file name is empty in XML file then we define it with a default value like "Log" if (Settings.Default.LogFileName.Trim() == string.Empty) { Settings.Default.LogFileName = "Log.txt"; Settings.Default.Save(); } // if Company name is empty in XML file then we define it with a default value like "Company name" if (Settings.Default.CompanyName.Trim() == string.Empty) { Settings.Default.LogFileName = "Company name"; Settings.Default.Save(); } if (argumentDictionary["filename"].Trim() != string.Empty) { datedLogFileName = AddDateToFileName(Settings.Default.LogFileName); } else { Usage(); return; } // Add version of the program at the beginning of the log Log(datedLogFileName, argumentDictionary["log"], $"DeleteFileLine.exe is in version {GetAssemblyVersion()}"); // We log all arguments passed in. foreach (KeyValuePair<string, string> keyValuePair in argumentDictionary) { if (argumentDictionary["log"] == "true") { Log(datedLogFileName, argumentDictionary["log"], $"Argument requested: {keyValuePair.Key}"); Log(datedLogFileName, argumentDictionary["log"], $"Value of the argument: {keyValuePair.Value}"); } } //we log extra arguments if (hasExtraArguments && argumentDictionary["log"] == "true") { Log(datedLogFileName, argumentDictionary["log"], $"Here are a list of argument passed in but not understood and thus not used."); for (int i = numberOfInitialDictionaryItems; i <= argumentDictionary.Count - 1; i++) { Log(datedLogFileName, argumentDictionary["log"], $"Extra argument requested: {argumentDictionary.Keys.ElementAt(i)}"); Log(datedLogFileName, argumentDictionary["log"], $"Value of the extra argument: {argumentDictionary.Values.ElementAt(i)}"); } } // reading of the CSV file try { if (argumentDictionary["filename"].Trim() != string.Empty) { if (File.Exists(argumentDictionary["filename"])) { using (StreamReader sr = new StreamReader(argumentDictionary["filename"])) { while (!sr.EndOfStream) { string tmpLine = sr.ReadLine(); if (tmpLine != null && tmpLine.StartsWith("0;")) { fileHasHeader = true; } if (tmpLine != null && tmpLine.StartsWith("9;")) { fileHasFooter = true; bool parseLastLineTointOk = int.TryParse(tmpLine.Substring(2, tmpLine.Length - 2).TrimStart('0'), NumberStyles.Any, CultureInfo.InvariantCulture, out numberOfLineInfile); if (!parseLastLineTointOk) { const string tmpErrorMessage = "There was an error while parsing the last line of the file to an integer to know the number of lines in the file."; Log(datedLogFileName, argumentDictionary["log"], $"{tmpErrorMessage}"); Console.WriteLine($"{tmpErrorMessage}"); } } if (tmpLine != null) { if (argumentDictionary["removeemptylines"] == "false") { fileContent.Add(tmpLine); } else if (argumentDictionary["removeemptylines"] == "true" && tmpLine != string.Empty) { fileContent.Add(tmpLine); } } } } Log(datedLogFileName, argumentDictionary["log"], "The file has been read correctly"); if (argumentDictionary["countlines"] == "true") { Log(datedLogFileName, argumentDictionary["log"], $"The footer of the file states {numberOfLineInfile} lines."); } } else { Log(datedLogFileName, argumentDictionary["log"], $"the filename: {argumentDictionary["filename"]} could be read because it doesn't exist"); } } else { Log(datedLogFileName, argumentDictionary["log"], $"the filename: {argumentDictionary["filename"]} is empty, it cannot be read"); } } catch (Exception exception) { Log(datedLogFileName, argumentDictionary["log"], $"There was an error while processing the file {exception}"); Console.WriteLine($"There was an error while processing the file {exception}"); } if (fileContent.Count != 0) { if (argumentDictionary["deleteheader"] == "true" && argumentDictionary["hasheader"] == "true" && fileHasHeader) { Log(datedLogFileName, argumentDictionary["log"], $"Header (which is the first line) has been removed, it was: {fileContent[0]}"); fileContent.RemoveAt(0); } if (argumentDictionary["deletefooter"] == "true" && argumentDictionary["hasfooter"] == "true" && fileContent.Count != 0 && fileHasFooter) { if (argumentDictionary["countlines"] == "true") { Log(datedLogFileName, argumentDictionary["log"], $"{numberOfLineInfile} lines stated in footer"); Log(datedLogFileName, argumentDictionary["log"], $"Footer (which is the last line) has been removed, it was: {fileContent[fileContent.Count - 1]}"); } Log(datedLogFileName, argumentDictionary["log"], $"The file has {fileContent.Count - 1} lines"); fileContent.RemoveAt(fileContent.Count - 1); } if (argumentDictionary["deletefirstcolumn"] == "true" && fileContent.Count != 0) { Log(datedLogFileName, argumentDictionary["log"], "The first column has been deleted"); fileTransformed = new List<string>(); foreach (string line in fileContent) { fileTransformed.Add(line.Substring(line.IndexOf(argumentDictionary["separator"], StringComparison.InvariantCulture) + 1, line.Length - line.IndexOf(argumentDictionary["separator"], StringComparison.InvariantCulture) - 1)); } fileContent = fileTransformed; } // we free up memory fileTransformed = null; //We check integrity of the file i.e. number of line stated equals to the number of line written if (fileContent.Count == numberOfLineInfile && argumentDictionary["countlines"] == "true") { Log(datedLogFileName, argumentDictionary["log"], $"The file has the same number of lines as stated in the last line which is {numberOfLineInfile} lines."); returnCode = Settings.Default.ReturnCodeOK; } else if (fileContent.Count != numberOfLineInfile && argumentDictionary["countlines"] == "true") { Log(datedLogFileName, argumentDictionary["log"], $"The file has not the same number of lines {fileContent.Count} as stated in the last line which is {numberOfLineInfile} lines."); returnCode = Settings.Default.ReturnCodeKO; } if (argumentDictionary["countlines"] == "false") { returnCode = Settings.Default.ReturnCodeOK; } // If the user wants a different name for the transformed file if (argumentDictionary["samename"] == "true" && argumentDictionary["filename"] != string.Empty) { try { File.Delete(argumentDictionary["filename"]); using (StreamWriter sw = new StreamWriter(argumentDictionary["filename"], true)) { foreach (string line in fileContent) { if (argumentDictionary["removeemptylines"] == "true" && line.Trim() != string.Empty) { sw.WriteLine(line); } } } Log(datedLogFileName, argumentDictionary["log"], $"The transformed file has been written correctly:{argumentDictionary["filename"]}"); } catch (Exception exception) { Log(datedLogFileName, argumentDictionary["log"], $"The filename {argumentDictionary["filename"]} cannot be written"); Log(datedLogFileName, argumentDictionary["log"], $"The exception is: {exception}"); } } if (argumentDictionary["samename"] == "false" && argumentDictionary["newname"] != string.Empty) { try { using (StreamWriter sw = new StreamWriter(argumentDictionary["newname"])) { foreach (string line in fileContent) { if (argumentDictionary["removeemptylines"] == "true" && line.Trim() != string.Empty) { sw.WriteLine(line); } } } Log(datedLogFileName, argumentDictionary["log"], $"The transformed file has been written correctly with the new name {argumentDictionary["newname"]}."); } catch (Exception exception) { Log(datedLogFileName, argumentDictionary["log"], $"The filename: {argumentDictionary["newname"]} cannot be written."); Log(Settings.Default.LogFileName, argumentDictionary["log"], $"The exception is: {exception}"); } } Log(Settings.Default.LogFileName, argumentDictionary["log"], $"The header was {Negative(fileHasHeader)}found in the file."); Log(Settings.Default.LogFileName, argumentDictionary["log"], $"The footer was {Negative(fileHasFooter)}found in the file."); } else { // filecontent is empty Log(Settings.Default.LogFileName, argumentDictionary["log"], "The file cannot be processed because it is empty."); } // Managing return code if header or footer were not found if (!fileHasHeader && argumentDictionary["countlines"] == "true" && returnCode != 0) { returnCode = Settings.Default.ReturnCodeHeaderMissing; } if (!fileHasFooter && argumentDictionary["countlines"] == "true" && returnCode != 0) { returnCode = Settings.Default.ReturnCodeFooterMissing; } if (argumentDictionary["countlines"] == "true") { // Managing return code : we write a file with the return code which will be read by the DOS script to import SQL tables into a database. const string returnCodeFileName = "ReturnCode.txt"; try { File.Delete(returnCodeFileName); StreamWriter sw = new StreamWriter(returnCodeFileName, false); sw.WriteLine(returnCode); sw.Close(); Log(datedLogFileName, argumentDictionary["log"], $"The return code has been written into the file {returnCodeFileName}, the return code is {returnCode}."); } catch (UnauthorizedAccessException unauthorizedAccessException) { Log(Settings.Default.LogFileName, argumentDictionary["log"], $"There was an error while writing the return code file: {returnCodeFileName}. The exception is: {unauthorizedAccessException}"); Console.WriteLine($"There was an error while writing the return code file: {returnCodeFileName}. The exception is:{unauthorizedAccessException}"); } catch (IOException ioException) { Log(Settings.Default.LogFileName, argumentDictionary["log"], $"There was an error while writing the return code file: {returnCodeFileName}. The exception is: {ioException}"); Console.WriteLine($"There was an error while writing the return code file: {returnCodeFileName}. The exception is:{ioException}"); } catch (Exception exception) { Log(Settings.Default.LogFileName, argumentDictionary["log"], $"There was an error while writing the return code file: {returnCodeFileName}. The exception is: {exception}"); Console.WriteLine($"There was an error while writing the return code file: {returnCodeFileName}. The exception is:{exception}"); } } chrono.Stop(); TimeSpan tickTimeSpan = chrono.Elapsed; Log(datedLogFileName, argumentDictionary["log"], $"This program took {chrono.ElapsedMilliseconds} milliseconds which is {ConvertToTimeString(tickTimeSpan)}."); Log(datedLogFileName, argumentDictionary["log"], $"END OF LOG."); Log(datedLogFileName, argumentDictionary["log"], "-----------"); } /// <summary> /// Convert a Time span to days hours minutes seconds milliseconds. /// </summary> /// <param name="ts">The time span.</param> /// <param name="removeZeroArgument">Do you want zero argument not send back, true by default.</param> /// <returns>Returns a string with the number of days, hours, minutes, seconds and milliseconds.</returns> public static string ConvertToTimeString(TimeSpan ts, bool removeZeroArgument = true) { string result = string.Empty; if (!removeZeroArgument || ts.Days != 0 ) { result = $"{ts.Days} jour{Plural(ts.Days)} "; } if (!removeZeroArgument || ts.Hours != 0) { result += $"{ts.Hours} heure{Plural(ts.Hours)} "; } if (!removeZeroArgument || ts.Minutes != 0) { result += $"{ts.Minutes} minute{Plural(ts.Minutes)} "; } if (!removeZeroArgument || ts.Seconds != 0) { result += $"{ts.Seconds} seconde{Plural(ts.Seconds)} "; } if (!removeZeroArgument || ts.Milliseconds != 0) { result += $"{ts.Milliseconds} milliseconde{Plural(ts.Milliseconds)}"; } return result.TrimEnd(); } /// <summary> /// Add an 's' if the number is greater than 1. /// </summary> /// <param name="number"></param> /// <returns>Returns an 's' if number if greater than one ortherwise returns an empty string.</returns> public static string Plural(int number) { return number > 1 ? "s" : string.Empty; } /// <summary> /// The method returns the string Not according to the boolean value passed in. /// </summary> /// <param name="booleanValue"></param> /// <returns>Returns the string "Not" or nothing according to the boolean value passed in.</returns> public static string Negative(bool booleanValue) { return booleanValue ? "" : "not "; } /// <summary> /// Remove all Windows forbidden characters for a Windows path. /// </summary> /// <param name="path">The initial string to be processed.</param> /// <returns>A string without Windows forbidden characters.</returns> private static string RemoveWindowsForbiddenCharacters(string path) { string result = path; // We remove all characters which are forbidden for a Windows path string[] forbiddenWindowsFilenameCharacters = { "\\", "/", ":", "*", "?", "\"", "<", ">", "|" }; foreach (var item in forbiddenWindowsFilenameCharacters) { result = result.Replace(item, string.Empty); } return result; } /// <summary> /// Add date to the file name. /// </summary> /// <param name="fileName">The name of the file.</param> /// <returns>A string with the date at the end of the file name.</returns> private static string AddDateToFileName(string fileName) { string result = string.Empty; // We strip the fileName and add a datetime before the extension of the filename. string tmpFileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); string tmpFileNameExtension = Path.GetExtension(fileName); string tmpDateTime = DateTime.Now.ToShortDateString(); tmpDateTime = tmpDateTime.Replace('/', '-'); result = $"{tmpFileNameWithoutExtension}_{tmpDateTime}{tmpFileNameExtension}"; return result; } /// <summary> /// Get assembly version. /// </summary> /// <returns>A string with all assembly versions like major, minor, build.</returns> private static string GetAssemblyVersion() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); return $"{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}"; } /// <summary> /// The log file to record all activities. /// </summary> /// <param name="filename">The name of the file.</param> /// <param name="logging">Do we log or not?</param> /// <param name="message">The message to be logged.</param> private static void Log(string filename, string logging, string message) { if (logging.ToLower() != "true") return; if (filename.Trim() == string.Empty) return; try { StreamWriter sw = new StreamWriter(filename, true); sw.WriteLine($"{DateTime.Now} - {message}"); sw.Close(); } catch (Exception exception) { Console.WriteLine($"There was an error while writing the file: {filename}. The exception is:{exception}"); } } /// <summary> /// If the user requests help or gives no argument, then we display the help section. /// </summary> private static void Usage() { Action<string> display = Console.WriteLine; display(string.Empty); display($"DeleteFileLine is a console application written by Sogeti for {Settings.Default.CompanyName}."); display($"DeleteFileLine.exe is in version {GetAssemblyVersion()}"); display("DeleteFileLine needs Microsoft .NET framework 4.0 to run, if you don't have it, download it from microsoft.com."); display($"Copyrighted (c) 2017 by {Settings.Default.CompanyName}, all rights reserved."); display(string.Empty); display("Usage of this program:"); display(string.Empty); display("List of arguments:"); display(string.Empty); display("/help (this help)"); display("/? (this help)"); display(string.Empty); display( "You can write argument name (not its value) in uppercase or lowercase or a mixed of them (case insensitive)"); display("/filename is the same as /FileName or /fileName or /FILENAME"); display(string.Empty); display("/fileName:<name of the file to be processed>"); display("/separator:<the CSV separator> semicolon (;) is the default separator"); display("/hasHeader:<true or false> false by default"); display("/hasFooter:<true or false> false by default"); display("/deleteHeader:<true or false> false by default"); display("/deleteFooter:<true or false> false by default"); display("/deleteFirstColumn:<true or false> true by default"); display("/sameName:<true or false> true by default"); display("/newName:<new name of the file which has been processed>"); display("/log:<true or false> false by default"); display("/removeemptylines:<true or false> true by default"); display("countlines:<true or false> false by default"); display("verifyheaderandfooter:<true or false> false by default"); display(string.Empty); display("Examples:"); display(string.Empty); display("DeleteFileLine /filename:MyCSVFile.txt /separator:, /hasheader:true /hasfooter:true /deleteheader:true /deletefooter:true /deletefirstcolumn:true /log:true"); display(string.Empty); display("DeleteFileLine /help (this help)"); display("DeleteFileLine /? (this help)"); display(string.Empty); } } }
using FilenameBuddy; using Microsoft.Xna.Framework.Content; using System; using System.Collections.Generic; using System.Linq; using System.Xml; using TetrisRandomizer; using XmlBuddy; namespace FlashCards.Core { /// <summary> /// A pile of flash cards to run through. /// </summary> public class Deck : XmlFileBuddy { #region Properties /// <summary> /// what category of words is covered by this deck /// </summary> public string Category { get; set; } /// <summary> /// list of all the flash cards in this deck /// </summary> public List<FlashCard> Cards { get; private set; } /// <summary> /// the random bag we are gonna use to pull cards out /// </summary> private readonly RandomBag questionRand; private Random translationRand = new Random(); public string Language1 { get; set; } public string Language2 { get; set; } #endregion //Properties #region Methods /// <summary> /// default construictor /// </summary> public Deck() : base("FlashCards.Deck") { Cards = new List<FlashCard>(); questionRand = new RandomBag(10); } /// <summary> /// construcgtor with string /// </summary> /// <param name="filename"></param> public Deck(string filename) : this() { Filename = new Filename(filename); } /// <summary> /// construcgtor with filename /// </summary> /// <param name="filename"></param> public Deck(Filename filename) : this() { Filename = filename; } /// <summary> /// Get a question and answers, with a list of possible incorrect answers. /// </summary> /// <param name="question"></param> /// <param name="correctAnswer"></param> /// <param name="wrongAnswers"></param> public void GetQuestion(out FlashCard questionCard, out Translation correctTranslation, out List<FlashCard> wrongQuestionCards, out List<Translation> wrongTranslations) { //grab a random flash card to be the question questionRand.MaxNum = Cards.Count - 1; var cardIndex = questionRand.Next(); questionCard = Cards[cardIndex]; //Get the correct answer var correctIndex = translationRand.Next(questionCard.Translations.Count); var correctAnswer = questionCard.Translations[correctIndex]; correctTranslation = correctAnswer; //add all the possible incorrect answers wrongQuestionCards = new List<FlashCard>(); wrongTranslations = new List<Translation>(); for (int i = 0; i < Cards.Count; i++) { if (cardIndex != i) { //Get the translation from this card that matches the correct answer var wrongCard = Cards[i]; var wrongAnswer = wrongCard.Translations.FirstOrDefault(x => x.Language == correctAnswer.Language); if (null != wrongAnswer) { wrongQuestionCards.Add(wrongCard); wrongTranslations.Add(wrongAnswer); } } } } /// <summary> /// You can read in multiple decks and add them together to do comprehension lessons. /// </summary> /// <param name="otherDeck">A deck of cards to add to this one</param> public void AddDeck(Deck otherDeck) { //Add the cards Cards.AddRange(otherDeck.Cards); //Add the category Category += ", " + otherDeck.Category; //make sure the random bag will pull the new cards too questionRand.MaxNum = Cards.Count; } #endregion //Methods #region File Parsing public override void ReadXmlFile(ContentManager content = null) { base.ReadXmlFile(content); questionRand.MaxNum = Cards.Count; } public override void ParseXmlNode(XmlNode xmlNode) { string name = xmlNode.Name; string value = xmlNode.InnerText; switch (name) { case "Category": { Category = value; } break; case "FlashCards": { ReadChildNodes(xmlNode, ParseFlashCardXmlNodes); } break; case "Cards": { ReadChildNodes(xmlNode, ParseCardXmlNodes); } break; default: { throw new Exception("unknown XML node: " + name); } } } private void ParseFlashCardXmlNodes(XmlNode xmlNode) { //create a new flash card var card = new FlashCard() { Language1 = this.Language1, Language2 = this.Language2 }; //read it in XmlFileBuddy.ReadChildNodes(xmlNode, card.ParseCardXmlNodes); //store the card Cards.Add(card); } private void ParseCardXmlNodes(XmlNode xmlNode) { //create a new flash card var card = new FlashCard() { Language1 = this.Language1, Language2 = this.Language2 }; //read it in XmlFileBuddy.ReadChildNodes(xmlNode, card.ParseChildNode); //store the card Cards.Add(card); } public override void WriteXmlNodes(System.Xml.XmlTextWriter xmlFile) { xmlFile.WriteStartElement("Category"); xmlFile.WriteString(Category); xmlFile.WriteEndElement(); //write out all the cards xmlFile.WriteStartElement("Cards"); foreach (var card in Cards) { card.WriteXmlNodes(xmlFile); } xmlFile.WriteEndElement(); } #endregion //File Parsing } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using Axiom.MathLib; using Axiom.Core; namespace Multiverse.Tools.WorldEditor { public delegate bool DragComplete(bool accept, Vector3 location); public class DragHelper : IDisposable { protected DragComplete dragCallback; protected WorldEditor app; protected DisplayObject dragObject; protected List<DisplayObject> dragObjs = new List<DisplayObject>(); protected List<IObjectDrag> dragObjects = new List<IObjectDrag>(); protected List<Vector3> dragOffset = new List<Vector3>(); protected List<float> terrainOffset = new List<float>(); protected bool disposeDragObject; protected bool dragging = true; protected bool stopOnUp = false; protected string imageName; protected Vector2 size; protected TerrainDecal decal; protected string name; protected List<IObjectCutCopy> origObjs = new List<IObjectCutCopy>(); protected MouseButtons but; protected Vector3 location = new Vector3(0, 0, 0); protected List<Vector3> dragOffsets; /// <summary> /// Use this constructor when dragging an existing object, or one that needs rotation or scaling. /// </summary> /// <param name="worldEditor"></param> /// <param name="displayObject"></param> /// <param name="callback"></param> public DragHelper(WorldEditor worldEditor, DisplayObject displayObject, DragComplete callback) { app = worldEditor; dragObject = displayObject; dragCallback = callback; disposeDragObject = false; but = app.MouseSelectButton; // set up mouse capture and callbacks for placing the object app.InterceptMouse(new MouseMoveIntercepter(DragMove), new MouseButtonIntercepter(DragButtonDown), new MouseButtonIntercepter(DragButtonUp), new MouseCaptureLost(DragCaptureLost), true); } /// <summary> /// Use this constructor when placing point lights and markers to allow them to be placed on other objects. /// </summary> /// <param name="worldEditor"></param> /// <param name="callback"></param> /// <param name="displayObject"></param> public DragHelper(WorldEditor worldEditor, DragComplete callback, DisplayObject displayObject) { app = worldEditor; dragObject = displayObject; dragCallback = callback; disposeDragObject = false; but = app.MouseSelectButton; // set up mouse capture and callbacks for placing the object app.InterceptMouse(new MouseMoveIntercepter(DragMoveAllowObject), new MouseButtonIntercepter(DragButtonDownAllowObject), new MouseButtonIntercepter(DragButtonUp), new MouseCaptureLost(DragCaptureLost), true); } /// <summary> /// Use this constructor when you want to choose to stop on the mouse up or down. stopOnUP should /// be false for stoping with mouse down and true for stopping on the mouse being up. /// This will preserve the objects scale and rotation. /// /// </summary> /// <param name="worldEditor"></param> /// <param name="displayObject"></param> /// <param name="callback"></param> /// <param name="stopOnUp"></param> public DragHelper(WorldEditor worldEditor, DisplayObject displayObject, DragComplete callback, bool stopOnUp) { app = worldEditor; dragObject = displayObject; dragCallback = callback; disposeDragObject = false; this.stopOnUp = stopOnUp; but = app.MouseSelectButton; // set up mouse capture and callbacks for placing the object app.InterceptMouse(new MouseMoveIntercepter(DragMove), new MouseButtonIntercepter(DragButtonDown), new MouseButtonIntercepter(DragButtonUp), new MouseCaptureLost(DragCaptureLost), true); } /// <summary> /// This is used when placing a single static object it preserves the object rotation and scale and allows placement on another object. /// /// </summary> /// <param name="worldEditor"></param> /// <param name="displayObject"></param> /// <param name="callback"></param> /// <param name="stopOnUp"></param> public DragHelper(WorldEditor worldEditor, DragComplete callback, DisplayObject displayObject, bool stopOnUp) { app = worldEditor; dragObject = displayObject; dragCallback = callback; disposeDragObject = false; this.stopOnUp = stopOnUp; but = app.MouseSelectButton; // set up mouse capture and callbacks for placing the object app.InterceptMouse(new MouseMoveIntercepter(DragMoveAllowObject), new MouseButtonIntercepter(DragButtonDownAllowObject), new MouseButtonIntercepter(DragButtonUp), new MouseCaptureLost(DragCaptureLost), true); } /// <summary> /// Use this constructor when you want the DragHelper to create the displayObject for you /// based on the meshName. /// </summary> /// <param name="worldEditor"></param> /// <param name="meshName"></param> /// <param name="callback"></param> public DragHelper(WorldEditor worldEditor, String meshName, DragComplete callback) { app = worldEditor; dragObject = new DisplayObject(meshName, app, "Drag", app.Scene, meshName, location, new Vector3(1,1,1), new Vector3(0,0,0), null); dragCallback = callback; disposeDragObject = true; but = app.MouseSelectButton; // set up mouse capture and callbacks for placing the object app.InterceptMouse(new MouseMoveIntercepter(DragMove), new MouseButtonIntercepter(DragButtonDown), new MouseButtonIntercepter(DragButtonUp), new MouseCaptureLost(DragCaptureLost), true); } public DragHelper(WorldEditor worldEditor, string meshName, DragComplete callback, bool accept, Vector3 loc, int index) { app = worldEditor; dragCallback = callback; disposeDragObject = true; this.location = loc; but = app.MouseSelectButton; // set up mouse capture and callbacks for placing the object app.InterceptMouse(new MouseMoveIntercepter(DecalDragMove), new MouseButtonIntercepter(DragButtonDown), new MouseButtonIntercepter(DragButtonUp), new MouseCaptureLost(DragCaptureLost), true); } /// <summary> /// Use this constructor when you want to drag a TerrainDecal and have the drag stopped on a left button mouse down. Creates its own decal and disposes it. /// Usually used to place new decals. /// </summary> /// <param name="worldEditor"></param> /// <param name="parent"></param> /// <param name="name"></param> /// <param name="position"></param> /// <param name="size"></param> /// <param name="callback"></param> public DragHelper(WorldEditor worldEditor, IWorldContainer parent, string name, string fname, Vector2 size, DragComplete callback) { this.app = worldEditor; this.imageName = fname; this.size = size; this.name = name; stopOnUp = false; disposeDragObject = true; decal = new TerrainDecal(app, parent, name, new Vector2(0f, 0f), size, imageName, 1); decal.AddToScene(); dragCallback = callback; but = app.MouseSelectButton; app.InterceptMouse(new MouseMoveIntercepter(DecalDragMove), new MouseButtonIntercepter(DecalDragButtonDown), new MouseButtonIntercepter(DecalDragButtonUp), new MouseCaptureLost(DragCaptureLost), true); } /// <summary> /// Use this constructor to drag top level objects. Used when placing objects from the clipboard in to the world and when top level objects (not MPPoints) /// are being dragged. Not used for doing the original placement of points, objects, markers, point lights, or decals. /// </summary> /// <param name="worldEditor"></param> /// <param name="displayObject"></param> /// <param name="callback"></param> /// <param name="stopOnUp"></param> public DragHelper(WorldEditor worldEditor, List<IObjectDrag> dragObjes, List<Vector3> dragOffsets, List<float> terrainOffset, DragComplete callback, bool stopOnUp) { app = worldEditor; dragCallback = callback; disposeDragObject = false; this.stopOnUp = stopOnUp; Vector3 baseObjPosition = dragObjes[0].Position; int i = 0; but = app.MouseSelectButton; foreach (IObjectDrag obj in dragObjes) { this.dragObjects.Add(obj); this.dragOffset.Add(dragOffsets[i]); this.terrainOffset.Add(terrainOffset[i]); i++; } app.InterceptMouse(new MouseMoveIntercepter(MultipleDragMove), new MouseButtonIntercepter(MultipleDragButtonDown), new MouseButtonIntercepter(MultipleDragButtonUp), new MouseCaptureLost(DragCaptureLost), true); } protected void StopDrag(bool accept) { bool valid = dragCallback(accept, location); // if the callback accepts the placement, then stop the drag and clean up if (valid) { app.ReleaseMouse(); if (disposeDragObject) { dragObject.Dispose(); } dragging = false; } } protected void DecalStopDrag(bool accept) { bool valid = dragCallback(accept, location); if (valid) { app.ReleaseMouse(); if (disposeDragObject) { decal.Dispose(); } } } public void DragButtonDown(WorldEditor app, MouseButtons button, int x, int y) { if (dragging) { DragMove(app, x, y); if (button == but) { StopDrag(true); } else { StopDrag(false); } } } public void DragButtonDownAllowObject(WorldEditor app, MouseButtons button, int x, int y) { if (dragging) { DragMoveAllowObject(app, x, y); if (button == but) { StopDrag(true); } else { StopDrag(false); } } } public void DragButtonUp(WorldEditor app, MouseButtons button, int x, int y) { if (dragging && stopOnUp) { DragMove(app, x, y); if (button == but) { StopDrag(true); stopOnUp = false; } else { StopDrag(false); } } } public void DecalDragButtonUp(WorldEditor app, MouseButtons button, int x, int y) { DecalDragMove(app, x, y); if (dragging && stopOnUp) { if (button == but) { DecalStopDrag(true); stopOnUp = false; } } else { DecalStopDrag(false); } } public void DecalDragButtonDown(WorldEditor app, MouseButtons button, int x, int y) { DecalDragMove(app, x, y); if (dragging && !stopOnUp) { if (!stopOnUp && button == but) { DecalStopDrag(true); } } else { DecalStopDrag(false); } } public void MultipleDragButtonDown(WorldEditor app, MouseButtons button, int x, int y) { if (dragging) { MultipleDragMove(app, x, y); if (button == but && !stopOnUp) { StopDrag(true); } else { StopDrag(false); } } } public void MultipleDragButtonUp(WorldEditor app, MouseButtons button, int x, int y) { if (dragging && stopOnUp) { MultipleDragMove(app, x, y); if (button == but) { StopDrag(true); stopOnUp = false; } else { StopDrag(false); } } } public void DragMoveAllowObject(WorldEditor app, int x, int y) { if (dragging) { location = app.ObjectPlacementLocation(x, y); location.y = location.y + dragObject.TerrainOffset; dragObject.Position = location; } } public void DragMove(WorldEditor app, int x, int y) { if (dragging) { location = app.PickTerrain(x, y); location.y = app.GetTerrainHeight(location.x, location.z) + dragObject.TerrainOffset; dragObject.Position = location; } } public void DecalDragMove(WorldEditor app, int x, int y) { if (dragging) { location = app.PickTerrain(x, y); decal.Position = location; } } public void MultipleDragMove(WorldEditor app, int x, int y) { int i = 0; location = app.PickTerrain(x, y); Vector3 position; foreach (IObjectDrag disObject in dragObjects) { switch (disObject.ObjectType) { case "PointLight": case "Marker": case "Object": position = location + dragOffset[i]; if (i == 0) { if (disObject.AllowAdjustHeightOffTerrain) { position = app.ObjectPlacementLocation(x, y) + new Vector3(0, terrainOffset[i], 0); } else { position = app.ObjectPlacementLocation(x, y); } disObject.Position = position; break; } else { if (disObject.AllowAdjustHeightOffTerrain) { position = app.ObjectPlacementLocation(location + dragOffset[i]) + new Vector3(0, terrainOffset[i], 0); } else { position = app.ObjectPlacementLocation(location + dragOffset[i]); } disObject.Position = position; break; } default: position = location + dragOffset[i]; position.y = app.GetTerrainHeight(location.x, location.z); disObject.Position = position; if (String.Equals(disObject.ObjectType, "Points") && (disObject as PointCollection).DisplayMarkers != true) { (disObject as PointCollection).DisplayMarkers = true; } break; } if (!disObject.InScene) { (disObject as IWorldObject).AddToScene(); } i++; } } public void DragCaptureLost(WorldEditor app) { // It looks like we dont need to worry about capture lost //if (dragging) //{ // StopDrag(false); //} } #region IDisposable Members public void Dispose() { if (dragging) { StopDrag(false); } } #endregion } }
namespace todo_list.Droid.UI.Fragments { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Android.Support.V7.Widget; public class TaskListFragment : Android.Support.V4.App.Fragment { #region Inner Classes private class TaskListViewHolder : RecyclerView.ViewHolder { public TextView TitleLabel; public TextView DescriptionLabel; public TaskListViewHolder(View view, Action<int> listener) : base(view) { this.TitleLabel = view.FindViewById<TextView>(Resource.Id.TitleLabel); this.DescriptionLabel = view.FindViewById<TextView>(Resource.Id.DescriptionLabel); view.Click += (sender, e) => listener(Position); } } private class TaskListAdapter : RecyclerView.Adapter { private List<Poco.TodoItem> _tasks = null; public event EventHandler<int> ItemClick; public TaskListAdapter(IEnumerable<Poco.TodoItem> items) { _tasks = new List<Poco.TodoItem>(items); } public override int ItemCount { get { return _tasks.Count; } } void OnClick(int position) { if (ItemClick != null) ItemClick(this, position); } public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) { TaskListViewHolder h = (TaskListViewHolder)holder; Poco.TodoItem item = _tasks[position]; h.TitleLabel.Text = item.Title; h.DescriptionLabel.Text = item.Description; } public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.From(parent.Context); View view = inflater.Inflate(Resource.Layout.CellTask, parent, false); RecyclerView.ViewHolder holder = new TaskListViewHolder(view, OnClick); return holder; } } #endregion #region Constants and Fields private TaskListAdapter _adapter; #endregion #region Widgets private RecyclerView _taskList; #endregion #region Constructors public TaskListFragment() { } #endregion #region Properties #endregion #region Fragment Methods public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); this.HasOptionsMenu = true; } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { #region Desinger Stuff View view = inflater.Inflate(Resource.Layout.FragmentTaskList, container, false); #endregion ((Android.Support.V7.App.AppCompatActivity)this.Activity).SupportActionBar.Show(); ((Android.Support.V7.App.AppCompatActivity)this.Activity).SupportActionBar.Title = "Tasks"; _taskList = view.FindViewById<RecyclerView>(Resource.Id.TaskList); _adapter = new TaskListAdapter(new[] { new Poco.TodoItem() { Title = "Title1", Description = "Description 1" }, new Poco.TodoItem() { Title = "Title2", Description = "Description 2" }, new Poco.TodoItem() { Title = "Title3", Description = "Description 3" }, new Poco.TodoItem() { Title = "Title4", Description = "Description 4" }, new Poco.TodoItem() { Title = "Title5", Description = "Description 5" }, new Poco.TodoItem() { Title = "Title6", Description = "Description 6" }, new Poco.TodoItem() { Title = "Title7", Description = "Description 7" }, new Poco.TodoItem() { Title = "Title8", Description = "Description 8" }, new Poco.TodoItem() { Title = "Title9", Description = "Description 9" }, new Poco.TodoItem() { Title = "Title10", Description = "Description 10" }, new Poco.TodoItem() { Title = "Title11", Description = "Description 11" }, new Poco.TodoItem() { Title = "Title12", Description = "Description 12" }, new Poco.TodoItem() { Title = "Title13", Description = "Description 13" }}); _adapter.ItemClick += _adapter_ItemClick; _taskList.SetLayoutManager(new LinearLayoutManager(this.Context)); _taskList.SetAdapter(_adapter); return view; } public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater) { base.OnCreateOptionsMenu(menu, inflater); menu.Add("New").SetShowAsAction(ShowAsAction.Always); } public override bool OnOptionsItemSelected(IMenuItem item) { switch(item.ItemId) { case 0: return true; // lo stiamo gestendo default: return base.OnOptionsItemSelected(item); } } private void _adapter_ItemClick(object sender, int position) { //int photoNum = position + 1; //Toast.MakeText(this.Context, "This is photo number " + photoNum, ToastLength.Short).Show(); Bundle arguments = new Bundle(); arguments.PutInt("id", position); TaskFragment fragment = new TaskFragment(); fragment.Arguments = arguments; this.FragmentManager.BeginTransaction() .AddToBackStack("before_TaskFragment") // identificatore nel back stack .Replace(Resource.Id.ContentLayout, fragment, "TaskFragment") .Commit(); } public override void OnDestroyView() { base.OnDestroyView(); } #endregion #region Public Methods #endregion #region Methods #endregion #region Event Handlers #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; #if !NOT_UNITY3D using UnityEngine; #endif namespace ModestTree.Util { public static class ReflectionUtil { public static bool IsGenericList(Type type) { return type.IsGenericType() && type.GetGenericTypeDefinition() == typeof(List<>); } public static bool IsGenericList(Type type, out Type contentsType) { if (IsGenericList(type)) { contentsType = type.GenericArguments().Single(); return true; } contentsType = null; return false; } public static IList CreateGenericList(Type elementType, object[] contentsAsObj) { var genericType = typeof(List<>).MakeGenericType(elementType); var list = (IList)Activator.CreateInstance(genericType); foreach (var obj in contentsAsObj) { if (obj != null) { Assert.That(obj.GetType().DerivesFromOrEqual(elementType), "Wrong type when creating generic list, expected something assignable from '"+ elementType +"', but found '" + obj.GetType() + "'"); } list.Add(obj); } return list; } public static IDictionary CreateGenericDictionary( Type keyType, Type valueType, object[] keysAsObj, object[] valuesAsObj) { Assert.That(keysAsObj.Length == valuesAsObj.Length); var genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); var dictionary = (IDictionary)Activator.CreateInstance(genericType); for (int i = 0; i < keysAsObj.Length; i++) { dictionary.Add(keysAsObj[i], valuesAsObj[i]); } return dictionary; } public static object DowncastList<TFrom, TTo>(IEnumerable<TFrom> fromList) where TTo : class, TFrom { var toList = new List<TTo>(); foreach (var obj in fromList) { toList.Add(obj as TTo); } return toList; } public static IEnumerable<IMemberInfo> GetFieldsAndProperties<T>(BindingFlags flags) { return GetFieldsAndProperties(typeof(T), flags); } public static IEnumerable<IMemberInfo> GetFieldsAndProperties(Type type, BindingFlags flags) { foreach (var propInfo in type.GetProperties(flags)) { yield return new PropertyMemberInfo(propInfo); } foreach (var fieldInfo in type.GetFields(flags)) { yield return new FieldMemberInfo(fieldInfo); } } public static string ToDebugString(this MethodInfo method) { return "{0}.{1}".Fmt(method.DeclaringType.Name(), method.Name); } public static string ToDebugString(this Action action) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return action.ToString(); #else return action.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1>(this Action<TParam1> action) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return action.ToString(); #else return action.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1, TParam2>(this Action<TParam1, TParam2> action) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return action.ToString(); #else return action.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1, TParam2, TParam3>(this Action<TParam1, TParam2, TParam3> action) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return action.ToString(); #else return action.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1, TParam2, TParam3, TParam4>(this Action<TParam1, TParam2, TParam3, TParam4> action) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return action.ToString(); #else return action.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1, TParam2, TParam3, TParam4, TParam5>(this ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5> action) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return action.ToString(); #else return action.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6>(this ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> action) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return action.ToString(); #else return action.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1>(this Func<TParam1> func) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return func.ToString(); #else return func.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1, TParam2>(this Func<TParam1, TParam2> func) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return func.ToString(); #else return func.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1, TParam2, TParam3>(this Func<TParam1, TParam2, TParam3> func) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return func.ToString(); #else return func.Method.ToDebugString(); #endif } public static string ToDebugString<TParam1, TParam2, TParam3, TParam4>(this Func<TParam1, TParam2, TParam3, TParam4> func) { #if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR return func.ToString(); #else return func.Method.ToDebugString(); #endif } public interface IMemberInfo { Type MemberType { get; } string MemberName { get; } object GetValue(object instance); void SetValue(object instance, object value); } public class PropertyMemberInfo : IMemberInfo { PropertyInfo _propInfo; public PropertyMemberInfo(PropertyInfo propInfo) { _propInfo = propInfo; } public Type MemberType { get { return _propInfo.PropertyType; } } public string MemberName { get { return _propInfo.Name; } } public object GetValue(object instance) { try { #if NOT_UNITY3D return _propInfo.GetValue(instance, null); #else if (Application.platform == RuntimePlatform.WebGLPlayer) { // GetValue() doesn't work on webgl for some reason // This is a bit slower though so only do this on webgl return _propInfo.GetGetMethod().Invoke(instance, null); } else { return _propInfo.GetValue(instance, null); } #endif } catch (Exception e) { throw new Exception("Error occurred while accessing property '{0}'".Fmt(_propInfo.Name), e); } } public void SetValue(object instance, object value) { _propInfo.SetValue(instance, value, null); } } public class FieldMemberInfo : IMemberInfo { FieldInfo _fieldInfo; public FieldMemberInfo(FieldInfo fieldInfo) { _fieldInfo = fieldInfo; } public Type MemberType { get { return _fieldInfo.FieldType; } } public string MemberName { get { return _fieldInfo.Name; } } public object GetValue(object instance) { return _fieldInfo.GetValue(instance); } public void SetValue(object instance, object value) { _fieldInfo.SetValue(instance, value); } } } }
using System; using System.IO; using System.Collections; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Runtime.Serialization.Formatters; using System.Reflection; using System.Threading; using log4net; using log4net.Config; using PNUnit.Framework; using NUnit.Util; namespace PNUnit.Agent { class Agent { [STAThread] static void Main(string[] args) { ConfigureLogging(); AgentConfig config = new AgentConfig(); // read --daemon bool bDaemonMode = ReadFlag(args, "--daemon"); bool bDomainPool = ReadFlag(args, "--domainpool"); bool bNoTimeout = ReadFlag(args, "--notimeout"); string configfile = ReadArg(args); int port = -1; string pathtoassemblies = ReadArg(args); if (pathtoassemblies != null) { port = int.Parse(configfile); configfile = null; } // Load the test configuration file if (pathtoassemblies == null && configfile == null) { Console.WriteLine("Usage: agent [configfile | port path_to_assemblies] [--daemon] [--domainpool] [--noTimeout]"); return; } if (configfile != null) { config = AgentConfigLoader.LoadFromFile(configfile); if (config == null) { Console.WriteLine("No agent.conf file found"); } } else { config.Port = port; config.PathToAssemblies = pathtoassemblies; } // only override if set if( bDomainPool ) { config.UseDomainPool = true; } if( bNoTimeout ) { config.NoTimeout = true; } // initialize NUnit services // Add Standard Services to ServiceManager ServiceManager.Services.AddService(new SettingsService()); ServiceManager.Services.AddService(new DomainManager()); ServiceManager.Services.AddService(new ProjectService()); // initialize NUnit services // Add Standard Services to ServiceManager ServiceManager.Services.AddService(new SettingsService()); ServiceManager.Services.AddService(new DomainManager()); ServiceManager.Services.AddService(new ProjectService()); // Initialize Services ServiceManager.Services.InitializeServices(); PNUnitAgent agent = new PNUnitAgent(); agent.Run(config, bDaemonMode); } private static bool ReadFlag(string[] args, string flag) { for (int i = args.Length - 1; i >= 0; --i) if (args[i] == flag) { args[i] = null; return true; } return false; } private static string ReadArg(string[] args) { for (int i = 0; i < args.Length; ++i) if (args[i] != null) { string result = args[i]; args[i] = null; return result; } return null; } private static void ConfigureLogging() { string log4netpath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "agent.log.conf"); XmlConfigurator.Configure(new FileInfo(log4netpath)); } } public class PNUnitAgent : MarshalByRefObject, IPNUnitAgent { private AgentConfig mConfig; private static readonly ILog log = LogManager.GetLogger(typeof(PNUnitAgent)); #region IPNUnitAgent public void RunTest(PNUnitTestInfo info) { log.InfoFormat("RunTest called for Test {0}, AssemblyName {1}, TestToRun {2}", info.TestName, info.AssemblyName, info.TestToRun); new PNUnitTestRunner(info, mConfig).Run(); } #endregion #region MarshallByRefObject // Lives forever public override object InitializeLifetimeService() { return null; } #endregion private void ConfigureRemoting(int port) { if( File.Exists("agent.remoting.conf") ) { log.Info("Using agent.remoting.conf"); #if CLR_2_0 || CLR_4_0 RemotingConfiguration.Configure("agent.remoting.conf", false); #else RemotingConfiguration.Configure("agent.remoting.conf"); #endif return; } // init remoting BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider(); BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full; IDictionary props = new Hashtable(); props["port"] = port; string s = System.Guid.NewGuid().ToString(); props["name"] = s; props["typeFilterLevel"] = TypeFilterLevel.Full; try { TcpChannel chan = new TcpChannel( props, clientProvider, serverProvider); log.InfoFormat("Registering channel on port {0}", port); #if CLR_2_0 || CLR_4_0 ChannelServices.RegisterChannel(chan, false); #else ChannelServices.RegisterChannel(chan); #endif } catch (Exception e) { log.InfoFormat("Can't register channel.\n{0}", e.Message); return; } } public void Run(AgentConfig config, bool bDaemonMode) { if( config.UseDomainPool ) log.Info("Agent using a domain pool to launch tests"); mConfig = config; ConfigureRemoting(mConfig.Port); // publish RemotingServices.Marshal(this, PNUnit.Framework.Names.PNUnitAgentServiceName); // otherwise in .NET 2.0 memory grows continuosly FreeMemory(); if( bDaemonMode ) { // wait continously while (true) { Thread.Sleep(10000); } } else { string line; while( (line = Console.ReadLine()) != "" ) { switch( line ) { case "gc": Console.WriteLine("Cleaning up memory {0} Mb", GC.GetTotalMemory(true)/1024/1024); break; case "collect": Console.WriteLine("Collecting memory {0} Mb", GC.GetTotalMemory(false)/1024/1024); GC.Collect(); Console.WriteLine("Memory collected {0} Mb", GC.GetTotalMemory(false)/1024/1024); break; } } } //RemotingServices.Disconnect(this); } private void FreeMemory() { GC.GetTotalMemory(true); } } }
// (c) Xavalon. All rights reserved. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Xml; using Xavalon.XamlStyler.Extensions; using Xavalon.XamlStyler.MarkupExtensions.Formatter; using Xavalon.XamlStyler.Model; using Xavalon.XamlStyler.Options; using Xavalon.XamlStyler.Parser; using Xavalon.XamlStyler.Services; namespace Xavalon.XamlStyler.DocumentProcessors { internal class ElementDocumentProcessor : IDocumentProcessor { private readonly IStylerOptions options; private readonly AttributeInfoFactory attributeInfoFactory; private readonly AttributeInfoFormatter attributeInfoFormatter; private readonly IndentService indentService; private readonly XmlEscapingService xmlEscapingService; private readonly IList<string> noNewLineElementsList; private readonly IList<string> firstLineAttributes; private readonly string[] inlineCollections = { "TextBlock", "RichTextBlock", "Paragraph", "Run", "Span", "InlineUIContainer", "AnchoredBlock" }; private readonly string[] inlineTypes = { "Paragraph", "Run", "Span", "InlineUIContainer", "AnchoredBlock", "Hyperlink", "Bold", "Italic", "Underline", "LineBreak" }; public ElementDocumentProcessor( IStylerOptions options, AttributeInfoFactory attributeInfoFactory, AttributeInfoFormatter attributeInfoFormatter, IndentService indentService, XmlEscapingService xmlEscapingService) { this.options = options; this.attributeInfoFactory = attributeInfoFactory; this.attributeInfoFormatter = attributeInfoFormatter; this.indentService = indentService; this.xmlEscapingService = xmlEscapingService; this.noNewLineElementsList = options.NoNewLineElements.ToList(); this.firstLineAttributes = options.FirstLineAttributes.ToList(); } public void Process(XmlReader xmlReader, StringBuilder output, ElementProcessContext elementProcessContext) { elementProcessContext.UpdateParentElementProcessStatus(ContentTypes.Mixed); var elementName = xmlReader.Name; elementProcessContext.Push( new ElementProcessStatus { Parent = elementProcessContext.Current, Name = elementName, ContentType = ContentTypes.None, IsMultlineStartTag = false, IsPreservingSpace = elementProcessContext.Current.IsPreservingSpace }); var currentIndentString = this.indentService.GetIndentString(xmlReader.Depth); var attributeIndetationString = this.GetAttributeIndetationString(xmlReader); // Calculate how element should be indented if (!elementProcessContext.Current.IsPreservingSpace) { // Preserve spacing if element is an inline type has a parent that supports inline types. if ((elementProcessContext.Current.Parent.Name != null) && this.inlineCollections.Any(elementProcessContext.Current.Parent.Name.Contains) && this.inlineTypes.Any(elementName.Contains)) { elementProcessContext.Current.Parent.IsSignificantWhiteSpace = true; if ((output.Length == 0) || output.IsNewLine()) { output.Append(currentIndentString); } } else { elementProcessContext.Current.Parent.IsSignificantWhiteSpace = false; if ((output.Length == 0) || output.IsNewLine()) { output.Append(currentIndentString); } else { output.Append(Environment.NewLine).Append(currentIndentString); } } } // Output the element itself. output.Append('<').Append(elementName); bool isEmptyElement = xmlReader.IsEmptyElement; if (xmlReader.HasAttributes) { bool isNoLineBreakElement = this.IsNoLineBreakElement(elementName); this.ProcessAttributes( xmlReader, output, elementProcessContext, isNoLineBreakElement, attributeIndetationString); } // Determine if to put ending bracket on new line. bool putEndingBracketOnNewLine = (this.options.PutEndingBracketOnNewLine && elementProcessContext.Current.IsMultlineStartTag); if (putEndingBracketOnNewLine) { // Indent ending bracket just like an attribute. output.Append(Environment.NewLine).Append(attributeIndetationString); } if (isEmptyElement) { if (!putEndingBracketOnNewLine && this.options.SpaceBeforeClosingSlash) { output.Append(' '); } output.Append("/>"); // Self closing element. Remember to pop element context. elementProcessContext.Pop(); } else { output.Append(">"); } } private void ProcessAttributes( XmlReader xmlReader, StringBuilder output, ElementProcessContext elementProcessContext, bool isNoLineBreakElement, string attributeIndentationString) { var list = new List<AttributeInfo>(xmlReader.AttributeCount); var firstLineList = new List<AttributeInfo>(xmlReader.AttributeCount); while (xmlReader.MoveToNextAttribute()) { var attributeInfo = this.attributeInfoFactory.Create(xmlReader); list.Add(attributeInfo); // Maintain separate list of first line attributes. if (this.options.EnableAttributeReordering && this.IsFirstLineAttribute(attributeInfo.Name)) { firstLineList.Add(attributeInfo); } // Check for xml:space as defined in http://www.w3.org/TR/2008/REC-xml-20081126/#sec-white-space if (xmlReader.IsXmlSpaceAttribute()) { elementProcessContext.Current.IsPreservingSpace = (xmlReader.Value == "preserve"); } } if (this.options.EnableAttributeReordering) { // .NET performs insertion sort if collection partition size is fewer than 16 elements, but it uses // Heapsort or Quicksort under different conditions. This can lead to an unstable sort and randomized // attributbes while formatting. Even though insertion sort is less performant, XAML elements with more // than 16 attributes are not common, so the effect of forcing insertion sort is negligable in all but // the most extreme of cases. - https://msdn.microsoft.com/en-us/library/b0zbh7b6(v=vs.110).aspx list.InsertionSort(this.AttributeInfoComparison); firstLineList.InsertionSort(this.AttributeInfoComparison); } var noLineBreakInAttributes = (list.Count <= this.options.AttributesTolerance) || isNoLineBreakElement; var forceLineBreakInAttributes = false; // Root element? if (elementProcessContext.Count == 2) { switch (this.options.RootElementLineBreakRule) { case LineBreakRule.Default: break; case LineBreakRule.Always: noLineBreakInAttributes = false; forceLineBreakInAttributes = true; break; case LineBreakRule.Never: noLineBreakInAttributes = true; break; default: throw new NotImplementedException(); } } // No need to break attributes. if (noLineBreakInAttributes) { foreach (var attrInfo in list) { output.Append(' ').Append(this.attributeInfoFormatter.ToSingleLineString(attrInfo)); } elementProcessContext.Current.IsMultlineStartTag = false; } else { // Need to break attributes. var attributeLines = new List<string>(); var currentLineBuffer = new StringBuilder(); int attributeCountInCurrentLineBuffer = 0; int xmlnsAliasesBypassLengthInCurrentLine = 0; AttributeInfo lastAttributeInfo = null; // Process first line attributes. string firstLine = String.Empty; foreach (var attrInfo in firstLineList) { firstLine = $"{firstLine} {this.attributeInfoFormatter.ToSingleLineString(attrInfo)}"; } if (firstLine.Length > 0) { attributeLines.Add(firstLine); } foreach (AttributeInfo attrInfo in list) { // Skip attributes already added to first line. if (firstLineList.Contains(attrInfo)) { continue; } // Attributes with markup extension, always put on new line if (attrInfo.IsMarkupExtension && this.options.FormatMarkupExtension) { if (currentLineBuffer.Length > 0) { attributeLines.Add(currentLineBuffer.ToString()); currentLineBuffer.Length = 0; attributeCountInCurrentLineBuffer = 0; } attributeLines.Add( this.attributeInfoFormatter.ToMultiLineString(attrInfo, attributeIndentationString)); } else { string pendingAppend = this.attributeInfoFormatter.ToSingleLineString(attrInfo); var actualPendingAppend = this.xmlEscapingService.RestoreXmlnsAliasesBypass(pendingAppend); xmlnsAliasesBypassLengthInCurrentLine += pendingAppend.Length - actualPendingAppend.Length; bool isAttributeCharLengthExceeded = (attributeCountInCurrentLineBuffer > 0) && (this.options.MaxAttributeCharactersPerLine > 0) && ((currentLineBuffer.Length + pendingAppend.Length - xmlnsAliasesBypassLengthInCurrentLine) > this.options.MaxAttributeCharactersPerLine); bool isAttributeCountExceeded = (this.options.MaxAttributesPerLine > 0) && ((attributeCountInCurrentLineBuffer + 1) > this.options.MaxAttributesPerLine); bool isAttributeRuleGroupChanged = this.options.PutAttributeOrderRuleGroupsOnSeparateLines && (lastAttributeInfo != null) && (lastAttributeInfo.OrderRule.Group != attrInfo.OrderRule.Group); if ((currentLineBuffer.Length > 0) && (forceLineBreakInAttributes || isAttributeCharLengthExceeded || isAttributeCountExceeded || isAttributeRuleGroupChanged)) { attributeLines.Add(currentLineBuffer.ToString()); currentLineBuffer.Length = 0; attributeCountInCurrentLineBuffer = 0; xmlnsAliasesBypassLengthInCurrentLine = 0; } currentLineBuffer.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pendingAppend); attributeCountInCurrentLineBuffer++; xmlnsAliasesBypassLengthInCurrentLine += pendingAppend.Length - actualPendingAppend.Length; } lastAttributeInfo = attrInfo; } if (currentLineBuffer.Length > 0) { attributeLines.Add(currentLineBuffer.ToString()); } for (int i = 0; i < attributeLines.Count; i++) { // Put first attribute line on same line as element? if ((i == 0) && (this.options.KeepFirstAttributeOnSameLine || (firstLineList.Count > 0))) { output.Append(' ').Append(attributeLines[i].Trim()); } else { output.Append(Environment.NewLine) .Append(this.indentService.Normalize(attributeIndentationString + attributeLines[i].Trim())); } } elementProcessContext.Current.IsMultlineStartTag = true; } } private int AttributeInfoComparison(AttributeInfo x, AttributeInfo y) { if (x.OrderRule.Group != y.OrderRule.Group) { return x.OrderRule.Group.CompareTo(y.OrderRule.Group); } if (x.OrderRule.Priority != y.OrderRule.Priority) { return x.OrderRule.Priority.CompareTo(y.OrderRule.Priority); } if (this.options.OrderAttributesByName) { if (x.AttributeHasIgnoredNamespace && y.AttributeHasIgnoredNamespace) { return String.Compare(x.AttributeNameWithoutNamespace, y.AttributeNameWithoutNamespace, StringComparison.Ordinal); } // If we have attribute with ignored namespace, we want to compare it by full name // if it is compared with analogical attribute without this namespace. else if (x.AttributeHasIgnoredNamespace && ! String.Equals(x.AttributeNameWithoutNamespace, y.Name, StringComparison.InvariantCulture)) { return String.Compare(x.AttributeNameWithoutNamespace, y.Name, StringComparison.Ordinal); } // If we have attribute with ignored namespace, we want to compare it by full name // if it is compared with analogical attribute without this namespace. else if (y.AttributeHasIgnoredNamespace && ! String.Equals(y.AttributeNameWithoutNamespace, x.Name, StringComparison.InvariantCulture)) { return String.Compare(x.Name, y.AttributeNameWithoutNamespace, StringComparison.Ordinal); } else { return String.Compare(x.Name, y.Name, StringComparison.Ordinal); } } return 0; } private string GetAttributeIndetationString(XmlReader xmlReader) { if (this.options.AttributeIndentation == 0) { if (this.options.KeepFirstAttributeOnSameLine) { return this.indentService.GetIndentString(xmlReader.Depth, (xmlReader.Name.Length + 2)); } else { return this.indentService.GetIndentString(xmlReader.Depth + 1); } } else { return this.indentService.GetIndentString(xmlReader.Depth, this.options.AttributeIndentation); } } private bool IsFirstLineAttribute(string attributeName) { return this.firstLineAttributes.Contains(attributeName); } private bool IsNoLineBreakElement(string elementName) { return this.noNewLineElementsList.Contains(elementName); } } }
/* * OEML - REST API * * This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) * * The version of the OpenAPI document: v1 * Contact: support@coinapi.io * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using RestSharp; using CoinAPI.OMS.REST.V1.Client; using CoinAPI.OMS.REST.V1.Model; namespace CoinAPI.OMS.REST.V1.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IBalancesApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Get balances /// </summary> /// <remarks> /// Get current currency balance from all or single exchange. /// </remarks> /// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="exchangeId">Filter the balances to the specific exchange. (optional)</param> /// <returns>List&lt;Balance&gt;</returns> List<Balance> V1BalancesGet (string exchangeId = default(string)); /// <summary> /// Get balances /// </summary> /// <remarks> /// Get current currency balance from all or single exchange. /// </remarks> /// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="exchangeId">Filter the balances to the specific exchange. (optional)</param> /// <returns>ApiResponse of List&lt;Balance&gt;</returns> ApiResponse<List<Balance>> V1BalancesGetWithHttpInfo (string exchangeId = default(string)); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Get balances /// </summary> /// <remarks> /// Get current currency balance from all or single exchange. /// </remarks> /// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="exchangeId">Filter the balances to the specific exchange. (optional)</param> /// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param> /// <returns>Task of List&lt;Balance&gt;</returns> System.Threading.Tasks.Task<List<Balance>> V1BalancesGetAsync (string exchangeId = default(string), CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get balances /// </summary> /// <remarks> /// Get current currency balance from all or single exchange. /// </remarks> /// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="exchangeId">Filter the balances to the specific exchange. (optional)</param> /// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param> /// <returns>Task of ApiResponse (List&lt;Balance&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<Balance>>> V1BalancesGetWithHttpInfoAsync (string exchangeId = default(string), CancellationToken cancellationToken = default(CancellationToken)); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class BalancesApi : IBalancesApi { private CoinAPI.OMS.REST.V1.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="BalancesApi"/> class. /// </summary> /// <returns></returns> public BalancesApi(String basePath) { this.Configuration = new CoinAPI.OMS.REST.V1.Client.Configuration { BasePath = basePath }; ExceptionFactory = CoinAPI.OMS.REST.V1.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="BalancesApi"/> class /// </summary> /// <returns></returns> public BalancesApi() { this.Configuration = CoinAPI.OMS.REST.V1.Client.Configuration.Default; ExceptionFactory = CoinAPI.OMS.REST.V1.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="BalancesApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public BalancesApi(CoinAPI.OMS.REST.V1.Client.Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = CoinAPI.OMS.REST.V1.Client.Configuration.Default; else this.Configuration = configuration; ExceptionFactory = CoinAPI.OMS.REST.V1.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public CoinAPI.OMS.REST.V1.Client.Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public CoinAPI.OMS.REST.V1.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public IDictionary<String, String> DefaultHeader() { return new ReadOnlyDictionary<string, string>(this.Configuration.DefaultHeader); } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Get balances Get current currency balance from all or single exchange. /// </summary> /// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="exchangeId">Filter the balances to the specific exchange. (optional)</param> /// <returns>List&lt;Balance&gt;</returns> public List<Balance> V1BalancesGet (string exchangeId = default(string)) { ApiResponse<List<Balance>> localVarResponse = V1BalancesGetWithHttpInfo(exchangeId); return localVarResponse.Data; } /// <summary> /// Get balances Get current currency balance from all or single exchange. /// </summary> /// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="exchangeId">Filter the balances to the specific exchange. (optional)</param> /// <returns>ApiResponse of List&lt;Balance&gt;</returns> public ApiResponse<List<Balance>> V1BalancesGetWithHttpInfo (string exchangeId = default(string)) { var localVarPath = "/v1/balances"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "appliction/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (exchangeId != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "exchange_id", exchangeId)); // query parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("V1BalancesGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<Balance>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (List<Balance>) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Balance>))); } /// <summary> /// Get balances Get current currency balance from all or single exchange. /// </summary> /// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="exchangeId">Filter the balances to the specific exchange. (optional)</param> /// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param> /// <returns>Task of List&lt;Balance&gt;</returns> public async System.Threading.Tasks.Task<List<Balance>> V1BalancesGetAsync (string exchangeId = default(string), CancellationToken cancellationToken = default(CancellationToken)) { ApiResponse<List<Balance>> localVarResponse = await V1BalancesGetWithHttpInfoAsync(exchangeId, cancellationToken); return localVarResponse.Data; } /// <summary> /// Get balances Get current currency balance from all or single exchange. /// </summary> /// <exception cref="CoinAPI.OMS.REST.V1.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="exchangeId">Filter the balances to the specific exchange. (optional)</param> /// <param name="cancellationToken">Cancellation Token to cancel request (optional) </param> /// <returns>Task of ApiResponse (List&lt;Balance&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<Balance>>> V1BalancesGetWithHttpInfoAsync (string exchangeId = default(string), CancellationToken cancellationToken = default(CancellationToken)) { var localVarPath = "/v1/balances"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new List<KeyValuePair<String, String>>(); var localVarHeaderParams = new Dictionary<String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "appliction/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (exchangeId != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("", "exchange_id", exchangeId)); // query parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType, cancellationToken); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("V1BalancesGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<Balance>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), (List<Balance>) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Balance>))); } } }
namespace newtelligence.DasBlog.Web { using System; using System.Data; using System.Drawing; using System.Web; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.IO; using System.Xml; using System.Xml.Serialization; using newtelligence.DasBlog.Web.Core; /// <summary> /// Summary description for EditNavigatorLinksBox. /// </summary> public partial class EditNavigatorLinksBox : System.Web.UI.UserControl { protected NavigationRoot navigationRoot; protected System.Web.UI.WebControls.RequiredFieldValidator validatorRFname; private string baseFileName="navigatorLinks.xml"; protected System.Resources.ResourceManager resmgr; public string BaseFileName { get { return baseFileName; } set { baseFileName = value; } } private void SaveList( string fileName ) { using (StreamWriter s = new StreamWriter(fileName,false,System.Text.Encoding.UTF8)) { XmlSerializer ser = new XmlSerializer(typeof(NavigationRoot)); ser.Serialize(s,navigationRoot); } } private void LoadList( string fileName ) { if (File.Exists(fileName)) { using (Stream s = File.OpenRead(fileName)) { XmlSerializer ser = new XmlSerializer(typeof(NavigationRoot)); navigationRoot = (NavigationRoot)ser.Deserialize(s); } } else { navigationRoot = new NavigationRoot(); } Session["newtelligence.DasBlog.Web.EditNavigatorLinksBox.NavigationRoot"] = navigationRoot; } private void BindGrid() { navigatorLinksGrid.DataSource = navigationRoot.Items; navigatorLinksGrid.Columns[0].HeaderText = resmgr.GetString("text_navigatorlinks_title"); DataBind(); } protected void Page_Load(object sender, System.EventArgs e) { if (SiteSecurity.IsInRole("admin") == false) { Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html"); } resmgr = ((System.Resources.ResourceManager)ApplicationResourceTable.Get()); if ( !IsPostBack || Session["newtelligence.DasBlog.Web.EditNavigatorLinksBox.NavigationRoot"] == null ) { SharedBasePage requestPage = Page as SharedBasePage; string fileName = Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(),baseFileName); LoadList( fileName ); } else { navigationRoot = Session["newtelligence.DasBlog.Web.EditNavigatorLinksBox.NavigationRoot"] as NavigationRoot; } BindGrid(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.navigatorLinksGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.navigatorLinksGrid_ItemCommand); this.navigatorLinksGrid.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.navigatorLinksGrid_PageIndexChanged); this.navigatorLinksGrid.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.navigatorLinksGrid_CancelCommand); this.navigatorLinksGrid.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.navigatorLinksGrid_EditCommand); this.navigatorLinksGrid.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.navigatorLinksGrid_UpdateCommand); this.navigatorLinksGrid.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.navigatorLinksGrid_DeleteCommand); } #endregion private void navigatorLinksGrid_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { navigatorLinksGrid.EditItemIndex = e.Item.ItemIndex; navigatorLinksGrid.DataBind(); } private void navigatorLinksGrid_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { navigationRoot.Items.RemoveAt(e.Item.DataSetIndex); SaveList( Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(),baseFileName)); Session["newtelligence.DasBlog.Web.EditNavigatorLinksBox.NavigationRoot"] = null; Response.Redirect( Page.Request.Url.AbsoluteUri, true ); } private void navigatorLinksGrid_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { navigatorLinksGrid.EditItemIndex = -1; navigatorLinksGrid.DataBind(); } private void navigatorLinksGrid_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { NavigationLink link = navigationRoot.Items[e.Item.DataSetIndex]; link.Name = ((TextBox)e.Item.FindControl("textname")).Text; link.Url = ((TextBox)e.Item.FindControl("texturl")).Text; SaveList( Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(),baseFileName)); Session["newtelligence.DasBlog.Web.EditNavigatorLinksBox.NavigationRoot"] = null; Response.Redirect( Page.Request.Url.AbsoluteUri, true ); } private void navigatorLinksGrid_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e) { navigatorLinksGrid.CurrentPageIndex = e.NewPageIndex; navigatorLinksGrid.DataBind(); } private void navigatorLinksGrid_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { if ( e.CommandName == "AddItem" ) { NavigationLink newLink = new NavigationLink(); newLink.Name = "New Entry"; navigationRoot.Items.Insert(0,newLink); navigatorLinksGrid.CurrentPageIndex = 0; navigatorLinksGrid.EditItemIndex = 0; BindGrid(); } else if ( e.CommandName == "MoveUp" && e.Item != null ) { int position = e.Item.DataSetIndex; if ( position > 0 ) { NavigationLink link = new NavigationLink(); link.Name = navigationRoot.Items[position].Name; link.Url = navigationRoot.Items[position].Url; navigationRoot.Items.RemoveAt( position ); navigationRoot.Items.Insert( position-1, link ); navigatorLinksGrid.CurrentPageIndex = (position-1) / navigatorLinksGrid.PageSize; if ( navigatorLinksGrid.EditItemIndex == position ) { navigatorLinksGrid.EditItemIndex = position - 1; } else if ( navigatorLinksGrid.EditItemIndex == position - 1) { navigatorLinksGrid.EditItemIndex = position; } } SaveList( Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(),baseFileName)); Session["newtelligence.DasBlog.Web.EditNavigatorLinksBox.NavigationRoot"] = null; Response.Redirect( Page.Request.Url.AbsoluteUri, true ); } else if ( e.CommandName == "MoveDown" && e.Item != null ) { int position = e.Item.DataSetIndex; if ( position < navigationRoot.Items.Count-1 ) { NavigationLink link = new NavigationLink(); link.Name = navigationRoot.Items[position].Name; link.Url = navigationRoot.Items[position].Url; navigationRoot.Items.RemoveAt( position ); navigationRoot.Items.Insert( position+1, link ); navigatorLinksGrid.CurrentPageIndex = (position+1) / navigatorLinksGrid.PageSize; if ( navigatorLinksGrid.EditItemIndex == position ) { navigatorLinksGrid.EditItemIndex = position + 1; } else if ( navigatorLinksGrid.EditItemIndex == position + 1) { navigatorLinksGrid.EditItemIndex = position; } } SaveList( Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(),baseFileName)); Session["newtelligence.DasBlog.Web.EditNavigatorLinksBox.NavigationRoot"] = null; Response.Redirect( Page.Request.Url.AbsoluteUri, true ); } } } }
// 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 Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Algorithms.Tests { public class IncrementalHashTests { // Some arbitrarily chosen OID segments private static readonly byte[] s_hmacKey = { 2, 5, 29, 54, 1, 2, 84, 113, 54, 91, 1, 1, 2, 5, 29, 10, }; private static readonly byte[] s_inputBytes = ByteUtils.RepeatByte(0xA5, 512); public static IEnumerable<object[]> GetHashAlgorithms() { return new[] { new object[] { MD5.Create(), HashAlgorithmName.MD5 }, new object[] { SHA1.Create(), HashAlgorithmName.SHA1 }, new object[] { SHA256.Create(), HashAlgorithmName.SHA256 }, new object[] { SHA384.Create(), HashAlgorithmName.SHA384 }, new object[] { SHA512.Create(), HashAlgorithmName.SHA512 }, }; } public static IEnumerable<object[]> GetHMACs() { return new[] { new object[] { new HMACMD5(), HashAlgorithmName.MD5 }, new object[] { new HMACSHA1(), HashAlgorithmName.SHA1 }, new object[] { new HMACSHA256(), HashAlgorithmName.SHA256 }, new object[] { new HMACSHA384(), HashAlgorithmName.SHA384 }, new object[] { new HMACSHA512(), HashAlgorithmName.SHA512 }, }; } [Theory] [MemberData(nameof(GetHashAlgorithms))] public static void VerifyIncrementalHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } } [Theory] [MemberData(nameof(GetHMACs))] public static void VerifyIncrementalHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; VerifyIncrementalResult(referenceAlgorithm, incrementalHash); } } private static void VerifyIncrementalResult(HashAlgorithm referenceAlgorithm, IncrementalHash incrementalHash) { byte[] referenceHash = referenceAlgorithm.ComputeHash(s_inputBytes); const int StepA = 13; const int StepB = 7; int position = 0; while (position < s_inputBytes.Length - StepA) { incrementalHash.AppendData(s_inputBytes, position, StepA); position += StepA; } incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position); byte[] incrementalA = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalA); // Now try again, verifying both immune to step size behaviors, and that GetHashAndReset resets. position = 0; while (position < s_inputBytes.Length - StepB) { incrementalHash.AppendData(s_inputBytes, position, StepA); position += StepA; } incrementalHash.AppendData(s_inputBytes, position, s_inputBytes.Length - position); byte[] incrementalB = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalB); } [Theory] [MemberData(nameof(GetHashAlgorithms))] public static void VerifyEmptyHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { for (int i = 0; i < 10; i++) { incrementalHash.AppendData(Array.Empty<byte>()); } byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData(nameof(GetHMACs))] public static void VerifyEmptyHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; for (int i = 0; i < 10; i++) { incrementalHash.AppendData(Array.Empty<byte>()); } byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData(nameof(GetHashAlgorithms))] public static void VerifyTrivialHash(HashAlgorithm referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm)) { byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Theory] [MemberData(nameof(GetHMACs))] public static void VerifyTrivialHMAC(HMAC referenceAlgorithm, HashAlgorithmName hashAlgorithm) { using (referenceAlgorithm) using (IncrementalHash incrementalHash = IncrementalHash.CreateHMAC(hashAlgorithm, s_hmacKey)) { referenceAlgorithm.Key = s_hmacKey; byte[] referenceHash = referenceAlgorithm.ComputeHash(Array.Empty<byte>()); byte[] incrementalResult = incrementalHash.GetHashAndReset(); Assert.Equal(referenceHash, incrementalResult); } } [Fact] public static void AppendDataAfterHashClose() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { byte[] firstHash = hash.GetHashAndReset(); hash.AppendData(Array.Empty<byte>()); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void AppendDataAfterHMACClose() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { byte[] firstHash = hash.GetHashAndReset(); hash.AppendData(Array.Empty<byte>()); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void GetHashTwice() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { byte[] firstHash = hash.GetHashAndReset(); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void GetHMACTwice() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { byte[] firstHash = hash.GetHashAndReset(); byte[] secondHash = hash.GetHashAndReset(); Assert.Equal(firstHash, secondHash); } } [Fact] public static void ModifyAfterHashDispose() { using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { hash.Dispose(); Assert.Throws<ObjectDisposedException>(() => hash.AppendData(Array.Empty<byte>())); Assert.Throws<ObjectDisposedException>(() => hash.GetHashAndReset()); } } [Fact] public static void ModifyAfterHMACDispose() { using (IncrementalHash hash = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, s_hmacKey)) { hash.Dispose(); Assert.Throws<ObjectDisposedException>(() => hash.AppendData(Array.Empty<byte>())); Assert.Throws<ObjectDisposedException>(() => hash.GetHashAndReset()); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; 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 Apress.Recipes.WebApi.Areas.HelpPage.ModelDescriptions; using Apress.Recipes.WebApi.Areas.HelpPage.Models; namespace Apress.Recipes.WebApi.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; } if (complexTypeDescription != null) { 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 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); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Xml; namespace System.Runtime.Serialization { internal abstract class PrimitiveDataContract : DataContract { internal static readonly PrimitiveDataContract NullContract = new NullPrimitiveDataContract(); private PrimitiveDataContractCriticalHelper _helper; protected PrimitiveDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new PrimitiveDataContractCriticalHelper(type, name, ns)) { _helper = base.Helper as PrimitiveDataContractCriticalHelper; } internal static PrimitiveDataContract GetPrimitiveDataContract(Type type) { return DataContract.GetBuiltInDataContract(type) as PrimitiveDataContract; } internal static PrimitiveDataContract GetPrimitiveDataContract(string name, string ns) { return DataContract.GetBuiltInDataContract(name, ns) as PrimitiveDataContract; } internal abstract string WriteMethodName { get; } internal abstract string ReadMethodName { get; } public override XmlDictionaryString TopLevelElementNamespace { get { return DictionaryGlobals.SerializationNamespace; } set { } } internal override bool CanContainReferences => false; internal override bool IsPrimitive => true; public override bool IsBuiltInDataContract => true; internal MethodInfo XmlFormatWriterMethod { get { if (_helper.XmlFormatWriterMethod == null) { if (UnderlyingType.IsValueType) _helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); else _helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); } return _helper.XmlFormatWriterMethod; } } internal MethodInfo XmlFormatContentWriterMethod { get { if (_helper.XmlFormatContentWriterMethod == null) { if (UnderlyingType.IsValueType) _helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType }); else _helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType }); } return _helper.XmlFormatContentWriterMethod; } } internal MethodInfo XmlFormatReaderMethod { get { if (_helper.XmlFormatReaderMethod == null) { _helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers); } return _helper.XmlFormatReaderMethod; } } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { xmlWriter.WriteAnyType(obj); } protected object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { Attributes attributes = new Attributes(); attributes.Read(reader); if (attributes.Ref != Globals.NewObjectId) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotDeserializeRefAtTopLevel, attributes.Ref))); if (attributes.XsiNil) { reader.Skip(); return true; } return false; } private class PrimitiveDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private MethodInfo _xmlFormatWriterMethod; private MethodInfo _xmlFormatContentWriterMethod; private MethodInfo _xmlFormatReaderMethod; internal PrimitiveDataContractCriticalHelper(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(type) { SetDataContractName(name, ns); } internal MethodInfo XmlFormatWriterMethod { get { return _xmlFormatWriterMethod; } set { _xmlFormatWriterMethod = value; } } internal MethodInfo XmlFormatContentWriterMethod { get { return _xmlFormatContentWriterMethod; } set { _xmlFormatContentWriterMethod = value; } } internal MethodInfo XmlFormatReaderMethod { get { return _xmlFormatReaderMethod; } set { _xmlFormatReaderMethod = value; } } } } internal class CharDataContract : PrimitiveDataContract { public CharDataContract() : this(DictionaryGlobals.CharLocalName, DictionaryGlobals.SerializationNamespace) { } internal CharDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(char), name, ns) { } internal override string WriteMethodName { get { return "WriteChar"; } } internal override string ReadMethodName { get { return "ReadElementContentAsChar"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteChar((char)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsChar() : HandleReadValue(reader.ReadElementContentAsChar(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteChar((char)obj, name, ns); } } internal class AsmxCharDataContract : CharDataContract { internal AsmxCharDataContract() : base(DictionaryGlobals.CharLocalName, DictionaryGlobals.AsmxTypesNamespace) { } } internal class BooleanDataContract : PrimitiveDataContract { public BooleanDataContract() : base(typeof(bool), DictionaryGlobals.BooleanLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteBoolean"; } } internal override string ReadMethodName { get { return "ReadElementContentAsBoolean"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteBoolean((bool)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsBoolean() : HandleReadValue(reader.ReadElementContentAsBoolean(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteBoolean((bool)obj, name, ns); } } internal class SignedByteDataContract : PrimitiveDataContract { public SignedByteDataContract() : base(typeof(sbyte), DictionaryGlobals.SignedByteLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteSignedByte"; } } internal override string ReadMethodName { get { return "ReadElementContentAsSignedByte"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteSignedByte((sbyte)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsSignedByte() : HandleReadValue(reader.ReadElementContentAsSignedByte(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteSignedByte((sbyte)obj, name, ns); } } internal class UnsignedByteDataContract : PrimitiveDataContract { public UnsignedByteDataContract() : base(typeof(byte), DictionaryGlobals.UnsignedByteLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUnsignedByte"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedByte"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedByte((byte)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsUnsignedByte() : HandleReadValue(reader.ReadElementContentAsUnsignedByte(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteUnsignedByte((byte)obj, name, ns); } } internal class ShortDataContract : PrimitiveDataContract { public ShortDataContract() : base(typeof(short), DictionaryGlobals.ShortLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteShort"; } } internal override string ReadMethodName { get { return "ReadElementContentAsShort"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteShort((short)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsShort() : HandleReadValue(reader.ReadElementContentAsShort(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteShort((short)obj, name, ns); } } internal class UnsignedShortDataContract : PrimitiveDataContract { public UnsignedShortDataContract() : base(typeof(ushort), DictionaryGlobals.UnsignedShortLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUnsignedShort"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedShort"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedShort((ushort)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsUnsignedShort() : HandleReadValue(reader.ReadElementContentAsUnsignedShort(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteUnsignedShort((ushort)obj, name, ns); } } internal class NullPrimitiveDataContract : PrimitiveDataContract { public NullPrimitiveDataContract() : base(typeof(NullPrimitiveDataContract), DictionaryGlobals.EmptyString, DictionaryGlobals.EmptyString) { } internal override string ReadMethodName { get { throw new NotImplementedException(); } } internal override string WriteMethodName { get { throw new NotImplementedException(); } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { throw new NotImplementedException(); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { throw new NotImplementedException(); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { throw new NotImplementedException(); } } internal class IntDataContract : PrimitiveDataContract { public IntDataContract() : base(typeof(int), DictionaryGlobals.IntLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteInt"; } } internal override string ReadMethodName { get { return "ReadElementContentAsInt"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteInt((int)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsInt() : HandleReadValue(reader.ReadElementContentAsInt(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteInt((int)obj, name, ns); } } internal class UnsignedIntDataContract : PrimitiveDataContract { public UnsignedIntDataContract() : base(typeof(uint), DictionaryGlobals.UnsignedIntLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUnsignedInt"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedInt"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedInt((uint)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsUnsignedInt() : HandleReadValue(reader.ReadElementContentAsUnsignedInt(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteUnsignedInt((uint)obj, name, ns); } } internal class LongDataContract : PrimitiveDataContract { public LongDataContract() : this(DictionaryGlobals.LongLocalName, DictionaryGlobals.SchemaNamespace) { } internal LongDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(long), name, ns) { } internal override string WriteMethodName { get { return "WriteLong"; } } internal override string ReadMethodName { get { return "ReadElementContentAsLong"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteLong((long)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsLong() : HandleReadValue(reader.ReadElementContentAsLong(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteLong((long)obj, name, ns); } } internal class IntegerDataContract : LongDataContract { internal IntegerDataContract() : base(DictionaryGlobals.integerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class PositiveIntegerDataContract : LongDataContract { internal PositiveIntegerDataContract() : base(DictionaryGlobals.positiveIntegerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NegativeIntegerDataContract : LongDataContract { internal NegativeIntegerDataContract() : base(DictionaryGlobals.negativeIntegerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NonPositiveIntegerDataContract : LongDataContract { internal NonPositiveIntegerDataContract() : base(DictionaryGlobals.nonPositiveIntegerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NonNegativeIntegerDataContract : LongDataContract { internal NonNegativeIntegerDataContract() : base(DictionaryGlobals.nonNegativeIntegerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class UnsignedLongDataContract : PrimitiveDataContract { public UnsignedLongDataContract() : base(typeof(ulong), DictionaryGlobals.UnsignedLongLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUnsignedLong"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedLong"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedLong((ulong)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsUnsignedLong() : HandleReadValue(reader.ReadElementContentAsUnsignedLong(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteUnsignedLong((ulong)obj, name, ns); } } internal class FloatDataContract : PrimitiveDataContract { public FloatDataContract() : base(typeof(float), DictionaryGlobals.FloatLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteFloat"; } } internal override string ReadMethodName { get { return "ReadElementContentAsFloat"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteFloat((float)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsFloat() : HandleReadValue(reader.ReadElementContentAsFloat(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteFloat((float)obj, name, ns); } } internal class DoubleDataContract : PrimitiveDataContract { public DoubleDataContract() : base(typeof(double), DictionaryGlobals.DoubleLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteDouble"; } } internal override string ReadMethodName { get { return "ReadElementContentAsDouble"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteDouble((double)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsDouble() : HandleReadValue(reader.ReadElementContentAsDouble(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteDouble((double)obj, name, ns); } } internal class DecimalDataContract : PrimitiveDataContract { public DecimalDataContract() : base(typeof(decimal), DictionaryGlobals.DecimalLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteDecimal"; } } internal override string ReadMethodName { get { return "ReadElementContentAsDecimal"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteDecimal((decimal)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsDecimal() : HandleReadValue(reader.ReadElementContentAsDecimal(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteDecimal((decimal)obj, name, ns); } } internal class DateTimeDataContract : PrimitiveDataContract { public DateTimeDataContract() : base(typeof(DateTime), DictionaryGlobals.DateTimeLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteDateTime"; } } internal override string ReadMethodName { get { return "ReadElementContentAsDateTime"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteDateTime((DateTime)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsDateTime() : HandleReadValue(reader.ReadElementContentAsDateTime(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteDateTime((DateTime)obj, name, ns); } } internal class StringDataContract : PrimitiveDataContract { public StringDataContract() : this(DictionaryGlobals.StringLocalName, DictionaryGlobals.SchemaNamespace) { } internal StringDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(string), name, ns) { } internal override string WriteMethodName { get { return "WriteString"; } } internal override string ReadMethodName { get { return "ReadElementContentAsString"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteString((string)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsString(); } else { return HandleReadValue(reader.ReadElementContentAsString(), context); } } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { context.WriteString(xmlWriter, (string)obj, name, ns); } } internal class TimeDataContract : StringDataContract { internal TimeDataContract() : base(DictionaryGlobals.timeLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class DateDataContract : StringDataContract { internal DateDataContract() : base(DictionaryGlobals.dateLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class HexBinaryDataContract : StringDataContract { internal HexBinaryDataContract() : base(DictionaryGlobals.hexBinaryLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GYearMonthDataContract : StringDataContract { internal GYearMonthDataContract() : base(DictionaryGlobals.gYearMonthLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GYearDataContract : StringDataContract { internal GYearDataContract() : base(DictionaryGlobals.gYearLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GMonthDayDataContract : StringDataContract { internal GMonthDayDataContract() : base(DictionaryGlobals.gMonthDayLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GDayDataContract : StringDataContract { internal GDayDataContract() : base(DictionaryGlobals.gDayLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GMonthDataContract : StringDataContract { internal GMonthDataContract() : base(DictionaryGlobals.gMonthLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NormalizedStringDataContract : StringDataContract { internal NormalizedStringDataContract() : base(DictionaryGlobals.normalizedStringLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class TokenDataContract : StringDataContract { internal TokenDataContract() : base(DictionaryGlobals.tokenLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class LanguageDataContract : StringDataContract { internal LanguageDataContract() : base(DictionaryGlobals.languageLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NameDataContract : StringDataContract { internal NameDataContract() : base(DictionaryGlobals.NameLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NCNameDataContract : StringDataContract { internal NCNameDataContract() : base(DictionaryGlobals.NCNameLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class IDDataContract : StringDataContract { internal IDDataContract() : base(DictionaryGlobals.XSDIDLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class IDREFDataContract : StringDataContract { internal IDREFDataContract() : base(DictionaryGlobals.IDREFLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class IDREFSDataContract : StringDataContract { internal IDREFSDataContract() : base(DictionaryGlobals.IDREFSLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class ENTITYDataContract : StringDataContract { internal ENTITYDataContract() : base(DictionaryGlobals.ENTITYLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class ENTITIESDataContract : StringDataContract { internal ENTITIESDataContract() : base(DictionaryGlobals.ENTITIESLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NMTOKENDataContract : StringDataContract { internal NMTOKENDataContract() : base(DictionaryGlobals.NMTOKENLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NMTOKENSDataContract : StringDataContract { internal NMTOKENSDataContract() : base(DictionaryGlobals.NMTOKENSLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class ByteArrayDataContract : PrimitiveDataContract { public ByteArrayDataContract() : base(typeof(byte[]), DictionaryGlobals.ByteArrayLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteBase64"; } } internal override string ReadMethodName { get { return "ReadElementContentAsBase64"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteBase64((byte[])obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsBase64(); } else { return HandleReadValue(reader.ReadElementContentAsBase64(), context); } } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteStartElement(name, ns); xmlWriter.WriteBase64((byte[])obj); xmlWriter.WriteEndElement(); } } internal class ObjectDataContract : PrimitiveDataContract { public ObjectDataContract() : base(typeof(object), DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteAnyType"; } } internal override string ReadMethodName { get { return "ReadElementContentAsAnyType"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { // write nothing } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { object obj; if (reader.IsEmptyElement) { reader.Skip(); obj = new object(); } else { string localName = reader.LocalName; string ns = reader.NamespaceURI; reader.Read(); try { reader.ReadEndElement(); obj = new object(); } catch (XmlException xes) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlForObjectCannotHaveContent, localName, ns), xes)); } } return (context == null) ? obj : HandleReadValue(obj, context); } internal override bool CanContainReferences { get { return true; } } internal override bool IsPrimitive { get { return false; } } } internal class TimeSpanDataContract : PrimitiveDataContract { public TimeSpanDataContract() : this(DictionaryGlobals.TimeSpanLocalName, DictionaryGlobals.SerializationNamespace) { } internal TimeSpanDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(TimeSpan), name, ns) { } internal override string WriteMethodName { get { return "WriteTimeSpan"; } } internal override string ReadMethodName { get { return "ReadElementContentAsTimeSpan"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteTimeSpan((TimeSpan)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsTimeSpan() : HandleReadValue(reader.ReadElementContentAsTimeSpan(), context); } public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { writer.WriteTimeSpan((TimeSpan)obj, name, ns); } } internal class XsDurationDataContract : TimeSpanDataContract { public XsDurationDataContract() : base(DictionaryGlobals.TimeSpanLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GuidDataContract : PrimitiveDataContract { public GuidDataContract() : this(DictionaryGlobals.GuidLocalName, DictionaryGlobals.SerializationNamespace) { } internal GuidDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(Guid), name, ns) { } internal override string WriteMethodName { get { return "WriteGuid"; } } internal override string ReadMethodName { get { return "ReadElementContentAsGuid"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteGuid((Guid)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsGuid() : HandleReadValue(reader.ReadElementContentAsGuid(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteGuid((Guid)obj, name, ns); } } internal class AsmxGuidDataContract : GuidDataContract { internal AsmxGuidDataContract() : base(DictionaryGlobals.GuidLocalName, DictionaryGlobals.AsmxTypesNamespace) { } } internal class UriDataContract : PrimitiveDataContract { public UriDataContract() : base(typeof(Uri), DictionaryGlobals.UriLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUri"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUri"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUri((Uri)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsUri(); } else { return HandleReadValue(reader.ReadElementContentAsUri(), context); } } public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { writer.WriteUri((Uri)obj, name, ns); } } internal class QNameDataContract : PrimitiveDataContract { public QNameDataContract() : base(typeof(XmlQualifiedName), DictionaryGlobals.QNameLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteQName"; } } internal override string ReadMethodName { get { return "ReadElementContentAsQName"; } } internal override bool IsPrimitive { get { return false; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteQName((XmlQualifiedName)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsQName(); } else { return HandleReadValue(reader.ReadElementContentAsQName(), context); } } public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { context.WriteQName(writer, (XmlQualifiedName)obj, name, ns); } internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns) { if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace)) writer.WriteStartElement(Globals.SerPrefix, name, ns); else if (ns != null && ns.Value != null && ns.Value.Length > 0) writer.WriteStartElement(Globals.ElementPrefix, name, ns); else writer.WriteStartElement(name, ns); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace Phonix { public class SyllableBuilder { public enum NucleusDirection { Neutral, Left, Right } public readonly List<IEnumerable<IMatrixMatcher>> Onsets = new List<IEnumerable<IMatrixMatcher>>(); public readonly List<IEnumerable<IMatrixMatcher>> Nuclei = new List<IEnumerable<IMatrixMatcher>>(); public readonly List<IEnumerable<IMatrixMatcher>> Codas = new List<IEnumerable<IMatrixMatcher>>(); public NucleusDirection Direction = NucleusDirection.Neutral; public AbstractRule GetSyllableRule() { if (Nuclei.Count == 0) { throw new InvalidOperationException("nuclei list cannot be empty"); } var rs = new RuleSet(); var list = new List<Syllable>(); var rules = BuildRuleList(list); foreach (var rule in rules) { rs.Add(rule); } return new SyllableRule(rs, BuildDescription(), list, Direction); } private class SyllableRule : AbstractRule { private readonly RuleSet _rs; private readonly string _description; private readonly List<Syllable> _list; private readonly NucleusDirection _direction; public SyllableRule(RuleSet rs, string description, List<Syllable> syllableList, NucleusDirection direction) : base ("syllabify") { _rs = rs; _description = description; _list = syllableList; _direction = direction; } public override string Description { get { return _description; } } public override void Apply(Word word) { int applied = 0; Action<AbstractRule, Word, WordSlice> ruleApplied = (r, w, s) => { applied++; }; _rs.RuleApplied += ruleApplied; try { // clear the list of syllables. All of the syllables // constructed during ApplyAll() will get added to the list _list.Clear(); OnEntered(word); _rs.ApplyAll(word); SelectOptimalSyllables(_list, word, _direction); if (applied > 0) { OnApplied(word, null); } } finally { _rs.RuleApplied -= ruleApplied; _list.Clear(); OnExited(word); } } public override string ShowApplication(Word word, WordSlice slice, SymbolSet symbolSet) { StringBuilder str = new StringBuilder(); Segment lastSyll = null; Segment lastSegment = null; foreach (var segment in word) { Segment thisSyll; if (segment.HasAncestor(Tier.Syllable)) { var ancestors = segment.FindAncestors(Tier.Syllable); thisSyll = ancestors.First(); if (thisSyll != lastSyll) { if (lastSyll != null) { str.Append("> "); } str.Append(" <"); lastSyll = thisSyll; } } else { if (lastSyll != null) { str.Append("> "); } lastSyll = null; } if (lastSegment != null) { if (segment.HasAncestor(Tier.Nucleus) && lastSegment.HasAncestor(Tier.Onset)) { str.Append(" :: "); } else if (segment.HasAncestor(Tier.Coda) && lastSegment.HasAncestor(Tier.Nucleus)) { str.Append(" : "); } } try { str.Append(symbolSet.Spell(segment.Matrix)); } catch (SpellingException) { str.Append(Symbol.Unknown); } lastSegment = segment; } if (lastSyll != null) { str.Append(">"); } str.AppendLine(); return str.ToString(); } } // end SyllableRule private IEnumerable<Rule> BuildRuleList(List<Syllable> syllableList) { var rules = new List<Rule>(); var activeOnsets = new List<IEnumerable<IMatrixMatcher>>(); var activeCodas = new List<IEnumerable<IMatrixMatcher>>(); activeOnsets.AddRange(Onsets); activeCodas.AddRange(Codas); if (activeOnsets.Count == 0) { activeOnsets.Add(null); } if (activeCodas.Count == 0) { activeCodas.Add(null); } foreach (var onset in activeOnsets) { foreach (var nucleus in Nuclei) { foreach (var coda in activeCodas) { var rule = BuildRule(onset, nucleus, coda, syllableList); rules.Add(rule); } } } Debug.Assert(rules.Count > 0); return rules; } private Rule BuildRule(IEnumerable<IMatrixMatcher> onset, IEnumerable<IMatrixMatcher> nucleus, IEnumerable<IMatrixMatcher> coda, List<Syllable> syllableList) { var list = new List<IRuleSegment>(); var ctx = new SyllableContext(syllableList); list.Add(new SyllableBegin(ctx)); if (onset != null) { list.AddRange(onset.Select(onsetSeg => (IRuleSegment) new SyllableElement(onsetSeg, ctx.Onset))); } Debug.Assert(nucleus != null); list.AddRange(nucleus.Select(nucleusSeg => (IRuleSegment) new SyllableElement(nucleusSeg, ctx.Nucleus))); if (coda != null) { list.AddRange(coda.Select(codaSeg => (IRuleSegment) new SyllableElement(codaSeg, ctx.Coda))); } list.Add(new SyllableEnd(ctx)); var rule = new Rule("syllable", list, new IRuleSegment[] {}); rule.Direction = Phonix.Direction.Leftward; return rule; } private string BuildDescription() { var str = new StringBuilder(); bool firstChar = true; foreach (var onset in Onsets.Where(o => o.Count() > 0)) { if (firstChar) { str.Append("onset "); } else { str.Append(" onset "); } foreach (var match in onset) { str.Append(match.ToString()); } } foreach (var nucleus in Nuclei) { str.Append(" nucleus "); foreach (var match in nucleus) { str.Append(match.ToString()); } } foreach (var coda in Codas.Where(o => o.Count() > 0)) { str.Append(" coda "); foreach (var match in coda) { str.Append(match.ToString()); } } return str.ToString(); } private static void SelectOptimalSyllables(List<Syllable> list, Word word, NucleusDirection direction) { var available = new List<Syllable>(list); var selected = new List<Syllable>(); List<Syllable> best = null; RecurseSelectSyllables(available, selected, word, direction, ref best); // detach everything foreach (var segment in word) { ((MutableSegment) segment).Detach(Tier.Syllable); } Debug.Assert(word.All(segment => !segment.HasAncestor(Tier.Syllable))); // reattach all of our selected syllables if (best != null) { best.ForEach(syllable => syllable.BuildSupraSegments()); } } private static void RecurseSelectSyllables(List<Syllable> available, List<Syllable> selected, Word word, NucleusDirection direction, ref List<Syllable> best) { if (available.Count > 0) // still need to select syllables { var syllable = available[0]; var availableModified = new List<Syllable>(available); availableModified.Remove(syllable); // recurse once *without* selecting this syllable RecurseSelectSyllables(availableModified, selected, word, direction, ref best); // we can only select this syllable if it doesn't overlap an // already-selected syllable if (!selected.Any(selectedSyllable => selectedSyllable.Overlaps(syllable))) { // recurse once *with* this syllable var selectedModified = new List<Syllable>(selected); selectedModified.Add(syllable); RecurseSelectSyllables(availableModified, selectedModified, word, direction, ref best); } } else // evaluate the selected syllables { best = RankSyllables(best, selected, direction, word); } } private static List<Syllable> RankSyllables(List<Syllable> a, List<Syllable> b, NucleusDirection direction, Word word) { // if either is null, return the other if (a == null || b == null) { return a ?? b; } // select based on fewest unsyllabified segments int aUnsyllabified = CountUnsyllabified(a, word); int bUnsyllabified = CountUnsyllabified(b, word); if (aUnsyllabified < bUnsyllabified) { return a; } else if (bUnsyllabified < aUnsyllabified) { return b; } // select based on fewest number of syllables if (a.Count < b.Count) { return a; } if (b.Count < a.Count) { return b; } // select on alignment, if not neutral if (direction != NucleusDirection.Neutral) { var wordList = new List<Segment>(word); int aNucleusSum = a.Aggregate(0, (sum, syllable) => { return sum + wordList.IndexOf(syllable.Nucleus.First()); }); int bNucleusSum = b.Aggregate(0, (sum, syllable) => { return sum + wordList.IndexOf(syllable.Nucleus.First()); }); if (direction == NucleusDirection.Left) { // select the set with nuclei more to the left (smaller indices) return aNucleusSum < bNucleusSum ? a : b; } else if (direction == NucleusDirection.Right) { // select the set with nuclei more to the right (larger indices) return aNucleusSum > bNucleusSum ? a : b; } } // select based on most onsets int aOnsets = a.Aggregate(0, (sum, syllable) => { return sum + syllable.Onset.Count(); }); int bOnsets = b.Aggregate(0, (sum, syllable) => { return sum + syllable.Onset.Count(); }); if (aOnsets > bOnsets) { return a; } if (bOnsets > aOnsets) { return b; } // no choice? return the first one return a; } private static int CountUnsyllabified(List<Syllable> list, Word word) { int count = 0; foreach (var seg in word) { if (!list.Any(syllable => syllable.Contains(seg))) { count++; } } return count; } private class SyllableContext { public readonly List<Segment> Onset = new List<Segment>(); public readonly List<Segment> Nucleus = new List<Segment>(); public readonly List<Segment> Coda = new List<Segment>(); public readonly List<Syllable> SyllableList; public SyllableContext(List<Syllable> syllableList) { SyllableList = syllableList; } } // this abstract class provides an implementation of IRuleSegment that // the syllable segments use, leaving only Combine and (optionally) // Matches as methods that the subclasses need to implement. private abstract class SyllableSegment : IRuleSegment { public virtual bool Matches(RuleContext ctx, SegmentEnumerator segment) { return true; } public abstract void Combine(RuleContext ctx, MutableSegmentEnumerator segment); // these are implemented here for convenience public bool IsMatchOnlySegment { get { return false; } } public string MatchString { get { return ""; } } public string CombineString { get { return ""; } } } private class SyllableBegin : SyllableSegment { private readonly SyllableContext _syllCtx; public SyllableBegin(SyllableContext syllCtx) { _syllCtx = syllCtx; } public override void Combine(RuleContext ctx, MutableSegmentEnumerator segment) { // set up the context for the new syllable _syllCtx.Onset.Clear(); _syllCtx.Nucleus.Clear(); _syllCtx.Coda.Clear(); } } private class SyllableEnd : SyllableSegment { private readonly SyllableContext _syllCtx; public SyllableEnd(SyllableContext syllCtx) { _syllCtx = syllCtx; } public override void Combine(RuleContext ctx, MutableSegmentEnumerator segment) { var syllable = new Syllable(_syllCtx.Onset, _syllCtx.Nucleus, _syllCtx.Coda); if (!_syllCtx.SyllableList.Contains(syllable)) { _syllCtx.SyllableList.Add(syllable); } } } private class SyllableElement : SyllableSegment { private readonly IMatrixMatcher _match; private readonly List<Segment> _list; public SyllableElement(IMatrixMatcher match, List<Segment> list) { _match = match; _list = list; } public override bool Matches(RuleContext ctx, SegmentEnumerator seg) { return seg.MoveNext() && _match.Matches(ctx, seg.Current); } public override void Combine(RuleContext ctx, MutableSegmentEnumerator seg) { seg.MoveNext(); _list.Add(seg.Current); } } } }
// 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: This class represents settings specified by de jure or // de facto standards for a particular country/region. In // contrast to CultureInfo, the RegionInfo does not represent // preferences of the user and does not depend on the user's // language or culture. // // //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { [Serializable] public class RegionInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // // // Name of this region (ie: es-US): serialized, the field used for deserialization // internal String _name; // // The CultureData instance that we are going to read data from. // internal CultureData _cultureData; // // The RegionInfo for our current region // internal static volatile RegionInfo s_currentRegionInfo; //////////////////////////////////////////////////////////////////////// // // RegionInfo Constructors // // Note: We prefer that a region be created with a full culture name (ie: en-US) // because otherwise the native strings won't be right. // // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// public RegionInfo(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, nameof(name)); } Contract.EndContractBlock(); // // For CoreCLR we only want the region names that are full culture names // _cultureData = CultureData.GetCultureDataForRegion(name, true); if (_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, name), nameof(name)); // Not supposed to be neutral if (_cultureData.IsNeutralCulture) throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), nameof(name)); SetName(name); } [System.Security.SecuritySafeCritical] // auto-generated public RegionInfo(int culture) { if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture); } if (culture == CultureInfo.LOCALE_NEUTRAL) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CustomCultureCannotBePassedByNumber, culture), nameof(culture)); } _cultureData = CultureData.GetCultureData(culture, true); _name = _cultureData.SREGIONNAME; if (_cultureData.IsNeutralCulture) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } } internal RegionInfo(CultureData cultureData) { _cultureData = cultureData; _name = _cultureData.SREGIONNAME; } private void SetName(string name) { // when creating region by culture name, we keep the region name as the culture name so regions // created by custom culture names can be differentiated from built in regions. this._name = name.Equals(_cultureData.SREGIONNAME, StringComparison.OrdinalIgnoreCase) ? _cultureData.SREGIONNAME : _cultureData.CultureName; } //////////////////////////////////////////////////////////////////////// // // GetCurrentRegion // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// public static RegionInfo CurrentRegion { get { RegionInfo temp = s_currentRegionInfo; if (temp == null) { temp = new RegionInfo(CultureInfo.CurrentCulture.m_cultureData); // Need full name for custom cultures temp._name = temp._cultureData.SREGIONNAME; s_currentRegionInfo = temp; } return temp; } } //////////////////////////////////////////////////////////////////////// // // GetName // // Returns the name of the region (ie: en-US) // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already"); return (_name); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the name of the region in English. (ie: United States) // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { get { return (_cultureData.SENGCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetDisplayName // // Returns the display name (localized) of the region. (ie: United States // if the current UI language is en-US) // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { get { return (_cultureData.SLOCALIZEDCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the native name of the region. (ie: Deutschland) // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual String NativeName { get { return (_cultureData.SNATIVECOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // TwoLetterISORegionName // // Returns the two letter ISO region name (ie: US) // //////////////////////////////////////////////////////////////////////// public virtual String TwoLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterISORegionName // // Returns the three letter ISO region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME2); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsRegionName // // Returns the three letter windows region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsRegionName { get { // ThreeLetterWindowsRegionName is really same as ThreeLetterISORegionName return ThreeLetterISORegionName; } } //////////////////////////////////////////////////////////////////////// // // IsMetric // // Returns true if this region uses the metric measurement system // //////////////////////////////////////////////////////////////////////// public virtual bool IsMetric { get { int value = _cultureData.IMEASURE; return (value == 0); } } public virtual int GeoId { get { return (_cultureData.IGEOID); } } //////////////////////////////////////////////////////////////////////// // // CurrencyEnglishName // // English name for this region's currency, ie: Swiss Franc // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyEnglishName { get { return (_cultureData.SENGLISHCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencyNativeName // // Native name for this region's currency, ie: Schweizer Franken // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyNativeName { get { return (_cultureData.SNATIVECURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencySymbol // // Currency Symbol for this locale, ie: Fr. or $ // //////////////////////////////////////////////////////////////////////// public virtual String CurrencySymbol { get { return (_cultureData.SCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // ISOCurrencySymbol // // ISO Currency Symbol for this locale, ie: CHF // //////////////////////////////////////////////////////////////////////// public virtual String ISOCurrencySymbol { get { return (_cultureData.SINTLSYMBOL); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same RegionInfo as the current instance. // // RegionInfos are considered equal if and only if they have the same name // (ie: en-US) // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { RegionInfo that = value as RegionInfo; if (that != null) { return this.Name.Equals(that.Name); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for RegionInfo // A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the Region, ie: es-US // //////////////////////////////////////////////////////////////////////// public override String ToString() { return (Name); } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.IO; using System.Linq; using NLog.Targets; using Xunit; using Xunit.Extensions; public class ColoredConsoleTargetTests : NLogTestBase { [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextTest(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The C", "at", " S", "at", " At The Bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextIgnoreCase(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", IgnoreCase = true, CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The C", "at", " S", "at", " ", "At", " The Bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextWholeWords(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", WholeWords = true, CompileRegex = compileRegex }); AssertOutput(target, "The cat sat at the bar.", new string[] { "The cat sat ", "at", " the bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingRegex(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Regex = "\\wat", CompileRegex = compileRegex }); AssertOutput(target, "The cat sat at the bar.", new string[] { "The ", "cat", " ", "sat", " at the bar." }); } /// <summary> /// With or wihout CompileRegex, CompileRegex is never null, even if not used when CompileRegex=false. (needed for backwardscomp) /// </summary> /// <param name="compileRegex"></param> [Theory] [InlineData(true)] [InlineData(false)] public void CompiledRegexPropertyNotNull(bool compileRegex) { var rule = new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Regex = "\\wat", CompileRegex = compileRegex }; Assert.NotNull(rule.CompiledRegex); } [Theory] [InlineData(true)] [InlineData(false)] public void DonRemoveIfRegexIsEmpty(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = null, IgnoreCase = true, CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The Cat Sat At The Bar." }); } private static void AssertOutput(Target target, string message, string[] expectedParts) { var consoleOutWriter = new PartsWriter(); TextWriter oldConsoleOutWriter = Console.Out; Console.SetOut(consoleOutWriter); try { var exceptions = new List<Exception>(); target.Initialize(null); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger", message).WithContinuation(exceptions.Add)); target.Close(); Assert.Equal(1, exceptions.Count); Assert.True(exceptions.TrueForAll(e => e == null)); } finally { Console.SetOut(oldConsoleOutWriter); } var expected = Enumerable.Repeat("Logger " + expectedParts[0], 1).Concat(expectedParts.Skip(1)); Assert.Equal(expected, consoleOutWriter.Values); } private class PartsWriter : StringWriter { public PartsWriter() { Values = new List<string>(); } public List<string> Values { get; private set; } public override void Write(string value) { Values.Add(value); } } } } #endif
/************************************************************************************ Filename : MoviePlayerSample.cs Content : An example of how to use the Moonlight video player Created : July 12, 2014 Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Use of this software is subject to the terms of the Oculus LLC license agreement provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. ************************************************************************************/ using UnityEngine; using System.Collections; // required for Coroutines using System.Runtime.InteropServices; // required for DllImport using System; // requred for IntPtr using System.IO; // required for File /************************************************************************************ Usage: Place a simple textured quad surface with the correct aspect ratio in your scene. Add the MoviePlayerSample.cs script to the surface object. Supply the name of the media file to play: This sample assumes the media file is placed in "Assets/StreamingAssets", ie "ProjectName/Assets/StreamingAssets/MovieName.mp4". On Desktop, Unity MovieTexture functionality is used. Note: the media file is loaded at runtime, and therefore expected to be converted to Ogg Theora beforehand. Implementation: In the MoviePlayerSample Awake() call, GetNativeTexturePtr() is called on renderer.material.mainTexture. When the MediaSurface plugin gets the initialization event on the render thread, it creates a new Android SurfaceTexture and Surface object in preparation for receiving media. When the game wants to start the video playing, it calls the StartVideoPlayerOnTextureId() script call, which creates an Android MediaPlayer java object, issues a native plugin call to tell the native code which texture id to put the video on and return the Android Surface object to pass to MediaPlayer, then sets up the media stream and starts it. Every frame, the SurfaceTexture object is checked for updates. If there is one, the target texId is re-created at the correct dimensions and format if it is the first frame, then the video image is rendered to it and mipmapped. The following frame, instead of Unity drawing the image that was placed on the surface in the Unity editor, it will draw the current video frame. It is important to note that the texture is actually replaced -- the original version is gone, and the video will now show up everywhere that texture was used, not just on the GameObject that ran the script. ************************************************************************************/ public class MoviePlayerSample : MonoBehaviour { public string movieName = string.Empty; private string mediaFullPath = string.Empty; private bool startedVideo = false; private bool videoPaused = false; #if (UNITY_ANDROID && !UNITY_EDITOR) private IntPtr nativeTexturePtr = IntPtr.Zero; private int nativeTextureWidth = 0; private int nativeTextureHeight = 0; private AndroidJavaObject mediaPlayer = null; #else private MovieTexture movieTexture = null; private AudioSource audioEmitter = null; #endif private Renderer mediaRenderer = null; private enum MediaSurfaceEventType { Initialize = 0, Shutdown = 1, Update = 2, Max_EventType }; /// <summary> /// The start of the numeric range used by event IDs. /// </summary> /// <description> /// If multiple native rundering plugins are in use, the Oculus Media Surface plugin's event IDs /// can be re-mapped to avoid conflicts. /// /// Set this value so that it is higher than the highest event ID number used by your plugin. /// Oculus Media Surface plugin event IDs start at eventBase and end at eventBase plus the highest /// value in MediaSurfaceEventType. /// </description> public static int eventBase { get { return _eventBase; } set { _eventBase = value; #if (UNITY_ANDROID && !UNITY_EDITOR) OVR_Media_Surface_SetEventBase(_eventBase); #endif } } private static int _eventBase = 0; private static void IssuePluginEvent(MediaSurfaceEventType eventType) { GL.IssuePluginEvent((int)eventType + eventBase); } /// <summary> /// Initialization of the movie surface /// </summary> void Awake() { Debug.Log("MovieSample Awake"); #if UNITY_ANDROID && !UNITY_EDITOR OVR_Media_Surface_Init(); #endif mediaRenderer = GetComponent<Renderer>(); #if !UNITY_ANDROID || UNITY_EDITOR audioEmitter = GetComponent<AudioSource>(); #endif if (mediaRenderer.material == null || mediaRenderer.material.mainTexture == null) { Debug.LogError("Can't GetNativeTexturePtr() for movie surface"); } if (movieName != string.Empty) { StartCoroutine(RetrieveStreamingAsset(movieName)); } else { Debug.LogError("No media file name provided"); } #if UNITY_ANDROID && !UNITY_EDITOR // This apparently has to be done at Awake time, before // multi-threaded rendering starts. nativeTexturePtr = mediaRenderer.material.mainTexture.GetNativeTexturePtr(); nativeTextureWidth = mediaRenderer.material.mainTexture.width; nativeTextureHeight = mediaRenderer.material.mainTexture.height; Debug.Log("Movie Texture id: " + nativeTexturePtr); IssuePluginEvent(MediaSurfaceEventType.Initialize); #endif } /// <summary> /// Construct the streaming asset path. /// Note: For Android, we need to retrieve the data from the apk. /// </summary> IEnumerator RetrieveStreamingAsset(string mediaFileName) { #if UNITY_ANDROID && !UNITY_EDITOR string streamingMediaPath = Application.streamingAssetsPath + "/" + mediaFileName; string persistentPath = Application.persistentDataPath + "/" + mediaFileName; if (!File.Exists(persistentPath)) { WWW wwwReader = new WWW(streamingMediaPath); yield return wwwReader; if (wwwReader.error != null) { Debug.LogError("wwwReader error: " + wwwReader.error); } System.IO.File.WriteAllBytes(persistentPath, wwwReader.bytes); } mediaFullPath = persistentPath; #else string mediaFileNameOgv = Path.GetFileNameWithoutExtension(mediaFileName) + ".ogv"; string streamingMediaPath = "file:///" + Application.streamingAssetsPath + "/" + mediaFileNameOgv; WWW wwwReader = new WWW(streamingMediaPath); yield return wwwReader; if (wwwReader.error != null) { Debug.LogError("wwwReader error: " + wwwReader.error); } movieTexture = wwwReader.movie; mediaRenderer.material.mainTexture = movieTexture; audioEmitter.clip = movieTexture.audioClip; mediaFullPath = streamingMediaPath; #endif Debug.Log("Movie FullPath: " + mediaFullPath); } /// <summary> /// Auto-starts video playback /// </summary> IEnumerator DelayedStartVideo() { yield return null; // delay 1 frame to allow MediaSurfaceInit from the render thread. if (!startedVideo) { Debug.Log("Mediasurface DelayedStartVideo"); startedVideo = true; #if (UNITY_ANDROID && !UNITY_EDITOR) // This can only be done once multi-threaded rendering is running mediaPlayer = StartVideoPlayerOnTextureId(nativeTexturePtr, nativeTextureWidth, nativeTextureHeight, mediaFullPath); #else if (movieTexture != null && movieTexture.isReadyToPlay) { movieTexture.Play(); if (audioEmitter != null) { audioEmitter.Play(); } } #endif } } void Start() { Debug.Log("MovieSample Start"); StartCoroutine(DelayedStartVideo()); } void Update() { #if (UNITY_ANDROID && !UNITY_EDITOR) IssuePluginEvent(MediaSurfaceEventType.Update); #else if (movieTexture != null) { if ( movieTexture.isReadyToPlay != movieTexture.isPlaying) { movieTexture.Play(); if (audioEmitter != null) { audioEmitter.Play(); } } } #endif } /// <summary> /// Pauses video playback when the app loses or gains focus /// </summary> void OnApplicationPause(bool wasPaused) { Debug.Log("OnApplicationPause: " + wasPaused); #if (UNITY_ANDROID && !UNITY_EDITOR) if (mediaPlayer != null) { videoPaused = wasPaused; try { mediaPlayer.Call((videoPaused) ? "pause" : "start"); } catch (Exception e) { Debug.Log("Failed to start/pause mediaPlayer with message " + e.Message); } } #else if (movieTexture != null) { videoPaused = wasPaused; if (videoPaused) { movieTexture.Pause(); if (audioEmitter != null) { audioEmitter.Pause(); } } else { movieTexture.Play(); if (audioEmitter != null) { audioEmitter.Play(); } } } #endif } private void OnApplicationQuit() { #if (UNITY_ANDROID && !UNITY_EDITOR) Debug.Log("OnApplicationQuit"); // This will trigger the shutdown on the render thread IssuePluginEvent(MediaSurfaceEventType.Shutdown); #endif } #if (UNITY_ANDROID && !UNITY_EDITOR) /// <summary> /// Set up the video player with the movie surface texture id. /// </summary> AndroidJavaObject StartVideoPlayerOnTextureId(IntPtr texId, int texWidth, int texHeight, string mediaPath) { Debug.Log("MoviePlayer: SetUpVideoPlayer"); IntPtr androidSurface = OVR_Media_Surface(texId, texWidth, texHeight); Debug.Log("MoviePlayer: SetUpVideoPlayer after create surface"); AndroidJavaObject mediaPlayer = new AndroidJavaObject("android/media/MediaPlayer"); // Can't use AndroidJavaObject.Call() with a jobject, must use low level interface //mediaPlayer.Call("setSurface", androidSurface); IntPtr setSurfaceMethodId = AndroidJNI.GetMethodID(mediaPlayer.GetRawClass(),"setSurface","(Landroid/view/Surface;)V"); jvalue[] parms = new jvalue[1]; parms[0] = new jvalue(); parms[0].l = androidSurface; AndroidJNI.CallVoidMethod(mediaPlayer.GetRawObject(), setSurfaceMethodId, parms); try { mediaPlayer.Call("setDataSource", mediaPath); mediaPlayer.Call("prepare"); mediaPlayer.Call("setLooping", true); mediaPlayer.Call("start"); } catch (Exception e) { Debug.Log("Failed to start mediaPlayer with message " + e.Message); } return mediaPlayer; } #endif #if (UNITY_ANDROID && !UNITY_EDITOR) [DllImport("OculusMediaSurface")] private static extern void OVR_Media_Surface_Init(); // This function returns an Android Surface object that is // bound to a SurfaceTexture object on an independent OpenGL texture id. // Each frame, before the TimeWarp processing, the SurfaceTexture is checked // for updates, and if one is present, the contents of the SurfaceTexture // will be copied over to the provided surfaceTexId and mipmaps will be // generated so normal Unity rendering can use it. [DllImport("OculusMediaSurface")] private static extern IntPtr OVR_Media_Surface(IntPtr surfaceTexId, int surfaceWidth, int surfaceHeight); [DllImport("OculusMediaSurface")] private static extern void OVR_Media_Surface_SetEventBase(int eventBase); #endif }
// These interfaces serve as an extension to the BCL's SymbolStore interfaces. namespace OpenRiaServices.DomainServices.Tools.Pdb.SymStore { using System; using System.Diagnostics.SymbolStore; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; [ ComImport, Guid("AA544d42-28CB-11d3-bd22-0000f80849bd"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false) ] internal interface ISymUnmanagedBinder { // These methods will often return error HRs in common cases. // If there are no symbols for the given target, a failing hr is returned. // This is pretty common. // // Using PreserveSig and manually handling error cases provides a big performance win. // Far fewer exceptions will be thrown and caught. // Exceptions should be reserved for truely "exceptional" cases. [PreserveSig] int GetReaderForFile(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String filename, [MarshalAs(UnmanagedType.LPWStr)] String SearchPath, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); [PreserveSig] int GetReaderFromStream(IntPtr importer, IStream stream, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); } [ ComImport, Guid("ACCEE350-89AF-4ccb-8B40-1C2C4C6F9434"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false) ] internal interface ISymUnmanagedBinder2 : ISymUnmanagedBinder { // ISymUnmanagedBinder methods (need to define the base interface methods also, per COM interop requirements) [PreserveSig] new int GetReaderForFile(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String filename, [MarshalAs(UnmanagedType.LPWStr)] String SearchPath, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); [PreserveSig] new int GetReaderFromStream(IntPtr importer, IStream stream, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); // ISymUnmanagedBinder2 methods [PreserveSig] int GetReaderForFile2(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String fileName, [MarshalAs(UnmanagedType.LPWStr)] String searchPath, int searchPolicy, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader pRetVal); } [ ComImport, Guid("28AD3D43-B601-4d26-8A1B-25F9165AF9D7"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComVisible(false) ] internal interface ISymUnmanagedBinder3 : ISymUnmanagedBinder2 { // ISymUnmanagedBinder methods (need to define the base interface methods also, per COM interop requirements) [PreserveSig] new int GetReaderForFile(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String filename, [MarshalAs(UnmanagedType.LPWStr)] String SearchPath, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); [PreserveSig] new int GetReaderFromStream(IntPtr importer, IStream stream, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader retVal); // ISymUnmanagedBinder2 methods (need to define the base interface methods also, per COM interop requirements) [PreserveSig] new int GetReaderForFile2(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String fileName, [MarshalAs(UnmanagedType.LPWStr)] String searchPath, int searchPolicy, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader pRetVal); // ISymUnmanagedBinder3 methods [PreserveSig] int GetReaderFromCallback(IntPtr importer, [MarshalAs(UnmanagedType.LPWStr)] String fileName, [MarshalAs(UnmanagedType.LPWStr)] String searchPath, int searchPolicy, [MarshalAs(UnmanagedType.IUnknown)] object callback, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedReader pRetVal); } //// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder"]/*' /> internal class SymbolBinder: ISymbolBinder1, ISymbolBinder2 { ISymUnmanagedBinder m_binder; protected static readonly Guid CLSID_CorSymBinder = new Guid("0A29FF9E-7F9C-4437-8B11-F424491E3931"); //// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.SymbolBinder"]/*' /> public SymbolBinder() { Type binderType = Type.GetTypeFromCLSID(CLSID_CorSymBinder); object comBinder = (ISymUnmanagedBinder)Activator.CreateInstance(binderType); m_binder = (ISymUnmanagedBinder)comBinder; } /// <summary> /// Create a SymbolBinder given the underling COM object for ISymUnmanagedBinder /// </summary> /// <param name="comBinderObject"></param> /// <remarks>Note that this could be protected, but C# doesn't have a way to express "internal AND /// protected", just "internal OR protected"</remarks> internal SymbolBinder(ISymUnmanagedBinder comBinderObject) { // We should not wrap null instances if (comBinderObject == null) throw new ArgumentNullException("comBinderObject"); m_binder = comBinderObject; } //// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReader"]/*' /> public ISymbolReader GetReader(IntPtr importer, String filename, String searchPath) { ISymUnmanagedReader reader = null; int hr = m_binder.GetReaderForFile(importer, filename, searchPath, out reader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); return new SymReader(reader); } //// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderForFile"]/*' /> public ISymbolReader GetReaderForFile(Object importer, String filename, String searchPath) { ISymUnmanagedReader reader = null; IntPtr uImporter = IntPtr.Zero; try { uImporter = Marshal.GetIUnknownForObject(importer); int hr = m_binder.GetReaderForFile(uImporter, filename, searchPath, out reader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); } finally { if (uImporter != IntPtr.Zero) Marshal.Release(uImporter); } return new SymReader(reader); } //// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderForFile1"]/*' /> public ISymbolReader GetReaderForFile(Object importer, String fileName, String searchPath, SymSearchPolicies searchPolicy) { ISymUnmanagedReader symReader = null; IntPtr uImporter = IntPtr.Zero; try { uImporter = Marshal.GetIUnknownForObject(importer); int hr = ((ISymUnmanagedBinder2)m_binder).GetReaderForFile2(uImporter, fileName, searchPath, (int)searchPolicy, out symReader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); } finally { if (uImporter != IntPtr.Zero) Marshal.Release(uImporter); } return new SymReader(symReader); } //// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderForFile2"]/*' /> public ISymbolReader GetReaderForFile(Object importer, String fileName, String searchPath, SymSearchPolicies searchPolicy, object callback) { ISymUnmanagedReader reader = null; IntPtr uImporter = IntPtr.Zero; try { uImporter = Marshal.GetIUnknownForObject(importer); int hr = ((ISymUnmanagedBinder3)m_binder).GetReaderFromCallback(uImporter, fileName, searchPath, (int)searchPolicy, callback, out reader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); } finally { if (uImporter != IntPtr.Zero) Marshal.Release(uImporter); } return new SymReader(reader); } //// <include file='doc\symbinder.uex' path='docs/doc[@for="SymbolBinder.GetReaderFromStream"]/*' /> public ISymbolReader GetReaderFromStream(Object importer, IStream stream) { ISymUnmanagedReader reader = null; IntPtr uImporter = IntPtr.Zero; try { uImporter = Marshal.GetIUnknownForObject(importer); int hr = ((ISymUnmanagedBinder2)m_binder).GetReaderFromStream(uImporter, stream, out reader); if (IsFailingResultNormal(hr)) { return null; } Marshal.ThrowExceptionForHR(hr); } finally { if (uImporter != IntPtr.Zero) Marshal.Release(uImporter); } return new SymReader(reader); } /// <summary> /// Get an ISymbolReader interface given a raw COM symbol reader object. /// </summary> /// <param name="reader">A COM object implementing ISymUnmanagedReader</param> /// <returns>The ISybmolReader interface wrapping the provided COM object</returns> /// <remarks>This method is on SymbolBinder because it's conceptually similar to the /// other methods for creating a reader. It does not, however, actually need to use the underlying /// Binder, so it could be on SymReader instead (but we'd have to make it a public class instead of /// internal).</remarks> public static ISymbolReader GetReaderFromCOM(Object reader) { return new SymReader((ISymUnmanagedReader)reader); } private static bool IsFailingResultNormal(int hr) { // If a pdb is not found, that's a pretty common thing. if (hr == unchecked((int)0x806D0005)) // E_PDB_NOT_FOUND { return true; } // Other fairly common things may happen here, but we don't want to hide // this from the programmer. // You may get 0x806D0014 if the pdb is there, but just old (mismatched) // Or if you ask for the symbol information on something that's not an assembly. // If that may happen for your application, wrap calls to GetReaderForFile in // try-catch(COMException) blocks and use the error code in the COMException to report error. return false; } } }
// 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 EventTest : ServerTestBase<ToggleExecutionModeServerFixture<Program>> { public EventTest( BrowserFixture browserFixture, ToggleExecutionModeServerFixture<Program> serverFixture, ITestOutputHelper output) : base(browserFixture, serverFixture, output) { } protected override void InitializeAsyncCore() { Navigate(ServerPathBase, noReload: true); } [Fact] public void FocusEvents_CanTrigger() { Browser.MountTestComponent<FocusEventComponent>(); var input = Browser.Exists(By.Id("input")); var output = Browser.Exists(By.Id("output")); Assert.Equal(string.Empty, output.Text); // Focus the target, verify onfocusin is fired input.Click(); Browser.Equal("onfocus,onfocusin,", () => output.Text); // Focus something else, verify onfocusout is also fired var other = Browser.Exists(By.Id("other")); other.Click(); Browser.Equal("onfocus,onfocusin,onblur,onfocusout,", () => output.Text); } [Fact] public void FocusEvents_CanReceiveBlurCausedByElementRemoval() { // Represents https://github.com/dotnet/aspnetcore/issues/26838 Browser.MountTestComponent<FocusEventComponent>(); Browser.FindElement(By.Id("button-that-disappears")).Click(); Browser.Equal("True", () => Browser.FindElement(By.Id("button-received-focus-out")).Text); } [Fact] public void MouseOverAndMouseOut_CanTrigger() { Browser.MountTestComponent<MouseEventComponent>(); var input = Browser.Exists(By.Id("mouseover_input")); var output = Browser.Exists(By.Id("output")); Assert.Equal(string.Empty, output.Text); var other = Browser.Exists(By.Id("other")); // Mouse over the button and then back off var actions = new Actions(Browser) .MoveToElement(input) .MoveToElement(other); actions.Perform(); Browser.Equal("onmouseover,onmouseout,", () => output.Text); } [Fact] public void MouseMove_CanTrigger() { Browser.MountTestComponent<MouseEventComponent>(); var input = Browser.Exists(By.Id("mousemove_input")); var output = Browser.Exists(By.Id("output")); Assert.Equal(string.Empty, output.Text); // Move a little bit var actions = new Actions(Browser) .MoveToElement(input) .MoveToElement(input, 10, 10); actions.Perform(); Browser.Contains("onmousemove,", () => output.Text); } [Fact] public void MouseDownAndMouseUp_CanTrigger() { Browser.MountTestComponent<MouseEventComponent>(); var input = Browser.Exists(By.Id("mousedown_input")); var output = Browser.Exists(By.Id("output")); Assert.Equal(string.Empty, output.Text); var other = Browser.Exists(By.Id("other")); // Mousedown var actions = new Actions(Browser).ClickAndHold(input); actions.Perform(); Browser.Equal("onmousedown,", () => output.Text); actions = new Actions(Browser).Release(input); actions.Perform(); Browser.Equal("onmousedown,onmouseup,", () => output.Text); } [Fact] public void Toggle_CanTrigger() { Browser.MountTestComponent<ToggleEventComponent>(); var detailsToggle = Browser.Exists(By.Id("details-toggle")); var output = Browser.Exists(By.Id("output")); Assert.Equal(string.Empty, output.Text); // Click var actions = new Actions(Browser).Click(detailsToggle); actions.Perform(); Browser.Equal("ontoggle,", () => output.Text); } [Fact] public void PointerDown_CanTrigger() { Browser.MountTestComponent<MouseEventComponent>(); var input = Browser.Exists(By.Id("pointerdown_input")); var output = Browser.Exists(By.Id("output")); Assert.Equal(string.Empty, output.Text); var actions = new Actions(Browser).ClickAndHold(input); actions.Perform(); Browser.Equal("onpointerdown", () => output.Text); } [Fact] public void DragDrop_CanTrigger() { Browser.MountTestComponent<MouseEventComponent>(); var input = Browser.Exists(By.Id("drag_input")); var target = Browser.Exists(By.Id("drop")); var output = Browser.Exists(By.Id("output")); Assert.Equal(string.Empty, output.Text); var actions = new Actions(Browser).DragAndDrop(input, target); actions.Perform(); // drop doesn't seem to trigger in Selenium. But it's sufficient to determine "any" drag event works Browser.Equal("ondragstart,", () => output.Text); } [Fact(Skip = "https://github.com/dotnet/aspnetcore/issues/32373")] public void TouchEvent_CanTrigger() { Browser.MountTestComponent<TouchEventComponent>(); var input = Browser.Exists(By.Id("touch_input")); var output = Browser.Exists(By.Id("output")); Assert.Equal(string.Empty, output.Text); var actions = new TouchActions(Browser).SingleTap(input); actions.Perform(); Browser.Equal("touchstarttouchend,", () => output.Text); } [Fact] public void PreventDefault_AppliesToFormOnSubmitHandlers() { var appElement = Browser.MountTestComponent<EventPreventDefaultComponent>(); appElement.FindElement(By.Id("form-1-button")).Click(); Browser.Equal("Event was handled", () => appElement.FindElement(By.Id("event-handled")).Text); } [Fact] public void PreventDefault_DotNotApplyByDefault() { var appElement = Browser.MountTestComponent<EventPreventDefaultComponent>(); appElement.FindElement(By.Id("form-2-button")).Click(); Assert.Contains("about:blank", Browser.Url); } [Fact] public void InputEvent_RespondsOnKeystrokes() { Browser.MountTestComponent<InputEventComponent>(); var input = Browser.Exists(By.TagName("input")); var output = Browser.Exists(By.Id("test-result")); Browser.Equal(string.Empty, () => output.Text); SendKeysSequentially(input, "abcdefghijklmnopqrstuvwxyz"); Browser.Equal("abcdefghijklmnopqrstuvwxyz", () => output.Text); input.SendKeys(Keys.Backspace); Browser.Equal("abcdefghijklmnopqrstuvwxy", () => output.Text); } [Fact] public void InputEvent_RespondsOnKeystrokes_EvenIfUpdatesAreLaggy() { // This test doesn't mean much on WebAssembly - it just shows that even if the CPU is locked // up for a bit it doesn't cause typing to lose keystrokes. But when running server-side, this // shows that network latency doesn't cause keystrokes to be lost even if: // [1] By the time a keystroke event arrives, the event handler ID has since changed // [2] We have the situation described under "the problem" at https://github.com/dotnet/aspnetcore/issues/8204#issuecomment-493986702 Browser.MountTestComponent<LaggyTypingComponent>(); var input = Browser.Exists(By.TagName("input")); var output = Browser.Exists(By.Id("test-result")); Browser.Equal(string.Empty, () => output.Text); SendKeysSequentially(input, "abcdefg"); Browser.Equal("abcdefg", () => output.Text); SendKeysSequentially(input, "hijklmn"); Browser.Equal("abcdefghijklmn", () => output.Text); } [Fact] public void NonInteractiveElementWithDisabledAttributeDoesRespondToMouseEvents() { Browser.MountTestComponent<EventDisablingComponent>(); var element = Browser.Exists(By.Id("disabled-div")); var eventLog = Browser.Exists(By.Id("event-log")); Browser.Equal(string.Empty, () => eventLog.GetAttribute("value")); element.Click(); Browser.Equal("Got event on div", () => eventLog.GetAttribute("value")); } [Theory] [InlineData("#disabled-button")] [InlineData("#disabled-button span")] [InlineData("#disabled-textarea")] public void InteractiveElementWithDisabledAttributeDoesNotRespondToMouseEvents(string elementSelector) { Browser.MountTestComponent<EventDisablingComponent>(); var element = Browser.Exists(By.CssSelector(elementSelector)); var eventLog = Browser.Exists(By.Id("event-log")); Browser.Equal(string.Empty, () => eventLog.GetAttribute("value")); element.Click(); // It's no use observing that the log is still empty, since maybe the UI just hasn't updated yet // To be sure that the preceding action has no effect, we need to trigger a different action that does have an effect Browser.Exists(By.Id("enabled-button")).Click(); Browser.Equal("Got event on enabled button", () => eventLog.GetAttribute("value")); } [Fact] public virtual void EventDuringBatchRendering_CanTriggerDOMEvents() { Browser.MountTestComponent<EventDuringBatchRendering>(); var input = Browser.Exists(By.CssSelector("#reversible-list input")); var eventLog = Browser.Exists(By.Id("event-log")); SendKeysSequentially(input, "abc"); Browser.Equal("abc", () => input.GetAttribute("value")); Browser.Equal( "Change event on item First with value a\n" + "Change event on item First with value ab\n" + "Change event on item First with value abc", () => eventLog.Text.Trim().Replace("\r\n", "\n")); } [Fact] public void EventDuringBatchRendering_CannotTriggerJSInterop() { Browser.MountTestComponent<EventDuringBatchRendering>(); var errorLog = Browser.Exists(By.Id("web-component-error-log")); Browser.Exists(By.Id("add-web-component")).Click(); var expectedMessage = _serverFixture.ExecutionMode == ExecutionMode.Client ? "Assertion failed - heap is currently locked" : "There was an exception invoking 'SomeMethodThatDoesntNeedToExistForThisTest' on assembly 'SomeAssembly'"; Browser.Contains(expectedMessage, () => errorLog.Text); } [Fact] public void RenderAttributesBeforeConnectedCallBack() { Browser.MountTestComponent<RenderAttributesBeforeConnectedCallback>(); var element = Browser.Exists(By.TagName("custom-web-component-data-from-attribute")); var expectedContent = "success"; Browser.Contains(expectedContent, () => element.Text); } [Fact] public void PolymorphicEventHandlersReceiveCorrectArgsSubclass() { // This is to show that the type of event argument received corresponds to the declared event // name, and not to the argument type on the event handler delegate. Note that this is only // supported (for back-compat) for the built-in standard web event types. For custom events, // the eventargs deserialization type is determined purely by the delegate's parameters list. Browser.MountTestComponent<MouseEventComponent>(); var elem = Browser.Exists(By.Id("polymorphic_event_elem")); // Output is initially empty var output = Browser.Exists(By.Id("output")); Assert.Equal(string.Empty, output.Text); // We can trigger a pointer event and receive a PointerEventArgs new Actions(Browser).Click(elem).Perform(); Browser.Equal("Microsoft.AspNetCore.Components.Web.PointerEventArgs:mouse", () => output.Text); // We can trigger a drag event and receive a DragEventArgs *on the same handler delegate* Browser.FindElement(By.Id("clear_event_log")).Click(); new Actions(Browser).DragAndDrop(elem, Browser.FindElement(By.Id("other"))).Perform(); Browser.Equal("Microsoft.AspNetCore.Components.Web.DragEventArgs:1", () => output.Text); } void SendKeysSequentially(IWebElement target, string text) { // Calling it for each character works around some chars being skipped // https://stackoverflow.com/a/40986041 foreach (var c in text) { target.SendKeys(c.ToString()); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Core.Cache; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; using umbraco.interfaces; namespace Umbraco.Core.Sync { /// <summary> /// An <see cref="IServerMessenger"/> that works by storing messages in the database. /// </summary> // // this messenger writes ALL instructions to the database, // but only processes instructions coming from remote servers, // thus ensuring that instructions run only once // public class DatabaseServerMessenger : ServerMessengerBase { private readonly ApplicationContext _appContext; private readonly DatabaseServerMessengerOptions _options; private readonly ManualResetEvent _syncIdle; private readonly object _locko = new object(); private readonly ILogger _logger; private int _lastId = -1; private DateTime _lastSync; private bool _initialized; private bool _syncing; private bool _released; private readonly ProfilingLogger _profilingLogger; protected ApplicationContext ApplicationContext { get { return _appContext; } } public DatabaseServerMessenger(ApplicationContext appContext, bool distributedEnabled, DatabaseServerMessengerOptions options) : base(distributedEnabled) { if (appContext == null) throw new ArgumentNullException("appContext"); if (options == null) throw new ArgumentNullException("options"); _appContext = appContext; _options = options; _lastSync = DateTime.UtcNow; _syncIdle = new ManualResetEvent(true); _profilingLogger = appContext.ProfilingLogger; _logger = appContext.ProfilingLogger.Logger; } #region Messenger protected override bool RequiresDistributed(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, MessageType dispatchType) { // we don't care if there's servers listed or not, // if distributed call is enabled we will make the call return _initialized && DistributedEnabled; } protected override void DeliverRemote( IEnumerable<IServerAddress> servers, ICacheRefresher refresher, MessageType messageType, IEnumerable<object> ids = null, string json = null) { var idsA = ids == null ? null : ids.ToArray(); Type idType; if (GetArrayType(idsA, out idType) == false) throw new ArgumentException("All items must be of the same type, either int or Guid.", "ids"); var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json); var dto = new CacheInstructionDto { UtcStamp = DateTime.UtcNow, Instructions = JsonConvert.SerializeObject(instructions, Formatting.None), OriginIdentity = LocalIdentity }; ApplicationContext.DatabaseContext.Database.Insert(dto); } #endregion #region Sync /// <summary> /// Boots the messenger. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// Callers MUST ensure thread-safety. /// </remarks> protected void Boot() { // weight:10, must release *before* the facade service, because once released // the service will *not* be able to properly handle our notifications anymore const int weight = 10; var registered = ApplicationContext.MainDom.Register( () => { lock (_locko) { _released = true; // no more syncs } _syncIdle.WaitOne(); // wait for pending sync }, weight); if (registered == false) return; ReadLastSynced(); // get _lastId EnsureInstructions(); // reset _lastId if instrs are missing Initialize(); // boot } /// <summary> /// Initializes a server that has never synchronized before. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// Callers MUST ensure thread-safety. /// </remarks> private void Initialize() { lock (_locko) { if (_released) return; if (_lastId < 0) // never synced before { // we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new // server and it will need to rebuild it's own caches, eg Lucene or the xml cache file. _logger.Warn<DatabaseServerMessenger>("No last synced Id found, this generally means this is a new server/install. The server will rebuild its caches and indexes and then adjust it's last synced id to the latest found in the database and will start maintaining cache updates based on that id"); // go get the last id in the db and store it // note: do it BEFORE initializing otherwise some instructions might get lost // when doing it before, some instructions might run twice - not an issue var lastId = _appContext.DatabaseContext.Database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction"); if (lastId > 0) SaveLastSynced(lastId); // execute initializing callbacks if (_options.InitializingCallbacks != null) foreach (var callback in _options.InitializingCallbacks) callback(); } _initialized = true; } } /// <summary> /// Synchronize the server (throttled). /// </summary> protected void Sync() { lock (_locko) { if (_syncing) return; if (_released) return; if ((DateTime.UtcNow - _lastSync).Seconds <= _options.ThrottleSeconds) return; _syncing = true; _syncIdle.Reset(); _lastSync = DateTime.UtcNow; } try { using (_profilingLogger.DebugDuration<DatabaseServerMessenger>("Syncing from database...")) { ProcessDatabaseInstructions(); PruneOldInstructions(); } } finally { _syncing = false; _syncIdle.Set(); } } /// <summary> /// Process instructions from the database. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// </remarks> private void ProcessDatabaseInstructions() { // NOTE // we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that // would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests // (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are // pending requests after being processed, they'll just be processed on the next poll. // // FIXME not true if we're running on a background thread, assuming we can? var sql = new Sql().Select("*") .From<CacheInstructionDto>() .Where<CacheInstructionDto>(dto => dto.Id > _lastId) .OrderBy<CacheInstructionDto>(dto => dto.Id); var dtos = _appContext.DatabaseContext.Database.Fetch<CacheInstructionDto>(sql); if (dtos.Count <= 0) return; // only process instructions coming from a remote server, and ignore instructions coming from // the local server as they've already been processed. We should NOT assume that the sequence of // instructions in the database makes any sense whatsoever, because it's all async. var localIdentity = LocalIdentity; var lastId = 0; foreach (var dto in dtos) { if (dto.OriginIdentity == localIdentity) { // just skip that local one but update lastId nevertheless lastId = dto.Id; continue; } // deserialize remote instructions & skip if it fails JArray jsonA; try { jsonA = JsonConvert.DeserializeObject<JArray>(dto.Instructions); } catch (JsonException ex) { _logger.Error<DatabaseServerMessenger>(string.Format("Failed to deserialize instructions ({0}: \"{1}\").", dto.Id, dto.Instructions), ex); lastId = dto.Id; // skip continue; } // execute remote instructions & update lastId try { NotifyRefreshers(jsonA); lastId = dto.Id; } catch (Exception ex) { _logger.Error<DatabaseServerMessenger>( string.Format("DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions ({0}: \"{1}\"). Instruction is being skipped/ignored", dto.Id, dto.Instructions), ex); //we cannot throw here because this invalid instruction will just keep getting processed over and over and errors // will be thrown over and over. The only thing we can do is ignore and move on. lastId = dto.Id; } } if (lastId > 0) SaveLastSynced(lastId); } /// <summary> /// Remove old instructions from the database. /// </summary> private void PruneOldInstructions() { _appContext.DatabaseContext.Database.Delete<CacheInstructionDto>("WHERE utcStamp < @pruneDate", new { pruneDate = DateTime.UtcNow.AddDays(-_options.DaysToRetainInstructions) }); } /// <summary> /// Ensure that the last instruction that was processed is still in the database. /// </summary> /// <remarks>If the last instruction is not in the database anymore, then the messenger /// should not try to process any instructions, because some instructions might be lost, /// and it should instead cold-boot.</remarks> private void EnsureInstructions() { var sql = new Sql().Select("*") .From<CacheInstructionDto>() .Where<CacheInstructionDto>(dto => dto.Id == _lastId); var dtos = _appContext.DatabaseContext.Database.Fetch<CacheInstructionDto>(sql); if (dtos.Count == 0) _lastId = -1; } /// <summary> /// Reads the last-synced id from file into memory. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// </remarks> private void ReadLastSynced() { var path = SyncFilePath; if (File.Exists(path) == false) return; var content = File.ReadAllText(path); int last; if (int.TryParse(content, out last)) _lastId = last; } /// <summary> /// Updates the in-memory last-synced id and persists it to file. /// </summary> /// <param name="id">The id.</param> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// </remarks> private void SaveLastSynced(int id) { File.WriteAllText(SyncFilePath, id.ToString(CultureInfo.InvariantCulture)); _lastId = id; } /// <summary> /// Gets the unique local identity of the executing AppDomain. /// </summary> /// <remarks> /// <para>It is not only about the "server" (machine name and appDomainappId), but also about /// an AppDomain, within a Process, on that server - because two AppDomains running at the same /// time on the same server (eg during a restart) are, practically, a LB setup.</para> /// <para>Practically, all we really need is the guid, the other infos are here for information /// and debugging purposes.</para> /// </remarks> protected readonly static string LocalIdentity = NetworkHelper.MachineName // eg DOMAIN\SERVER + "/" + HttpRuntime.AppDomainAppId // eg /LM/S3SVC/11/ROOT + " [P" + Process.GetCurrentProcess().Id // eg 1234 + "/D" + AppDomain.CurrentDomain.Id // eg 22 + "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique /// <summary> /// Gets the sync file path for the local server. /// </summary> /// <returns>The sync file path for the local server.</returns> private static string SyncFilePath { get { var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/DistCache/" + NetworkHelper.FileSafeMachineName); if (Directory.Exists(tempFolder) == false) Directory.CreateDirectory(tempFolder); return Path.Combine(tempFolder, HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt"); } } #endregion #region Notify refreshers private static ICacheRefresher GetRefresher(Guid id) { var refresher = CacheRefreshersResolver.Current.GetById(id); if (refresher == null) throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist."); return refresher; } private static IJsonCacheRefresher GetJsonRefresher(Guid id) { return GetJsonRefresher(GetRefresher(id)); } private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher) { var jsonRefresher = refresher as IJsonCacheRefresher; if (jsonRefresher == null) throw new InvalidOperationException("Cache refresher with ID \"" + refresher.UniqueIdentifier + "\" does not implement " + typeof(IJsonCacheRefresher) + "."); return jsonRefresher; } private static void NotifyRefreshers(IEnumerable<JToken> jsonArray) { foreach (var jsonItem in jsonArray) { // could be a JObject in which case we can convert to a RefreshInstruction, // otherwise it could be another JArray - in which case we'll iterate that. var jsonObj = jsonItem as JObject; if (jsonObj != null) { var instruction = jsonObj.ToObject<RefreshInstruction>(); switch (instruction.RefreshType) { case RefreshMethodType.RefreshAll: RefreshAll(instruction.RefresherId); break; case RefreshMethodType.RefreshByGuid: RefreshByGuid(instruction.RefresherId, instruction.GuidId); break; case RefreshMethodType.RefreshById: RefreshById(instruction.RefresherId, instruction.IntId); break; case RefreshMethodType.RefreshByIds: RefreshByIds(instruction.RefresherId, instruction.JsonIds); break; case RefreshMethodType.RefreshByJson: RefreshByJson(instruction.RefresherId, instruction.JsonPayload); break; case RefreshMethodType.RemoveById: RemoveById(instruction.RefresherId, instruction.IntId); break; } } else { var jsonInnerArray = (JArray) jsonItem; NotifyRefreshers(jsonInnerArray); // recurse } } } private static void RefreshAll(Guid uniqueIdentifier) { var refresher = GetRefresher(uniqueIdentifier); refresher.RefreshAll(); } private static void RefreshByGuid(Guid uniqueIdentifier, Guid id) { var refresher = GetRefresher(uniqueIdentifier); refresher.Refresh(id); } private static void RefreshById(Guid uniqueIdentifier, int id) { var refresher = GetRefresher(uniqueIdentifier); refresher.Refresh(id); } private static void RefreshByIds(Guid uniqueIdentifier, string jsonIds) { var refresher = GetRefresher(uniqueIdentifier); foreach (var id in JsonConvert.DeserializeObject<int[]>(jsonIds)) refresher.Refresh(id); } private static void RefreshByJson(Guid uniqueIdentifier, string jsonPayload) { var refresher = GetJsonRefresher(uniqueIdentifier); refresher.Refresh(jsonPayload); } private static void RemoveById(Guid uniqueIdentifier, int id) { var refresher = GetRefresher(uniqueIdentifier); refresher.Remove(id); } #endregion } }
// This file is part of SNMP#NET. // // SNMP#NET is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // SNMP#NET 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 SNMP#NET. If not, see <http://www.gnu.org/licenses/>. // using System; namespace SnmpSharpNet { /// <summary>Base SNMP packet class.</summary> /// <remarks> /// All SNMP packets begin with the SMI_SEQUENCE header and SNMP protocol version number. /// This class parses and encodes these values. Derived classes parse further information from SNMP packets. /// </remarks> public abstract class SnmpPacket { /// <summary> /// SNMP protocol version /// </summary> protected Integer32 _protocolVersion; /// <summary> /// SNMP Protocol version /// </summary> public SnmpVersion Version { get { return (SnmpVersion)_protocolVersion.Value; } } /// <summary> /// Get Pdu /// </summary> public virtual Pdu Pdu { get { return null; } } /// <summary> /// Constructor. Sets SNMP version to SNMPV1. /// </summary> public SnmpPacket() { _protocolVersion = new Integer32((int)SnmpVersion.Ver1); } /// <summary> /// Constructor. Initialize SNMP version as supplied. /// </summary> /// <param name="protocolVersion">Protocol version. Acceptable values are SnmpConstants.SNMPV1, /// SnmpConstants.SNMPV2 and SnmpConstants.SNMPV3</param> public SnmpPacket(SnmpVersion protocolVersion) { _protocolVersion = new Integer32((int)protocolVersion); } /// <summary> /// Decode SNMP packet header. This class decodes the initial sequence and SNMP protocol version /// number. /// </summary> /// <param name="buffer">BER encoded SNMP packet</param> /// <param name="length">Packet length</param> /// <returns>Offset position after the initial sequence header and protocol version value</returns> /// <exception cref="SnmpDecodingException">Thrown when invalid sequence type is found at the start of the SNMP packet being decoded</exception> public virtual int decode(byte[] buffer, int length) { int offset = 0; if (length < 2) { // we need at least 2 bytes throw new OverflowException("Packet too small."); } // make sure you get the right length buffer to be able to check for over/under flow errors MutableByte buf = new MutableByte(buffer, length); Sequence seq = new Sequence(); offset = seq.decode(buf, offset); if( seq.Type != SnmpConstants.SMI_SEQUENCE ) throw new SnmpDecodingException("Invalid sequence type at the start of the SNMP packet."); offset = _protocolVersion.decode(buf, offset); return offset; } /// <summary> /// Place holder for derived class implementations. /// </summary> /// <returns>Nothing</returns> public abstract byte[] encode(); /// <summary> /// Wrap BER encoded SNMP information contained in the parameter <see cref="MutableByte"/> class. /// /// Information in the parameter is prepended by the SNMP version field and wrapped in a sequence header. /// /// Derived classes call this method to finalize SNMP packet encoding. /// </summary> /// <param name="buffer">Buffer containing BER encoded SNMP information</param> public virtual void encode(MutableByte buffer) { // Encode SNMP protocol version MutableByte temp = new MutableByte(); _protocolVersion.encode(temp); buffer.Prepend(temp); temp.Reset(); AsnType.BuildHeader(temp, SnmpConstants.SMI_SEQUENCE, buffer.Length); buffer.Prepend(temp); } /// <summary> /// Get SNMP protocol version from the packet. This routine does not verify if version number is valid. Caller /// should verify that returned value represents a valid SNMP protocol version number. /// /// <code> /// int protocolVersion = Packet.GetProtocolVersion(inPacket, inLength); /// if( protocolVersion != -1 ) /// { /// if( protocolVersion == SnmpConstants.SNMPV1 || protocolVersion == SnmpConstants.SNMPV2 || protocolVersion == SnmpConstants.SNMPV3 ) /// { /// // do something /// } /// else /// { /// Console.WriteLine("Invalid SNMP protocol version."); /// } /// } /// else /// { /// Console.WriteLine("Invalid SNMP packet."); /// } /// </code> /// </summary> /// <param name="buffer">BER encoded SNMP packet</param> /// <param name="bufferLength">Length of the BER encoded packet</param> /// <returns>Returns SNMP protocol version, if packet is not valid returned value is -1.</returns> /// <exception cref="SnmpDecodingException">Thrown when invalid sequence type is found at the start of the SNMP packet being decoded</exception> public static int GetProtocolVersion(byte[] buffer, int bufferLength) { int offset = 0; int length = 0; byte asnType = AsnType.ParseHeader(buffer, ref offset, out length); if ((offset + length) > bufferLength) { return -1; // This is not a valid packet } if( asnType != SnmpConstants.SMI_SEQUENCE ) throw new SnmpDecodingException("Invalid sequence type at the start of the SNMP packet."); Integer32 version = new Integer32(); offset = version.decode(buffer, offset); return version.Value; } #region Packet type check properties /// <summary> /// Packet is a report /// </summary> public bool IsReport { get { if (Pdu.Type == PduType.Response) return true; return false; } } /// <summary> /// Packet is a request /// </summary> /// <remarks> /// Checks if the class content is a SNMP Get, GetNext, GetBulk or Set request. /// </remarks> public bool IsRequest { get { if (Pdu.Type == PduType.Get || Pdu.Type == PduType.GetNext || Pdu.Type == PduType.GetBulk || Pdu.Type == PduType.Set) return true; return false; } } /// <summary> /// Packet is a response /// </summary> public bool IsResponse { get { if (Pdu.Type == PduType.Response) return true; return false; } } /// <summary> /// Packet is a notification /// </summary> public bool IsNotification { get { if (Pdu.Type == PduType.Trap || Pdu.Type == PduType.V2Trap || Pdu.Type == PduType.Inform) return true; return false; } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.Reflection; using System.IO; using System.Xml.Serialization; using BitDiffer.Common.Utility; using BitDiffer.Client.Properties; using BitDiffer.Common.Misc; using BitDiffer.Core; using BitDiffer.Common.Interfaces; using BitDiffer.Common.TraceListeners; using BitDiffer.Common.Configuration; using BitDiffer.Client.Controls; using BitDiffer.Client.MailSender; using BitDiffer.Client.Models; using BitDiffer.Common.Exceptions; namespace BitDiffer.Client.Forms { public partial class MainFrm : Form, IHandleProgress { private bool _enableEvents; private bool _dirty; private string _tipText; private const string _filter = "Comparison Sets|*.cset"; private Progress _progress; private AssemblyComparison _ac; private ComparisonSet _set; private ErrorLevelTraceListener _eltl = new ErrorLevelTraceListener(); public MainFrm() { InitializeComponent(); if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) { this.Icon = Resources.App; //ProfessionalColorTable colorTable = new ProfessionalColorTable(); //colorTable.UseSystemColors = true; //statusStrip1.Renderer = new ToolStripProfessionalRenderer(colorTable); //toolStrip1.Renderer = new ToolStripProfessionalRenderer(colorTable); Trace.Listeners.Add(_eltl); ProgramArguments args = new ProgramArguments(); try { args.Parse(false, Environment.GetCommandLineArgs()); if (args.Help) { ShowHelp(); } if (args.ComparisonSet.Items.Count > 0) { _set = args.ComparisonSet; this.Show(); UpdateCheckStates(); UpdateTitleBar(); Compare(); } } catch (ArgumentParserException ex) { MessageBox.Show(this, ex.Message, "Error Parsing Arguments", MessageBoxButtons.OK, MessageBoxIcon.Stop); } Application.Idle += new EventHandler(Application_Idle); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); UpdateTitleBar(); Log.Info("{0} GUI", Constants.ProductName); Log.Info("Version {0} ({1:d})", Assembly.GetExecutingAssembly().GetName().Version, DateTime.Today); } private void Compare() { SetStatusWorking(); _eltl.Reset(); traceViewer1.Clear(); _progress = new Progress(); backgroundWorker1.RunWorkerAsync(); _progress.ShowDialog(this); } private void ApplyFilter() { _ac.Recompare(_set.Filter); navigator.LoadFrom(_ac, true); } private void SetStatusOK() { SetStatus(Resources.OK, "Ready"); } private void SetStatusWorking() { SetStatus(Resources.clock, "Working..."); } private void SetStatus(TraceLevel traceLevel) { switch (traceLevel) { case TraceLevel.Error: SetStatus(Resources.Critical, "Completed with errors. Check the log messages for details."); _tipText = "Errors occurred during the comparison. Check the log messages for details."; resultToolTip.ToolTipTitle = "Completed With Errors"; resultToolTip.ToolTipIcon = ToolTipIcon.Error; showTipTimer.Start(); break; case TraceLevel.Warning: SetStatus(Resources.Warning, "Completed with warnings. Check the log messages for details."); _tipText = "Warnings occurred during the comparison. Check the log messages for details."; resultToolTip.ToolTipTitle = "Completed With Warnings"; resultToolTip.ToolTipIcon = ToolTipIcon.Warning; showTipTimer.Start(); break; default: SetStatus(Resources.OK, "Ready"); break; } } private void showTipTimer_Tick(object sender, EventArgs e) { showTipTimer.Stop(); resultToolTip.Show(_tipText, this, 4, this.Height - 90, 2500); } private void SetStatus(Image image, string text) { statusStripIcon.Image = image; statusStripStatusText.Text = " " + text; Update(); } private void tsbRefresh_Click(object sender, EventArgs e) { Compare(); } private void navigator_SelectedAssemblyGroupChanged(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; try { AssemblyGroup grp = navigator.SelectedAssemblyGroup; changeInfoDetail1.LoadFrom(grp); diffViewer1.LoadFrom(grp); if (!string.IsNullOrEmpty(_set.Filter.TextFilter)) { diffViewer1.ExpandAll(); } } finally { this.Cursor = Cursors.Default; } } private void diffViewer1_SelectedDetailItemChanged(object sender, EventArgs e) { ICanCompare item = diffViewer1.SelectedItem; if (item != null) { changeInfoDetail1.LoadFromItem(item, diffViewer1.SelectedColumnIndex == 0); return; } AssemblyGroup grp = diffViewer1.SelectedGroupItem; if (grp != null) { changeInfoDetail1.LoadFrom(grp); return; } changeInfoDetail1.Clear(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { using (new BitDiffer.Common.Utility.Stopwatch("Main loop")) { e.Result = new AssemblyComparer(this).CompareAssemblies(_set); } } private void DoLoadSet(string fileName) { _set = LoadSet(fileName); _dirty = false; UserPrefs.LastSelectedComparisonSet = fileName; UpdateCheckStates(); UpdateTitleBar(); Compare(); } private ComparisonSet LoadSet(string fileName) { _enableEvents = true; try { using (FileStream fs = File.Open(fileName, FileMode.Open)) { XmlSerializer xs = new XmlSerializer(typeof(ComparisonSet)); ComparisonSet set = (ComparisonSet)xs.Deserialize(fs); set.FileName = fileName; return set; } } finally { _enableEvents = true; } } private void SaveSet(bool promptRename) { if (_set.FileName == null || promptRename) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = _filter; string lastSelected = UserPrefs.LastSelectedComparisonSet; if (!string.IsNullOrEmpty(lastSelected)) { sfd.InitialDirectory = Path.GetDirectoryName(lastSelected); } if (sfd.ShowDialog() != DialogResult.OK) { return; } UserPrefs.LastSelectedComparisonSet = sfd.FileName; _set.FileName = sfd.FileName; } using (FileStream fs = File.Open(_set.FileName, FileMode.Create)) { XmlSerializer xs = new XmlSerializer(typeof(ComparisonSet)); xs.Serialize(fs, _set); _dirty = false; UpdateTitleBar(); } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { lock (this) { _progress.UpdateProgress((ProgressStatus)e.UserState); } } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { _progress.Close(); _progress = null; if (e.Error != null) { ThreadExceptionDialog ted = new ThreadExceptionDialog(e.Error); ted.ShowDialog(); } else { SetStatus(_eltl.HighestLoggedLevel); _ac = (AssemblyComparison)e.Result; if (_ac != null) { ApplyFilter(); } } } private delegate void SetMaxRangeDelegate(int max); public void SetMaxRange(int max) { if (this.InvokeRequired) { this.Invoke(new SetMaxRangeDelegate(SetMaxRange), max); } else { _progress.SetMaxRange(max); } } public bool CancelRequested { get { return _progress.CancelRequested; } } public void UpdateProgress(ProgressStatus progress) { backgroundWorker1.ReportProgress(0, progress); } private void tstbTextFilter_TextChanged(object sender, EventArgs e) { if (_enableEvents) { typeFilterTimer.Stop(); typeFilterTimer.Start(); } } private void typeFilterTimer_Tick(object sender, EventArgs e) { typeFilterTimer.Stop(); _set.Filter.TextFilter = tstbTextFilter.Text; ApplyFilter(); } private void tsmiPublic_Click(object sender, EventArgs e) { if (_enableEvents) { _dirty = true; tsmiPublic.Checked = !tsmiPublic.Checked; _set.Filter.IncludePublic = tsmiPublic.Checked; ApplyFilter(); } } private void tsmiProtected_Click(object sender, EventArgs e) { if (_enableEvents) { _dirty = true; tsmiProtected.Checked = !tsmiProtected.Checked; _set.Filter.IncludeProtected = tsmiProtected.Checked; ApplyFilter(); } } private void tsmiInternal_Click(object sender, EventArgs e) { if (_enableEvents) { _dirty = true; tsmiInternal.Checked = !tsmiInternal.Checked; _set.Filter.IncludeInternal = tsmiInternal.Checked; ApplyFilter(); } } private void tsmiPrivate_Click(object sender, EventArgs e) { if (_enableEvents) { _dirty = true; tsmiPrivate.Checked = !tsmiPrivate.Checked; _set.Filter.IncludePrivate = tsmiPrivate.Checked; ApplyFilter(); } } private void tsmiCompareMethods_Click(object sender, EventArgs e) { if (_enableEvents) { _dirty = true; tsmiShowImplChanges.Checked = !tsmiShowImplChanges.Checked; _set.Filter.CompareMethodImplementations = tsmiShowImplChanges.Checked; ApplyFilter(); } } private void tsmiIgnoreAttrChanges_Click(object sender, EventArgs e) { if (_enableEvents) { _dirty = true; tsmiIgnoreAttrChanges.Checked = !tsmiIgnoreAttrChanges.Checked; _set.Filter.IgnoreAssemblyAttributeChanges = tsmiIgnoreAttrChanges.Checked; ApplyFilter(); } } private void tsmiShowChangesOnly_Click(object sender, EventArgs e) { if (_enableEvents) { _dirty = true; tsmiShowChangesOnly.Checked = !tsmiShowChangesOnly.Checked; _set.Filter.ChangedItemsOnly = tsmiShowChangesOnly.Checked; ApplyFilter(); } } private void Application_Idle(object sender, EventArgs e) { bool enable = (_ac != null); tsbPrint.Enabled = tsmiPrintAll.Enabled = tsmiPrintSelected.Enabled = tsmiPrintPreview.Enabled = tsbPrintSelected.Enabled = tsbPrintAll.Enabled = enable; tsbSendTo.Enabled = tsmiSendAll.Enabled = tsmiSendSelected.Enabled = tsbSendSelected.Enabled = tsbSendAll.Enabled = enable; tsbExport.Enabled = tsmiExport.Enabled = enable; tsbRefresh.Enabled = enable; tsbView.Enabled = enable; tslTextFilter.Enabled = enable; tstbTextFilter.Enabled = enable; enable = (_set != null); tsmiConfig.Enabled = tsbConfigure.Enabled = enable; tsbSave.Enabled = tsmiSave.Enabled = (enable && _dirty); tsmiSaveAs.Enabled = enable; } private void tsbNew_Click(object sender, EventArgs e) { if (!CheckSaveChanges()) { return; } _set = new ComparisonSet(); if (EditProject()) { UpdateCheckStates(); UpdateTitleBar(); Compare(); } } private bool CheckSaveChanges() { if (!_dirty) { return true; } switch (MessageBox.Show(this, string.Format("You have unsaved changes. Save changes to comparison set {0}?", Path.GetFileName(_set.FileName)), "Confirm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning)) { case DialogResult.Yes: this.SaveSet(false); return true; case DialogResult.No: return true; case DialogResult.Cancel: return false; default: return false; } } private void tsbOpen_Click(object sender, EventArgs e) { if (!CheckSaveChanges()) { return; } OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = _filter; string lastSelected = UserPrefs.LastSelectedComparisonSet; if (!string.IsNullOrEmpty(lastSelected)) { ofd.InitialDirectory = Path.GetDirectoryName(lastSelected); } if (ofd.ShowDialog() == DialogResult.OK) { if (Path.GetExtension(ofd.FileName).ToUpper() != ".CSET") { MessageBox.Show(this, "Please select an existing comparison set (*.cset) file.\n\nTo compare a new set of binaries, select 'New' from the toolbar.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } DoLoadSet(ofd.FileName); } } private void tsbSave_Click(object sender, EventArgs e) { SaveSet(false); } private void tsmiSaveAs_Click(object sender, EventArgs e) { SaveSet(true); } private void tsmiExit_Click(object sender, EventArgs e) { Application.Exit(); } private void tsmiAbout_Click(object sender, EventArgs e) { AboutBox ab = new AboutBox(); ab.ShowDialog(); } private void tsbHelp_Click(object sender, EventArgs e) { ShowHelp(); } private void UpdateCheckStates() { _enableEvents = false; try { tsmiShowImplChanges.Checked = _set.Filter.CompareMethodImplementations; tsmiPublic.Checked = _set.Filter.IncludePublic; tsmiProtected.Checked = _set.Filter.IncludeProtected; tsmiInternal.Checked = _set.Filter.IncludeInternal; tsmiPrivate.Checked = _set.Filter.IncludePrivate; tsmiIgnoreAttrChanges.Checked = _set.Filter.IgnoreAssemblyAttributeChanges; tsmiShowChangesOnly.Checked = _set.Filter.ChangedItemsOnly; tstbTextFilter.Text = _set.Filter.TextFilter; } finally { _enableEvents = true; } } private void UpdateTitleBar() { if (_set == null || _set.FileName == null) { this.Text = string.Format("{0} {1}", Constants.ProductName, Assembly.GetExecutingAssembly().GetName().Version); } else { this.Text = string.Format("{0} - {1} {2}", Path.GetFileName(_set.FileName), Constants.ProductName, Assembly.GetExecutingAssembly().GetName().Version); } } private void MainFrm_FormClosing(object sender, FormClosingEventArgs e) { if (!CheckSaveChanges()) { e.Cancel = true; return; } } private void tsmiConfig_Click(object sender, EventArgs e) { if (EditProject()) { Compare(); } } private void tsbConfigure_Click(object sender, EventArgs e) { if (EditProject()) { Compare(); } } private bool EditProject() { if (_set != null) { ProjectSetup ps = new ProjectSetup(_set); if (ps.ShowDialog(this) == DialogResult.OK) { _dirty = true; return true; } } return false; } private void tsmiCopy_Click(object sender, EventArgs e) { changeInfoDetail1.Copy(); } private void tsmiPrintSelected_Click(object sender, EventArgs e) { PrintSelected(); } private void tsbPrintSelected_Click(object sender, EventArgs e) { PrintSelected(); } private void PrintSelected() { changeInfoDetail1.Print(); } private void tsmiPrintPreview_Click(object sender, EventArgs e) { changeInfoDetail1.PrintPreview(); } private void tsbPrintAll_Click(object sender, EventArgs e) { PrintAll(); } private void tsmiPrintAll_Click(object sender, EventArgs e) { PrintAll(); } private void PrintAll() { if (!CheckFilterSanity()) { return; } auxWebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(auxWebBrowser_PrintContent); auxWebBrowser.DocumentText = GetFullReportText(); } private string GetFullReportText() { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { HtmlUtility.WriteHtmlStart(sw); this.navigator.SelectedAssemblyGroup.WriteHtmlReport(sw); HtmlUtility.WriteHtmlEnd(sw); } return sb.ToString(); } private bool CheckFilterSanity() { if ((!_set.Filter.ChangedItemsOnly || _set.Filter.IncludePrivate || _set.Filter.IncludeInternal) && (string.IsNullOrEmpty(_set.Filter.TextFilter))) { if (MessageBox.Show(this, "Your current view filter will be set to show only public or protected changed items excluding implementation before printing all items. To reset the filter, use the dropdown menu on the toolbar.\n\nTo archive unfiltered data, use the 'export' option.", "Filter Data", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) { return false; } _set.Filter.ChangedItemsOnly = true; _set.Filter.IncludePrivate = false; _set.Filter.IncludeInternal = false; _set.Filter.CompareMethodImplementations = false; ApplyFilter(); UpdateCheckStates(); } return true; } void auxWebBrowser_PrintContent(object sender, WebBrowserDocumentCompletedEventArgs e) { auxWebBrowser.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(auxWebBrowser_PrintContent); auxWebBrowser.ShowPrintDialog(); } private void tsbSendSelected_Click(object sender, EventArgs e) { SendSelected(); } private void tsmiSendSelected_Click(object sender, EventArgs e) { SendSelected(); } private void SendSelected() { changeInfoDetail1.SendTo(); } private void tsbExport_Click(object sender, EventArgs e) { Export(); } private void tsmiExport_Click(object sender, EventArgs e) { Export(); } private void Export() { if (this.navigator.SelectedAssemblyGroup == null) { return; } SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "HTML Report (*.html)|*.html|XML Report (*.xml)|*.xml"; sfd.CheckPathExists = true; sfd.AddExtension = true; if (sfd.ShowDialog(this) == DialogResult.OK) { _ac.WriteReport(sfd.FileName, AssemblyComparisonXmlWriteMode.Normal); Process.Start(sfd.FileName); } } private void tsbSendAll_Click(object sender, EventArgs e) { SendAll(); } private void tsmiSendAll_Click(object sender, EventArgs e) { SendAll(); } private void SendAll() { if (!CheckFilterSanity()) { return; } MailSenderController.SendEmail(this, Constants.ComparisonEmailSubject, GetFullReportText()); } private void tsmiHelpSearch_Click(object sender, EventArgs e) { ShowHelp(); } private void ShowHelp() { Process.Start(Constants.HelpUrl); } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public static class UnaryBitwiseNotTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryBitwiseNotBoolTest(bool useInterpreter) { bool[] values = new bool[] { false, true }; for (int i = 0; i < values.Length; i++) { VerifyBitwiseNotBool(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryBitwiseNotByteTest(bool useInterpreter) { byte[] values = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyBitwiseNotByte(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryBitwiseNotIntTest(bool useInterpreter) { int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyBitwiseNotInt(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryBitwiseNotLongTest(bool useInterpreter) { long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyBitwiseNotLong(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryBitwiseNotSByteTest(bool useInterpreter) { sbyte[] values = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyBitwiseNotSByte(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryBitwiseNotShortTest(bool useInterpreter) { short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyBitwiseNotShort(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryBitwiseNotUIntTest(bool useInterpreter) { uint[] values = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyBitwiseNotUInt(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryBitwiseNotULongTest(bool useInterpreter) { ulong[] values = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyBitwiseNotULong(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryBitwiseNotUShortTest(bool useInterpreter) { ushort[] values = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyBitwiseNotUShort(values[i], useInterpreter); } } [Fact] public static void ToStringTest() { var e = Expression.Not(Expression.Parameter(typeof(bool), "x")); Assert.Equal("Not(x)", e.ToString()); } #endregion #region Test verifiers private static void VerifyBitwiseNotBool(bool value, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Not(Expression.Constant(value, typeof(bool))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(useInterpreter); Assert.Equal((bool)(!value), f()); } private static void VerifyBitwiseNotByte(byte value, bool useInterpreter) { Expression<Func<byte>> e = Expression.Lambda<Func<byte>>( Expression.Not(Expression.Constant(value, typeof(byte))), Enumerable.Empty<ParameterExpression>()); Func<byte> f = e.Compile(useInterpreter); Assert.Equal((byte)(~value), f()); } private static void VerifyBitwiseNotInt(int value, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Not(Expression.Constant(value, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal((int)(~value), f()); } private static void VerifyBitwiseNotLong(long value, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.Not(Expression.Constant(value, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal((long)(~value), f()); } private static void VerifyBitwiseNotSByte(sbyte value, bool useInterpreter) { Expression<Func<sbyte>> e = Expression.Lambda<Func<sbyte>>( Expression.Not(Expression.Constant(value, typeof(sbyte))), Enumerable.Empty<ParameterExpression>()); Func<sbyte> f = e.Compile(useInterpreter); Assert.Equal((sbyte)(~value), f()); } private static void VerifyBitwiseNotShort(short value, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.Not(Expression.Constant(value, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal((short)(~value), f()); } private static void VerifyBitwiseNotUInt(uint value, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.Not(Expression.Constant(value, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal((uint)(~value), f()); } private static void VerifyBitwiseNotULong(ulong value, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.Not(Expression.Constant(value, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal((ulong)(~value), f()); } private static void VerifyBitwiseNotUShort(ushort value, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.Not(Expression.Constant(value, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal((ushort)(~value), f()); } #endregion } }
// 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.Linq; using System.Threading.Tasks; using Xunit; namespace Moq.Tests { public class EmptyDefaultValueProviderFixture { [Fact] public void ProvidesNullString() { var value = GetDefaultValueForProperty(nameof(IFoo.StringValue)); Assert.Null(value); } [Fact] public void ProvidesDefaultInt() { var value = GetDefaultValueForProperty(nameof(IFoo.IntValue)); Assert.Equal(default(int), value); } [Fact] public void ProvidesNullInt() { var value = GetDefaultValueForProperty(nameof(IFoo.NullableIntValue)); Assert.Null(value); } [Fact] public void ProvidesDefaultBool() { var value = GetDefaultValueForProperty(nameof(IFoo.BoolValue)); Assert.Equal(default(bool), value); } [Fact] public void ProvidesDefaultEnum() { var value = GetDefaultValueForProperty(nameof(IFoo.UriKind)); Assert.Equal(default(UriKind), value); } [Fact] public void ProvidesEmptyEnumerable() { var value = GetDefaultValueForProperty(nameof(IFoo.Indexes)); Assert.True(value is IEnumerable<int> && ((IEnumerable<int>)value).Count() == 0); } [Fact] public void ProvidesEmptyArray() { var value = GetDefaultValueForProperty(nameof(IFoo.Bars)); Assert.True(value is IBar[] && ((IBar[])value).Length == 0); } [Fact] public void ProvidesNullReferenceTypes() { var value1 = GetDefaultValueForProperty(nameof(IFoo.Bar)); var value2 = GetDefaultValueForProperty(nameof(IFoo.Object)); Assert.Null(value1); Assert.Null(value2); } [Fact] public void ProvideEmptyQueryable() { var value = GetDefaultValueForProperty(nameof(IFoo.Queryable)); Assert.IsAssignableFrom<IQueryable<int>>(value); Assert.Equal(0, ((IQueryable<int>)value).Count()); } [Fact] public void ProvideEmptyQueryableObjects() { var value = GetDefaultValueForProperty(nameof(IFoo.QueryableObjects)); Assert.IsAssignableFrom<IQueryable>(value); Assert.Equal(0, ((IQueryable)value).Cast<object>().Count()); } [Fact] public void ProvidesDefaultTask() { var value = GetDefaultValueForProperty(nameof(IFoo.TaskValue)); Assert.NotNull(value); Assert.True(((Task)value).IsCompleted); } [Fact] public void ProvidesDefaultGenericTaskOfValueType() { var value = GetDefaultValueForProperty(nameof(IFoo.GenericTaskOfValueType)); Assert.NotNull(value); Assert.True(((Task)value).IsCompleted); Assert.Equal(default(int), ((Task<int>)value).Result); } [Fact] public void ProvidesDefaultGenericTaskOfReferenceType() { var value = GetDefaultValueForProperty(nameof(IFoo.GenericTaskOfReferenceType)); Assert.NotNull(value); Assert.True(((Task)value).IsCompleted); Assert.Equal(default(string), ((Task<string>)value).Result); } [Fact] public void ProvidesDefaultTaskOfGenericTask() { var value = GetDefaultValueForProperty(nameof(IFoo.TaskOfGenericTaskOfValueType)); Assert.NotNull(value); Assert.True(((Task)value).IsCompleted); Assert.Equal(default(int), ((Task<Task<int>>) value).Result.Result); } [Fact] public void ProvidesDefaultValueTaskOfValueType() { var value = GetDefaultValueForProperty(nameof(IFoo.ValueTaskOfValueType)); var result = (ValueTask<int>)value; Assert.True(result.IsCompleted); Assert.Equal(default(int), result.Result); } [Fact] public void ProvidesDefaultValueTaskOfValueTypeArray() { var value = GetDefaultValueForProperty(nameof(IFoo.ValueTaskOfValueTypeArray)); var result = (ValueTask<int[]>)value; Assert.True(result.IsCompleted); Assert.NotNull(result.Result); Assert.Empty(result.Result); } [Fact] public void ProvidesDefaultValueTaskOfReferenceType() { var value = GetDefaultValueForProperty(nameof(IFoo.ValueTaskOfReferenceType)); var result = (ValueTask<string>)value; Assert.True(result.IsCompleted); Assert.Equal(default(string), result.Result); } [Fact] public void ProvidesDefaultValueTaskOfTaskOfValueType() { var value = GetDefaultValueForProperty(nameof(IFoo.ValueTaskOfTaskOfValueType)); var result = (ValueTask<Task<int>>)value; Assert.True(result.IsCompleted); Assert.NotNull(result.Result); Assert.True(result.Result.IsCompleted); Assert.Equal(default(int), result.Result.Result); } [Fact] public void ProvidesDefaultValueTupleOfReferenceTypeArrayAndTaskOfReferenceType() { var value = GetDefaultValueForProperty(nameof(IFoo.ValueTupleOfReferenceTypeArrayAndTaskOfReferenceType)); var (bars, barTask) = ((IBar[], Task<IBar>))value; Assert.NotNull(bars); Assert.Empty(bars); Assert.NotNull(barTask); Assert.True(barTask.IsCompleted); Assert.Equal(default(IBar), barTask.Result); } private static object GetDefaultValueForProperty(string propertyName) { var propertyGetter = typeof(IFoo).GetProperty(propertyName).GetGetMethod(); return DefaultValueProvider.Empty.GetDefaultReturnValue(propertyGetter, new Mock<IFoo>()); } public interface IFoo { object Object { get; set; } IBar Bar { get; set; } string StringValue { get; set; } int IntValue { get; set; } bool BoolValue { get; set; } int? NullableIntValue { get; set; } UriKind UriKind { get; set; } IEnumerable<int> Indexes { get; set; } IBar[] Bars { get; set; } IQueryable<int> Queryable { get; } IQueryable QueryableObjects { get; } Task TaskValue { get; set; } Task<int> GenericTaskOfValueType { get; set; } Task<string> GenericTaskOfReferenceType { get; set; } Task<Task<int>> TaskOfGenericTaskOfValueType { get; set; } ValueTask<int> ValueTaskOfValueType { get; set; } ValueTask<int[]> ValueTaskOfValueTypeArray { get; set; } ValueTask<string> ValueTaskOfReferenceType { get; set; } ValueTask<Task<int>> ValueTaskOfTaskOfValueType { get; set; } (IBar[], Task<IBar>) ValueTupleOfReferenceTypeArrayAndTaskOfReferenceType { get; } } public interface IBar { } } }
namespace Microsoft.Protocols.TestSuites.MS_OUTSPS { using System; using System.Collections.Generic; using System.Net; using System.Web.Services.Protocols; using System.Xml; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// A test class contains test cases of S01 scenario. /// </summary> [TestClass] public class S01_OperateAttachment : TestSuiteBase { #region Additional test attributes, Initialization and clean up /// <summary> /// Class initialization /// </summary> /// <param name="testContext">The context of the test suite.</param> [ClassInitialize] public static new void ClassInitialize(TestContext testContext) { TestSuiteBase.ClassInitialize(testContext); } /// <summary> /// Class clean up /// </summary> [ClassCleanup] public static new void ClassCleanup() { TestSuiteBase.ClassCleanup(); } #endregion #region Test cases #region MSOUTSPS_S01_TC01_OperateAttachment_AppointmentTemplateType /// <summary> /// This test case is used to verify AddAttachment operation, DeleteAttachment operation, GetAttachment operation, /// and GetAttachmentCollection operation with Appointment template type. /// </summary> [TestCategory("MSOUTSPS"), TestMethod()] public void MSOUTSPS_S01_TC01_OperateAttachment_AppointmentTemplateType() { #region Add a list item // Add one list into SUT. string listId = this.AddListToSUT(TemplateType.Events); // Add one list item List<string> addedListitems = this.AddItemsToList(listId, 1); string addedListitemId = addedListitems[0]; byte[] attachmentContent = this.GenerateUniqueAttachmentContents(5); string attachmentName = this.GetUniqueAttachmentName(); #endregion #region AddAttachment operation // Call AddAttachment operation. string fileUrl = OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentName, attachmentContent); #endregion #region HTTPGET operation // Get full URL of an attachment string fullUrlOfAttachment = this.GetAttachmentFullUrl(listId, addedListitemId, attachmentName); Uri fullUrlOfAttachmentPath; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } // Call HTTPGET operation. byte[] getContentsOfAttachment = OutspsAdapter.HTTPGET(fullUrlOfAttachmentPath, "f"); #endregion #region Capture R1062, R1070, R1073, R1075 // If the length of attachment content in protocol SUT equal to added by AddAttachment operation, then capture R1062, R1070, R1073 Site.CaptureRequirementIfAreEqual( attachmentContent.Length, getContentsOfAttachment.Length, 1062, "[In Message Processing Events and Sequencing Rules][The operation]AddAttachment Adds an attachment to an item."); // Verify MS-OUTSPS requirement: MS-OUTSPS_R1070 Site.CaptureRequirementIfAreEqual( attachmentContent.Length, getContentsOfAttachment.Length, 1070, "[In AddAttachment]AddAttachment is used by protocol clients to create a new attachment on an item on the protocol server."); // Verify MS-OUTSPS requirement: MS-OUTSPS_R10730 Site.CaptureRequirementIfAreEqual( attachmentContent.Length, getContentsOfAttachment.Length, 10730, "[In Messages]AddAttachmentResponse specified the response to a request to create a new attachment on an item on the protocol server."); // If the AddAttachment operation return valid attachment url, then Capture R1075 Site.CaptureRequirementIfIsNotNull( fileUrl, 1075, "[In AddAttachmentResponse]If an AddAttachmentResponse is received, then the upload was successful."); #endregion #region GetAttachmentCollection operation byte[] attachmentContentSecond = this.GenerateUniqueAttachmentContents(5); string attachmentNameSecond = this.GetUniqueAttachmentName(); // Call the AddAttachment operation. OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentNameSecond, attachmentContentSecond); // Call GetAttachmentCollection operation. GetAttachmentCollectionResponseGetAttachmentCollectionResult getAttachementCollectionResult = OutspsAdapter.GetAttachmentCollection(listId, addedListitemId); #endregion #region Capture R1065, R11000 // If add new attachment successfully, total attachment number is 2, Capture R1065, R11000 bool isContainExpectedAttachment = this.VerifyWhetherContainExpectedNumberAttachment(getAttachementCollectionResult, 2); this.Site.CaptureRequirementIfIsTrue( isContainExpectedAttachment, 1065, "[In Message Processing Events and Sequencing Rules][The operation]GetAttachmentCollection Gets a list of the attachments on an item."); this.Site.CaptureRequirementIfIsTrue( isContainExpectedAttachment, 11000, "[In Messages]GetAttachmentCollectionResponse specified the response to a request to get the list of all attachments on a single item in one list."); #endregion if (Common.IsRequirementEnabled(106802, this.Site)) { #region GetListItemChangesSinceToken operation // Set CamlQueryOptions and view fields make the "attachment" field present in response. CamlQueryOptions camloptions = new CamlQueryOptions(); camloptions.QueryOptions = new CamlQueryOptionsQueryOptions(); camloptions.QueryOptions.IncludeAttachmentUrls = bool.TrueString; camloptions.QueryOptions.IncludeAttachmentVersion = bool.TrueString; CamlViewFields viewfieds = this.GenerateViewFields(false, new List<string> { "Attachments" }); // Call GetListItemChangesSinceToken operation. GetListItemChangesSinceTokenResponseGetListItemChangesSinceTokenResult getListItemChangesRes = null; getListItemChangesRes = OutspsAdapter.GetListItemChangesSinceToken( listId, null, null, viewfieds, null, camloptions, null, null); this.Site.Assert.IsNotNull(getListItemChangesRes, "SUT should return a response contain data."); string headerValue = this.GetIfMatchHeaderValueFromResponse(getListItemChangesRes, fullUrlOfAttachment, int.Parse(addedListitemId)); #endregion #region Capture R1241 // If the header is returned, then R1241 should be covered. this.Site.CaptureRequirementIfIsNotNull( headerValue, 1241, "[In HTTP PUT]The Attachments property MUST contain a file version if protocol clients have included the IncludeAttachmentUrls and IncludeAttachmentVersion elements specified in [MS-LISTSWS]."); #endregion #region HTTPPUT operation // Call HTTPPUT operation to update the attachment contents for the first attachment. fullUrlOfAttachmentPath = null; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } byte[] newattachmentContents = this.GenerateUniqueAttachmentContents(6); OutspsAdapter.HTTPPUT(fullUrlOfAttachmentPath, headerValue, newattachmentContents); // Verify the updated attachment contents' length this.VerifyAttachmentContentsLength(fullUrlOfAttachment, newattachmentContents.Length); #endregion #region HTTPPUT operation with the header data does not match the current version getListItemChangesRes = OutspsAdapter.GetListItemChangesSinceToken( listId, null, null, viewfieds, null, camloptions, null, null); this.Site.Assert.IsNotNull(getListItemChangesRes, "SUT should return a response contain data."); string headerValue2 = this.GetIfMatchHeaderValueFromResponse(getListItemChangesRes, fullUrlOfAttachment, int.Parse(addedListitemId)); int index = Int32.Parse(headerValue2.Replace("\"", string.Empty).Split(',')[1]); string invalidHeaderValue = headerValue2.Split(',')[0] + "," + (index + 1) + "\""; try { OutspsAdapter.HTTPPUT(fullUrlOfAttachmentPath, invalidHeaderValue, newattachmentContents); } catch (WebException exception) { HttpWebResponse webResponse = exception.Response as HttpWebResponse; // Verify MS-OUTSPS requirement: MS-OUTSPS_R1243 this.Site.CaptureRequirementIfAreEqual<int>( 412, (int)webResponse.StatusCode, 1243, "[In HTTP PUT]Protocol servers MUST respond with an HTTP status code 412 (which indicates a precondition failed) if the header data does not match the current version."); } #endregion } OutspsAdapter.DeleteAttachment(listId, addedListitemId, fullUrlOfAttachment); #region Capture R10930 // If the operation does not return SoapException, capture R10930 directly. Because the schema of the DeleteAttachmentResponse define in [MS-LISTSWS]: <s:element name="DeleteAttachmentResponse"><s:complexType/></s:element>, does not contain any complex type definition, so the proxy class marked this operation as void type return. this.Site.CaptureRequirement( 10930, "[In Messages]DeleteAttachmentResponse specified the response to a request to delete attachments from an item on the protocol server."); #endregion // Verify whether the attachment was deleted. bool isDeleteSucceed = this.VerifyDeleteAttachmentSucceed(fullUrlOfAttachment); #region Capture R1064, R1091 // Because the specified attachment was deleted, the HTTPGET operation could not find it, so there will have a soap exception. this.Site.CaptureRequirementIfIsTrue( isDeleteSucceed, 1064, @"[In Message Processing Events and Sequencing Rules][The operation]DeleteAttachment Deletes an attachment from an item on a list."); this.Site.CaptureRequirementIfIsTrue( isDeleteSucceed, 1091, @"[In DeleteAttachment]Protocol clients use DeleteAttachment to delete attachments from an item on the protocol server."); #endregion } #endregion #region MSOUTSPS_S01_TC02_OperateAttachment_ContactsTemplateType /// <summary> /// This test case is used to verify AddAttachment operation, DeleteAttachment operation, GetAttachment operation, /// and GetAttachmentCollection operation with Contacts template type. /// </summary> [TestCategory("MSOUTSPS"), TestMethod()] public void MSOUTSPS_S01_TC02_OperateAttachment_ContactsTemplateType() { #region Add a list item // Add one list into SUT. string listId = this.AddListToSUT(TemplateType.Contacts); // Add one list item List<string> addedListitems = this.AddItemsToList(listId, 1); string addedListitemId = addedListitems[0]; byte[] attachmentContent = this.GenerateUniqueAttachmentContents(5); string attachmentName = this.GetUniqueAttachmentName(); #endregion #region AddAttachment operation // Call AddAttachment operation. OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentName, attachmentContent); #endregion #region HTTPGET operation // Get full URL of an attachment string fullUrlOfAttachment = this.GetAttachmentFullUrl(listId, addedListitemId, attachmentName); Uri fullUrlOfAttachmentPath; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } // Call HTTPGET operation. byte[] getContentsOfAttachment = OutspsAdapter.HTTPGET(fullUrlOfAttachmentPath, "f"); this.Site.Assert.AreEqual<int>( attachmentContent.Length, getContentsOfAttachment.Length, "The attachment content's length should equal to added by AddAttachment operation."); #endregion #region GetAttachmentCollection operation byte[] attachmentContentSecond = this.GenerateUniqueAttachmentContents(5); string attachmentNameSecond = this.GetUniqueAttachmentName(); // Call the AddAttachment operation. OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentNameSecond, attachmentContentSecond); // Call GetAttachmentCollection operation. GetAttachmentCollectionResponseGetAttachmentCollectionResult getAttachementCollectionResult = OutspsAdapter.GetAttachmentCollection(listId, addedListitemId); // If add new attachment successfully, total attachment number is 2 this.VerifyWhetherContainExpectedNumberAttachment(getAttachementCollectionResult, 2); #endregion if (Common.IsRequirementEnabled(106802, this.Site)) { #region GetListItemChangesSinceToken operation // Set CamlQueryOptions and view fields make the "attachment" field present in response. CamlQueryOptions camloptions = new CamlQueryOptions(); camloptions.QueryOptions = new CamlQueryOptionsQueryOptions(); camloptions.QueryOptions.IncludeAttachmentUrls = bool.TrueString; camloptions.QueryOptions.IncludeAttachmentVersion = bool.TrueString; CamlViewFields viewfieds = this.GenerateViewFields(false, new List<string> { "Attachments" }); // Call GetListItemChangesSinceToken operation. GetListItemChangesSinceTokenResponseGetListItemChangesSinceTokenResult getlistItemChangesRes = null; getlistItemChangesRes = OutspsAdapter.GetListItemChangesSinceToken( listId, null, null, viewfieds, null, camloptions, null, null); this.Site.Assert.IsNotNull(getlistItemChangesRes, "SUT should return a response contain data."); string headerValue = this.GetIfMatchHeaderValueFromResponse(getlistItemChangesRes, fullUrlOfAttachment, int.Parse(addedListitemId)); #endregion #region HTTPPUT operation // Call HTTPPUT operation. fullUrlOfAttachmentPath = null; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } byte[] newattachmentContents = this.GenerateUniqueAttachmentContents(6); OutspsAdapter.HTTPPUT(fullUrlOfAttachmentPath, headerValue, newattachmentContents); // Verify updated attachment. this.VerifyAttachmentContentsLength(fullUrlOfAttachment, newattachmentContents.Length); #endregion } OutspsAdapter.DeleteAttachment(listId, addedListitemId, fullUrlOfAttachment); // Verify whether delete attachment succeed. this.VerifyDeleteAttachmentSucceed(fullUrlOfAttachment); } #endregion #region MSOUTSPS_S01_TC03_OperateAttachment_DiscussionBoardTemplateType /// <summary> /// This test case is used to verify AddAttachment operation, DeleteAttachment operation, GetAttachment operation, /// and GetAttachmentCollection operation with Discussion_Board template type. /// </summary> [TestCategory("MSOUTSPS"), TestMethod()] public void MSOUTSPS_S01_TC03_OperateAttachment_DiscussionBoardTemplateType() { #region Add a list item // Add one list into SUT. string listId = this.AddListToSUT(TemplateType.Discussion_Board); // Add one list item List<string> addedListitems = this.AddItemsToList(listId, 1); string addedListitemId = addedListitems[0]; byte[] attachmentContent = this.GenerateUniqueAttachmentContents(5); string attachmentName = this.GetUniqueAttachmentName(); #endregion #region AddAttachment operation // Call AddAttachment operation. OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentName, attachmentContent); #endregion #region HTTPGET operation // Get full URL of an attachment string fullUrlOfAttachment = this.GetAttachmentFullUrl(listId, addedListitemId, attachmentName); Uri fullUrlOfAttachmentPath; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } // Call HTTPGET operation. byte[] getContentsOfAttachment = OutspsAdapter.HTTPGET(fullUrlOfAttachmentPath, "f"); this.Site.Assert.AreEqual<int>( attachmentContent.Length, getContentsOfAttachment.Length, "The attachment content's length should equal to added by AddAttachment operation."); #endregion #region GetAttachmentCollection operation byte[] attachmentContentSecond = this.GenerateUniqueAttachmentContents(5); string attachmentNameSecond = this.GetUniqueAttachmentName(); // Call the AddAttachment operation. OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentNameSecond, attachmentContentSecond); // Call GetAttachmentCollection operation. GetAttachmentCollectionResponseGetAttachmentCollectionResult getAttachementCollectionResult = OutspsAdapter.GetAttachmentCollection(listId, addedListitemId); // If the new attachment was added successfully,, total attachment number is 2 this.VerifyWhetherContainExpectedNumberAttachment(getAttachementCollectionResult, 2); #endregion if (Common.IsRequirementEnabled(106802, this.Site)) { #region GetListItemChangesSinceToken operation // Set CamlQueryOptions and view fields make the "attachment" field present in response. CamlQueryOptions camloptions = new CamlQueryOptions(); camloptions.QueryOptions = new CamlQueryOptionsQueryOptions(); camloptions.QueryOptions.IncludeAttachmentUrls = bool.TrueString; camloptions.QueryOptions.IncludeAttachmentVersion = bool.TrueString; CamlViewFields viewfieds = this.GenerateViewFields(false, new List<string> { "Attachments" }); // Call GetListItemChangesSinceToken operation. GetListItemChangesSinceTokenResponseGetListItemChangesSinceTokenResult getlistItemChangesRes = null; getlistItemChangesRes = OutspsAdapter.GetListItemChangesSinceToken( listId, null, null, viewfieds, null, camloptions, null, null); this.Site.Assert.IsNotNull(getlistItemChangesRes, "SUT should return a response contain data."); string headerValue = this.GetIfMatchHeaderValueFromResponse(getlistItemChangesRes, fullUrlOfAttachment, int.Parse(addedListitemId)); #endregion #region HTTPPUT operation // Call HTTPPUT operation. fullUrlOfAttachmentPath = null; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } byte[] newattachmentContents = this.GenerateUniqueAttachmentContents(6); OutspsAdapter.HTTPPUT(fullUrlOfAttachmentPath, headerValue, newattachmentContents); // Verify updated attachment. this.VerifyAttachmentContentsLength(fullUrlOfAttachment, newattachmentContents.Length); #endregion } OutspsAdapter.DeleteAttachment(listId, addedListitemId, fullUrlOfAttachment); // Verify whether delete attachment succeed. this.VerifyDeleteAttachmentSucceed(fullUrlOfAttachment); } #endregion #region MSOUTSPS_S01_TC04_OperateAttachment_TasksTemplateType /// <summary> /// This test case is used to verify AddAttachment operation, DeleteAttachment operation, GetAttachment operation, /// and GetAttachmentCollection operation with Tasks template type. /// </summary> [TestCategory("MSOUTSPS"), TestMethod()] public void MSOUTSPS_S01_TC04_OperateAttachment_TasksTemplateType() { #region Add a list item // Add one list into SUT. string listId = this.AddListToSUT(TemplateType.Tasks); // Add one list item List<string> addedListitems = this.AddItemsToList(listId, 1); string addedListitemId = addedListitems[0]; byte[] attachmentContent = this.GenerateUniqueAttachmentContents(5); string attachmentName = this.GetUniqueAttachmentName(); #endregion #region AddAttachment operation // Call AddAttachment operation. OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentName, attachmentContent); #endregion #region HTTPGET operation // Get full URL of an attachment string fullUrlOfAttachment = this.GetAttachmentFullUrl(listId, addedListitemId, attachmentName); // Call HTTPGET operation. Uri fullUrlOfAttachmentPath; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } byte[] getContentsOfAttachment = OutspsAdapter.HTTPGET(fullUrlOfAttachmentPath, "f"); this.Site.Assert.AreEqual<int>( attachmentContent.Length, getContentsOfAttachment.Length, "The attachment content's length should equal to added by AddAttachment operation."); #endregion #region GetAttachmentCollection operation byte[] attachmentContentSecond = this.GenerateUniqueAttachmentContents(5); string attachmentNameSecond = this.GetUniqueAttachmentName(); // Call the AddAttachment operation. OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentNameSecond, attachmentContentSecond); // Call GetAttachmentCollection operation. GetAttachmentCollectionResponseGetAttachmentCollectionResult getAttachementCollectionResult = OutspsAdapter.GetAttachmentCollection(listId, addedListitemId); // If add new attachment successfully, total attachment number is 2 this.VerifyWhetherContainExpectedNumberAttachment(getAttachementCollectionResult, 2); #endregion if (Common.IsRequirementEnabled(106802, this.Site)) { #region GetListItemChangesSinceToken operation // Set CamlQueryOptions and view fields make the "attachment" field present in response. CamlQueryOptions camloptions = new CamlQueryOptions(); camloptions.QueryOptions = new CamlQueryOptionsQueryOptions(); camloptions.QueryOptions.IncludeAttachmentUrls = bool.TrueString; camloptions.QueryOptions.IncludeAttachmentVersion = bool.TrueString; CamlViewFields viewfieds = this.GenerateViewFields(false, new List<string> { "Attachments" }); // Call GetListItemChangesSinceToken operation. GetListItemChangesSinceTokenResponseGetListItemChangesSinceTokenResult getlistItemChangesRes = null; getlistItemChangesRes = OutspsAdapter.GetListItemChangesSinceToken( listId, null, null, viewfieds, null, camloptions, null, null); this.Site.Assert.IsNotNull(getlistItemChangesRes, "SUT should return a response contain data."); string headerValue = this.GetIfMatchHeaderValueFromResponse(getlistItemChangesRes, fullUrlOfAttachment, int.Parse(addedListitemId)); #endregion #region HTTPPUT operation // Call HTTPPUT operation. fullUrlOfAttachmentPath = null; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } byte[] newattachmentContents = this.GenerateUniqueAttachmentContents(6); OutspsAdapter.HTTPPUT(fullUrlOfAttachmentPath, headerValue, newattachmentContents); // Verify updated attachment. this.VerifyAttachmentContentsLength(fullUrlOfAttachment, newattachmentContents.Length); #endregion } OutspsAdapter.DeleteAttachment(listId, addedListitemId, fullUrlOfAttachment); // Verify whether delete attachment succeed. this.VerifyDeleteAttachmentSucceed(fullUrlOfAttachment); } #endregion #region MSOUTSPS_S01_TC05_AddAttachment_Fail /// <summary> /// This test case is used to verify AddAttachment operation, create a new attachment failed. /// </summary> [TestCategory("MSOUTSPS"), TestMethod()] public void MSOUTSPS_S01_TC05_AddAttachment_Fail() { // Add one list into SUT. string listId = this.AddListToSUT(TemplateType.Events); // Add one list item List<string> addedListitems = this.AddItemsToList(listId, 1); string addedListitemId = addedListitems[0]; byte[] attachmentContent = this.GenerateUniqueAttachmentContents(5); string attachmentName = this.GetUniqueAttachmentName(); string errorCode = null; // Call AddAttachment operation. OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentName, attachmentContent); try { OutspsAdapter.AddAttachment( listId, addedListitemId, attachmentName, attachmentContent); } catch (SoapException soapException) { errorCode = Common.ExtractErrorCodeFromSoapFault(soapException); } // Verify MS-OUTSPS requirement: MS-OUTSPS_R1076 Site.CaptureRequirementIfAreEqual( "0x81020067", errorCode, 1076, "[In AddAttachmentResponse][If a SOAP exception is received instead of an AddAttachmentResponse, the protocol client SHOULD behave as follows:]If the exception errorcode (see [MS-LISTSWS] section 3.1.4.1) is 0x81020067, this indicates that the item already has an attachment with the same file name."); } #endregion #endregion Test cases #region Private method /// <summary> /// A method used to get IF-MATCH header value by specified attachment url. /// </summary> /// <param name="getListItemChangesRes">A parameter represents a response of "GetListItemChangesSinceToken" operation where method will find the expected IF-MATCH header value.</param> /// <param name="attachmentFullUrl">A parameter represents the full url of attachment which is used to match attachment field value.</param> /// <param name="listItemId">A parameter represents the list item id of a list item where the attachment is added.</param> /// <returns>A return value represents the expected IF-MATCH header value.</returns> private string GetIfMatchHeaderValueFromResponse(GetListItemChangesSinceTokenResponseGetListItemChangesSinceTokenResult getListItemChangesRes, string attachmentFullUrl, int listItemId) { if (null == getListItemChangesRes || null == getListItemChangesRes.listitems || null == getListItemChangesRes.listitems.data || null == getListItemChangesRes.listitems.data.Any) { throw new ArgumentException("Should contain valid item changed data.", "getListItemChangesRes"); } if (listItemId <= 0) { throw new ArgumentException("The value should be large than Zero.", "listItemId"); } if (string.IsNullOrEmpty(attachmentFullUrl)) { throw new ArgumentException("The value should have non-empty string value", "attachmentFullUrl"); } if (0 == getListItemChangesRes.listitems.data.Any.Length) { throw new InvalidOperationException("Could not get the attachment changed record."); } // Get attachment field value. XmlNode[] changesRecords = this.GetZrowItems(getListItemChangesRes.listitems.data.Any); string attachmentFieldValue = Common.GetZrowAttributeValue(changesRecords, listItemId - 1, "ows_attachments"); if (!attachmentFieldValue.StartsWith(@";#", StringComparison.OrdinalIgnoreCase)) { this.Site.Assert.Fail("the attachment field value must begin with [;#]."); } if (!attachmentFieldValue.EndsWith(@";#", StringComparison.OrdinalIgnoreCase)) { this.Site.Assert.Fail("the attachment field value must end with [;#]."); } string[] splitValues = attachmentFieldValue.Split(new string[] { @";#" }, StringSplitOptions.RemoveEmptyEntries); // The parse logic is described in MS-LISTSWS section 2.2.4.4 string expectedHeaderValue = string.Empty; for (int index = 0; index < splitValues.Length; index++) { if (splitValues[index].Equals(attachmentFullUrl, StringComparison.OrdinalIgnoreCase) && index + 1 < splitValues.Length) { expectedHeaderValue = splitValues[index + 1]; break; } } if (string.IsNullOrEmpty(expectedHeaderValue)) { string errorMsg = string.Format("Could not find expected [IF-Match] header value by specified attachment url[{0}]", attachmentFullUrl); this.Site.Assert.Fail(errorMsg); } expectedHeaderValue = string.Format(@"""{0}""", expectedHeaderValue); return expectedHeaderValue; } /// <summary> /// A method used to verify the response of GetAttachmentCollection whether contain expected Number Attachment items. If it does not pass the verification, this method will throw a Assert exception. /// </summary> /// <param name="getAttachementCollectionResult">A parameter represents the response of GetAttachmentCollection operation.</param> /// <param name="expectedAttachmentsNumber">A parameter represents the expected attachment items' number which is used to check the response of GetAttachmentCollection operation.</param> /// <returns>Return true indicating the response of GetAttachmentCollection contains expected number of attachment items</returns> private bool VerifyWhetherContainExpectedNumberAttachment(GetAttachmentCollectionResponseGetAttachmentCollectionResult getAttachementCollectionResult, int expectedAttachmentsNumber) { this.Site.Assert.IsNotNull(getAttachementCollectionResult, "The GetAttachmentCollection operation should return valid response."); this.Site.Assert.IsNotNull(getAttachementCollectionResult.Attachments, "The response of GetAttachmentCollection operation should contain valid attachments data."); // Verify the number of attachment collection's items whether equal to expected value. this.Site.Assert.AreEqual<int>( expectedAttachmentsNumber, getAttachementCollectionResult.Attachments.Length, "The response of GetAttachmentCollection operation should contain [{0}] expected attachments data, actual:[{1}]", expectedAttachmentsNumber, getAttachementCollectionResult.Attachments.Length); return true; } /// <summary> /// A method used to verify attachment contents' length which is got from protocol SUT whether equal to specified value. If it does not pass the verification, this method will throw a Assert exception. /// </summary> /// <param name="fullUrlOfAttachment">A parameter represents the full url of attachment which is used by HTTPGET operation to get the actual attachment content.</param> /// <param name="expectedContentsLength">A parameter represents the expected content length.</param> /// <returns>Return true indicating the attachment content length equal to the expected value.</returns> private bool VerifyAttachmentContentsLength(string fullUrlOfAttachment, int expectedContentsLength) { if (string.IsNullOrEmpty(fullUrlOfAttachment)) { throw new ArgumentNullException("fullUrlOfAttachment"); } Uri fullUrlOfAttachmentPath; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } byte[] getContentsOfAttachment = OutspsAdapter.HTTPGET(fullUrlOfAttachmentPath, "f"); this.Site.Assert.AreEqual<int>( expectedContentsLength, getContentsOfAttachment.Length, "The attachment contents' length should equal to expected value[{0}]", expectedContentsLength); return true; } /// <summary> /// A method used to verify whether the attachment have been deleted or not. /// </summary> /// <param name="fullUrlOfAttachment">A parameter represents the full url of attachment which is used by HTTPGET operation to get the actual attachment content.</param> /// <returns>Return true indicating delete attachment succeed.</returns> private bool VerifyDeleteAttachmentSucceed(string fullUrlOfAttachment) { if (string.IsNullOrEmpty(fullUrlOfAttachment)) { throw new ArgumentNullException("fullUrlOfAttachment"); } HttpStatusCode lowLevelStatusCode = HttpStatusCode.OK; Uri fullUrlOfAttachmentPath; if (!Uri.TryCreate(fullUrlOfAttachment, UriKind.RelativeOrAbsolute, out fullUrlOfAttachmentPath)) { this.Site.Assert.Fail("The full url of attachment should be valid Uri format string."); } try { OutspsAdapter.HTTPGET(fullUrlOfAttachmentPath, "f"); } catch (WebException webException) { lowLevelStatusCode = this.GetStatusCodeFromWebException(webException); Site.Log.Add(LogEntryKind.Debug, "The attachment has not been found" + webException.Message.ToString()); } this.Site.Assert.AreEqual<HttpStatusCode>( HttpStatusCode.NotFound, lowLevelStatusCode, @"The protocol SUT should return ""404"" status code which means ""NotFound"", if the attachment[{0}] have been deleted.", fullUrlOfAttachment); return true; } #endregion Private method } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WK.Orion.Applications.ADM.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * 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 log4net; using OpenMetaverse; using OpenSim.Framework; using System.Reflection; using System.Text; namespace OpenSim.Region.CoreModules.World.Estate { /// <summary> /// Estate management console commands. /// </summary> public class EstateManagementCommands { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected EstateManagementModule m_module; public EstateManagementCommands(EstateManagementModule module) { m_module = module; } public void Initialise() { // m_log.DebugFormat("[ESTATE MODULE]: Setting up estate commands for region {0}", m_module.Scene.RegionInfo.RegionName); m_module.Scene.AddCommand("Regions", m_module, "set terrain texture", "set terrain texture <number> <uuid> [<x>] [<y>]", "Sets the terrain <number> to <uuid>, if <x> or <y> are specified, it will only " + "set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" + " that coordinate.", consoleSetTerrainTexture); m_module.Scene.AddCommand("Regions", m_module, "set terrain heights", "set terrain heights <corner> <min> <max> [<x>] [<y>]", "Sets the terrain texture heights on corner #<corner> to <min>/<max>, if <x> or <y> are specified, it will only " + "set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" + " that coordinate. Corner # SW = 0, NW = 1, SE = 2, NE = 3, all corners = -1.", consoleSetTerrainHeights); m_module.Scene.AddCommand("Regions", m_module, "set water height", "set water height <height> [<x>] [<y>]", "Sets the water height in meters. If <x> and <y> are specified, it will only set it on regions with a matching coordinate. " + "Specify -1 in <x> or <y> to wildcard that coordinate.", consoleSetWaterHeight); m_module.Scene.AddCommand( "Estates", m_module, "estate show", "estate show", "Shows all estates on the simulator.", ShowEstatesCommand); } public void Close() {} #region CommandHandlers protected void consoleSetTerrainTexture(string module, string[] args) { string num = args[3]; string uuid = args[4]; int x = (args.Length > 5 ? int.Parse(args[5]) : -1); int y = (args.Length > 6 ? int.Parse(args[6]) : -1); if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x) { if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y) { int corner = int.Parse(num); UUID texture = UUID.Parse(uuid); m_log.Debug("[ESTATEMODULE]: Setting terrain textures for " + m_module.Scene.RegionInfo.RegionName + string.Format(" (C#{0} = {1})", corner, texture)); switch (corner) { case 0: m_module.Scene.RegionInfo.RegionSettings.TerrainTexture1 = texture; break; case 1: m_module.Scene.RegionInfo.RegionSettings.TerrainTexture2 = texture; break; case 2: m_module.Scene.RegionInfo.RegionSettings.TerrainTexture3 = texture; break; case 3: m_module.Scene.RegionInfo.RegionSettings.TerrainTexture4 = texture; break; } m_module.Scene.RegionInfo.RegionSettings.Save(); m_module.TriggerRegionInfoChange(); m_module.sendRegionHandshakeToAll(); } } } protected void consoleSetWaterHeight(string module, string[] args) { string heightstring = args[3]; int x = (args.Length > 4 ? int.Parse(args[4]) : -1); int y = (args.Length > 5 ? int.Parse(args[5]) : -1); if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x) { if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y) { double selectedheight = double.Parse(heightstring); m_log.Debug("[ESTATEMODULE]: Setting water height in " + m_module.Scene.RegionInfo.RegionName + " to " + string.Format(" {0}", selectedheight)); m_module.Scene.RegionInfo.RegionSettings.WaterHeight = selectedheight; m_module.Scene.RegionInfo.RegionSettings.Save(); m_module.TriggerRegionInfoChange(); m_module.sendRegionHandshakeToAll(); } } } protected void consoleSetTerrainHeights(string module, string[] args) { string num = args[3]; string min = args[4]; string max = args[5]; int x = (args.Length > 6 ? int.Parse(args[6]) : -1); int y = (args.Length > 7 ? int.Parse(args[7]) : -1); if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x) { if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y) { int corner = int.Parse(num); float lowValue = float.Parse(min, Culture.NumberFormatInfo); float highValue = float.Parse(max, Culture.NumberFormatInfo); m_log.Debug("[ESTATEMODULE]: Setting terrain heights " + m_module.Scene.RegionInfo.RegionName + string.Format(" (C{0}, {1}-{2}", corner, lowValue, highValue)); switch (corner) { case -1: m_module.Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2SW = highValue; m_module.Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2NW = highValue; m_module.Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2SE = highValue; m_module.Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2NE = highValue; break; case 0: m_module.Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2SW = highValue; break; case 1: m_module.Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2NW = highValue; break; case 2: m_module.Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2SE = highValue; break; case 3: m_module.Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; m_module.Scene.RegionInfo.RegionSettings.Elevation2NE = highValue; break; } m_module.Scene.RegionInfo.RegionSettings.Save(); m_module.TriggerRegionInfoChange(); m_module.sendRegionHandshakeToAll(); } } } protected void ShowEstatesCommand(string module, string[] cmd) { StringBuilder report = new StringBuilder(); RegionInfo ri = m_module.Scene.RegionInfo; EstateSettings es = ri.EstateSettings; report.AppendFormat("Estate information for region {0}\n", ri.RegionName); report.AppendFormat( "{0,-20} {1,-7} {2,-20}\n", "Estate Name", "ID", "Owner"); report.AppendFormat( "{0,-20} {1,-7} {2,-20}\n", es.EstateName, es.EstateID, m_module.UserManager.GetUserName(es.EstateOwner)); MainConsole.Instance.Output(report.ToString()); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Threading; using Windows.Foundation; using Windows.Storage.Streams; namespace System.IO { /// <summary>Depending on the concrete type of the stream managed by a <c>NetFxToWinRtStreamAdapter</c>, /// we want the <c>ReadAsync</c> / <c>WriteAsync</c> / <c>FlushAsync</c> / etc. operation to be implemented /// differently. This is for best performance as we can take advantage of the specifics of particular stream /// types. For instance, <c>ReadAsync</c> currently has a special implementation for memory streams. /// Moreover, knowledge about the actual runtime type of the <c>IBuffer</c> can also help chosing the optimal /// implementation. This type provides static methods that encapsulate the performance logic and can be used /// by <c>NetFxToWinRtStreamAdapter</c>.</summary> internal static class StreamOperationsImplementation { #region ReadAsync implementations internal static IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync_MemoryStream(Stream stream, IBuffer buffer, UInt32 count) { Debug.Assert(stream != null); Debug.Assert(stream is MemoryStream); Debug.Assert(stream.CanRead); Debug.Assert(stream.CanSeek); Debug.Assert(buffer != null); Debug.Assert(buffer is IBufferByteAccess); Debug.Assert(0 <= count); Debug.Assert(count <= Int32.MaxValue); Debug.Assert(count <= buffer.Capacity); Contract.EndContractBlock(); // We will return a different buffer to the user backed directly by the memory stream (avoids memory copy). // This is permitted by the WinRT stream contract. // The user specified buffer will not have any data put into it: buffer.Length = 0; MemoryStream memStream = stream as MemoryStream; Debug.Assert(memStream != null); try { IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((Int32)memStream.Position, (Int32)count); if (dataBuffer.Length > 0) memStream.Seek(dataBuffer.Length, SeekOrigin.Current); return AsyncInfo.CreateCompletedOperation<IBuffer, UInt32>(dataBuffer); } catch (Exception ex) { return AsyncInfo.CreateFaultedOperation<IBuffer, UInt32>(ex); } } // ReadAsync_MemoryStream internal static IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync_AbstractStream(Stream stream, IBuffer buffer, UInt32 count, InputStreamOptions options) { Debug.Assert(stream != null); Debug.Assert(stream.CanRead); Debug.Assert(buffer != null); Debug.Assert(buffer is IBufferByteAccess); Debug.Assert(0 <= count); Debug.Assert(count <= Int32.MaxValue); Debug.Assert(count <= buffer.Capacity); Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead); Contract.EndContractBlock(); Int32 bytesRequested = (Int32)count; // Check if the buffer is our implementation. // IF YES: In that case, we can read directly into its data array. // IF NO: The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only // read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read. // The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own // buffer instance, read data *directly* into the array backing it and then return it to the user. // Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we we would need to create // an array to read into either way. IBuffer dataBuffer = buffer as WindowsRuntimeBuffer; if (dataBuffer == null) dataBuffer = WindowsRuntimeBuffer.Create((Int32)Math.Min((UInt32)Int32.MaxValue, buffer.Capacity)); // This operation delegate will we run inside of the returned IAsyncOperationWithProgress: Func<CancellationToken, IProgress<UInt32>, Task<IBuffer>> readOperation = async (cancelToken, progressListener) => { // No bytes read yet: dataBuffer.Length = 0; // Get the buffer backing array: Byte[] data; Int32 offset; bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset); Debug.Assert(managedBufferAssert); // Init tracking values: bool done = cancelToken.IsCancellationRequested; Int32 bytesCompleted = 0; // Loop until EOS, cancelled or read enough data according to options: while (!done) { Int32 bytesRead = 0; try { // Read asynchronously: bytesRead = await stream.ReadAsync(data, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken) .ConfigureAwait(continueOnCapturedContext: false); // We will continue here on a different thread when read async completed: bytesCompleted += bytesRead; // We will handle a cancelation exception and re-throw all others: } catch (OperationCanceledException) { // We assume that cancelToken.IsCancellationRequested is has been set and simply proceed. // (we check cancelToken.IsCancellationRequested later) Debug.Assert(cancelToken.IsCancellationRequested); // This is because if the cancellation came after we read some bytes we want to return the results we got instead // of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation: if (bytesCompleted == 0 && bytesRead == 0) throw; } // Update target buffer: dataBuffer.Length = (UInt32)bytesCompleted; Debug.Assert(bytesCompleted <= bytesRequested); // Check if we are done: done = options == InputStreamOptions.Partial // If no complete read was requested, any amount of data is OK || bytesRead == 0 // this implies EndOfStream || bytesCompleted == bytesRequested // read all requested bytes || cancelToken.IsCancellationRequested; // operation was cancelled // Call user Progress handler: if (progressListener != null) progressListener.Report(dataBuffer.Length); } // while (!done) // If we got here, then no error was detected. Return the results buffer: return dataBuffer; }; // readOperation return AsyncInfo.Run<IBuffer, UInt32>(readOperation); } // ReadAsync_AbstractStream #endregion ReadAsync implementations #region WriteAsync implementations internal static IAsyncOperationWithProgress<UInt32, UInt32> WriteAsync_AbstractStream(Stream stream, IBuffer buffer) { Debug.Assert(stream != null); Debug.Assert(stream.CanWrite); Debug.Assert(buffer != null); Contract.EndContractBlock(); // Choose the optimal writing strategy for the kind of buffer supplied: Func<CancellationToken, IProgress<UInt32>, Task<UInt32>> writeOperation; Byte[] data; Int32 offset; // If buffer is backed by a managed array: if (buffer.TryGetUnderlyingData(out data, out offset)) { writeOperation = async (cancelToken, progressListener) => { if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable return 0; Debug.Assert(buffer.Length <= Int32.MaxValue); Int32 bytesToWrite = (Int32)buffer.Length; await stream.WriteAsync(data, offset, bytesToWrite, cancelToken).ConfigureAwait(continueOnCapturedContext: false); if (progressListener != null) progressListener.Report((UInt32)bytesToWrite); return (UInt32)bytesToWrite; }; // Otherwise buffer is of an unknown implementation: } else { writeOperation = async (cancelToken, progressListener) => { if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable return 0; UInt32 bytesToWrite = buffer.Length; Stream dataStream = buffer.AsStream(); Int32 buffSize = 0x4000; if (bytesToWrite < buffSize) buffSize = (Int32)bytesToWrite; await dataStream.CopyToAsync(stream, buffSize, cancelToken).ConfigureAwait(continueOnCapturedContext: false); if (progressListener != null) progressListener.Report((UInt32)bytesToWrite); return (UInt32)bytesToWrite; }; } // if-else // Construct and run the async operation: return AsyncInfo.Run<UInt32, UInt32>(writeOperation); } // WriteAsync_AbstractStream #endregion WriteAsync implementations #region FlushAsync implementations internal static IAsyncOperation<Boolean> FlushAsync_AbstractStream(Stream stream) { Debug.Assert(stream != null); Debug.Assert(stream.CanWrite); Contract.EndContractBlock(); Func<CancellationToken, Task<Boolean>> flushOperation = async (cancelToken) => { if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable return false; await stream.FlushAsync(cancelToken).ConfigureAwait(continueOnCapturedContext: false); return true; }; // Construct and run the async operation: return AsyncInfo.Run<Boolean>(flushOperation); } #endregion FlushAsync implementations } // class StreamOperationsImplementation } // namespace
// Copyright (C) 2014 dot42 // // Original filename: Javax.Crypto.Interfaces.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 Javax.Crypto.Interfaces { /// <summary> /// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHPublicKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IDHPublicKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -6628103563352519193; } /// <summary> /// <para>The interface for a public key in the Diffie-Hellman key exchange protocol. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHPublicKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHPublicKey", AccessFlags = 1537)] public partial interface IDHPublicKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPublicKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns this key's public value Y. </para> /// </summary> /// <returns> /// <para>this key's public value Y. </para> /// </returns> /// <java-name> /// getY /// </java-name> [Dot42.DexImport("getY", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetY() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a Diffie-Hellman key. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHKey", AccessFlags = 1537)] public partial interface IDHKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the parameters for this key.</para><para></para> /// </summary> /// <returns> /// <para>the parameters for this key. </para> /// </returns> /// <java-name> /// getParams /// </java-name> [Dot42.DexImport("getParams", "()Ljavax/crypto/spec/DHParameterSpec;", AccessFlags = 1025)] global::Javax.Crypto.Spec.DHParameterSpec GetParams() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface to a <b>password-based-encryption</b> key. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/PBEKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IPBEKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -1430015993304333921; } /// <summary> /// <para>The interface to a <b>password-based-encryption</b> key. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/PBEKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/PBEKey", AccessFlags = 1537)] public partial interface IPBEKey : global::Javax.Crypto.ISecretKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the iteration count, 0 if not specified.</para><para></para> /// </summary> /// <returns> /// <para>the iteration count, 0 if not specified. </para> /// </returns> /// <java-name> /// getIterationCount /// </java-name> [Dot42.DexImport("getIterationCount", "()I", AccessFlags = 1025)] int GetIterationCount() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a copy of the salt data or null if not specified.</para><para></para> /// </summary> /// <returns> /// <para>a copy of the salt data or null if not specified. </para> /// </returns> /// <java-name> /// getSalt /// </java-name> [Dot42.DexImport("getSalt", "()[B", AccessFlags = 1025, IgnoreFromJava = true)] byte[] GetSalt() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a copy to the password.</para><para></para> /// </summary> /// <returns> /// <para>a copy to the password. </para> /// </returns> /// <java-name> /// getPassword /// </java-name> [Dot42.DexImport("getPassword", "()[C", AccessFlags = 1025)] char[] GetPassword() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHPrivateKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IDHPrivateKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serialization version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 2211791113380396553; } /// <summary> /// <para>The interface for a private key in the Diffie-Hellman key exchange protocol. </para> /// </summary> /// <java-name> /// javax/crypto/interfaces/DHPrivateKey /// </java-name> [Dot42.DexImport("javax/crypto/interfaces/DHPrivateKey", AccessFlags = 1537)] public partial interface IDHPrivateKey : global::Javax.Crypto.Interfaces.IDHKey, global::Java.Security.IPrivateKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns this key's private value x. </para> /// </summary> /// <returns> /// <para>this key's private value x. </para> /// </returns> /// <java-name> /// getX /// </java-name> [Dot42.DexImport("getX", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetX() /* MethodBuilder.Create */ ; } }
using System; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class PageLoadingTest : DriverTestFixture { private IWebDriver localDriver; [SetUp] public void RestartOriginalDriver() { driver = EnvironmentManager.Instance.GetCurrentDriver(); } [TearDown] public void QuitAdditionalDriver() { if (localDriver != null) { localDriver.Quit(); localDriver = null; } } [Test] public void NoneStrategyShouldNotWaitForPageToLoad() { InitLocalDriver(PageLoadStrategy.None); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); DateTime start = DateTime.Now; localDriver.Url = slowPage; DateTime end = DateTime.Now; TimeSpan duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'get' operation should not wait. Assert.That(duration.TotalMilliseconds, Is.LessThan(1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] public void NoneStrategyShouldNotWaitForPageToRefresh() { InitLocalDriver(PageLoadStrategy.None); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); // We discard the element, but want a check to make sure the page is loaded WaitFor(() => localDriver.FindElement(By.TagName("body")), TimeSpan.FromSeconds(10), "did not find body"); DateTime start = DateTime.Now; localDriver.Navigate().Refresh(); DateTime end = DateTime.Now; TimeSpan duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'refresh' operation should not wait. Assert.That(duration.TotalMilliseconds, Is.LessThan(1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Edge, "Edge driver does not support eager page load strategy")] public void EagerStrategyShouldNotWaitForResources() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("slowLoadingResourcePage.html"); DateTime start = DateTime.Now; localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime end = DateTime.Now; // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. TimeSpan duration = end - start; Assert.That(duration.TotalMilliseconds, Is.LessThan(5 * 1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Edge, "Edge driver does not support eager page load strategy")] public void EagerStrategyShouldNotWaitForResourcesOnRefresh() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("slowLoadingResourcePage.html"); localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime start = DateTime.Now; localDriver.Navigate().Refresh(); // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime end = DateTime.Now; // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. TimeSpan duration = end - start; Assert.That(duration.TotalMilliseconds, Is.LessThan(5 * 1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Edge, "Edge driver does not support eager page load strategy")] public void EagerStrategyShouldWaitForDocumentToBeLoaded() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=3"); localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually completed. WaitFor(() => localDriver.FindElement(By.TagName("body")), TimeSpan.FromSeconds(10), "did not find body"); } [Test] public void NormalStrategyShouldWaitForDocumentToBeLoaded() { driver.Url = simpleTestPage; Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldFollowRedirectsSentInTheHttpResponseHeaders() { driver.Url = redirectPage; Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldFollowMetaRedirects() { driver.Url = metaRedirectPage; WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [IgnoreBrowser(Browser.Firefox, "Browser doesn't see subsequent navigation to a fragment as a new navigation.")] public void ShouldBeAbleToGetAFragmentOnTheCurrentPage() { driver.Url = xhtmlTestPage; driver.Url = xhtmlTestPage + "#text"; driver.FindElement(By.Id("id1")); } [Test] public void ShouldReturnWhenGettingAUrlThatDoesNotResolve() { try { // Of course, we're up the creek if this ever does get registered driver.Url = "http://www.thisurldoesnotexist.comx/"; } catch (Exception e) { if (!IsIeDriverTimedOutException(e)) { throw e; } } } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldThrowIfUrlIsMalformed() { Assert.That(() => driver.Url = "www.test.com", Throws.InstanceOf<WebDriverException>()); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldThrowIfUrlIsMalformedInPortPart() { Assert.That(() => driver.Url = "http://localhost:30001bla", Throws.InstanceOf<WebDriverException>()); } [Test] public void ShouldReturnWhenGettingAUrlThatDoesNotConnect() { // Here's hoping that there's nothing here. There shouldn't be driver.Url = "http://localhost:3001"; } [Test] public void ShouldReturnUrlOnNotExistedPage() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("not_existed_page.html"); driver.Url = url; Assert.AreEqual(url, driver.Url); } [Test] public void ShouldBeAbleToLoadAPageWithFramesetsAndWaitUntilAllFramesAreLoaded() { driver.Url = framesetPage; driver.SwitchTo().Frame(0); IWebElement pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "1"); driver.SwitchTo().DefaultContent().SwitchTo().Frame(1); pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "2"); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldDoNothingIfThereIsNothingToGoBackTo() { string originalTitle = driver.Title; driver.Url = formsPage; driver.Navigate().Back(); // We may have returned to the browser's home page string currentTitle = driver.Title; Assert.That(currentTitle, Is.EqualTo(originalTitle).Or.EqualTo("We Leave From Here")); if (driver.Title == originalTitle) { driver.Navigate().Back(); Assert.AreEqual(originalTitle, driver.Title); } } [Test] public void ShouldBeAbleToNavigateBackInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); } [Test] public void ShouldBeAbleToNavigateBackInTheBrowserHistoryInPresenceOfIframes() { driver.Url = xhtmlTestPage; driver.FindElement(By.Name("sameWindow")).Click(); WaitFor(TitleToBeEqualTo("This page has iframes"), "Browser title was not 'This page has iframes'"); Assert.AreEqual(driver.Title, "This page has iframes"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Browser title was not 'XHTML Test Page'"); Assert.AreEqual(driver.Title, "XHTML Test Page"); } [Test] public void ShouldBeAbleToNavigateForwardsInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); driver.Navigate().Forward(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [IgnoreBrowser(Browser.IE, "Browser does not support using insecure SSL certs")] [IgnoreBrowser(Browser.Safari, "Browser does not support using insecure SSL certs")] [IgnoreBrowser(Browser.EdgeLegacy, "Browser does not support using insecure SSL certs")] public void ShouldBeAbleToAccessPagesWithAnInsecureSslCertificate() { String url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("simpleTest.html"); driver.Url = url; // This should work Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldBeAbleToRefreshAPage() { driver.Url = xhtmlTestPage; driver.Navigate().Refresh(); Assert.AreEqual(driver.Title, "XHTML Test Page"); } /// <summary> /// see <a href="http://code.google.com/p/selenium/issues/detail?id=208">Issue 208</a> /// </summary> [Test] [IgnoreBrowser(Browser.IE, "Browser does, in fact, hang in this case.")] [IgnoreBrowser(Browser.Firefox, "Browser does, in fact, hang in this case.")] public void ShouldNotHangIfDocumentOpenCallIsNeverFollowedByDocumentCloseCall() { driver.Url = documentWrite; // If this command succeeds, then all is well. driver.FindElement(By.XPath("//body")); } [Test] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void PageLoadTimeoutCanBeChanged() { TestPageLoadTimeoutIsEnforced(2); TestPageLoadTimeoutIsEnforced(3); } [Test] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void CanHandleSequentialPageLoadTimeouts() { long pageLoadTimeout = 2; long pageLoadTimeBuffer = 10; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (pageLoadTimeout + pageLoadTimeBuffer)); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, pageLoadTimeout, pageLoadTimeBuffer); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, pageLoadTimeout, pageLoadTimeBuffer); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToLoad() { try { TestPageLoadTimeoutIsEnforced(2); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [IgnoreBrowser(Browser.EdgeLegacy, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToLoadAfterClick() { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("page_with_link_to_slow_loading_page.html"); IWebElement link = WaitFor(() => driver.FindElement(By.Id("link-to-slow-loading-page")), "Could not find link"); try { AssertPageLoadTimeoutIsEnforced(() => link.Click(), 2, 3); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToRefresh() { // Get the sleeping servlet with a pause of 5 seconds long pageLoadTimeout = 2; long pageLoadTimeBuffer = 0; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (pageLoadTimeout + pageLoadTimeBuffer)); driver.Url = slowLoadingPageUrl; driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); try { AssertPageLoadTimeoutIsEnforced(() => driver.Navigate().Refresh(), 2, 4); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.EdgeLegacy, "Test hangs browser.")] [IgnoreBrowser(Browser.Chrome, "Chrome driver does, in fact, stop loading page after a timeout.")] [IgnoreBrowser(Browser.Edge, "Edge driver does, in fact, stop loading page after a timeout.")] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldNotStopLoadingPageAfterTimeout() { try { TestPageLoadTimeoutIsEnforced(1); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } WaitFor(() => { try { string text = driver.FindElement(By.TagName("body")).Text; return text.Contains("Slept for 11s"); } catch (NoSuchElementException) { } catch (StaleElementReferenceException) { } return false; }, TimeSpan.FromSeconds(30), "Did not find expected text"); } private Func<bool> TitleToBeEqualTo(string expectedTitle) { return () => { return driver.Title == expectedTitle; }; } /** * Sets given pageLoadTimeout to the {@link #driver} and asserts that attempt to navigate to a * page that takes much longer (10 seconds longer) to load results in a TimeoutException. * <p> * Side effects: 1) {@link #driver} is configured to use given pageLoadTimeout, * 2) test HTTP server still didn't serve the page to browser (some browsers may still * be waiting for the page to load despite the fact that driver responded with the timeout). */ private void TestPageLoadTimeoutIsEnforced(long webDriverPageLoadTimeoutInSeconds) { // Test page will load this many seconds longer than WD pageLoadTimeout. long pageLoadTimeBufferInSeconds = 10; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (webDriverPageLoadTimeoutInSeconds + pageLoadTimeBufferInSeconds)); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(webDriverPageLoadTimeoutInSeconds); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, webDriverPageLoadTimeoutInSeconds, pageLoadTimeBufferInSeconds); } private void AssertPageLoadTimeoutIsEnforced(TestDelegate delegateToTest, long webDriverPageLoadTimeoutInSeconds, long pageLoadTimeBufferInSeconds) { DateTime start = DateTime.Now; Assert.That(delegateToTest, Throws.InstanceOf<WebDriverTimeoutException>(), "I should have timed out after " + webDriverPageLoadTimeoutInSeconds + " seconds"); DateTime end = DateTime.Now; TimeSpan duration = end - start; Assert.That(duration.TotalSeconds, Is.GreaterThan(webDriverPageLoadTimeoutInSeconds)); Assert.That(duration.TotalSeconds, Is.LessThan(webDriverPageLoadTimeoutInSeconds + pageLoadTimeBufferInSeconds)); } private void InitLocalDriver(PageLoadStrategy strategy) { EnvironmentManager.Instance.CloseCurrentDriver(); if (localDriver != null) { localDriver.Quit(); } PageLoadStrategyOptions options = new PageLoadStrategyOptions(); options.PageLoadStrategy = strategy; localDriver = EnvironmentManager.Instance.CreateDriverInstance(options); } private class PageLoadStrategyOptions : DriverOptions { [Obsolete] public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { } public override ICapabilities ToCapabilities() { return null; } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// DashControl /// </summary> public class DashControl : Control { #region Fields private readonly Timer _highlightTimer; private SizeF _blockSize; private List<SquareButton> _horizontalButtons; private List<SquareButton> _verticalButtons; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DashControl"/> class. /// </summary> public DashControl() { _blockSize.Width = 10F; _blockSize.Height = 10F; HorizontalSlider = new DashSliderHorizontal { Size = new SizeF(_blockSize.Width, _blockSize.Height * 3 / 2) }; VerticalSlider = new DashSliderVertical { Size = new SizeF(_blockSize.Width * 3 / 2, _blockSize.Height) }; ButtonDownDarkColor = SystemColors.ControlDark; ButtonDownLitColor = SystemColors.ControlDark; ButtonUpDarkColor = SystemColors.Control; ButtonUpLitColor = SystemColors.Control; _highlightTimer = new Timer { Interval = 100 }; _highlightTimer.Tick += HighlightTimerTick; } #endregion #region Events /// <summary> /// Occurs any time any action has occurred that changes the pattern. /// </summary> public event EventHandler PatternChanged; #endregion #region Properties /// <summary> /// Gets or sets the floating point size of each block in pixels. /// </summary> [Description("Gets or sets the floating point size of each block in pixels.")] public SizeF BlockSize { get { return _blockSize; } set { _blockSize = value; if (HorizontalSlider != null) HorizontalSlider.Size = new SizeF(_blockSize.Width, _blockSize.Height * 3 / 2); if (VerticalSlider != null) VerticalSlider.Size = new SizeF(_blockSize.Width * 3 / 2, _blockSize.Height); } } /// <summary> /// Gets or sets the color for all the buttons when they are pressed and inactive /// </summary> [Description("Gets or sets the base color for all the buttons when they are pressed and inactive")] public Color ButtonDownDarkColor { get; set; } /// <summary> /// Gets or sets the base color for all the buttons when they are pressed and active /// </summary> [Description("Gets or sets the base color for all the buttons when they are pressed and active")] public Color ButtonDownLitColor { get; set; } /// <summary> /// Gets or sets the base color for all the buttons when they are not pressed and not active. /// </summary> [Description("Gets or sets the base color for all the buttons when they are not pressed and not active.")] public Color ButtonUpDarkColor { get; set; } /// <summary> /// Gets or sets the base color for all the buttons when they are not pressed but are active. /// </summary> [Description("Gets or sets the base color for all the buttons when they are not pressed but are active.")] public Color ButtonUpLitColor { get; set; } /// <summary> /// Gets or sets the boolean pattern for the vertical patterns that control the custom /// compound array. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool[] CompoundButtons { get { bool[] result = new bool[_verticalButtons.Count]; for (int i = 0; i < _verticalButtons.Count; i++) { result[i] = _verticalButtons[i].IsDown; } return result; } set { SetVerticalPattern(value); } } /// <summary> /// Gets or sets the boolean pattern for the horizontal patterns that control the custom /// dash style. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool[] DashButtons { get { bool[] result = new bool[_horizontalButtons.Count]; for (int i = 0; i < _horizontalButtons.Count; i++) { result[i] = _horizontalButtons[i].IsDown; } return result; } set { SetHorizontalPattern(value); } } /// <summary> /// Gets or sets the position of the sliders. The X describes the horizontal placement /// of the horizontal slider, while the Y describes the vertical placement of the vertical slider. /// </summary> [Description("Gets or sets the position of the sliders. The X describes the horizontal placement of the horizontal slider, while the Y describes the vertical placement of the vertical slider.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DashSliderHorizontal HorizontalSlider { get; set; } /// <summary> /// Gets or sets the color of the line /// </summary> [Description("Gets or sets the color that should be used for the filled sections of the line.")] public Color LineColor { get; set; } /// <summary> /// Gets or sets the line width for the actual line being described, regardless of scale mode. /// </summary> public double LineWidth { get; set; } /// <summary> /// Gets the height of the square /// </summary> public double SquareHeight => LineWidth * Height / _blockSize.Height; /// <summary> /// Gets the width of a square in the same units used for the line width. /// </summary> public double SquareWidth => LineWidth * Width / _blockSize.Width; /// <summary> /// Gets or sets the vertical Slider /// </summary> [Description("Gets or sets the image to use as the vertical slider. If this is null, a simple triangle will be used.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DashSliderVertical VerticalSlider { get; set; } #endregion #region Methods /// <summary> /// Gets a compound array. /// </summary> /// <returns>The compound array.</returns> public float[] GetCompoundArray() { bool pressed = false; List<float> pattern = new List<float>(); int i = 0; foreach (SquareButton button in _verticalButtons) { if (button.IsDown != pressed) { float position = i / (float)_verticalButtons.Count; pattern.Add(position); pressed = !pressed; } i++; } if (pressed) { pattern.Add(1F); } if (pattern.Count == 0) return null; return pattern.ToArray(); } /// <summary> /// Gets the dash pattern. /// </summary> /// <returns>The dash pattern.</returns> public float[] GetDashPattern() { bool pressed = true; List<float> pattern = new List<float>(); float previousPosition = 0F; int i = 0; foreach (SquareButton button in _horizontalButtons) { if (button.IsDown != pressed) { float position = i / ((float)_verticalButtons.Count); if (position == 0) position = .0000001f; pattern.Add(position - previousPosition); previousPosition = position; pressed = !pressed; } i++; } float final = i / (float)_verticalButtons.Count; if (final == 0) final = 0.000001F; pattern.Add(final - previousPosition); if (pattern.Count % 2 == 1) pattern.Add(.00001F); if (pattern.Count == 0) return null; return pattern.ToArray(); } /// <summary> /// Sets the pattern of squares for this pen by working with the given dash and compound patterns. /// </summary> /// <param name="stroke">Completely defines the ICartographicStroke that is being used to set the pattern.</param> public void SetPattern(ICartographicStroke stroke) { LineColor = stroke.Color; LineWidth = stroke.Width; if (stroke.DashButtons == null) { _horizontalButtons = null; HorizontalSlider.Position = new PointF(50F, 0F); } else { SetHorizontalPattern(stroke.DashButtons); } if (stroke.CompoundButtons == null) { _verticalButtons = null; VerticalSlider.Position = new PointF(0F, 20F); } else { SetVerticalPattern(stroke.CompoundButtons); } CalculatePattern(); Invalidate(); } /// <summary> /// Occurs when the dash control needs to calculate the pattern /// </summary> protected override void OnCreateControl() { base.OnCreateControl(); CalculatePattern(); } /// <summary> /// Actually controls the basic drawing control. /// </summary> /// <param name="g">The graphics object used for drawing.</param> /// <param name="clipRectangle">The clip rectangle.</param> protected virtual void OnDraw(Graphics g, Rectangle clipRectangle) { Brush b = new SolidBrush(LineColor); foreach (SquareButton vButton in _verticalButtons) { foreach (SquareButton hButton in _horizontalButtons) { float x = hButton.Bounds.X; float y = vButton.Bounds.Y; if (hButton.IsDown && vButton.IsDown) { g.FillRectangle(b, x, y, _blockSize.Width, _blockSize.Height); } else { g.FillRectangle(Brushes.White, x, y, _blockSize.Width, _blockSize.Height); } g.DrawRectangle(Pens.Gray, x, y, _blockSize.Width, _blockSize.Height); } } for (int v = 0; v < Height / _blockSize.Height; v++) { float y = v * _blockSize.Height; if (y < clipRectangle.Y - _blockSize.Height) continue; if (y > clipRectangle.Bottom + _blockSize.Height) continue; for (int u = 0; u < Width / _blockSize.Width; u++) { float x = u * _blockSize.Width; if (x < clipRectangle.X - _blockSize.Width) continue; if (x > clipRectangle.Right + _blockSize.Width) continue; g.DrawRectangle(Pens.Gray, x, y, _blockSize.Width, _blockSize.Height); } } foreach (SquareButton button in _horizontalButtons) { button.Draw(g, clipRectangle); } foreach (SquareButton button in _verticalButtons) { button.Draw(g, clipRectangle); } HorizontalSlider.Draw(g, clipRectangle); VerticalSlider.Draw(g, clipRectangle); } /// <summary> /// Handles the mouse down event /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseDown(MouseEventArgs e) { // Sliders have priority over buttons if (e.Button != MouseButtons.Left) return; if (VerticalSlider.Bounds.Contains(new PointF(e.X, e.Y))) { VerticalSlider.IsDragging = true; return; // Vertical is drawn on top, so if they are both selected, select vertical } if (HorizontalSlider.Bounds.Contains(new PointF(e.X, e.Y))) { HorizontalSlider.IsDragging = true; return; } base.OnMouseDown(e); } /// <summary> /// Handles mouse movement. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseMove(MouseEventArgs e) { _highlightTimer.Stop(); // Activate buttons only if the mouse is over them. Inactivate them otherwise. bool invalid = UpdateHighlight(e.Location); // Sliders RectangleF area = default(RectangleF); if (HorizontalSlider.IsDragging) { area = HorizontalSlider.Bounds; PointF loc = HorizontalSlider.Position; loc.X = e.X; HorizontalSlider.Position = loc; area = RectangleF.Union(area, HorizontalSlider.Bounds); } area.Inflate(10F, 10F); if (invalid == false) Invalidate(new Region(area)); if (VerticalSlider.IsDragging) { area = VerticalSlider.Bounds; PointF loc = VerticalSlider.Position; loc.Y = e.Y; VerticalSlider.Position = loc; area = RectangleF.Union(area, VerticalSlider.Bounds); } area.Inflate(10F, 10F); if (invalid == false) Invalidate(new Region(area)); if (invalid) Invalidate(); base.OnMouseMove(e); _highlightTimer.Start(); } /// <summary> /// Handles the mouse up event. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseUp(MouseEventArgs e) { if (e.Button == MouseButtons.Right) return; bool invalid = false; bool handled = false; if (HorizontalSlider.IsDragging) { CalculatePattern(); HorizontalSlider.IsDragging = false; invalid = true; handled = true; } if (VerticalSlider.IsDragging) { CalculatePattern(); VerticalSlider.IsDragging = false; invalid = true; handled = true; } if (handled == false) { foreach (SquareButton button in _horizontalButtons) { invalid = invalid || button.UpdatePressed(e.Location); } foreach (SquareButton button in _verticalButtons) { invalid = invalid || button.UpdatePressed(e.Location); } } if (invalid) { Invalidate(); OnPatternChanged(); } base.OnMouseUp(e); } /// <summary> /// Creates a bitmap to draw to instead of drawing directly to the image. /// </summary> /// <param name="e">The event args.</param> protected override void OnPaint(PaintEventArgs e) { Rectangle clip = default(Rectangle); if (clip.IsEmpty) clip = ClientRectangle; Bitmap bmp = new Bitmap(clip.Width, clip.Height); Graphics g = Graphics.FromImage(bmp); g.TranslateTransform(clip.X, clip.Y); g.Clear(BackColor); OnDraw(g, e.ClipRectangle); g.Dispose(); e.Graphics.DrawImage(bmp, clip, clip, GraphicsUnit.Pixel); } /// <summary> /// Prevent flicker /// </summary> /// <param name="e">The event args.</param> protected override void OnPaintBackground(PaintEventArgs e) { } /// <summary> /// Fires the pattern changed event. /// </summary> protected virtual void OnPatternChanged() { PatternChanged?.Invoke(this, EventArgs.Empty); } /// <summary> /// Forces a calculation during the resizing that changes the pattern squares. /// </summary> /// <param name="e">The event args.</param> protected override void OnResize(EventArgs e) { base.OnResize(e); CalculatePattern(); } /// <summary> /// Sets the horizontal pattern for this control. /// </summary> /// <param name="buttonPattern">Pattern that is set.</param> protected virtual void SetHorizontalPattern(bool[] buttonPattern) { HorizontalSlider.Position = new PointF((buttonPattern.Length + 1) * _blockSize.Width, 0); _horizontalButtons = new List<SquareButton>(); for (int i = 0; i < buttonPattern.Length; i++) { SquareButton sq = new SquareButton { Bounds = new RectangleF((i + 1) * _blockSize.Width, 0, _blockSize.Width, _blockSize.Height), ColorDownDark = ButtonDownDarkColor, ColorDownLit = ButtonDownLitColor, ColorUpDark = ButtonUpDarkColor, ColorUpLit = ButtonUpLitColor, IsDown = buttonPattern[i] }; _horizontalButtons.Add(sq); } } /// <summary> /// Sets the vertical pattern for this control. /// </summary> /// <param name="buttonPattern">Pattern that is set.</param> protected virtual void SetVerticalPattern(bool[] buttonPattern) { VerticalSlider.Position = new PointF(0, (buttonPattern.Length + 1) * _blockSize.Width); _verticalButtons = new List<SquareButton>(); for (int i = 0; i < buttonPattern.Length; i++) { SquareButton sq = new SquareButton { Bounds = new RectangleF(0, (i + 1) * _blockSize.Width, _blockSize.Width, _blockSize.Height), ColorDownDark = ButtonDownDarkColor, ColorDownLit = ButtonDownLitColor, ColorUpDark = ButtonUpDarkColor, ColorUpLit = ButtonUpLitColor, IsDown = buttonPattern[i] }; _verticalButtons.Add(sq); } } private void CalculatePattern() { // Horizontal PointF loc = HorizontalSlider.Position; if (loc.X > Width) loc.X = Width; int hCount = (int)Math.Ceiling(loc.X / _blockSize.Width); loc.X = hCount * _blockSize.Width; HorizontalSlider.Position = loc; List<SquareButton> newButtonsH = new List<SquareButton>(); int start = 1; if (_horizontalButtons != null) { int minLen = Math.Min(_horizontalButtons.Count, hCount - 1); for (int i = 0; i < minLen; i++) { newButtonsH.Add(_horizontalButtons[i]); } start = minLen + 1; } for (int j = start; j < hCount; j++) { SquareButton sq = new SquareButton { Bounds = new RectangleF(j * _blockSize.Width, 0, _blockSize.Width, _blockSize.Height), ColorDownDark = ButtonDownDarkColor, ColorDownLit = ButtonDownLitColor, ColorUpDark = ButtonUpDarkColor, ColorUpLit = ButtonUpLitColor, IsDown = true }; newButtonsH.Add(sq); } _horizontalButtons = newButtonsH; // Vertical loc = VerticalSlider.Position; if (loc.Y > Height) loc.Y = Height; int vCount = (int)Math.Ceiling(loc.Y / _blockSize.Height); loc.Y = vCount * _blockSize.Height; VerticalSlider.Position = loc; List<SquareButton> buttons = new List<SquareButton>(); start = 1; if (_verticalButtons != null) { int minLen = Math.Min(_verticalButtons.Count, vCount - 1); for (int i = 0; i < minLen; i++) { buttons.Add(_verticalButtons[i]); } start = minLen + 1; } for (int j = start; j < vCount; j++) { SquareButton sq = new SquareButton { Bounds = new RectangleF(0, j * _blockSize.Height, _blockSize.Width, _blockSize.Height), ColorDownDark = ButtonDownDarkColor, ColorDownLit = ButtonDownLitColor, ColorUpDark = ButtonUpDarkColor, ColorUpLit = ButtonUpLitColor, IsDown = true }; buttons.Add(sq); } _verticalButtons = buttons; } private void HighlightTimerTick(object sender, EventArgs e) { Point pt = PointToClient(MousePosition); // If the mouse is still in the control, then the mouse move is enough // to update the highlight. if (ClientRectangle.Contains(pt) == false) { _highlightTimer.Stop(); UpdateHighlight(pt); } } /// <summary> /// Updates the highlight based on mouse position. /// </summary> /// <param name="location">The mouse position.</param> /// <returns>True, if the highlight is valid.</returns> private bool UpdateHighlight(Point location) { bool invalid = false; foreach (SquareButton button in _horizontalButtons) { invalid = invalid || button.UpdateLight(location); } foreach (SquareButton button in _verticalButtons) { invalid = invalid || button.UpdateLight(location); } return invalid; } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UIView.cs" company="Catel development team"> // Copyright (c) 2008 - 2014 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.MonoTouch.UIKit { using System; using System.ComponentModel; using IoC; using Logging; using MVVM; using MVVM.Providers; using MVVM.Views; using global::MonoTouch.Foundation; /// <summary> /// UIView implementation that automatically takes care of view models. /// </summary> [Register("UIView")] public class UIView : global::MonoTouch.UIKit.UIView, IUserControl { #region Fields private static readonly ILog Log = LogManager.GetCurrentClassLogger(); private static readonly IViewModelLocator _viewModelLocator; private readonly UserControlLogic _logic; private object _dataContext; private BindingContext _bindingContext; #endregion #region Constructors /// <summary> /// Initializes static members of the <see cref="UIView"/> class. /// </summary> static UIView() { var dependencyResolver = IoCConfiguration.DefaultDependencyResolver; _viewModelLocator = dependencyResolver.Resolve<IViewModelLocator>(); } /// <summary> /// Initializes a new instance of the <see cref="UIView"/> class. /// </summary> public UIView() { if (CatelEnvironment.IsInDesignMode) { return; } var viewModelType = GetViewModelType(); if (viewModelType == null) { Log.Debug("GetViewModelType() returned null, using the ViewModelLocator to resolve the view model"); viewModelType = _viewModelLocator.ResolveViewModel(GetType()); if (viewModelType == null) { const string error = "The view model of the view could not be resolved. Use either the GetViewModelType() method or IViewModelLocator"; Log.Error(error); throw new NotSupportedException(error); } } _logic = new UserControlLogic(this, viewModelType); _logic.TargetViewPropertyChanged += (sender, e) => { OnPropertyChanged(e); PropertyChanged.SafeInvoke(this, e); }; _logic.ViewModelChanged += (sender, e) => RaiseViewModelChanged(); _logic.ViewModelPropertyChanged += (sender, e) => { OnViewModelPropertyChanged(e); ViewModelPropertyChanged.SafeInvoke(this, e); }; _logic.DetermineViewModelInstance += (sender, e) => { e.ViewModel = GetViewModelInstance(e.DataContext); }; _logic.DetermineViewModelType += (sender, e) => { e.ViewModelType = GetViewModelType(e.DataContext); }; _logic.ViewLoading += (sender, e) => ViewLoading.SafeInvoke(this); _logic.ViewLoaded += (sender, e) => ViewLoaded.SafeInvoke(this); _logic.ViewUnloading += (sender, e) => ViewUnloading.SafeInvoke(this); _logic.ViewUnloaded += (sender, e) => ViewUnloaded.SafeInvoke(this); } #endregion #region Properties /// <summary> /// Gets or sets the data context. /// </summary> /// <value>The data context.</value> public object DataContext { get { return _dataContext; } set { _dataContext = value; DataContextChanged.SafeInvoke(this); } } /// <summary> /// Gets the type of the view model that this user control uses. /// </summary> public Type ViewModelType { get { return _logic.GetValue<PageLogic, Type>(x => x.ViewModelType); } } /// <summary> /// Gets or sets a value indicating whether the view model container should prevent the /// creation of a view model. /// <para /> /// This property is very useful when using views in transitions where the view model is no longer required. /// </summary> /// <value><c>true</c> if the view model container should prevent view model creation; otherwise, <c>false</c>.</value> public bool PreventViewModelCreation { get { return _logic.GetValue<PageLogic, bool>(x => x.PreventViewModelCreation); } set { _logic.SetValue<PageLogic>(x => x.PreventViewModelCreation = value); } } /// <summary> /// Gets the view model that is contained by the container. /// </summary> /// <value>The view model.</value> public IViewModel ViewModel { get { return _logic.GetValue<PageLogic, IViewModel>(x => x.ViewModel); } } /// <summary> /// Gets the parent of the view. /// </summary> /// <value>The parent.</value> object IView.Parent { get { return null; } } /// <summary> /// Gets or sets a value indicating whether the view is enabled. /// </summary> /// <value><c>true</c> if the view is enabled; otherwise, <c>false</c>.</value> public bool IsEnabled { get; set; } #endregion #region Events /// <summary> /// Occurs when a property on the container has changed. /// </summary> /// <remarks> /// This event makes it possible to externally subscribe to property changes of a view /// (mostly the container of a view model) because the .NET Framework does not allows us to. /// </remarks> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Occurs when the <see cref="ViewModel"/> property has changed. /// </summary> public event EventHandler<EventArgs> ViewModelChanged; /// <summary> /// Occurs when a property on the <see cref="ViewModel"/> has changed. /// </summary> public event EventHandler<PropertyChangedEventArgs> ViewModelPropertyChanged; /// <summary> /// Occurs when the view model container is loading. /// </summary> public event EventHandler<EventArgs> ViewLoading; /// <summary> /// Occurs when the view model container is loaded. /// </summary> public event EventHandler<EventArgs> ViewLoaded; /// <summary> /// Occurs when the view model container starts unloading. /// </summary> public event EventHandler<EventArgs> ViewUnloading; /// <summary> /// Occurs when the view model container is unloaded. /// </summary> public event EventHandler<EventArgs> ViewUnloaded; /// <summary> /// Occurs when the view is loaded. /// </summary> public event EventHandler<EventArgs> Loaded; /// <summary> /// Occurs when the view is unloaded. /// </summary> public event EventHandler<EventArgs> Unloaded; /// <summary> /// Occurs when the data context has changed. /// </summary> public event EventHandler<EventArgs> DataContextChanged; #endregion #region Methods private void RaiseViewModelChanged() { OnViewModelChanged(); ViewModelChanged.SafeInvoke(this); PropertyChanged.SafeInvoke(this, new PropertyChangedEventArgs("ViewModel")); if (_bindingContext != null) { _bindingContext.DetermineIfBindingsAreRequired(ViewModel); } } /// <summary> /// Called when the bindings must be added. This can happen /// <para /> /// Normally the binding system would take care of this. /// </summary> /// <param name="bindingContext">The binding context.</param> /// <param name="viewModel">The view model.</param> /// <returns><c>true</c> if the bindings were successfully added.</returns> protected virtual void AddBindings(BindingContext bindingContext, IViewModel viewModel) { } /// <summary> /// Called when the view is loaded. /// </summary> public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); RaiseViewModelChanged(); Loaded.SafeInvoke(this); InitializeBindingContext(); } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Note: call *after* base so NavigationAdapter always gets called Unloaded.SafeInvoke(this); UninitializeBindingContext(); } private void InitializeBindingContext() { if (_bindingContext != null) { UninitializeBindingContext(); } _bindingContext = new BindingContext(); _bindingContext.BindingUpdateRequired += OnBindingUpdateRequired; _bindingContext.DetermineIfBindingsAreRequired(ViewModel); } private void UninitializeBindingContext() { if (_bindingContext == null) { return; } _bindingContext.BindingUpdateRequired -= OnBindingUpdateRequired; _bindingContext.Clear(); _bindingContext = null; } private void OnBindingUpdateRequired(object sender, EventArgs e) { AddBindings(_bindingContext, ViewModel); } /// <summary> /// Gets the type of the view model. If this method returns <c>null</c>, the view model type will be retrieved by naming /// convention using the <see cref="IViewModelLocator"/> registered in the <see cref="IServiceLocator"/>. /// </summary> /// <returns>The type of the view model or <c>null</c> in case it should be auto determined.</returns> protected virtual Type GetViewModelType() { return null; } /// <summary> /// Gets the type of the view model at runtime based on the <see cref="DataContext"/>. If this method returns /// <c>null</c>, the earlier determined view model type will be used instead. /// </summary> /// <param name="dataContext">The data context. This value can be <c>null</c>.</param> /// <returns>The type of the view model or <c>null</c> in case it should be auto determined.</returns> /// <remarks> /// Note that this method is only called when the <see cref="DataContext"/> changes. /// </remarks> protected virtual Type GetViewModelType(object dataContext) { return null; } /// <summary> /// Gets the instance of the view model at runtime based on the <see cref="DataContext"/>. If this method returns /// <c>null</c>, the logic will try to construct the view model by itself. /// </summary> /// <param name="dataContext">The data context. This value can be <c>null</c>.</param> /// <returns>The instance of the view model or <c>null</c> in case it should be auto created.</returns> /// <remarks> /// Note that this method is only called when the <see cref="DataContext"/> changes. /// </remarks> protected virtual IViewModel GetViewModelInstance(object dataContext) { return null; } /// <summary> /// Called when a dependency property on this control has changed. /// </summary> /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { } /// <summary> /// Called when a property on the current <see cref="ViewModel"/> has changed. /// </summary> /// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param> protected virtual void OnViewModelPropertyChanged(PropertyChangedEventArgs e) { } /// <summary> /// Called when the <see cref="ViewModel"/> has changed. /// </summary> /// <remarks> /// This method does not implement any logic and saves a developer from subscribing/unsubscribing /// to the <see cref="ViewModelChanged"/> event inside the same user control. /// </remarks> protected virtual void OnViewModelChanged() { } /// <summary> /// Validates the data. /// </summary> /// <returns>True if successful, otherwise false.</returns> protected bool ValidateData() { return _logic.ValidateViewModel(); } /// <summary> /// Discards all changes made by this window. /// </summary> protected void DiscardChanges() { _logic.CancelViewModel(); } /// <summary> /// Applies all changes made by this window. /// </summary> /// <returns>True if successful, otherwise false.</returns> protected bool ApplyChanges() { return _logic.SaveViewModel(); } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Pathfinding { using Pathfinding.RVO; using Pathfinding.Util; [AddComponentMenu("Pathfinding/AI/RichAI (3D, for navmesh)")] /** Advanced AI for navmesh based graphs. * \astarpro */ public partial class RichAI : AIBase, IAstarAI { /** Max acceleration of the agent. * In world units per second per second. */ public float acceleration = 5; /** Max rotation speed of the agent. * In degrees per second. */ public float rotationSpeed = 360; /** How long before reaching the end of the path to start to slow down. * A lower value will make the agent stop more abruptly. * * \note The agent may require more time to slow down if * its maximum #acceleration is not high enough. * * If set to zero the agent will not even attempt to slow down. * This can be useful if the target point is not a point you want the agent to stop at * but it might for example be the player and you want the AI to slam into the player. * * \note A value of zero will behave differently from a small but non-zero value (such as 0.0001). * When it is non-zero the agent will still respect its #acceleration when determining if it needs * to slow down, but if it is zero it will disable that check. * This is useful if the #destination is not a point where you want the agent to stop. * * \htmlonly <video class="tinyshadow" controls loop><source src="images/richai_slowdown_time.mp4" type="video/mp4"></video> \endhtmlonly */ public float slowdownTime = 0.5f; /** Max distance to the endpoint to consider it reached. * * \see #reachedEndOfPath * \see #OnTargetReached */ public float endReachedDistance = 0.01f; /** Force to avoid walls with. * The agent will try to steer away from walls slightly. * * \see #wallDist */ public float wallForce = 3; /** Walls within this range will be used for avoidance. * Setting this to zero disables wall avoidance and may improve performance slightly * * \see #wallForce */ public float wallDist = 1; /** Use funnel simplification. * On tiled navmesh maps, but sometimes on normal ones as well, it can be good to simplify * the funnel as a post-processing step to make the paths straighter. * * This has a moderate performance impact during frames when a path calculation is completed. * * The RichAI script uses its own internal funnel algorithm, so you never * need to attach the FunnelModifier component. * * \shadowimage{funnelSimplification.png} * * \see #Pathfinding.FunnelModifier */ public bool funnelSimplification = false; /** Slow down when not facing the target direction. * Incurs at a small performance overhead. */ public bool slowWhenNotFacingTarget = true; /** Called when the agent starts to traverse an off-mesh link. * Register to this callback to handle off-mesh links in a custom way. * * If this event is set to null then the agent will fall back to traversing * off-mesh links using a very simple linear interpolation. * * \snippet MiscSnippets.cs RichAI.onTraverseOffMeshLink */ public System.Func<RichSpecial, IEnumerator> onTraverseOffMeshLink; /** Holds the current path that this agent is following */ protected readonly RichPath richPath = new RichPath(); protected bool delayUpdatePath; protected bool lastCorner; /** Distance to #steeringTarget in the movement plane */ protected float distanceToSteeringTarget = float.PositiveInfinity; protected readonly List<Vector3> nextCorners = new List<Vector3>(); protected readonly List<Vector3> wallBuffer = new List<Vector3>(); public bool traversingOffMeshLink { get; protected set; } /** \copydoc Pathfinding::IAstarAI::remainingDistance */ public float remainingDistance { get { return distanceToSteeringTarget + Vector3.Distance(steeringTarget, richPath.Endpoint); } } /** \copydoc Pathfinding::IAstarAI::reachedEndOfPath */ public bool reachedEndOfPath { get { return approachingPathEndpoint && distanceToSteeringTarget < endReachedDistance; } } /** \copydoc Pathfinding::IAstarAI::hasPath */ public bool hasPath { get { return richPath.GetCurrentPart() != null; } } /** \copydoc Pathfinding::IAstarAI::pathPending */ public bool pathPending { get { return waitingForPathCalculation || delayUpdatePath; } } /** \copydoc Pathfinding::IAstarAI::steeringTarget */ public Vector3 steeringTarget { get; protected set; } /** \copydoc Pathfinding::IAstarAI::maxSpeed */ float IAstarAI.maxSpeed { get { return maxSpeed; } set { maxSpeed = value; } } /** \copydoc Pathfinding::IAstarAI::canSearch */ bool IAstarAI.canSearch { get { return canSearch; } set { canSearch = value; } } /** \copydoc Pathfinding::IAstarAI::canMove */ bool IAstarAI.canMove { get { return canMove; } set { canMove = value; } } /** \copydoc Pathfinding::IAstarAI::position */ Vector3 IAstarAI.position { get { return tr.position; } } /** True if approaching the last waypoint in the current part of the path. * Path parts are separated by off-mesh links. * * \see #approachingPathEndpoint */ public bool approachingPartEndpoint { get { return lastCorner && nextCorners.Count == 1; } } /** True if approaching the last waypoint of all parts in the current path. * Path parts are separated by off-mesh links. * * \see #approachingPartEndpoint */ public bool approachingPathEndpoint { get { return approachingPartEndpoint && richPath.IsLastPart; } } /** \copydoc Pathfinding::IAstarAI::Teleport * * When setting transform.position directly the agent * will be clamped to the part of the navmesh it can * reach, so it may not end up where you wanted it to. * This ensures that the agent can move to any part of the navmesh. */ public override void Teleport (Vector3 newPosition, bool clearPath = true) { // Clamp the new position to the navmesh var nearest = AstarPath.active != null ? AstarPath.active.GetNearest(newPosition) : new NNInfo(); float elevation; movementPlane.ToPlane(newPosition, out elevation); newPosition = movementPlane.ToWorld(movementPlane.ToPlane(nearest.node != null ? nearest.position : newPosition), elevation); if (clearPath) richPath.Clear(); base.Teleport(newPosition, clearPath); } /** Called when the component is disabled */ protected override void OnDisable () { // Note that the AIBase.OnDisable call will also stop all coroutines base.OnDisable(); lastCorner = false; distanceToSteeringTarget = float.PositiveInfinity; traversingOffMeshLink = false; delayUpdatePath = false; // Stop the off mesh link traversal coroutine StopAllCoroutines(); } protected override bool shouldRecalculatePath { get { // Don't automatically recalculate the path in the middle of an off-mesh link return base.shouldRecalculatePath && !traversingOffMeshLink; } } public override void SearchPath () { // Calculate paths after the current off-mesh link has been completed if (traversingOffMeshLink) { delayUpdatePath = true; } else { base.SearchPath(); } } protected override void OnPathComplete (Path p) { waitingForPathCalculation = false; p.Claim(this); if (p.error) { p.Release(this); return; } if (traversingOffMeshLink) { delayUpdatePath = true; } else { richPath.Initialize(seeker, p, true, funnelSimplification); // Check if we have already reached the end of the path // We need to do this here to make sure that the #reachedEndOfPath // property is up to date. var part = richPath.GetCurrentPart() as RichFunnel; if (part != null) { if (updatePosition) simulatedPosition = tr.position; var position = movementPlane.ToPlane(UpdateTarget(part)); if (lastCorner && nextCorners.Count == 1) { // Target point steeringTarget = nextCorners[0]; Vector2 targetPoint = movementPlane.ToPlane(steeringTarget); distanceToSteeringTarget = (targetPoint - position).magnitude; if (distanceToSteeringTarget <= endReachedDistance) { NextPart(); } } } } p.Release(this); } /** Declare that the AI has completely traversed the current part. * This will skip to the next part, or call OnTargetReached if this was the last part */ protected void NextPart () { if (!richPath.CompletedAllParts) { if (!richPath.IsLastPart) lastCorner = false; richPath.NextPart(); if (richPath.CompletedAllParts) { OnTargetReached(); } } } /** Called when the end of the path is reached */ protected virtual void OnTargetReached () { } protected virtual Vector3 UpdateTarget (RichFunnel fn) { nextCorners.Clear(); // This method assumes simulatedPosition is up to date as our current position. // We read and write to tr.position as few times as possible since doing so // is much slower than to read and write from/to a local/member variable. bool requiresRepath; Vector3 position = fn.Update(simulatedPosition, nextCorners, 2, out lastCorner, out requiresRepath); if (requiresRepath && !waitingForPathCalculation && canSearch) { // TODO: What if canSearch is false? How do we notify other scripts that might be handling the path calculation that a new path needs to be calculated? SearchPath(); } return position; } /** Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not */ protected override void MovementUpdateInternal (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) { if (updatePosition) simulatedPosition = tr.position; if (updateRotation) simulatedRotation = tr.rotation; RichPathPart currentPart = richPath.GetCurrentPart(); if (currentPart is RichSpecial) { if (!traversingOffMeshLink) { StartCoroutine(TraverseSpecial(currentPart as RichSpecial)); } nextPosition = steeringTarget = simulatedPosition; nextRotation = rotation; } else { var funnel = currentPart as RichFunnel; if (funnel != null && !isStopped) { TraverseFunnel(funnel, deltaTime, out nextPosition, out nextRotation); } else { // Unknown, null path part, or the character is stopped // Slow down as quickly as possible velocity2D -= Vector2.ClampMagnitude(velocity2D, acceleration * deltaTime); FinalMovement(simulatedPosition, deltaTime, float.PositiveInfinity, 1f, out nextPosition, out nextRotation); steeringTarget = simulatedPosition; } } } void TraverseFunnel (RichFunnel fn, float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) { // Clamp the current position to the navmesh // and update the list of upcoming corners in the path // and store that in the 'nextCorners' field var position3D = UpdateTarget(fn); float elevation; Vector2 position = movementPlane.ToPlane(position3D, out elevation); // Only find nearby walls every 5th frame to improve performance if (Time.frameCount % 5 == 0 && wallForce > 0 && wallDist > 0) { wallBuffer.Clear(); fn.FindWalls(wallBuffer, wallDist); } // Target point steeringTarget = nextCorners[0]; Vector2 targetPoint = movementPlane.ToPlane(steeringTarget); // Direction to target Vector2 dir = targetPoint - position; // Normalized direction to the target Vector2 normdir = VectorMath.Normalize(dir, out distanceToSteeringTarget); // Calculate force from walls Vector2 wallForceVector = CalculateWallForce(position, elevation, normdir); Vector2 targetVelocity; if (approachingPartEndpoint) { targetVelocity = slowdownTime > 0 ? Vector2.zero : normdir * maxSpeed; // Reduce the wall avoidance force as we get closer to our target wallForceVector *= System.Math.Min(distanceToSteeringTarget/0.5f, 1); if (distanceToSteeringTarget <= endReachedDistance) { // Reached the end of the path or an off mesh link NextPart(); } } else { var nextNextCorner = nextCorners.Count > 1 ? movementPlane.ToPlane(nextCorners[1]) : position + 2*dir; targetVelocity = (nextNextCorner - targetPoint).normalized * maxSpeed; } var forwards = movementPlane.ToPlane(simulatedRotation * (rotationIn2D ? Vector3.up : Vector3.forward)); Vector2 accel = MovementUtilities.CalculateAccelerationToReachPoint(targetPoint - position, targetVelocity, velocity2D, acceleration, rotationSpeed, maxSpeed, forwards); // Update the velocity using the acceleration velocity2D += (accel + wallForceVector*wallForce)*deltaTime; // Distance to the end of the path (almost as the crow flies) var distanceToEndOfPath = distanceToSteeringTarget + Vector3.Distance(steeringTarget, fn.exactEnd); var slowdownFactor = distanceToEndOfPath < maxSpeed * slowdownTime ? Mathf.Sqrt(distanceToEndOfPath / (maxSpeed * slowdownTime)) : 1; FinalMovement(position3D, deltaTime, distanceToEndOfPath, slowdownFactor, out nextPosition, out nextRotation); } void FinalMovement (Vector3 position3D, float deltaTime, float distanceToEndOfPath, float slowdownFactor, out Vector3 nextPosition, out Quaternion nextRotation) { var forwards = movementPlane.ToPlane(simulatedRotation * (rotationIn2D ? Vector3.up : Vector3.forward)); velocity2D = MovementUtilities.ClampVelocity(velocity2D, maxSpeed, slowdownFactor, slowWhenNotFacingTarget, forwards); ApplyGravity(deltaTime); if (rvoController != null && rvoController.enabled) { // Send a message to the RVOController that we want to move // with this velocity. In the next simulation step, this // velocity will be processed and it will be fed back to the // rvo controller and finally it will be used by this script // when calling the CalculateMovementDelta method below // Make sure that we don't move further than to the end point // of the path. If the RVO simulation FPS is low and we did // not do this, the agent might overshoot the target a lot. var rvoTarget = position3D + movementPlane.ToWorld(Vector2.ClampMagnitude(velocity2D, distanceToEndOfPath)); rvoController.SetTarget(rvoTarget, velocity2D.magnitude, maxSpeed); } // Direction and distance to move during this frame var deltaPosition = lastDeltaPosition = CalculateDeltaToMoveThisFrame(movementPlane.ToPlane(position3D), distanceToEndOfPath, deltaTime); // Rotate towards the direction we are moving in // Slow down the rotation of the character very close to the endpoint of the path to prevent oscillations var rotationSpeedFactor = approachingPartEndpoint ? Mathf.Clamp01(1.1f * slowdownFactor - 0.1f) : 1f; nextRotation = SimulateRotationTowards(deltaPosition, rotationSpeed * rotationSpeedFactor * deltaTime); nextPosition = position3D + movementPlane.ToWorld(deltaPosition, verticalVelocity * deltaTime); } protected override Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged) { if (richPath != null) { var funnel = richPath.GetCurrentPart() as RichFunnel; if (funnel != null) { var clampedPosition = funnel.ClampToNavmesh(position); // We cannot simply check for equality because some precision may be lost // if any coordinate transformations are used. var difference = movementPlane.ToPlane(clampedPosition - position); float sqrDifference = difference.sqrMagnitude; if (sqrDifference > 0.001f*0.001f) { // The agent was outside the navmesh. Remove that component of the velocity // so that the velocity only goes along the direction of the wall, not into it velocity2D -= difference * Vector2.Dot(difference, velocity2D) / sqrDifference; // Make sure the RVO system knows that there was a collision here // Otherwise other agents may think this agent continued // to move forwards and avoidance quality may suffer if (rvoController != null && rvoController.enabled) { rvoController.SetCollisionNormal(difference); } positionChanged = true; // Return the new position, but ignore any changes in the y coordinate from the ClampToNavmesh method as the y coordinates in the navmesh are rarely very accurate return position + movementPlane.ToWorld(difference); } } } positionChanged = false; return position; } Vector2 CalculateWallForce (Vector2 position, float elevation, Vector2 directionToTarget) { if (wallForce <= 0 || wallDist <= 0) return Vector2.zero; float wLeft = 0; float wRight = 0; var position3D = movementPlane.ToWorld(position, elevation); for (int i = 0; i < wallBuffer.Count; i += 2) { Vector3 closest = VectorMath.ClosestPointOnSegment(wallBuffer[i], wallBuffer[i+1], position3D); float dist = (closest-position3D).sqrMagnitude; if (dist > wallDist*wallDist) continue; Vector2 tang = movementPlane.ToPlane(wallBuffer[i+1]-wallBuffer[i]).normalized; // Using the fact that all walls are laid out clockwise (looking from inside the obstacle) // Then left and right (ish) can be figured out like this float dot = Vector2.Dot(directionToTarget, tang); float weight = 1 - System.Math.Max(0, (2*(dist / (wallDist*wallDist))-1)); if (dot > 0) wRight = System.Math.Max(wRight, dot * weight); else wLeft = System.Math.Max(wLeft, -dot * weight); } Vector2 normal = new Vector2(directionToTarget.y, -directionToTarget.x); return normal*(wRight-wLeft); } /** Traverses an off-mesh link */ protected virtual IEnumerator TraverseSpecial (RichSpecial link) { traversingOffMeshLink = true; // The current path part is a special part, for example a link // Movement during this part of the path is handled by the TraverseSpecial coroutine velocity2D = Vector3.zero; var offMeshLinkCoroutine = onTraverseOffMeshLink != null ? onTraverseOffMeshLink(link) : TraverseOffMeshLinkFallback(link); yield return StartCoroutine(offMeshLinkCoroutine); // Off-mesh link traversal completed traversingOffMeshLink = false; NextPart(); // If a path completed during the time we traversed the special connection, we need to recalculate it if (delayUpdatePath) { delayUpdatePath = false; // TODO: What if canSearch is false? How do we notify other scripts that might be handling the path calculation that a new path needs to be calculated? if (canSearch) SearchPath(); } } /** Fallback for traversing off-mesh links in case #onTraverseOffMeshLink is not set. * This will do a simple linear interpolation along the link. */ protected IEnumerator TraverseOffMeshLinkFallback (RichSpecial link) { float duration = maxSpeed > 0 ? Vector3.Distance(link.second.position, link.first.position) / maxSpeed : 1; float startTime = Time.time; while (true) { var pos = Vector3.Lerp(link.first.position, link.second.position, Mathf.InverseLerp(startTime, startTime + duration, Time.time)); if (updatePosition) tr.position = pos; else simulatedPosition = pos; if (Time.time >= startTime + duration) break; yield return null; } } protected static readonly Color GizmoColorPath = new Color(8.0f/255, 78.0f/255, 194.0f/255); protected override void OnDrawGizmos () { base.OnDrawGizmos(); if (tr != null) { Gizmos.color = GizmoColorPath; Vector3 lastPosition = position; for (int i = 0; i < nextCorners.Count; lastPosition = nextCorners[i], i++) { Gizmos.DrawLine(lastPosition, nextCorners[i]); } } } protected override int OnUpgradeSerializedData (int version, bool unityThread) { #pragma warning disable 618 if (unityThread && animCompatibility != null) anim = animCompatibility; #pragma warning restore 618 return base.OnUpgradeSerializedData(version, unityThread); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Orleans.Transactions.Abstractions; namespace Orleans.Transactions.TestKit.Correctnesss { [Serializable] [GenerateSerializer] public class BitArrayState { protected bool Equals(BitArrayState other) { if (ReferenceEquals(null, this.value)) return false; if (ReferenceEquals(null, other.value)) return false; if (this.value.Length != other.value.Length) return false; for (var i = 0; i < this.value.Length; i++) { if (this.value[i] != other.value[i]) { return false; } } return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((BitArrayState) obj); } public override int GetHashCode() { return (value != null ? value.GetHashCode() : 0); } private static readonly int BitsInInt = sizeof(int) * 8; [JsonProperty("v")] [Id(0)] private int[] value = { 0 }; [JsonIgnore] public int[] Value => value; [JsonIgnore] public int Length => this.value.Length; public BitArrayState() { } public BitArrayState(BitArrayState other) { this.value = new int[other.value.Length]; for (var i = 0; i < other.value.Length; i++) { this.value[i] = other.value[i]; } } public void Set(int index, bool value) { int idx = index / BitsInInt; if (idx >= this.value.Length) { Array.Resize(ref this.value, idx+1); } int shift = 1 << (index % BitsInInt); if (value) { this.value[idx] |= shift; } else this.value[idx] &= ~shift; } public IEnumerator<int> GetEnumerator() { foreach (var v in this.value) yield return v; } public override string ToString() { // Write the values from least significant bit to most significant bit var builder = new StringBuilder(); foreach (var v in this.value) { builder.Append(Reverse(Convert.ToString(v, 2)).PadRight(BitsInInt, '0')); string Reverse(string s) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } } return builder.ToString(); } public int this[int index] { get => this.value[index]; set => this.value[index] = value; } public static bool operator ==(BitArrayState left, BitArrayState right) { if (ReferenceEquals(left, right)) return true; if (ReferenceEquals(left, null)) return false; if (ReferenceEquals(right, null)) return false; return left.Equals(right); } public static bool operator !=(BitArrayState left, BitArrayState right) { return !(left == right); } public static BitArrayState operator ^(BitArrayState left, BitArrayState right) { return Apply(left, right, (l, r) => l ^ r); } public static BitArrayState operator |(BitArrayState left, BitArrayState right) { return Apply(left, right, (l, r) => l | r); } public static BitArrayState operator &(BitArrayState left, BitArrayState right) { return Apply(left, right, (l, r) => l & r); } public static BitArrayState Apply(BitArrayState left, BitArrayState right, Func<int, int, int> op) { var result = new BitArrayState(left.value.Length > right.value.Length ? left : right); var overlappingLength = Math.Min(left.value.Length, right.value.Length); var i = 0; for (; i < overlappingLength; i++) { result.value[i] = op(left.value[i], right.value[i]); } // Continue with the non-overlapping portion. for (; i < result.value.Length; i++) { var leftVal = left.value.Length > i ? left.value[i] : 0; var rightVal = right.value.Length > i ? right.value[i] : 0; result.value[i] = op(leftVal, rightVal); } return result; } } [GrainType("txn-correctness-MaxStateTransactionalGrain")] public class MaxStateTransactionalGrain : MultiStateTransactionalBitArrayGrain { public MaxStateTransactionalGrain(ITransactionalStateFactory stateFactory, ILoggerFactory loggerFactory) : base(Enumerable.Range(0, TransactionTestConstants.MaxCoordinatedTransactions) .Select(i => stateFactory.Create<BitArrayState>(new TransactionalStateConfiguration(new TransactionalStateAttribute($"data{i}", TransactionTestConstants.TransactionStore)))) .ToArray(), loggerFactory) { } } [GrainType("txn-correctness-DoubleStateTransactionalGrain")] public class DoubleStateTransactionalGrain : MultiStateTransactionalBitArrayGrain { public DoubleStateTransactionalGrain( [TransactionalState("data1", TransactionTestConstants.TransactionStore)] ITransactionalState<BitArrayState> data1, [TransactionalState("data2", TransactionTestConstants.TransactionStore)] ITransactionalState<BitArrayState> data2, ILoggerFactory loggerFactory) : base(new ITransactionalState<BitArrayState>[2] { data1, data2 }, loggerFactory) { } } [GrainType("txn-correctness-SingleStateTransactionalGrain")] public class SingleStateTransactionalGrain : MultiStateTransactionalBitArrayGrain { public SingleStateTransactionalGrain( [TransactionalState("data", TransactionTestConstants.TransactionStore)] ITransactionalState<BitArrayState> data, ILoggerFactory loggerFactory) : base(new ITransactionalState<BitArrayState>[1] { data }, loggerFactory) { } } [GrainType("txn-correctness-MultiStateTransactionalBitArrayGrain")] public class MultiStateTransactionalBitArrayGrain : Grain, ITransactionalBitArrayGrain { protected ITransactionalState<BitArrayState>[] dataArray; private readonly ILoggerFactory loggerFactory; protected ILogger logger; public MultiStateTransactionalBitArrayGrain( ITransactionalState<BitArrayState>[] dataArray, ILoggerFactory loggerFactory) { this.dataArray = dataArray; this.loggerFactory = loggerFactory; } public override Task OnActivateAsync(CancellationToken cancellationToken) { this.logger = this.loggerFactory.CreateLogger(this.GetGrainId().ToString()); this.logger.LogTrace($"GrainId : {this.GetPrimaryKey()}."); return base.OnActivateAsync(cancellationToken); } public Task Ping() { return Task.CompletedTask; } public Task SetBit(int index) { return Task.WhenAll(this.dataArray .Select(data => data.PerformUpdate(state => { this.logger.LogTrace($"Setting bit {index} in state {state}. Transaction {TransactionContext.CurrentTransactionId}"); state.Set(index, true); this.logger.LogTrace($"Set bit {index} in state {state}."); }))); } public async Task<List<BitArrayState>> Get() { return (await Task.WhenAll(this.dataArray .Select(state => state.PerformRead(s => { this.logger.LogTrace($"Get state {s}."); return s; })))).ToList(); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using Aurora.DataManager.Migration; using Aurora.Framework; using MySql.Data.MySqlClient; using OpenMetaverse; namespace Aurora.DataManager.MySQL { public class MySQLDataLoader : DataManagerBase { private string m_connectionString = ""; public override string Identifier { get { return "MySQLData"; } } #region Database public override void ConnectToDatabase(string connectionstring, string migratorName, bool validateTables) { m_connectionString = connectionstring; MySqlConnection c = new MySqlConnection(connectionstring); int subStrA = connectionstring.IndexOf("Database="); int subStrB = connectionstring.IndexOf(";", subStrA); string noDatabaseConnector = m_connectionString.Substring(0, subStrA) + m_connectionString.Substring(subStrB+1); retry: try { ExecuteNonQuery(noDatabaseConnector, "create schema IF NOT EXISTS " + c.Database, new Dictionary<string, object>(), false); } catch { MainConsole.Instance.Error("[MySQLDatabase]: We cannot connect to the MySQL instance you have provided. Please make sure it is online, and then press enter to try again."); Console.ReadKey(); goto retry; } var migrationManager = new MigrationManager(this, migratorName, validateTables); migrationManager.DetermineOperation(); migrationManager.ExecuteOperation(); } public void CloseDatabase(MySqlConnection connection) { //Interlocked.Decrement (ref m_locked); //connection.Close(); //connection.Dispose(); } public override void CloseDatabase() { //Interlocked.Decrement (ref m_locked); //m_connection.Close(); //m_connection.Dispose(); } #endregion #region Query public IDataReader Query(string sql, Dictionary<string, object> parameters) { try { MySqlParameter[] param = new MySqlParameter[parameters.Count]; int i = 0; foreach (KeyValuePair<string, object> p in parameters) { param[i] = new MySqlParameter(p.Key, p.Value); i++; } return MySqlHelper.ExecuteReader(m_connectionString, sql, param); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] Query(" + sql + "), " + e); return null; } } public void ExecuteNonQuery(string sql, Dictionary<string, object> parameters) { ExecuteNonQuery(m_connectionString, sql, parameters); } public void ExecuteNonQuery(string connStr, string sql, Dictionary<string, object> parameters) { ExecuteNonQuery(connStr, sql, parameters, true); } public void ExecuteNonQuery(string connStr, string sql, Dictionary<string, object> parameters, bool spamConsole) { try { MySqlParameter[] param = new MySqlParameter[parameters.Count]; int i = 0; foreach (KeyValuePair<string, object> p in parameters) { param[i] = new MySqlParameter(p.Key, p.Value); i++; } MySqlHelper.ExecuteNonQuery(connStr, sql, param); } catch (Exception e) { if (spamConsole) MainConsole.Instance.Error("[MySQLDataLoader] ExecuteNonQuery(" + sql + "), " + e); else throw e; } } public override List<string> QueryFullData(string whereClause, string table, string wantedValue) { string query = String.Format("select {0} from {1} {2}", wantedValue, table, whereClause); return QueryFullData2(query); } public override List<string> QueryFullData(string whereClause, QueryTables tables, string wantedValue) { string query = string.Format("SELECT {0} FROM {1} {2}", wantedValue, tables.ToSQL(), whereClause); return QueryFullData2(query); } private List<string> QueryFullData2(string query) { IDataReader reader = null; List<string> retVal = new List<string>(); try { using (reader = Query(query, new Dictionary<string, object>())) { while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { retVal.Add(reader.GetString(i)); } } return retVal; } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] QueryFullData(" + query + "), " + e); return null; } finally { try { if (reader != null) { reader.Close(); //reader.Dispose (); } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] Query(" + query + "), " + e); } } } public override IDataReader QueryData(string whereClause, string table, string wantedValue) { string query = String.Format("select {0} from {1} {2}", wantedValue, table, whereClause); return QueryData2(query); } public override IDataReader QueryData(string whereClause, QueryTables tables, string wantedValue) { string query = string.Format("SELECT {0} FROM {1} {2}", wantedValue, tables.ToSQL(), whereClause); return QueryData2(query); } private IDataReader QueryData2(string query) { return Query(query, new Dictionary<string, object>()); } public override List<string> Query(string[] wantedValue, string table, QueryFilter queryFilter, Dictionary<string, bool> sort, uint? start, uint? count) { string query = string.Format("SELECT {0} FROM {1}", string.Join(", ", wantedValue), table); return Query2(query, queryFilter, sort, start, count); } public override List<string> Query(string[] wantedValue, QueryTables tables, QueryFilter queryFilter, Dictionary<string, bool> sort, uint? start, uint? count) { string query = string.Format("SELECT {0} FROM {1}", string.Join(", ", wantedValue), tables.ToSQL()); return Query2(query, queryFilter, sort, start, count); } private List<string> Query2(string sqll, QueryFilter queryFilter, Dictionary<string, bool> sort, uint? start, uint? count) { string query = sqll; Dictionary<string, object> ps = new Dictionary<string,object>(); List<string> retVal = new List<string>(); List<string> parts = new List<string>(); if (queryFilter != null && queryFilter.Count > 0) { query += " WHERE " + queryFilter.ToSQL('?', out ps); } if (sort != null && sort.Count > 0) { parts = new List<string>(); foreach (KeyValuePair<string, bool> sortOrder in sort) { parts.Add(string.Format("`{0}` {1}", sortOrder.Key, sortOrder.Value ? "ASC" : "DESC")); } query += " ORDER BY " + string.Join(", ", parts.ToArray()); } if(start.HasValue){ query += " LIMIT " + start.Value.ToString(); if (count.HasValue) { query += ", " + count.Value.ToString(); } } IDataReader reader = null; int i = 0; try { using (reader = Query(query, ps)) { while (reader.Read()) { for (i = 0; i < reader.FieldCount; i++) { Type r = reader[i].GetType(); retVal.Add(r == typeof(DBNull) ? null : reader.GetString(i)); } } return retVal; } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] Query(" + query + "), " + e); return null; } finally { try { if (reader != null) { reader.Close(); //reader.Dispose (); } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] Query(" + query + "), " + e); } } } /*public override Dictionary<string, List<string>> QueryNames(string[] wantedValue, string table, QueryFilter queryFilter, Dictionary<string, bool> sort, uint? start, uint? count) { }*/ public override Dictionary<string, List<string>> QueryNames(string[] keyRow, object[] keyValue, string table, string wantedValue) { string query = String.Format("select {0} from {1} where ", wantedValue, table); return QueryNames2(keyRow, keyValue, query); } public override Dictionary<string, List<string>> QueryNames(string[] keyRow, object[] keyValue, QueryTables tables, string wantedValue) { string query = string.Format("SELECT {0} FROM {1} where ", wantedValue, tables.ToSQL()); return QueryNames2(keyRow, keyValue, query); } private Dictionary<string, List<string>> QueryNames2(string[] keyRow, object[] keyValue, string query) { IDataReader reader = null; Dictionary<string, List<string>> retVal = new Dictionary<string, List<string>>(); Dictionary<string, object> ps = new Dictionary<string, object>(); int i = 0; foreach (object value in keyValue) { query += String.Format("{0} = ?{1} and ", keyRow[i], keyRow[i]); ps["?" + keyRow[i]] = value; i++; } query = query.Remove(query.Length - 5); try { using (reader = Query(query, ps)) { while (reader.Read()) { for (i = 0; i < reader.FieldCount; i++) { Type r = reader[i].GetType(); AddValueToList(ref retVal, reader.GetName(i), r == typeof (DBNull) ? null : reader[i].ToString()); } } return retVal; } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] QueryNames(" + query + "), " + e); return null; } finally { try { if (reader != null) { reader.Close(); //reader.Dispose (); } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] QueryNames(" + query + "), " + e); } } } private void AddValueToList(ref Dictionary<string, List<string>> dic, string key, string value) { if (!dic.ContainsKey(key)) { dic.Add(key, new List<string>()); } dic[key].Add(value); } #endregion #region Update public override bool Update(string table, Dictionary<string, object> values, Dictionary<string, int> incrementValues, QueryFilter queryFilter, uint? start, uint? count) { if ((values == null || values.Count < 1) && (incrementValues == null || incrementValues.Count < 1)) { MainConsole.Instance.Warn("Update attempted with no values"); return false; } string query = string.Format("UPDATE {0}", table); ; Dictionary<string, object> ps = new Dictionary<string, object>(); string filter = ""; if (queryFilter != null && queryFilter.Count > 0) { filter = " WHERE " + queryFilter.ToSQL('?', out ps); } List<string> parts = new List<string>(); if (values != null) { foreach (KeyValuePair<string, object> value in values) { string key = "?updateSet_" + value.Key.Replace("`", ""); ps[key] = value.Value; parts.Add(string.Format("{0} = {1}", value.Key, key)); } } if (incrementValues != null) { foreach (KeyValuePair<string, int> value in incrementValues) { string key = "?updateSet_increment_" + value.Key.Replace("`", ""); ps[key] = value.Value; parts.Add(string.Format("{0} = {0} + {1}", value.Key, key)); } } query += " SET " + string.Join(", ", parts.ToArray()) + filter; if (start.HasValue) { query += " LIMIT " + start.Value.ToString(); if (count.HasValue) { query += ", " + count.Value.ToString(); } } try { ExecuteNonQuery(query, ps); } catch (MySqlException e) { MainConsole.Instance.Error("[MySQLDataLoader] Update(" + query + "), " + e); } return true; } #endregion #region Insert public override bool InsertMultiple(string table, List<object[]> values) { string query = String.Format("insert into {0} select ", table); Dictionary<string, object> parameters = new Dictionary<string, object>(); int i = 0; foreach (object[] value in values) { foreach (object v in value) { parameters[Util.ConvertDecString(i)] = v; query += "?" + Util.ConvertDecString(i++) + ","; } query = query.Remove(query.Length - 1); query += " union all select "; } query = query.Remove(query.Length - (" union all select ").Length); try { ExecuteNonQuery(query, parameters); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] Insert(" + query + "), " + e); } return true; } public override bool Insert(string table, object[] values) { string query = String.Format("insert into {0} values (", table); Dictionary<string, object> parameters = new Dictionary<string, object>(); int i = 0; foreach (object o in values) { parameters[Util.ConvertDecString(i)] = o; query += "?" + Util.ConvertDecString(i++) + ","; } query = query.Remove(query.Length - 1); query += ")"; try { ExecuteNonQuery(query, parameters); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] Insert(" + query + "), " + e); } return true; } private bool InsertOrReplace(string table, Dictionary<string, object> row, bool insert) { string query = (insert ? "INSERT" : "REPLACE") + " INTO " + table + " (" + string.Join(", ", row.Keys.ToArray<string>()) + ")"; Dictionary<string, object> ps = new Dictionary<string, object>(); foreach (KeyValuePair<string, object> field in row) { string key = "?" + field.Key.Replace("`", "").Replace("(", "_").Replace(")", "").Replace(" ", "_").Replace("-", "minus").Replace("+", "add").Replace("/", "divide").Replace("*", "multiply"); ps[key] = field.Value; } query += " VALUES( " + string.Join(", ", ps.Keys.ToArray<string>()) + " )"; try { ExecuteNonQuery(query, ps); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] " + (insert ? "Insert" : "Replace") + "(" + query + "), " + e); } return true; } public override bool Insert(string table, Dictionary<string, object> row) { return InsertOrReplace(table, row, true); } public override bool Insert(string table, object[] values, string updateKey, object updateValue) { string query = String.Format("insert into {0} VALUES(", table); Dictionary<string, object> param = new Dictionary<string, object>(); int i = 0; foreach (object o in values) { param["?" + Util.ConvertDecString(i)] = o; query += "?" + Util.ConvertDecString(i++) + ","; } param["?update"] = updateValue; query = query.Remove(query.Length - 1); query += String.Format(") ON DUPLICATE KEY UPDATE {0} = ?update", updateKey); try { ExecuteNonQuery(query, param); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] Insert(" + query + "), " + e); return false; } return true; } public override bool InsertSelect(string tableA, string[] fieldsA, string tableB, string[] valuesB) { string query = string.Format("INSERT INTO {0}{1} SELECT {2} FROM {3}", tableA, (fieldsA.Length > 0 ? " (" + string.Join(", ", fieldsA) + ")" : ""), string.Join(", ", valuesB), tableB ); try { ExecuteNonQuery(query, new Dictionary<string,object>(0)); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] INSERT .. SELECT (" + query + "), " + e); } return true; } #endregion #region REPLACE INTO public override bool Replace(string table, Dictionary<string, object> row) { return InsertOrReplace(table, row, false); } #endregion #region Delete public override bool DeleteByTime(string table, string key) { QueryFilter filter = new QueryFilter(); filter.andLessThanEqFilters["(UNIX_TIMESTAMP(`" + key.Replace("`","") + "`) - UNIX_TIMESTAMP())"] = 0; return Delete(table, filter); } public override bool Delete(string table, QueryFilter queryFilter) { Dictionary<string, object> ps = new Dictionary<string,object>(); string query = "DELETE FROM " + table + (queryFilter != null ? (" WHERE " + queryFilter.ToSQL('?', out ps)) : ""); try { ExecuteNonQuery(query, ps); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] Delete(" + query + "), " + e); return false; } return true; } #endregion public override string ConCat(string[] toConcat) { #if (!ISWIN) string returnValue = "concat("; foreach (string s in toConcat) returnValue = returnValue + (s + ","); #else string returnValue = toConcat.Aggregate("concat(", (current, s) => current + (s + ",")); #endif return returnValue.Substring(0, returnValue.Length - 1) + ")"; } #region Tables public override void CreateTable(string table, ColumnDefinition[] columns, IndexDefinition[] indices) { table = table.ToLower(); if (TableExists(table)) { throw new DataManagerException("Trying to create a table with name of one that already exists."); } IndexDefinition primary = null; foreach (IndexDefinition index in indices) { if (index.Type == IndexType.Primary) { primary = index; break; } } List<string> columnDefinition = new List<string>(); foreach (ColumnDefinition column in columns) { columnDefinition.Add("`" + column.Name + "` " + GetColumnTypeStringSymbol(column.Type)); } if (primary != null && primary.Fields.Length > 0) { columnDefinition.Add("PRIMARY KEY (`" + string.Join("`, `", primary.Fields) + "`)"); } List<string> indicesQuery = new List<string>(indices.Length); foreach (IndexDefinition index in indices) { string type = "KEY"; switch (index.Type) { case IndexType.Primary: continue; case IndexType.Unique: type = "UNIQUE"; break; case IndexType.Index: default: type = "KEY"; break; } indicesQuery.Add(string.Format("{0}( {1} )", type, "`" + string.Join("`, `", index.Fields) + "`")); } string query = string.Format("create table " + table + " ( {0} {1}) ", string.Join(", ", columnDefinition.ToArray()), indicesQuery.Count > 0 ? ", " + string.Join(", ", indicesQuery.ToArray()) : string.Empty); try { ExecuteNonQuery(query, new Dictionary<string, object>()); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] CreateTable", e); } } public override void UpdateTable(string table, ColumnDefinition[] columns, IndexDefinition[] indices, Dictionary<string, string> renameColumns) { table = table.ToLower(); if (!TableExists(table)) { throw new DataManagerException("Trying to update a table with name of one that does not exist."); } List<ColumnDefinition> oldColumns = ExtractColumnsFromTable(table); Dictionary<string, ColumnDefinition> removedColumns = new Dictionary<string, ColumnDefinition>(); Dictionary<string, ColumnDefinition> modifiedColumns = new Dictionary<string, ColumnDefinition>(); #if (!ISWIN) Dictionary<string, ColumnDefinition> addedColumns = new Dictionary<string, ColumnDefinition>(); foreach (ColumnDefinition column in columns) { if (!oldColumns.Contains(column)) addedColumns.Add(column.Name.ToLower(), column); } foreach (ColumnDefinition column in oldColumns) { if (!columns.Contains(column)) { if (addedColumns.ContainsKey(column.Name.ToLower())) { if (column.Name.ToLower() != addedColumns[column.Name.ToLower()].Name.ToLower() || column.Type != addedColumns[column.Name.ToLower()].Type) { modifiedColumns.Add(column.Name.ToLower(), addedColumns[column.Name.ToLower()]); } addedColumns.Remove(column.Name.ToLower()); } else { removedColumns.Add(column.Name.ToLower(), column); } } } #else Dictionary<string, ColumnDefinition> addedColumns = columns.Where(column => !oldColumns.Contains(column)).ToDictionary(column => column.Name.ToLower()); foreach (ColumnDefinition column in oldColumns.Where(column => !columns.Contains(column))) { if (addedColumns.ContainsKey(column.Name.ToLower())) { if (column.Name.ToLower() != addedColumns[column.Name.ToLower()].Name.ToLower() || column.Type != addedColumns[column.Name.ToLower()].Type) { modifiedColumns.Add(column.Name.ToLower(), addedColumns[column.Name.ToLower()]); } addedColumns.Remove(column.Name.ToLower()); } else{ removedColumns.Add(column.Name.ToLower(), column); } } #endif try { #if (!ISWIN) foreach (ColumnDefinition column in addedColumns.Values) { string addedColumnsQuery = "add `" + column.Name + "` " + GetColumnTypeStringSymbol(column.Type) + " "; string query = string.Format("alter table " + table + " " + addedColumnsQuery); ExecuteNonQuery(query, new Dictionary<string, object>()); } foreach (ColumnDefinition column in modifiedColumns.Values) { string modifiedColumnsQuery = "modify column `" + column.Name + "` " + GetColumnTypeStringSymbol(column.Type) + " "; string query = string.Format("alter table " + table + " " + modifiedColumnsQuery); ExecuteNonQuery(query, new Dictionary<string, object>()); } foreach (ColumnDefinition column in removedColumns.Values) { string droppedColumnsQuery = "drop `" + column.Name + "` "; string query = string.Format("alter table " + table + " " + droppedColumnsQuery); ExecuteNonQuery(query, new Dictionary<string, object>()); } #else foreach (string query in addedColumns.Values.Select(column => "add `" + column.Name + "` " + GetColumnTypeStringSymbol(column.Type) + " ").Select(addedColumnsQuery => string.Format("alter table " + table + " " + addedColumnsQuery))) { ExecuteNonQuery(query, new Dictionary<string, object>()); } foreach (string query in modifiedColumns.Values.Select(column => "modify column `" + column.Name + "` " + GetColumnTypeStringSymbol(column.Type) + " ").Select(modifiedColumnsQuery => string.Format("alter table " + table + " " + modifiedColumnsQuery))) { ExecuteNonQuery(query, new Dictionary<string, object>()); } foreach (string query in removedColumns.Values.Select(column => "drop `" + column.Name + "` ").Select(droppedColumnsQuery => string.Format("alter table " + table + " " + droppedColumnsQuery))) { ExecuteNonQuery(query, new Dictionary<string, object>()); } #endif } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] UpdateTable", e); } Dictionary<string, IndexDefinition> oldIndicesDict = ExtractIndicesFromTable(table); List<string> removeIndices = new List<string>(); List<string> oldIndexNames = new List<string>(oldIndicesDict.Count); List<IndexDefinition> oldIndices = new List<IndexDefinition>(oldIndicesDict.Count); List<IndexDefinition> newIndices = new List<IndexDefinition>(); foreach (KeyValuePair<string, IndexDefinition> oldIndex in oldIndicesDict) { oldIndexNames.Add(oldIndex.Key); oldIndices.Add(oldIndex.Value); } int i=0; foreach(IndexDefinition oldIndex in oldIndices){ bool found = false; foreach (IndexDefinition newIndex in indices) { if (oldIndex.Equals(newIndex)) { found = true; break; } } if (!found) { removeIndices.Add(oldIndexNames[i]); } ++i; } foreach (IndexDefinition newIndex in indices) { bool found = false; foreach (IndexDefinition oldIndex in oldIndices) { if (oldIndex.Equals(newIndex)) { found = true; break; } } if (!found) { newIndices.Add(newIndex); } } foreach (string oldIndex in removeIndices) { ExecuteNonQuery(string.Format("ALTER TABLE `{0}` DROP INDEX `{1}`", table, oldIndex), new Dictionary<string, object>()); } foreach (IndexDefinition newIndex in newIndices) { ExecuteNonQuery(string.Format("ALTER TABLE `{0}` ADD {1} (`{2}`)", table, newIndex.Type == IndexType.Primary ? "PRIMARY KEY" : (newIndex.Type == IndexType.Unique ? "UNIQUE" : "INDEX"), string.Join("`, `", newIndex.Fields)), new Dictionary<string,object>()); } } public override string GetColumnTypeStringSymbol(ColumnTypes type) { switch (type) { case ColumnTypes.Double: return "DOUBLE"; case ColumnTypes.Integer11: return "int(11)"; case ColumnTypes.Integer30: return "int(30)"; case ColumnTypes.UInteger11: return "INT(11) UNSIGNED"; case ColumnTypes.UInteger30: return "INT(30) UNSIGNED"; case ColumnTypes.Char36: return "char(36)"; case ColumnTypes.Char32: return "char(32)"; case ColumnTypes.Char5: return "char(5)"; case ColumnTypes.String: return "TEXT"; case ColumnTypes.String1: return "VARCHAR(1)"; case ColumnTypes.String2: return "VARCHAR(2)"; case ColumnTypes.String10: return "VARCHAR(10)"; case ColumnTypes.String16: return "VARCHAR(16)"; case ColumnTypes.String30: return "VARCHAR(30)"; case ColumnTypes.String32: return "VARCHAR(32)"; case ColumnTypes.String36: return "VARCHAR(36)"; case ColumnTypes.String45: return "VARCHAR(45)"; case ColumnTypes.String50: return "VARCHAR(50)"; case ColumnTypes.String64: return "VARCHAR(64)"; case ColumnTypes.String128: return "VARCHAR(128)"; case ColumnTypes.String100: return "VARCHAR(100)"; case ColumnTypes.String255: return "VARCHAR(255)"; case ColumnTypes.String512: return "VARCHAR(512)"; case ColumnTypes.String1024: return "VARCHAR(1024)"; case ColumnTypes.String8196: return "VARCHAR(8196)"; case ColumnTypes.Text: return "TEXT"; case ColumnTypes.MediumText: return "MEDIUMTEXT"; case ColumnTypes.LongText: return "LONGTEXT"; case ColumnTypes.Blob: return "blob"; case ColumnTypes.LongBlob: return "longblob"; case ColumnTypes.Date: return "DATE"; case ColumnTypes.DateTime: return "DATETIME"; case ColumnTypes.Float: return "float"; case ColumnTypes.TinyInt1: return "TINYINT(1)"; case ColumnTypes.TinyInt4: return "TINYINT(4)"; default: throw new DataManagerException("Unknown column type."); } } public override string GetColumnTypeStringSymbol(ColumnTypeDef coldef) { string symbol; switch (coldef.Type) { case ColumnType.Blob: symbol = "BLOB"; break; case ColumnType.LongBlob: symbol = "LONGBLOB"; break; case ColumnType.Boolean: symbol = "TINYINT(1)"; break; case ColumnType.Char: symbol = "CHAR(" + coldef.Size + ")"; break; case ColumnType.Date: symbol = "DATE"; break; case ColumnType.DateTime: symbol = "DATETIME"; break; case ColumnType.Double: symbol = "DOUBLE"; break; case ColumnType.Float: symbol = "FLOAT"; break; case ColumnType.Integer: symbol = "INT(" + coldef.Size + ")" + (coldef.unsigned ? " unsigned" : ""); break; case ColumnType.TinyInt: symbol = "TINYINT(" + coldef.Size + ")" + (coldef.unsigned ? " unsigned" : ""); break; case ColumnType.String: symbol = "VARCHAR(" + coldef.Size + ")"; break; case ColumnType.Text: symbol = "TEXT"; break; case ColumnType.MediumText: symbol = "MEDIUMTEXT"; break; case ColumnType.LongText: symbol = "LONGTEXT"; break; case ColumnType.UUID: symbol = "CHAR(36)"; break; default: throw new DataManagerException("Unknown column type."); } return symbol + (coldef.isNull ? " NULL" : " NOT NULL") + ((coldef.isNull && coldef.defaultValue == null) ? " DEFAULT NULL" : (coldef.defaultValue != null ? " DEFAULT '" + coldef.defaultValue.MySqlEscape() + "'" : "")) + ((coldef.Type == ColumnType.Integer || coldef.Type == ColumnType.TinyInt) && coldef.auto_increment ? " AUTO_INCREMENT" : ""); } public override void DropTable(string tableName) { tableName = tableName.ToLower(); try { ExecuteNonQuery(string.Format("drop table {0}", tableName), new Dictionary<string, object>()); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] DropTable", e); } } public override void ForceRenameTable(string oldTableName, string newTableName) { newTableName = newTableName.ToLower(); try { ExecuteNonQuery(string.Format("RENAME TABLE {0} TO {1}", oldTableName, newTableName), new Dictionary<string, object>()); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] ForceRenameTable", e); } } protected override void CopyAllDataBetweenMatchingTables(string sourceTableName, string destinationTableName, ColumnDefinition[] columnDefinitions, IndexDefinition[] indexDefinitions) { sourceTableName = sourceTableName.ToLower(); destinationTableName = destinationTableName.ToLower(); try { ExecuteNonQuery(string.Format("insert into {0} select * from {1}", destinationTableName, sourceTableName), new Dictionary<string, object>()); } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] CopyAllDataBetweenMatchingTables", e); } } public override bool TableExists(string table) { IDataReader reader = null; List<string> retVal = new List<string>(); try { using (reader = Query("show tables", new Dictionary<string, object>())) { while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { retVal.Add(reader.GetString(i).ToLower()); } } } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] TableExists", e); } finally { try { if (reader != null) { reader.Close(); //reader.Dispose (); } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] TableExists", e); } } return retVal.Contains(table.ToLower()); } protected override List<ColumnDefinition> ExtractColumnsFromTable(string tableName) { var defs = new List<ColumnDefinition>(); tableName = tableName.ToLower(); IDataReader rdr = null; try { rdr = Query(string.Format("desc {0}", tableName), new Dictionary<string, object>()); while (rdr.Read()) { var name = rdr["Field"]; //var pk = rdr["Key"]; var type = rdr["Type"]; //var extra = rdr["Extra"]; object defaultValue = rdr["Default"]; ColumnTypeDef typeDef = ConvertTypeToColumnType(type.ToString()); typeDef.isNull = rdr["Null"].ToString() == "YES"; typeDef.auto_increment = rdr["Extra"].ToString().IndexOf("auto_increment") >= 0; typeDef.defaultValue = defaultValue.GetType() == typeof(System.DBNull) ? null : defaultValue.ToString(); defs.Add(new ColumnDefinition { Name = name.ToString(), Type = typeDef, }); } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] ExtractColumnsFromTable", e); } finally { try { if (rdr != null) { rdr.Close(); //rdr.Dispose (); } } catch (Exception e) { MainConsole.Instance.Debug("[MySQLDataLoader] ExtractColumnsFromTable", e); } } return defs; } protected override Dictionary<string, IndexDefinition> ExtractIndicesFromTable(string tableName) { Dictionary<string, IndexDefinition> defs = new Dictionary<string, IndexDefinition>(); tableName = tableName.ToLower(); IDataReader rdr = null; Dictionary<string, Dictionary<uint, string>> indexLookup = new Dictionary<string, Dictionary<uint, string>>(); Dictionary<string, bool> indexIsUnique = new Dictionary<string,bool>(); try { rdr = Query(string.Format("SHOW INDEX IN {0}", tableName), new Dictionary<string, object>()); while (rdr.Read()) { string name = rdr["Column_name"].ToString(); bool unique = uint.Parse(rdr["Non_unique"].ToString()) == 0; string index = rdr["Key_name"].ToString(); uint sequence = uint.Parse(rdr["Seq_in_index"].ToString()); if (indexLookup.ContainsKey(index) == false) { indexLookup[index] = new Dictionary<uint, string>(); } indexIsUnique[index] = unique; indexLookup[index][sequence - 1] = name; } } catch (Exception e) { MainConsole.Instance.Error("[MySQLDataLoader] ExtractIndicesFromTable", e); } finally { try { if (rdr != null) { rdr.Close(); } } catch (Exception e) { MainConsole.Instance.Debug("[MySQLDataLoader] ExtractIndicesFromTable", e); } } foreach (KeyValuePair<string, Dictionary<uint, string>> index in indexLookup) { index.Value.OrderBy(x=>x.Key); defs[index.Key] = new IndexDefinition { Fields = index.Value.Values.ToArray<string>(), Type = (indexIsUnique[index.Key] ? (index.Key == "PRIMARY" ? IndexType.Primary : IndexType.Unique) : IndexType.Index) }; } return defs; } #endregion public override IGenericData Copy() { return new MySQLDataLoader(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Byte : IComparable, IConvertible, IFormattable, IComparable<byte>, IEquatable<byte>, ISpanFormattable { private readonly byte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; // The minimum value that a Byte may represent: 0. public const byte MinValue = 0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type byte, this method throws an ArgumentException. // public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is byte)) { throw new ArgumentException(SR.Arg_MustBeByte); } return m_value - (((byte)value).m_value); } public int CompareTo(byte value) { return m_value - value; } // Determines whether two Byte objects are equal. public override bool Equals(object? obj) { if (!(obj is byte)) { return false; } return m_value == ((byte)obj).m_value; } [NonVersionable] public bool Equals(byte obj) { return m_value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return m_value; } public static byte Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static byte Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.CurrentInfo); } public static byte Parse(string s, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an unsigned byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. public static byte Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider)); } public static byte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static byte Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { Number.ParsingStatus status = Number.TryParseUInt32(s, style, info, out uint i); if (status != Number.ParsingStatus.OK) { Number.ThrowOverflowOrFormatException(status, TypeCode.Byte); } if (i > MaxValue) Number.ThrowOverflowException(TypeCode.Byte); return (byte)i; } public static bool TryParse(string? s, out byte result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out byte result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out byte result) { if (Number.TryParseUInt32(s, style, info, out uint i) != Number.ParsingStatus.OK || i > MaxValue) { result = 0; return false; } result = (byte)i; return true; } public override string ToString() { return Number.FormatUInt32(m_value, null, null); } public string ToString(string? format) { return Number.FormatUInt32(m_value, format, null); } public string ToString(IFormatProvider? provider) { return Number.FormatUInt32(m_value, null, provider); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatUInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null) { return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Byte; } bool IConvertible.ToBoolean(IFormatProvider? provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider? provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider? provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider? provider) { return m_value; } short IConvertible.ToInt16(IFormatProvider? provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider? provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider? provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider? provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider? provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider? provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider? provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider? provider) { return Convert.ToDouble(m_value); } decimal IConvertible.ToDecimal(IFormatProvider? provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
//* Bobo Browse Engine - High performance faceted/parametric search implementation //* that handles various types of semi-structured data. Originally written in Java. //* //* Ported and adapted for C# by Shad Storhaug, Alexey Shcherbachev, and zhengchun. //* //* Copyright (C) 2005-2015 John Wang //* //* 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. // Version compatibility level: 4.0.2 namespace BoboBrowse.Net.Facets.Data { using BoboBrowse.Net.Support; using System; using System.Globalization; /// <summary> /// NOTE: This was TermLongList in bobo-browse /// </summary> public class TermInt64List : TermNumberList<long> { protected long[] m_elements; private bool m_withDummy = true; public const long VALUE_MISSING = long.MinValue; protected virtual long Parse(string s) { if (s == null || s.Length == 0) { return 0; } else { try { // Since this value is stored in a file, we should always store it and parse it with the invariant culture. long result; if (!long.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out result)) { // If the invariant culture doesn't work, fall back to the passed in format provider // if the provider is null, this will use the culture of the current thread by default. result = long.Parse(s, NumberStyles.Any, this.FormatProvider); } return result; } catch (Exception ex) { if (NumericUtil.IsPrefixCodedInt64(s)) { throw new NotSupportedException("Lucene.Net index field must be a formatted string data type (typically padded with leading zeros). NumericField (INT64) is not supported.", ex); } throw ex; } } } public TermInt64List() : base() { } public TermInt64List(string formatString) : base(formatString) { } public TermInt64List(string formatString, IFormatProvider formatProvider) : base(formatString, formatProvider) { } public TermInt64List(int capacity, string formatString) : base(capacity, formatString) { } public TermInt64List(int capacity, string formatString, IFormatProvider formatProvider) : base(capacity, formatString, formatProvider) { } public override void Add(string o) { if (m_innerList.Count == 0 && o != null) m_withDummy = false; // the first value added is not null long item = Parse(o); m_innerList.Add(item); } public override void Clear() { base.Clear(); } public override string Get(int index) { return this[index]; } public override string this[int index]// From IList<string> { get { if (index < m_innerList.Count) { long val = m_elements[index]; if (m_withDummy && index == 0) { val = 0L; } if (!string.IsNullOrEmpty(this.FormatString)) { return val.ToString(this.FormatString, this.FormatProvider); } return val.ToString(); } return ""; } set { throw new NotSupportedException("not supported"); } } public virtual long GetPrimitiveValue(int index) { if (index < m_elements.Length) return m_elements[index]; else return VALUE_MISSING; } public override int IndexOf(object o) { if (m_withDummy) { if (o == null) return -1; long val; if (o is string) val = Parse((string)o); else val = (long)o; return Array.BinarySearch(m_elements, 1, m_elements.Length - 1, val); } else { if (o == null) return -1; long val; if (o is string) val = Parse((string)o); else val = (long)o; return Array.BinarySearch(m_elements, val); } } public virtual int IndexOf(long value) { if (m_withDummy) return Array.BinarySearch(m_elements, 1, m_elements.Length - 1, value); else return Array.BinarySearch(m_elements, value); } public override int IndexOfWithType(long value) { if (m_withDummy) return Array.BinarySearch(m_elements, 1, m_elements.Length - 1, value); else return Array.BinarySearch(m_elements, value); } public override void Seal() { m_innerList.TrimExcess(); m_elements = m_innerList.ToArray(); int negativeIndexCheck = m_withDummy ? 1 : 0; //reverse negative elements, because string order and numeric orders are completely opposite if (m_elements.Length > negativeIndexCheck && m_elements[negativeIndexCheck] < 0) { int endPosition = IndexOfWithType(0L); if (endPosition < 0) { endPosition = -1 * endPosition - 1; } long tmp; for (int i = 0; i < (endPosition - negativeIndexCheck) / 2; i++) { tmp = m_elements[i + negativeIndexCheck]; m_elements[i + negativeIndexCheck] = m_elements[endPosition - i - 1]; m_elements[endPosition - i - 1] = tmp; } } } protected override object ParseString(string o) { return Parse(o); } public virtual bool Contains(long val) { if (m_withDummy) return Array.BinarySearch(m_elements, 1, m_elements.Length - 1, val) >= 0; else return Array.BinarySearch(m_elements, val) >= 0; } public override bool ContainsWithType(long val) { if (m_withDummy) return Array.BinarySearch(m_elements, 1, m_elements.Length - 1, val) >= 0; else return Array.BinarySearch(m_elements, val) >= 0; } public virtual long[] Elements { get { return m_elements; } } public override double GetDoubleValue(int index) { return m_elements[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. using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; namespace Microsoft.SqlServer.Server { // Utilities for manipulating smi-related metadata. // // Since this class is built on top of SMI, SMI should not have a dependency on this class // // These are all based off of knowing the clr type of the value // as an ExtendedClrTypeCode enum for rapid access. internal class MetaDataUtilsSmi { internal const SqlDbType InvalidSqlDbType = (SqlDbType)(-1); internal const long InvalidMaxLength = -2; // Standard type inference map to get SqlDbType when all you know is the value's type (typecode) // This map's index is off by one (add one to typecode locate correct entry) in order // to support ExtendedSqlDbType.Invalid // This array is meant to be accessed from InferSqlDbTypeFromTypeCode. private static readonly SqlDbType[] s_extendedTypeCodeToSqlDbTypeMap = { InvalidSqlDbType, // Invalid extended type code SqlDbType.Bit, // System.Boolean SqlDbType.TinyInt, // System.Byte SqlDbType.NVarChar, // System.Char SqlDbType.DateTime, // System.DateTime InvalidSqlDbType, // System.DBNull doesn't have an inferable SqlDbType SqlDbType.Decimal, // System.Decimal SqlDbType.Float, // System.Double InvalidSqlDbType, // null reference doesn't have an inferable SqlDbType SqlDbType.SmallInt, // System.Int16 SqlDbType.Int, // System.Int32 SqlDbType.BigInt, // System.Int64 InvalidSqlDbType, // System.SByte doesn't have an inferable SqlDbType SqlDbType.Real, // System.Single SqlDbType.NVarChar, // System.String InvalidSqlDbType, // System.UInt16 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.UInt32 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.UInt64 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.Object doesn't have an inferable SqlDbType SqlDbType.VarBinary, // System.ByteArray SqlDbType.NVarChar, // System.CharArray SqlDbType.UniqueIdentifier, // System.Guid SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBinary SqlDbType.Bit, // System.Data.SqlTypes.SqlBoolean SqlDbType.TinyInt, // System.Data.SqlTypes.SqlByte SqlDbType.DateTime, // System.Data.SqlTypes.SqlDateTime SqlDbType.Float, // System.Data.SqlTypes.SqlDouble SqlDbType.UniqueIdentifier, // System.Data.SqlTypes.SqlGuid SqlDbType.SmallInt, // System.Data.SqlTypes.SqlInt16 SqlDbType.Int, // System.Data.SqlTypes.SqlInt32 SqlDbType.BigInt, // System.Data.SqlTypes.SqlInt64 SqlDbType.Money, // System.Data.SqlTypes.SqlMoney SqlDbType.Decimal, // System.Data.SqlTypes.SqlDecimal SqlDbType.Real, // System.Data.SqlTypes.SqlSingle SqlDbType.NVarChar, // System.Data.SqlTypes.SqlString SqlDbType.NVarChar, // System.Data.SqlTypes.SqlChars SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBytes SqlDbType.Xml, // System.Data.SqlTypes.SqlXml SqlDbType.Structured, // System.Data.DataTable SqlDbType.Structured, // System.Collections.IEnumerable, used for TVPs it must return IDataRecord SqlDbType.Structured, // System.Collections.Generic.IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord> SqlDbType.Time, // System.TimeSpan SqlDbType.DateTimeOffset, // System.DateTimeOffset }; // Dictionary to map from clr type object to ExtendedClrTypeCodeMap enum. // This dictionary should only be accessed from DetermineExtendedTypeCode and class ctor for setup. private static readonly Dictionary<Type, ExtendedClrTypeCode> s_typeToExtendedTypeCodeMap = CreateTypeToExtendedTypeCodeMap(); private static Dictionary<Type, ExtendedClrTypeCode> CreateTypeToExtendedTypeCodeMap() { int Count = 42; // Keep this initialization list in the same order as ExtendedClrTypeCode for ease in validating! var dictionary = new Dictionary<Type, ExtendedClrTypeCode>(Count) { { typeof(bool), ExtendedClrTypeCode.Boolean }, { typeof(byte), ExtendedClrTypeCode.Byte }, { typeof(char), ExtendedClrTypeCode.Char }, { typeof(DateTime), ExtendedClrTypeCode.DateTime }, { typeof(DBNull), ExtendedClrTypeCode.DBNull }, { typeof(decimal), ExtendedClrTypeCode.Decimal }, { typeof(double), ExtendedClrTypeCode.Double }, // lookup code will handle special-case null-ref, omitting the addition of ExtendedTypeCode.Empty { typeof(short), ExtendedClrTypeCode.Int16 }, { typeof(int), ExtendedClrTypeCode.Int32 }, { typeof(long), ExtendedClrTypeCode.Int64 }, { typeof(sbyte), ExtendedClrTypeCode.SByte }, { typeof(float), ExtendedClrTypeCode.Single }, { typeof(string), ExtendedClrTypeCode.String }, { typeof(ushort), ExtendedClrTypeCode.UInt16 }, { typeof(uint), ExtendedClrTypeCode.UInt32 }, { typeof(ulong), ExtendedClrTypeCode.UInt64 }, { typeof(object), ExtendedClrTypeCode.Object }, { typeof(byte[]), ExtendedClrTypeCode.ByteArray }, { typeof(char[]), ExtendedClrTypeCode.CharArray }, { typeof(Guid), ExtendedClrTypeCode.Guid }, { typeof(SqlBinary), ExtendedClrTypeCode.SqlBinary }, { typeof(SqlBoolean), ExtendedClrTypeCode.SqlBoolean }, { typeof(SqlByte), ExtendedClrTypeCode.SqlByte }, { typeof(SqlDateTime), ExtendedClrTypeCode.SqlDateTime }, { typeof(SqlDouble), ExtendedClrTypeCode.SqlDouble }, { typeof(SqlGuid), ExtendedClrTypeCode.SqlGuid }, { typeof(SqlInt16), ExtendedClrTypeCode.SqlInt16 }, { typeof(SqlInt32), ExtendedClrTypeCode.SqlInt32 }, { typeof(SqlInt64), ExtendedClrTypeCode.SqlInt64 }, { typeof(SqlMoney), ExtendedClrTypeCode.SqlMoney }, { typeof(SqlDecimal), ExtendedClrTypeCode.SqlDecimal }, { typeof(SqlSingle), ExtendedClrTypeCode.SqlSingle }, { typeof(SqlString), ExtendedClrTypeCode.SqlString }, { typeof(SqlChars), ExtendedClrTypeCode.SqlChars }, { typeof(SqlBytes), ExtendedClrTypeCode.SqlBytes }, { typeof(SqlXml), ExtendedClrTypeCode.SqlXml }, { typeof(DataTable), ExtendedClrTypeCode.DataTable }, { typeof(DbDataReader), ExtendedClrTypeCode.DbDataReader }, { typeof(IEnumerable<SqlDataRecord>), ExtendedClrTypeCode.IEnumerableOfSqlDataRecord }, { typeof(TimeSpan), ExtendedClrTypeCode.TimeSpan }, { typeof(DateTimeOffset), ExtendedClrTypeCode.DateTimeOffset }, }; return dictionary; } internal static bool IsCharOrXmlType(SqlDbType type) { return IsUnicodeType(type) || IsAnsiType(type) || type == SqlDbType.Xml; } internal static bool IsUnicodeType(SqlDbType type) { return type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText; } internal static bool IsAnsiType(SqlDbType type) { return type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text; } internal static bool IsBinaryType(SqlDbType type) { return type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Image; } // Does this type use PLP format values? internal static bool IsPlpFormat(SmiMetaData metaData) { return metaData.MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator || metaData.SqlDbType == SqlDbType.Image || metaData.SqlDbType == SqlDbType.NText || metaData.SqlDbType == SqlDbType.Text || metaData.SqlDbType == SqlDbType.Udt; } // If we know we're only going to use this object to assign to a specific SqlDbType back end object, // we can save some processing time by only checking for the few valid types that can be assigned to the dbType. // This assumes a switch statement over SqlDbType is faster than getting the ClrTypeCode and iterating over a // series of if statements, or using a hash table. // NOTE: the form of these checks is taking advantage of a feature of the JIT compiler that is supposed to // optimize checks of the form '(xxx.GetType() == typeof( YYY ))'. The JIT team claimed at one point that // this doesn't even instantiate a Type instance, thus was the fastest method for individual comparisons. // Given that there's a known SqlDbType, thus a minimal number of comparisons, it's likely this is faster // than the other approaches considered (both GetType().GetTypeCode() switch and hash table using Type keys // must instantiate a Type object. The typecode switch also degenerates into a large if-then-else for // all but the primitive clr types. internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType( SqlDbType dbType, bool isMultiValued, object value ) { ExtendedClrTypeCode extendedCode = ExtendedClrTypeCode.Invalid; // fast-track null, which is valid for all types if (null == value) { extendedCode = ExtendedClrTypeCode.Empty; } else if (DBNull.Value == value) { extendedCode = ExtendedClrTypeCode.DBNull; } else { switch (dbType) { case SqlDbType.BigInt: if (value.GetType() == typeof(Int64)) extendedCode = ExtendedClrTypeCode.Int64; else if (value.GetType() == typeof(SqlInt64)) extendedCode = ExtendedClrTypeCode.SqlInt64; break; case SqlDbType.Binary: case SqlDbType.VarBinary: case SqlDbType.Image: case SqlDbType.Timestamp: if (value.GetType() == typeof(byte[])) extendedCode = ExtendedClrTypeCode.ByteArray; else if (value.GetType() == typeof(SqlBinary)) extendedCode = ExtendedClrTypeCode.SqlBinary; else if (value.GetType() == typeof(SqlBytes)) extendedCode = ExtendedClrTypeCode.SqlBytes; else if (value.GetType() == typeof(StreamDataFeed)) extendedCode = ExtendedClrTypeCode.Stream; break; case SqlDbType.Bit: if (value.GetType() == typeof(bool)) extendedCode = ExtendedClrTypeCode.Boolean; else if (value.GetType() == typeof(SqlBoolean)) extendedCode = ExtendedClrTypeCode.SqlBoolean; break; case SqlDbType.Char: case SqlDbType.NChar: case SqlDbType.NText: case SqlDbType.NVarChar: case SqlDbType.Text: case SqlDbType.VarChar: if (value.GetType() == typeof(string)) extendedCode = ExtendedClrTypeCode.String; if (value.GetType() == typeof(TextDataFeed)) extendedCode = ExtendedClrTypeCode.TextReader; else if (value.GetType() == typeof(SqlString)) extendedCode = ExtendedClrTypeCode.SqlString; else if (value.GetType() == typeof(char[])) extendedCode = ExtendedClrTypeCode.CharArray; else if (value.GetType() == typeof(SqlChars)) extendedCode = ExtendedClrTypeCode.SqlChars; else if (value.GetType() == typeof(char)) extendedCode = ExtendedClrTypeCode.Char; break; case SqlDbType.Date: case SqlDbType.DateTime2: case SqlDbType.DateTime: case SqlDbType.SmallDateTime: if (value.GetType() == typeof(DateTime)) extendedCode = ExtendedClrTypeCode.DateTime; else if (value.GetType() == typeof(SqlDateTime)) extendedCode = ExtendedClrTypeCode.SqlDateTime; break; case SqlDbType.Decimal: if (value.GetType() == typeof(Decimal)) extendedCode = ExtendedClrTypeCode.Decimal; else if (value.GetType() == typeof(SqlDecimal)) extendedCode = ExtendedClrTypeCode.SqlDecimal; break; case SqlDbType.Real: if (value.GetType() == typeof(Single)) extendedCode = ExtendedClrTypeCode.Single; else if (value.GetType() == typeof(SqlSingle)) extendedCode = ExtendedClrTypeCode.SqlSingle; break; case SqlDbType.Int: if (value.GetType() == typeof(Int32)) extendedCode = ExtendedClrTypeCode.Int32; else if (value.GetType() == typeof(SqlInt32)) extendedCode = ExtendedClrTypeCode.SqlInt32; break; case SqlDbType.Money: case SqlDbType.SmallMoney: if (value.GetType() == typeof(SqlMoney)) extendedCode = ExtendedClrTypeCode.SqlMoney; else if (value.GetType() == typeof(Decimal)) extendedCode = ExtendedClrTypeCode.Decimal; break; case SqlDbType.Float: if (value.GetType() == typeof(SqlDouble)) extendedCode = ExtendedClrTypeCode.SqlDouble; else if (value.GetType() == typeof(Double)) extendedCode = ExtendedClrTypeCode.Double; break; case SqlDbType.UniqueIdentifier: if (value.GetType() == typeof(SqlGuid)) extendedCode = ExtendedClrTypeCode.SqlGuid; else if (value.GetType() == typeof(Guid)) extendedCode = ExtendedClrTypeCode.Guid; break; case SqlDbType.SmallInt: if (value.GetType() == typeof(Int16)) extendedCode = ExtendedClrTypeCode.Int16; else if (value.GetType() == typeof(SqlInt16)) extendedCode = ExtendedClrTypeCode.SqlInt16; break; case SqlDbType.TinyInt: if (value.GetType() == typeof(Byte)) extendedCode = ExtendedClrTypeCode.Byte; else if (value.GetType() == typeof(SqlByte)) extendedCode = ExtendedClrTypeCode.SqlByte; break; case SqlDbType.Variant: // SqlDbType doesn't help us here, call general-purpose function extendedCode = DetermineExtendedTypeCode(value); // Some types aren't allowed for Variants but are for the general-purpose function. // Match behavior of other types and return invalid in these cases. if (ExtendedClrTypeCode.SqlXml == extendedCode) { extendedCode = ExtendedClrTypeCode.Invalid; } break; case SqlDbType.Udt: throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); case SqlDbType.Time: if (value.GetType() == typeof(TimeSpan)) extendedCode = ExtendedClrTypeCode.TimeSpan; break; case SqlDbType.DateTimeOffset: if (value.GetType() == typeof(DateTimeOffset)) extendedCode = ExtendedClrTypeCode.DateTimeOffset; break; case SqlDbType.Xml: if (value.GetType() == typeof(SqlXml)) extendedCode = ExtendedClrTypeCode.SqlXml; if (value.GetType() == typeof(XmlDataFeed)) extendedCode = ExtendedClrTypeCode.XmlReader; else if (value.GetType() == typeof(System.String)) extendedCode = ExtendedClrTypeCode.String; break; case SqlDbType.Structured: if (isMultiValued) { if (value is DataTable) { extendedCode = ExtendedClrTypeCode.DataTable; } else if (value is IEnumerable<SqlDataRecord>) { extendedCode = ExtendedClrTypeCode.IEnumerableOfSqlDataRecord; } else if (value is DbDataReader) { extendedCode = ExtendedClrTypeCode.DbDataReader; } } break; default: // Leave as invalid break; } } return extendedCode; } // Method to map from Type to ExtendedTypeCode internal static ExtendedClrTypeCode DetermineExtendedTypeCodeFromType(Type clrType) { ExtendedClrTypeCode resultCode; return s_typeToExtendedTypeCodeMap.TryGetValue(clrType, out resultCode) ? resultCode : ExtendedClrTypeCode.Invalid; } // Returns the ExtendedClrTypeCode that describes the given value internal static ExtendedClrTypeCode DetermineExtendedTypeCode(object value) { return value != null ? DetermineExtendedTypeCodeFromType(value.GetType()) : ExtendedClrTypeCode.Empty; } // returns a sqldbtype for the given type code internal static SqlDbType InferSqlDbTypeFromTypeCode(ExtendedClrTypeCode typeCode) { Debug.Assert(typeCode >= ExtendedClrTypeCode.Invalid && typeCode <= ExtendedClrTypeCode.Last, "Someone added a typecode without adding support here!"); return s_extendedTypeCodeToSqlDbTypeMap[(int)typeCode + 1]; } // Infer SqlDbType from Type in the general case. Katmai-only (or later) features that need to // infer types should use InferSqlDbTypeFromType_Katmai. internal static SqlDbType InferSqlDbTypeFromType(Type type) { ExtendedClrTypeCode typeCode = DetermineExtendedTypeCodeFromType(type); SqlDbType returnType; if (ExtendedClrTypeCode.Invalid == typeCode) { returnType = InvalidSqlDbType; // Return invalid type so caller can generate specific error } else { returnType = InferSqlDbTypeFromTypeCode(typeCode); } return returnType; } // Inference rules changed for Katmai-or-later-only cases. Only features that are guaranteed to be // running against Katmai and don't have backward compat issues should call this code path. // example: TVP's are a new Katmai feature (no back compat issues) so can infer DATETIME2 // when mapping System.DateTime from DateTable or DbDataReader. DATETIME2 is better because // of greater range that can handle all DateTime values. internal static SqlDbType InferSqlDbTypeFromType_Katmai(Type type) { SqlDbType returnType = InferSqlDbTypeFromType(type); if (SqlDbType.DateTime == returnType) { returnType = SqlDbType.DateTime2; } return returnType; } internal static SqlMetaData SmiExtendedMetaDataToSqlMetaData(SmiExtendedMetaData source) { if (SqlDbType.Xml == source.SqlDbType) { return new SqlMetaData(source.Name, source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, source.TypeSpecificNamePart1, source.TypeSpecificNamePart2, source.TypeSpecificNamePart3, true ); } return new SqlMetaData(source.Name, source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, null); } // Convert SqlMetaData instance to an SmiExtendedMetaData instance. internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData(SqlMetaData source) { // now map everything across to the extended metadata object string typeSpecificNamePart1 = null; string typeSpecificNamePart2 = null; string typeSpecificNamePart3 = null; if (SqlDbType.Xml == source.SqlDbType) { typeSpecificNamePart1 = source.XmlSchemaCollectionDatabase; typeSpecificNamePart2 = source.XmlSchemaCollectionOwningSchema; typeSpecificNamePart3 = source.XmlSchemaCollectionName; } else if (SqlDbType.Udt == source.SqlDbType) { throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); } return new SmiExtendedMetaData(source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, source.Name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3); } // compare SmiMetaData to SqlMetaData and determine if they are compatible. internal static bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd) { return firstMd.SqlDbType == secondMd.SqlDbType && firstMd.MaxLength == secondMd.MaxLength && firstMd.Precision == secondMd.Precision && firstMd.Scale == secondMd.Scale && firstMd.CompareOptions == secondMd.CompareOptions && firstMd.LocaleId == secondMd.LocaleId && firstMd.SqlDbType != SqlDbType.Structured && // SqlMetaData doesn't support Structured types !firstMd.IsMultiValued; // SqlMetaData doesn't have a "multivalued" option } // Extract metadata for a single DataColumn internal static SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, DataTable parent) { SqlDbType dbType = InferSqlDbTypeFromType_Katmai(column.DataType); if (InvalidSqlDbType == dbType) { throw SQL.UnsupportedColumnTypeForSqlProvider(column.ColumnName, column.DataType.Name); } long maxLength = AdjustMaxLength(dbType, column.MaxLength); if (InvalidMaxLength == maxLength) { throw SQL.InvalidColumnMaxLength(column.ColumnName, maxLength); } byte precision; byte scale; if (column.DataType == typeof(SqlDecimal)) { // Must scan all values in column to determine best-fit precision & scale Debug.Assert(null != parent); scale = 0; byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision foreach (DataRow row in parent.Rows) { object obj = row[column]; if (!(obj is DBNull)) { SqlDecimal value = (SqlDecimal)obj; if (!value.IsNull) { byte tempNonFractPrec = checked((byte)(value.Precision - value.Scale)); if (tempNonFractPrec > nonFractionalPrecision) { nonFractionalPrecision = tempNonFractPrec; } if (value.Scale > scale) { scale = value.Scale; } } } } precision = checked((byte)(nonFractionalPrecision + scale)); if (SqlDecimal.MaxPrecision < precision) { throw SQL.InvalidTableDerivedPrecisionForTvp(column.ColumnName, precision); } else if (0 == precision) { precision = 1; } } else if (dbType == SqlDbType.DateTime2 || dbType == SqlDbType.DateTimeOffset || dbType == SqlDbType.Time) { // Time types care about scale, too. But have to infer maximums for these. precision = 0; scale = SmiMetaData.DefaultTime.Scale; } else if (dbType == SqlDbType.Decimal) { // Must scan all values in column to determine best-fit precision & scale Debug.Assert(null != parent); scale = 0; byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision foreach (DataRow row in parent.Rows) { object obj = row[column]; if (!(obj is DBNull)) { SqlDecimal value = (SqlDecimal)(Decimal)obj; byte tempNonFractPrec = checked((byte)(value.Precision - value.Scale)); if (tempNonFractPrec > nonFractionalPrecision) { nonFractionalPrecision = tempNonFractPrec; } if (value.Scale > scale) { scale = value.Scale; } } } precision = checked((byte)(nonFractionalPrecision + scale)); if (SqlDecimal.MaxPrecision < precision) { throw SQL.InvalidTableDerivedPrecisionForTvp(column.ColumnName, precision); } else if (0 == precision) { precision = 1; } } else { precision = 0; scale = 0; } // In Net Core, since DataColumn.Locale is not accessible because it is internal and in a separate assembly, // we try to get the Locale from the parent CultureInfo columnLocale = ((null != parent) ? parent.Locale : CultureInfo.CurrentCulture); return new SmiExtendedMetaData( dbType, maxLength, precision, scale, columnLocale.LCID, SmiMetaData.DefaultNVarChar.CompareOptions, false, // no support for multi-valued columns in a TVP yet null, // no support for structured columns yet null, // no support for structured columns yet column.ColumnName, null, null, null); } internal static long AdjustMaxLength(SqlDbType dbType, long maxLength) { if (SmiMetaData.UnlimitedMaxLengthIndicator != maxLength) { if (maxLength < 0) { maxLength = InvalidMaxLength; } switch (dbType) { case SqlDbType.Binary: if (maxLength > SmiMetaData.MaxBinaryLength) { maxLength = InvalidMaxLength; } break; case SqlDbType.Char: if (maxLength > SmiMetaData.MaxANSICharacters) { maxLength = InvalidMaxLength; } break; case SqlDbType.NChar: if (maxLength > SmiMetaData.MaxUnicodeCharacters) { maxLength = InvalidMaxLength; } break; case SqlDbType.NVarChar: // Promote to MAX type if it won't fit in a normal type if (SmiMetaData.MaxUnicodeCharacters < maxLength) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.VarBinary: // Promote to MAX type if it won't fit in a normal type if (SmiMetaData.MaxBinaryLength < maxLength) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.VarChar: // Promote to MAX type if it won't fit in a normal type if (SmiMetaData.MaxANSICharacters < maxLength) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; default: break; } } return maxLength; } // Map SmiMetaData from a schema table. // DEVNOTE: Since we're using SchemaTable, we can assume that we aren't directly using a SqlDataReader // so we don't support the Sql-specific stuff, like collation. internal static SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schemaRow) { string colName = ""; object temp = schemaRow[SchemaTableColumn.ColumnName]; if (DBNull.Value != temp) { colName = (string)temp; } // Determine correct SqlDbType. temp = schemaRow[SchemaTableColumn.DataType]; if (DBNull.Value == temp) { throw SQL.NullSchemaTableDataTypeNotSupported(colName); } Type colType = (Type)temp; SqlDbType colDbType = InferSqlDbTypeFromType_Katmai(colType); if (InvalidSqlDbType == colDbType) { // Unknown through standard mapping, use VarBinary for columns that are Object typed, otherwise error if (typeof(object) == colType) { colDbType = SqlDbType.VarBinary; } else { throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString()); } } // Determine metadata modifier values per type (maxlength, precision, scale, etc) long maxLength = 0; byte precision = 0; byte scale = 0; switch (colDbType) { case SqlDbType.BigInt: case SqlDbType.Bit: case SqlDbType.DateTime: case SqlDbType.Float: case SqlDbType.Image: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.NText: case SqlDbType.Real: case SqlDbType.UniqueIdentifier: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.Text: case SqlDbType.Timestamp: case SqlDbType.TinyInt: case SqlDbType.Variant: case SqlDbType.Xml: case SqlDbType.Date: // These types require no metadata modifies break; case SqlDbType.Binary: case SqlDbType.VarBinary: // These types need a binary max length temp = schemaRow[SchemaTableColumn.ColumnSize]; if (DBNull.Value == temp) { // source isn't specifying a size, so assume the worst if (SqlDbType.Binary == colDbType) { maxLength = SmiMetaData.MaxBinaryLength; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } } else { // We (should) have a valid maxlength, so use it. maxLength = Convert.ToInt64(temp, null); // Max length must be 0 to MaxBinaryLength or it can be UnlimitedMAX if type is varbinary. // If it's greater than MaxBinaryLength, just promote it to UnlimitedMAX, if possible. if (maxLength > SmiMetaData.MaxBinaryLength) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } if ((maxLength < 0 && (maxLength != SmiMetaData.UnlimitedMaxLengthIndicator || SqlDbType.Binary == colDbType))) { throw SQL.InvalidColumnMaxLength(colName, maxLength); } } break; case SqlDbType.Char: case SqlDbType.VarChar: // These types need an ANSI max length temp = schemaRow[SchemaTableColumn.ColumnSize]; if (DBNull.Value == temp) { // source isn't specifying a size, so assume the worst if (SqlDbType.Char == colDbType) { maxLength = SmiMetaData.MaxANSICharacters; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } } else { // We (should) have a valid maxlength, so use it. maxLength = Convert.ToInt64(temp, null); // Max length must be 0 to MaxANSICharacters or it can be UnlimitedMAX if type is varbinary. // If it's greater than MaxANSICharacters, just promote it to UnlimitedMAX, if possible. if (maxLength > SmiMetaData.MaxANSICharacters) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } if ((maxLength < 0 && (maxLength != SmiMetaData.UnlimitedMaxLengthIndicator || SqlDbType.Char == colDbType))) { throw SQL.InvalidColumnMaxLength(colName, maxLength); } } break; case SqlDbType.NChar: case SqlDbType.NVarChar: // These types need a unicode max length temp = schemaRow[SchemaTableColumn.ColumnSize]; if (DBNull.Value == temp) { // source isn't specifying a size, so assume the worst if (SqlDbType.NChar == colDbType) { maxLength = SmiMetaData.MaxUnicodeCharacters; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } } else { // We (should) have a valid maxlength, so use it. maxLength = Convert.ToInt64(temp, null); // Max length must be 0 to MaxUnicodeCharacters or it can be UnlimitedMAX if type is varbinary. // If it's greater than MaxUnicodeCharacters, just promote it to UnlimitedMAX, if possible. if (maxLength > SmiMetaData.MaxUnicodeCharacters) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } if ((maxLength < 0 && (maxLength != SmiMetaData.UnlimitedMaxLengthIndicator || SqlDbType.NChar == colDbType))) { throw SQL.InvalidColumnMaxLength(colName, maxLength); } } break; case SqlDbType.Decimal: // Decimal requires precision and scale temp = schemaRow[SchemaTableColumn.NumericPrecision]; if (DBNull.Value == temp) { precision = SmiMetaData.DefaultDecimal.Precision; } else { precision = Convert.ToByte(temp, null); } temp = schemaRow[SchemaTableColumn.NumericScale]; if (DBNull.Value == temp) { scale = SmiMetaData.DefaultDecimal.Scale; } else { scale = Convert.ToByte(temp, null); } if (precision < SmiMetaData.MinPrecision || precision > SqlDecimal.MaxPrecision || scale < SmiMetaData.MinScale || scale > SqlDecimal.MaxScale || scale > precision) { throw SQL.InvalidColumnPrecScale(); } break; case SqlDbType.Time: case SqlDbType.DateTime2: case SqlDbType.DateTimeOffset: // requires scale temp = schemaRow[SchemaTableColumn.NumericScale]; if (DBNull.Value == temp) { scale = SmiMetaData.DefaultTime.Scale; } else { scale = Convert.ToByte(temp, null); } if (scale > SmiMetaData.MaxTimeScale) { throw SQL.InvalidColumnPrecScale(); } else if (scale < 0) { scale = SmiMetaData.DefaultTime.Scale; } break; case SqlDbType.Udt: case SqlDbType.Structured: default: // These types are not supported from SchemaTable throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString()); } return new SmiExtendedMetaData( colDbType, maxLength, precision, scale, System.Globalization.CultureInfo.CurrentCulture.LCID, SmiMetaData.GetDefaultForType(colDbType).CompareOptions, null, // no support for UDTs from SchemaTable false, // no support for multi-valued columns in a TVP yet null, // no support for structured columns yet null, // no support for structured columns yet colName, null, null, null); } } }
// 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.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using Microsoft.NodejsTools.LogGeneration; using Microsoft.NodejsTools.SourceMapping; using NodeLogConverter; using NodeLogConverter.LogParsing; namespace Microsoft.NodejsTools.LogParsing { /// <summary> /// Parses a V8 profiling log which is just a CSV file. The CSV file includes several /// different record types including tick events with stack traces, code compilation events /// with function and line information, and other events which we don't really care about. /// /// VS expects to get it's profiling information in the form of an ETL file. This file is /// then zipped up into a VSPX. /// /// VS also expects to take the IP information that is in the file and resolve it against /// PDB files. /// /// So we do a few different things to translate the CSV file into a form which VS can understand. /// /// First, we create a new C# DLL which contains symbol information for the JITed JavaScript functions. /// We emit this with #line preprocessor directives so that when a method is resolved to it /// it points to the user's JavaScript files. We rely upon the fact that the C# compiler sequentially /// hands out managed method token IDs and we hand out the token IDs in the same order. We then /// open the DLL using the symbol APIs so we can get the checksum on it so VS will happily load /// our symbols. /// /// Once we've got our DLL produced we can then start processing the log to create the ETL events. /// We just run through all of the log entries and spew out the appropriate ETL events. This includes /// the initial process created, module load events, the code creation events, the tick/stack walk /// events, and finally the process end event. /// /// The log that we create then is a little bit weird - the time stamps have all been provided by /// the OS for the current date/time. On Windows 8 there's a new relogger API which we can use /// to re-write the timestamps. We timed the profiled process, and we know how many ticks we saw, /// so we can translate the timestamps to be spread across all of the ticks for the appropiate /// amount of time. /// /// Finally we zip up the resulting ETL file and save it under the filename requested. /// </summary> internal class LogConverter { private static readonly char[] _invalidPathChars = Path.GetInvalidPathChars(); private static readonly Version v012 = new Version(0, 12); private readonly string _filename; private readonly string _outputFile; private readonly TimeSpan? _executionTime; private readonly bool _justMyCode; private readonly Version _nodeVersion; private readonly SortedDictionary<AddressRange, bool> _codeAddresses = new SortedDictionary<AddressRange, bool>(); private Dictionary<string, SourceMap> _sourceMaps = new Dictionary<string, SourceMap>(StringComparer.OrdinalIgnoreCase); // Currently we maintain 2 layouts, one for code, one for shared libraries, // because V8 is dropping the high 32-bits of code loaded on 64-bit systems. // This will let us lookup against the JIT code layout, and then the lib layout, and // then the lib layout minus the high 32-bit bits to find the appropriate tag for // code and not have to deal with collisions. private static uint ThreadId = 0x1234; private static uint ProcessId = (uint)System.Diagnostics.Process.GetCurrentProcess().Id; private const int JitModuleId = 1; public LogConverter(string filename, string outputFile, TimeSpan? executionTime, bool justMyCode, Version nodeVersion) { _filename = filename; _outputFile = outputFile; _executionTime = executionTime; _justMyCode = justMyCode; _nodeVersion = nodeVersion; } [STAThread] public static int Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: [/jmc] [/v:<node version>] <v8.log path> <output.vspx path> [<start time> <execution time>]"); return 1; } var jmc = false; if (StringComparer.OrdinalIgnoreCase.Equals(args[0], "/jmc")) { args = args.Skip(1).ToArray(); jmc = true; } var nodeVersion = new Version(0, 10); if (args[0].StartsWith("/v:", StringComparison.OrdinalIgnoreCase)) { nodeVersion = new Version(args[0].Substring(3)); args = args.Skip(1).ToArray(); } string inputFile = args[0]; string outputFile = args[1]; TimeSpan? executionTime = null; if (args.Length > 3) { try { //startTime = DateTime.Parse(args[2]); executionTime = TimeSpan.Parse(args[3]); } catch { Console.WriteLine("Bad execution time: {0}", executionTime); return 2; } } #if DEBUG try { #endif var log = new LogConverter(inputFile, outputFile, executionTime, jmc, nodeVersion); log.Process(); return 0; #if DEBUG } catch (Exception e) { Console.WriteLine("Internal error while converting log: {0}", e.ToString()); MessageBox.Show(e.ToString()); throw; } #endif } public void Process() { string line; uint methodToken = 0x06000001; string filename = Path.Combine(Path.GetDirectoryName(_outputFile), Path.GetFileNameWithoutExtension(_outputFile)); Guid pdbSig; uint pdbAge; string dllPath = CreatePdbFile(out pdbSig, out pdbAge); _allMethods.Clear(); int tickCount = 0; using (var reader = new StreamReader(_filename)) { var logCreationTime = DateTime.Now; var logCreationTimeStamp = Stopwatch.GetTimestamp(); var log = TraceLog.Start(filename + ".etl", null); try { EVENT_TRACE_HEADER header; ////////////////////////////////////// header = NewHeader(); //header.TimeStamp = currentTimeStamp++; header.Guid = TraceLog.ProcessEventGuid; header.Version = 3; header.Type = 3; var processInfo = new ProcessInfo(); processInfo.UniqueProcessKey = 100; processInfo.ProcessId = ProcessId; processInfo.ParentId = 100; log.Trace(header, processInfo, Encoding.ASCII.GetBytes("node.exe"), string.Empty); ////////////////////////////////////// header = NewHeader(); header.Guid = TraceLog.ThreadEventGuid; header.Version = 3; header.Type = 3; var threadInfo = new ThreadInfo(); threadInfo.ProcessId = ProcessId; // setup the thread as if it was a reasonable real thread threadInfo.TThreadId = ThreadId; threadInfo.Affinity = 0xFF; threadInfo.Win32StartAddr = 0x8888; threadInfo.UserStackBase = 0xF0000; threadInfo.UserStackLimit = 0xF00200; threadInfo.IoPriority = 2; log.Trace(header, threadInfo); ////////////////////////////////////// header = NewHeader(); //header.TimeStamp = currentTimeStamp++; header.Guid = TraceLog.ImageEventGuid; header.Version = 2; header.Type = 3; var imgLoad = new ImageLoad(); imgLoad.ImageBase = 0x10000; imgLoad.ImageSize = 10000; imgLoad.ProcessId = ProcessId; log.Trace(header, imgLoad, dllPath); ////////////////////////////////////// header = NewHeader(); header.Guid = TraceLog.LoaderEventGuid; header.Version = 2; header.Type = 33; var moduleLoad = new ManagedModuleLoadUnload(); moduleLoad.AssemblyID = 1; moduleLoad.ModuleID = JitModuleId; log.Trace(header, moduleLoad, dllPath, dllPath, (ushort)1, // clr instance ID pdbSig, // pdb sig pdbAge, // pdb age dllPath.Substring(0, dllPath.Length - 4) + ".pdb", // path to PDB, Guid.Empty, 0, string.Empty ); while ((line = reader.ReadLine()) != null) { var records = SplitRecord(line); if (records.Length == 0) { continue; } switch (records[0]) { case "shared-library": if (records.Length < 4) { continue; // missing info? } break; case "profiler": break; case "code-creation": int shift = (_nodeVersion >= v012 ? 1 : 0); if (records.Length < shift + 5) { continue; // missing info? } var startAddr = ParseAddress(records[shift + 2]); header = NewMethodEventHeader(); var methodLoad = new MethodLoadUnload(); methodLoad.MethodID = methodToken; methodLoad.ModuleID = JitModuleId; methodLoad.MethodStartAddress = startAddr; methodLoad.MethodSize = (uint)ParseAddress(records[shift + 3]); methodLoad.MethodToken = methodToken; methodLoad.MethodFlags = 8; var funcInfo = ExtractNamespaceAndMethodName(records[shift + 4], records[1]); string functionName = funcInfo.Function; if (funcInfo.IsRecompilation) { functionName += " (recompiled)"; } _codeAddresses[new AddressRange(startAddr, methodLoad.MethodSize)] = IsMyCode(funcInfo); log.Trace(header, methodLoad, funcInfo.Namespace, functionName, string.Empty /* signature*/); methodToken++; break; case "tick": if (records.Length < 5) { continue; } var addr = ParseAddress(records[1]); header = NewTickRecord(); var profileInfo = new SampledProfile(); profileInfo.InstructionPointer = (uint)addr; profileInfo.ThreadId = ThreadId; profileInfo.Count = 1; log.Trace(header, profileInfo); if (records.Length > 2) { header = NewStackWalkRecord(); var sw = new StackWalk(); // this timestamp is independent from the timestamp in our header, // and this one is not filled in for us by ETW. So we need to fill // it in here. sw.TimeStamp = (ulong)Stopwatch.GetTimestamp(); sw.Process = ProcessId; sw.Thread = ThreadId; // tick, ip, esp, ? [always zero], ?, always zero[?], stack IPs... const int nonStackFrames = 6; // count of records, including IP, which aren't stack addresses. List<object> args = new List<object>(); args.Add(sw); var ipAddr = ParseAddress(records[1]); if (ipAddr != 0 && ShouldIncludeCode(ipAddr)) { args.Add(ipAddr); } for (int i = nonStackFrames; i < records.Length; i++) { var callerAddr = ParseAddress(records[i]); if (callerAddr != 0 && ShouldIncludeCode(callerAddr)) { args.Add(callerAddr); } } if ((records.Length - nonStackFrames) == 0) { // idle CPU time sw.Process = 0; } tickCount++; log.Trace(header, args.ToArray()); } break; default: Console.WriteLine("Unknown record type: {0}", line); break; } } header = NewHeader(); header.Guid = TraceLog.ProcessEventGuid; header.Version = 3; header.Type = 4; // DCEnd processInfo = new ProcessInfo(); processInfo.UniqueProcessKey = 100; processInfo.ProcessId = ProcessId; processInfo.ParentId = 100; log.Trace(header, processInfo, Encoding.ASCII.GetBytes("node.exe"), string.Empty); } finally { log.Stop(); } RelogTrace(_executionTime.Value, tickCount, filename + ".etl"); } // save the VSPX file using (var stream = new FileStream(filename + ".vspx", FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, false)) { var entry = archive.CreateEntry("VSProfilingData\\" + Path.GetFileName(filename) + ".etl"); using (FileStream etlStream = new FileStream(filename + ".etl", FileMode.Open, FileAccess.Read)) { using (var entryStream = entry.Open()) { etlStream.CopyTo(entryStream); } } } } } private bool ShouldIncludeCode(ulong callerAddr) { if (_justMyCode) { bool isMyCode; if (_codeAddresses.TryGetValue(new AddressRange(callerAddr), out isMyCode)) { return isMyCode; } } return true; } private static bool IsMyCode(FunctionInformation funcInfo) { return !string.IsNullOrWhiteSpace(funcInfo.Filename) && funcInfo.Filename.IndexOfAny(_invalidPathChars) == -1 && funcInfo.Filename.IndexOf("\\node_modules\\") == -1 && Path.IsPathRooted(funcInfo.Filename); } private static ulong ParseAddress(string address) { ulong res; if (address.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { if (UInt64.TryParse(address.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture.NumberFormat, out res)) { return res; } } else if (UInt64.TryParse(address, out res)) { return res; } return 0; } internal static string[] SplitRecord(string line) { int start = 0; List<string> records = new List<string>(); bool inQuote = false, containsDoubleQuote = false; for (int i = 0; i < line.Length; i++) { if (line[i] == ',' && !inQuote) { records.Add(RemoveDoubleQuotes(containsDoubleQuote, line.Substring(start, i - start))); start = i + 1; containsDoubleQuote = false; } else if (line[i] == '"') { if (i + 1 == line.Length || line[i + 1] != '"') { inQuote = !inQuote; } else if (inQuote) { containsDoubleQuote = true; i++; } } } if (start < line.Length) { var record = RemoveDoubleQuotes(containsDoubleQuote, line.Substring(start, line.Length - start)); records.Add(record); } return records.ToArray(); } private static string RemoveDoubleQuotes(bool containsDoubleQuote, string record) { if (containsDoubleQuote) { record = record.Replace("\"\"", "\""); } return record; } private HashSet<string> _allMethods = new HashSet<string>(); internal FunctionInformation ExtractNamespaceAndMethodName(string method, string type = "LazyCompile") { bool isRecompilation = !_allMethods.Add(method); return ExtractNamespaceAndMethodName(method, isRecompilation, type, _sourceMaps); } internal const string _topLevelModule = "<top-level module code>"; internal static FunctionInformation ExtractNamespaceAndMethodName(string location, bool isRecompilation, string type = "LazyCompile", Dictionary<string, SourceMap> sourceMaps = null) { string fileName = null; string moduleName = ""; string methodName = location; List<int> pos = null; if (location.Length >= 2 && location.StartsWith("\"", StringComparison.Ordinal) && location.EndsWith("\"", StringComparison.Ordinal)) { // v8 usually includes quotes, strip them location = location.Substring(1, location.Length - 2); } int firstSpace; if (type == "Script" || type == "Function") { // code-creation,Function,0xf1c38300,1928," assert.js:1",0xa6d4df58,~ // code-creation,Script,0xf1c38aa0,244,"assert.js",0xa6d4e050,~ // code-creation,Script,0xf1c141c0,844,"native runtime.js",0xa6d1aa98,~ // this is a top level script or module, report it as such methodName = _topLevelModule; if (type == "Function") { location = location.Substring(location.IndexOf(' ') + 1); } ParseLocation(location, out fileName, out moduleName, out pos); pos = new List<int> { 1 }; } else { // " net.js:931" // "func C:\Source\NodeApp2\NodeApp2\server.js:5" // " C:\Source\NodeApp2\NodeApp2\server.js:16" firstSpace = FirstSpace(location); if (firstSpace != -1) { if (firstSpace == 0) { methodName = "anonymous method"; } else { methodName = location.Substring(0, firstSpace); } location = location.Substring(firstSpace + 1); ParseLocation(location, out fileName, out moduleName, out pos); } } var lineNo = pos == null ? null : pos.Select(x => (int?)x).FirstOrDefault(); return SourceMapper.MaybeMap(new FunctionInformation(moduleName, methodName, lineNo, fileName, isRecompilation), sourceMaps); } private static int FirstSpace(string method) { int parenCount = 0; for (int i = 0; i < method.Length; i++) { switch (method[i]) { case '(': parenCount++; break; case ')': parenCount--; break; case ' ': if (parenCount == 0) { return i; } break; } } return -1; } private static void ParseLocation(string location, out string fileName, out string moduleName, out List<int> pos) { location = location.Trim(); pos = new List<int>(); // Possible variations include: // // C:\Foo\Bar\baz.js // C:\Foo\Bar\baz.js:1 // C:\Foo\Bar\baz.js:1:2 // // To cover them all, we just repeatedly strip the tail of the string after the last ':', // so long as it can be parsed as an integer. int colon; while ((colon = location.LastIndexOf(":", StringComparison.Ordinal)) != -1) { string tail = location.Substring(colon + 1, location.Length - (colon + 1)); int number; if (!Int32.TryParse(tail, out number)) { break; } pos.Insert(0, number); location = location.Substring(0, colon); } moduleName = fileName = location; if (string.IsNullOrEmpty(moduleName)) { moduleName = "<unknown module>"; } else if (moduleName.IndexOfAny(_invalidPathChars) == -1) { moduleName = Path.GetFileNameWithoutExtension(moduleName); } } private static EVENT_TRACE_HEADER NewMethodEventHeader() { var header = NewHeader(); header.Size = (ushort)(Marshal.SizeOf(typeof(EVENT_TRACE_HEADER)) + Marshal.SizeOf(typeof(MethodLoadUnload))); header.Guid = TraceLog.MethodEventGuid; header.Version = 0; header.Type = 40; return header; } private static EVENT_TRACE_HEADER NewTickRecord() { var header = NewHeader(); header.Size = (ushort)(Marshal.SizeOf(typeof(EVENT_TRACE_HEADER)) + Marshal.SizeOf(typeof(SampledProfile))); header.Guid = TraceLog.PerfInfoEventGuid; header.Version = 2; header.Type = 46; return header; } private static EVENT_TRACE_HEADER NewStackWalkRecord() { var header = NewHeader(); header.Size = (ushort)(Marshal.SizeOf(typeof(EVENT_TRACE_HEADER)) + Marshal.SizeOf(typeof(StackWalk)) + sizeof(int) * 2); header.Guid = TraceLog.StackWalkEventGuid; header.Version = 2; header.Type = 32; return header; } private static EVENT_TRACE_HEADER NewHeader() { var header = new EVENT_TRACE_HEADER(); header.ProcessId = ProcessId; header.ThreadId = ThreadId; //header.Flags = 0x200; //header.HeaderType = 1; return header; } #region PDB Generation /// <summary> /// Creates a .pdb file for the code creation in the /// </summary> /// <returns></returns> private string CreatePdbFile(out Guid pdbSig, out uint pdbAge) { StringBuilder pdbCode = new StringBuilder(); pdbCode.Append("class JavaScriptFunctions {"); int id = 0; string dllDirectory; for (;;) { dllDirectory = Path.Combine(Path.GetTempPath(), "JavaScriptFunctions_" + id); id++; if (!Directory.Exists(dllDirectory)) { try { Directory.CreateDirectory(dllDirectory); break; } catch { } } } string dllPath = Path.Combine(dllDirectory, "JavaScriptFunctions.dll"); uint methodToken = 0x06000001; using (var reader = new StreamReader(_filename)) { string line; while ((line = reader.ReadLine()) != null) { var records = SplitRecord(line); if (records.Length == 0) { continue; } switch (records[0]) { case "code-creation": int shift = (_nodeVersion >= v012 ? 1 : 0); var funcInfo = ExtractNamespaceAndMethodName(records[shift + 4]); if (funcInfo.LineNumber != null && !string.IsNullOrWhiteSpace(funcInfo.Filename)) { pdbCode.Append(string.Format(CultureInfo.InvariantCulture, @" #line {0} ""{1}"" public static void X{2:X}() {{ }} ", funcInfo.LineNumber, funcInfo.Filename, methodToken)); } else { // we need to keep outputting methods just to keep tokens lined up. pdbCode.Append(string.Format(CultureInfo.InvariantCulture, @" public static void X{0:X}() {{ }} ", methodToken)); } methodToken++; break; } } } pdbCode.Append("}"); var compiler = CodeDomProvider.GetCompilerInfo("csharp"); var parameters = compiler.CreateDefaultCompilerParameters(); parameters.IncludeDebugInformation = true; parameters.OutputAssembly = dllPath; parameters.GenerateExecutable = false; var res = compiler.CreateProvider().CompileAssemblyFromSource(parameters, pdbCode.ToString()); if (res.Errors.Count > 0) { #if DEBUG var tempPath = Path.GetTempFileName(); File.WriteAllText(tempPath, pdbCode.ToString()); #endif StringBuilder errors = new StringBuilder("Error while generating symbols:"); foreach (var error in res.Errors) { errors.AppendFormat(" {0}", error); errors.AppendLine(); } #if DEBUG Console.WriteLine(errors.ToString()); MessageBox.Show("Code saved to: " + tempPath + Environment.NewLine + errors.ToString()); #endif } ReadPdbSigAndAge(dllPath, out pdbSig, out pdbAge); return dllPath; } public static void ReadPdbSigAndAge(string dllPath, out Guid sig, out uint age) { sig = default(Guid); age = 0; var curProcHandle = System.Diagnostics.Process.GetCurrentProcess().Handle; IntPtr duplicatedHandle; if (!NativeMethods.DuplicateHandle( curProcHandle, curProcHandle, curProcHandle, out duplicatedHandle, 0, false, DuplicateOptions.DUPLICATE_SAME_ACCESS )) { return; } try { if (!NativeMethods.SymInitialize(duplicatedHandle, IntPtr.Zero, false)) { return; } try { ulong moduleAddress = NativeMethods.SymLoadModuleEx( duplicatedHandle, IntPtr.Zero, dllPath, null, 0, 0, IntPtr.Zero, 0 ); if (moduleAddress == 0) { return; } IMAGEHLP_MODULE64 module64 = new IMAGEHLP_MODULE64(); module64.SizeOfStruct = (uint)Marshal.SizeOf(typeof(IMAGEHLP_MODULE64)); if (!NativeMethods.SymGetModuleInfo64(duplicatedHandle, moduleAddress, ref module64)) { return; } sig = module64.PdbSig70; age = module64.PdbAge; } finally { NativeMethods.SymCleanup(duplicatedHandle); } } finally { NativeMethods.CloseHandle(duplicatedHandle); } } #endregion #region Relogging private void RelogTrace(TimeSpan executionTime, int stackWalkCount, string filename) { // if we're on Win8 or later we want to re-write the timestamps using the relogger ITraceRelogger traceRelogger = null; try { traceRelogger = (ITraceRelogger)Activator.CreateInstance(Type.GetTypeFromCLSID(EtlNativeMethods.CLSID_TraceRelogger)); } catch (COMException) { } if (traceRelogger != null) { var callback = new TraceReloggerCallback(executionTime, stackWalkCount); ulong newTraceHandle; traceRelogger.AddLogfileTraceStream(filename, IntPtr.Zero, out newTraceHandle); traceRelogger.SetOutputFilename(filename + ".tmp"); traceRelogger.RegisterCallback(callback); traceRelogger.ProcessTrace(); File.Copy(filename + ".tmp", filename, true); } else { Console.WriteLine("Failed to create relogger, timestamps will be incorrect"); } } private class TraceReloggerCallback : ITraceEventCallback { private readonly TimeSpan _executionTime; private readonly int _stackWalkCount; private long _currentTimeStamp; private long _ticksPerStack; private const int EmptyStackWalkSize = 24; // size of an empty stack walk record public TraceReloggerCallback(TimeSpan executionTime, int stackWalkCount) { _currentTimeStamp = Stopwatch.GetTimestamp(); _executionTime = executionTime; _stackWalkCount = stackWalkCount; } #region ITraceEventCallback Members public void OnBeginProcessTrace(ITraceEvent HeaderEvent, ITraceRelogger Relogger) { IntPtr recordPtr; HeaderEvent.GetEventRecord(out recordPtr); EVENT_RECORD record = (EVENT_RECORD)Marshal.PtrToStructure(recordPtr, typeof(EVENT_RECORD)); EventTrace_Header props = (EventTrace_Header)Marshal.PtrToStructure(record.UserData, typeof(EventTrace_Header)); var ticksPerMs = props.PerfFreq / 1000;// PerfFreq is frequence in # of ticks per second (same as Stopwatch.Frequency) var msPerStack = _executionTime.TotalMilliseconds / _stackWalkCount; _ticksPerStack = (long)(ticksPerMs * (ulong)msPerStack); } public void OnFinalizeProcessTrace(ITraceRelogger Relogger) { } public void OnEvent(ITraceEvent Event, ITraceRelogger Relogger) { IntPtr recordPtr; Event.GetEventRecord(out recordPtr); EVENT_RECORD record = (EVENT_RECORD)Marshal.PtrToStructure(recordPtr, typeof(EVENT_RECORD)); if (IsStackWalkRecord(ref record)) { // path the timestamp in the stack walk record. Marshal.WriteInt64(record.UserData, _currentTimeStamp); _currentTimeStamp += _ticksPerStack; if (record.UserDataLength == EmptyStackWalkSize) { // this is an empty stack walk, which means that the CPU is actually idle. // We inject these when writing the log, and then remove them when doing // the rewrite. This lets us keep the correct timing information but removing // them gets us correct CPU information in the graph. return; } } var prevTimeStamp = record.EventHeader.TimeStamp; var newTimeStamp = _currentTimeStamp; Event.SetTimeStamp(ref newTimeStamp); if (IsStackWalkRecord(ref record)) { } Relogger.Inject(Event); } private static bool IsStackWalkRecord(ref EVENT_RECORD record) { return record.EventHeader.ProviderId == TraceLog.StackWalkEventGuid && record.EventHeader.EventDescriptor.Opcode == 32 && record.EventHeader.EventDescriptor.Version == 2; } #endregion } #endregion private struct AddressRange : IComparable<AddressRange>, IEquatable<AddressRange> { public readonly ulong Start; public readonly uint Length; public readonly bool Lookup; public AddressRange(ulong start, uint length) { Start = start; Length = length; Lookup = false; } /// <summary> /// Creates a new AddressRange to perform a lookup /// </summary> /// <param name="start"></param> public AddressRange(ulong start) { Start = start; Length = 0; Lookup = true; } public int CompareTo(AddressRange other) { if (Lookup) { // fuzzy lookup if (Start >= other.Start && Start < other.Start + other.Length) { return 0; } } else if (other.Lookup) { if (other.Start >= Start && other.Start < Start + Length) { return 0; } } if (Start > other.Start) { return 1; } else if (other.Start == Start) { return 0; } else { return -1; } } public override string ToString() { return string.Format("AddressRange: {0} {1}", Start, Length); } public override int GetHashCode() { return (int)Start; } public bool Equals(AddressRange other) { return CompareTo(other) == 0; } } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Media; using System.IO; using Operation_Cronos; namespace Operation_Cronos.Sound { public enum Sounds { MainMenuVents, MainMenuStairs, MainMenuTimeGateWater, MainMenuRoboticArms, MainMenuPiston, MainMenuCreditsPanelOpening, MainMenuCreditsPanelClosing, MainMenuSlot, CommandCenterButton, CommandCenterZone, BackgroundSound, SlidingSoundLong, SlidingSoundShort, LeftMenuButtons, EconomyFactory, EconomyMine, EconomyOilWell, EconomySawMill, Education, Energy, EnvironmentNursery, EnvironmentRecycling, EnvironmentWaterPurification, FoodAnimalFarm, FoodCropFarm, FoodFarmedFisherie, FoodOrchard, Health, Population, None } public class SoundManager : GameComponent { #region Fields private List<WavSound> soundsList; private float DefaultVolume = 0.6f; private float generalSoundVolume; private bool generalSoundState = true; //On or Off private Timer tmrBackgroundStartPlayingDelay; #region sounds WavSound MainMenuVents; WavSound MainMenuStairs; WavSound MainMenuTimeGateWater; WavSound MainMenuRoboticArms; WavSound MainMenuPiston; WavSound MainMenuCreditsPanelOpening; WavSound MainMenuCreditsPanelClosing; WavSound MainMenuSlot; WavSound CommandCenterButton; WavSound CommandCenterZone; WavSound SlidingPanelLong; WavSound SlidingPanelShort; WavSound LeftMenuButtons; //sunete pt cladiri WavSound EconomyFactory; WavSound EconomyMine; WavSound EconomyOilWell; WavSound EconomySawMill; WavSound Education; WavSound Energy; WavSound EnvironmentNursery; WavSound EnvironmentRecycling; WavSound EnvironmentWaterPurification; WavSound FoodAnimalFarm; WavSound FoodCropFarm; WavSound FoodFarmedFisherie; WavSound FoodOrchard; WavSound Health; WavSound Population; #endregion #endregion #region Properties /// <summary> /// Gets or sets the general sound volume (float value between 0.0f and 1.0f) /// </summary> public float GeneralSoundVolume { get { return generalSoundVolume; } set { if (value >= 0.0f && value <= 1.0f) { generalSoundVolume = value; SetGeneralSoundVolume(); } } } /// <summary> /// Indicates whether the general volume is at the default volume level or /// sets the general volume to the default value /// </summary> public bool UseDefaultSoundVolume { get { return DefaultVolume == generalSoundVolume; } set { generalSoundVolume = DefaultVolume; SetGeneralSoundVolume(); } } /// <summary> /// Gets or sets the on or off state of all the sounds /// </summary> public bool SoundsOn { get { return generalSoundState; } set { generalSoundState = value; SetSoundOnOrOff(); } } #endregion #region Constructor public SoundManager(Game game) : base(game) { soundsList = new List<WavSound>(); MainMenuVents = new WavSound(game, "mainMenuVents", true); MainMenuVents.SoundType = Sounds.MainMenuVents; soundsList.Add(MainMenuVents); MainMenuStairs = new WavSound(game, "mainMenuStairs", false); MainMenuStairs.SoundType = Sounds.MainMenuStairs; soundsList.Add(MainMenuStairs); MainMenuTimeGateWater = new WavSound(game, "mainMenuTimeGateWater", true); MainMenuTimeGateWater.SoundType = Sounds.MainMenuTimeGateWater; soundsList.Add(MainMenuTimeGateWater); MainMenuRoboticArms = new WavSound(game, "mainMenuRoboticArms", false); MainMenuRoboticArms.SoundType = Sounds.MainMenuRoboticArms; soundsList.Add(MainMenuRoboticArms); MainMenuPiston = new WavSound(game, "mainMenuPiston", false); MainMenuPiston.SoundType = Sounds.MainMenuPiston; soundsList.Add(MainMenuPiston); MainMenuCreditsPanelOpening = new WavSound(game, "mainMenuCreditsPanelOpening", false); MainMenuCreditsPanelOpening.SoundType = Sounds.MainMenuCreditsPanelOpening; soundsList.Add(MainMenuCreditsPanelOpening); MainMenuCreditsPanelClosing = new WavSound(game, "mainMenuCreditsPanelClosing", false); MainMenuCreditsPanelClosing.SoundType = Sounds.MainMenuCreditsPanelClosing; soundsList.Add(MainMenuCreditsPanelClosing); MainMenuSlot = new WavSound(game, "mainMenuSlot", false); MainMenuSlot.SoundType = Sounds.MainMenuSlot; soundsList.Add(MainMenuSlot); CommandCenterButton = new WavSound(game, "commandCenterButton", false); CommandCenterButton.SoundType = Sounds.CommandCenterButton; soundsList.Add(CommandCenterButton); CommandCenterZone = new WavSound(game, "commandCenterZone", false); CommandCenterZone.SoundType = Sounds.CommandCenterZone; soundsList.Add(CommandCenterZone); SlidingPanelLong = new WavSound(game, "slidingPanelLong", false); SlidingPanelLong.SoundType = Sounds.SlidingSoundLong; soundsList.Add(SlidingPanelLong); SlidingPanelShort= new WavSound(game, "slidingPanelShort", false); SlidingPanelShort.SoundType = Sounds.SlidingSoundShort; soundsList.Add(SlidingPanelShort); LeftMenuButtons = new WavSound(game, "LeftMenuButtons", false); LeftMenuButtons.SoundType = Sounds.LeftMenuButtons; soundsList.Add(LeftMenuButtons); EconomyFactory = new WavSound(game, "BuildingSounds\\EconomyFactory", false); EconomyFactory.SoundType = Sounds.EconomyFactory; soundsList.Add(EconomyFactory); EconomyMine = new WavSound(game, "BuildingSounds\\EconomyMine", false); EconomyMine.SoundType = Sounds.EconomyMine; soundsList.Add(EconomyMine); EconomyOilWell = new WavSound(game, "BuildingSounds\\EconomyOilWell", false); EconomyOilWell.SoundType = Sounds.EconomyOilWell; soundsList.Add(EconomyOilWell); EconomySawMill = new WavSound(game, "BuildingSounds\\EconomySawMill", false); EconomySawMill.SoundType = Sounds.EconomySawMill; soundsList.Add(EconomySawMill); Education = new WavSound(game, "BuildingSounds\\Education", false); Education.SoundType = Sounds.Education; soundsList.Add(Education); Energy = new WavSound(game, "BuildingSounds\\Energy", false); Energy.SoundType = Sounds.Energy; soundsList.Add(Energy); EnvironmentNursery = new WavSound(game, "BuildingSounds\\EnvironmentNursery", false); EnvironmentNursery.SoundType = Sounds.EnvironmentNursery; soundsList.Add(EnvironmentNursery); EnvironmentRecycling = new WavSound(game, "BuildingSounds\\EnvironmentRecycling", false); EnvironmentRecycling.SoundType = Sounds.EnvironmentRecycling; soundsList.Add(EnvironmentRecycling); EnvironmentWaterPurification = new WavSound(game, "BuildingSounds\\EnvironmentWaterPurification", false); EnvironmentWaterPurification.SoundType = Sounds.EnvironmentWaterPurification; soundsList.Add(EnvironmentWaterPurification); FoodAnimalFarm = new WavSound(game, "BuildingSounds\\FoodAnimalFarm", false); FoodAnimalFarm.SoundType = Sounds.FoodAnimalFarm; soundsList.Add(FoodAnimalFarm); FoodCropFarm = new WavSound(game, "BuildingSounds\\FoodCropFarm", false); FoodCropFarm.SoundType = Sounds.FoodCropFarm; soundsList.Add(FoodCropFarm); FoodFarmedFisherie = new WavSound(game, "BuildingSounds\\FoodFarmedFisherie", false); FoodFarmedFisherie.SoundType = Sounds.FoodFarmedFisherie; soundsList.Add(FoodFarmedFisherie); FoodOrchard = new WavSound(game, "BuildingSounds\\FoodOrchard", false); FoodOrchard.SoundType = Sounds.FoodOrchard; soundsList.Add(FoodOrchard); Health = new WavSound(game, "BuildingSounds\\Health", false); Health.SoundType = Sounds.Health; soundsList.Add(Health); Population = new WavSound(game, "BuildingSounds\\Population", false); Population.SoundType = Sounds.Population; soundsList.Add(Population); UseDefaultSoundVolume = true; SetGeneralSoundVolume(); tmrBackgroundStartPlayingDelay = new Timer(game); tmrBackgroundStartPlayingDelay.IntervalType = TimerIntervalType.Seconds; tmrBackgroundStartPlayingDelay.Interval = 3;//3 seconds tmrBackgroundStartPlayingDelay.OnTick +=new EventHandler(tmrBackgroundStartPlayingDelay_OnTick); game.Components.Add(this); Game.Services.AddService(typeof(SoundManager), this); } #endregion #region Event Handlers void tmrBackgroundStartPlayingDelay_OnTick(object sender, EventArgs e) { tmrBackgroundStartPlayingDelay.Stop(); //the interval between background sounds will be between 6 and 11 seconds } #endregion #region Methods public void PlaySound(Sounds sound) { for (int i = 0; i < soundsList.Count; i++) { if (soundsList[i].SoundType == sound) { soundsList[i].Play(); } } } public void StopSound(Sounds sound) { for (int i = 0; i < soundsList.Count; i++) { if (soundsList[i].SoundType == sound) { soundsList[i].StopSound(); } } } public void PauseSound(Sounds sound) { for (int i = 0; i < soundsList.Count; i++) { if (soundsList[i].SoundType == sound) { soundsList[i].Pause(); } } } public void ResumeSound(Sounds sound) { for (int i = 0; i < soundsList.Count; i++) { if (soundsList[i].SoundType == sound) { soundsList[i].Resume(); } } } /// <summary> /// Sets all the sounds On or Off /// </summary> void SetSoundOnOrOff() { for (int i = 0; i < soundsList.Count; i++) { soundsList[i].IsTurnedOn = generalSoundState; } } void SetGeneralSoundVolume() { for (int i = 0; i < soundsList.Count; i++) { soundsList[i].Volume = generalSoundVolume; } } /// <summary> /// Stops all the MainMenu Sounds /// </summary> public void StopMainMenuSounds() { for (int i = 0; i < soundsList.Count; i++) { if (soundsList[i].SoundType.ToString().Contains("MainMenu")) soundsList[i].StopSound(); } } public void StartBackgroundSong() { } public void StopBackgroundSong() { } #endregion #region Overrides public override void Initialize() { base.Initialize(); } public override void Update(GameTime gameTime) { base.Update(gameTime); } #endregion } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; namespace NUnit.Framework.Constraints { #region PrefixConstraint /// <summary> /// Abstract base class used for prefixes /// </summary> public abstract class PrefixConstraint : Constraint { /// <summary> /// The base constraint /// </summary> protected Constraint baseConstraint; /// <summary> /// Construct given a base constraint /// </summary> /// <param name="resolvable"></param> protected PrefixConstraint(IResolveConstraint resolvable) : base(resolvable) { if ( resolvable != null ) this.baseConstraint = resolvable.Resolve(); } } #endregion #region NotConstraint /// <summary> /// NotConstraint negates the effect of some other constraint /// </summary> public class NotConstraint : PrefixConstraint { /// <summary> /// Initializes a new instance of the <see cref="T:NotConstraint"/> class. /// </summary> /// <param name="baseConstraint">The base constraint to be negated.</param> public NotConstraint(Constraint baseConstraint) : base( baseConstraint ) { } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for if the base constraint fails, false if it succeeds</returns> public override bool Matches(object actual) { this.actual = actual; return !baseConstraint.Matches(actual); } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo( MessageWriter writer ) { writer.WritePredicate( "not" ); baseConstraint.WriteDescriptionTo( writer ); } /// <summary> /// Write the actual value for a failing constraint test to a MessageWriter. /// </summary> /// <param name="writer">The writer on which the actual value is displayed</param> public override void WriteActualValueTo(MessageWriter writer) { baseConstraint.WriteActualValueTo (writer); } } #endregion #region AllItemsConstraint /// <summary> /// AllItemsConstraint applies another constraint to each /// item in a collection, succeeding if they all succeed. /// </summary> public class AllItemsConstraint : PrefixConstraint { /// <summary> /// Construct an AllItemsConstraint on top of an existing constraint /// </summary> /// <param name="itemConstraint"></param> public AllItemsConstraint(Constraint itemConstraint) : base( itemConstraint ) { this.DisplayName = "all"; } /// <summary> /// Apply the item constraint to each item in the collection, /// failing if any item fails. /// </summary> /// <param name="actual"></param> /// <returns></returns> public override bool Matches(object actual) { this.actual = actual; if ( !(actual is IEnumerable) ) throw new ArgumentException( "The actual value must be an IEnumerable", "actual" ); foreach(object item in (IEnumerable)actual) if (!baseConstraint.Matches(item)) return false; return true; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("all items"); baseConstraint.WriteDescriptionTo(writer); } } #endregion #region SomeItemsConstraint /// <summary> /// SomeItemsConstraint applies another constraint to each /// item in a collection, succeeding if any of them succeeds. /// </summary> public class SomeItemsConstraint : PrefixConstraint { /// <summary> /// Construct a SomeItemsConstraint on top of an existing constraint /// </summary> /// <param name="itemConstraint"></param> public SomeItemsConstraint(Constraint itemConstraint) : base( itemConstraint ) { this.DisplayName = "some"; } /// <summary> /// Apply the item constraint to each item in the collection, /// succeeding if any item succeeds. /// </summary> /// <param name="actual"></param> /// <returns></returns> public override bool Matches(object actual) { this.actual = actual; if ( !(actual is IEnumerable) ) throw new ArgumentException( "The actual value must be an IEnumerable", "actual" ); foreach(object item in (IEnumerable)actual) if (baseConstraint.Matches(item)) return true; return false; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("some item"); baseConstraint.WriteDescriptionTo(writer); } } #endregion #region NoItemConstraint /// <summary> /// NoItemConstraint applies another constraint to each /// item in a collection, failing if any of them succeeds. /// </summary> public class NoItemConstraint : PrefixConstraint { /// <summary> /// Construct a SomeItemsConstraint on top of an existing constraint /// </summary> /// <param name="itemConstraint"></param> public NoItemConstraint(Constraint itemConstraint) : base( itemConstraint ) { this.DisplayName = "none"; } /// <summary> /// Apply the item constraint to each item in the collection, /// failing if any item fails. /// </summary> /// <param name="actual"></param> /// <returns></returns> public override bool Matches(object actual) { this.actual = actual; if ( !(actual is IEnumerable) ) throw new ArgumentException( "The actual value must be an IEnumerable", "actual" ); foreach(object item in (IEnumerable)actual) if (baseConstraint.Matches(item)) return false; return true; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("no item"); baseConstraint.WriteDescriptionTo(writer); } } #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.Diagnostics; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.PythonTools; using Microsoft.PythonTools.Debugger; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Project; using Microsoft.Win32; namespace Microsoft.IronPythonTools.Debugger { class IronPythonLauncher : IProjectLauncher { private static Process _chironProcess; private static string _chironDir; private static int _chironPort; private static readonly Guid _cpyInterpreterGuid = new Guid("{2AF0F10D-7135-4994-9156-5D01C9C11B7E}"); private static readonly Guid _cpy64InterpreterGuid = new Guid("{9A7A9026-48C1-4688-9D5D-E5699D47D074}"); private readonly IPythonProject _project; private readonly PythonToolsService _pyService; private readonly IServiceProvider _serviceProvider; public IronPythonLauncher(IServiceProvider serviceProvider, PythonToolsService pyService, IPythonProject project) { _serviceProvider = serviceProvider; _pyService = pyService; _project = project; } #region IPythonLauncher Members private static readonly Lazy<string> NoIronPythonHelpPage = new Lazy<string>(() => { try { var path = Path.GetDirectoryName(typeof(IronPythonLauncher).Assembly.Location); return Path.Combine(path, "NoIronPython.mht"); } catch (ArgumentException) { } catch (NotSupportedException) { } return null; }); public int LaunchProject(bool debug) { LaunchConfiguration config; try { config = _project.GetLaunchConfigurationOrThrow(); } catch (NoInterpretersException) { throw new NoInterpretersException(null, NoIronPythonHelpPage.Value); } return Launch(config, debug); } public int LaunchFile(string file, bool debug) { LaunchConfiguration config; try { config = _project.GetLaunchConfigurationOrThrow(); } catch (NoInterpretersException) { throw new NoInterpretersException(null, NoIronPythonHelpPage.Value); } return Launch(config, debug); } private int Launch(LaunchConfiguration config, bool debug) { //if (factory.Id == _cpyInterpreterGuid || factory.Id == _cpy64InterpreterGuid) { // MessageBox.Show( // "The project is currently set to use the .NET debugger for IronPython debugging but the project is configured to start with a CPython interpreter.\r\n\r\nTo fix this change the debugger type in project properties->Debug->Launch mode.\r\nIf IronPython is not an available interpreter you may need to download it from http://ironpython.codeplex.com.", // "Python Tools for Visual Studio"); // return VSConstants.S_OK; //} string extension = Path.GetExtension(config.ScriptName); if (string.Equals(extension, ".html", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".htm", StringComparison.OrdinalIgnoreCase)) { try { StartSilverlightApp(config, debug); } catch (ChironNotFoundException ex) { MessageBox.Show(ex.Message, "Python Tools for Visual Studio"); } return VSConstants.S_OK; } try { if (debug) { if (string.IsNullOrEmpty(config.InterpreterArguments)) { config.InterpreterArguments = "-X:Debug"; } else if (config.InterpreterArguments.IndexOf("-X:Debug", StringComparison.InvariantCultureIgnoreCase) < 0) { config.InterpreterArguments = "-X:Debug " + config.InterpreterArguments; } var debugStdLib = _project.GetProperty(IronPythonLauncherOptions.DebugStandardLibrarySetting); bool debugStdLibResult; if (!bool.TryParse(debugStdLib, out debugStdLibResult) || !debugStdLibResult) { string interpDir = config.Interpreter.PrefixPath; config.InterpreterArguments += " -X:NoDebug \"" + System.Text.RegularExpressions.Regex.Escape(Path.Combine(interpDir, "Lib\\")) + ".*\""; } using (var dti = DebugLaunchHelper.CreateDebugTargetInfo(_serviceProvider, config)) { // Set the CLR debugger dti.Info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine; dti.Info.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd; // Clear the CLSID list while launching, then restore it // so Dispose() can free it. var clsidList = dti.Info.pClsidList; dti.Info.pClsidList = IntPtr.Zero; try { dti.Launch(); } finally { dti.Info.pClsidList = clsidList; } } } else { var psi = DebugLaunchHelper.CreateProcessStartInfo(_serviceProvider, config); Process.Start(psi).Dispose(); } } catch (FileNotFoundException) { } return VSConstants.S_OK; } #endregion private static Guid? guidSilverlightDebug = new Guid("{032F4B8C-7045-4B24-ACCF-D08C9DA108FE}"); public void StartSilverlightApp(LaunchConfiguration config, bool debug) { var root = Path.GetFullPath(config.WorkingDirectory).TrimEnd('\\'); var file = Path.Combine(root, config.ScriptName); int port = EnsureChiron(root); var url = string.Format( "http://localhost:{0}/{1}", port, (file.StartsWith(root + "\\") ? file.Substring(root.Length + 1) : file.TrimStart('\\')).Replace('\\', '/') ); StartInBrowser(url, debug ? guidSilverlightDebug : null); } public void StartInBrowser(string url, Guid? debugEngine) { if (debugEngine.HasValue) { // launch via VS debugger, it'll take care of figuring out the browsers VsDebugTargetInfo dbgInfo = new VsDebugTargetInfo(); dbgInfo.dlo = (DEBUG_LAUNCH_OPERATION)_DEBUG_LAUNCH_OPERATION3.DLO_LaunchBrowser; dbgInfo.bstrExe = url; dbgInfo.clsidCustom = debugEngine.Value; dbgInfo.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd | (uint)__VSDBGLAUNCHFLAGS4.DBGLAUNCH_UseDefaultBrowser; dbgInfo.cbSize = (uint)Marshal.SizeOf(dbgInfo); VsShellUtilities.LaunchDebugger(_serviceProvider, dbgInfo); } else { // run the users default browser var handler = GetBrowserHandlerProgId(); var browserCmd = (string)Registry.ClassesRoot.OpenSubKey(handler).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(""); if (browserCmd.IndexOf("%1") != -1) { browserCmd = browserCmd.Replace("%1", url); } else { browserCmd = browserCmd + " " + url; } bool inQuote = false; string cmdLine = null; for (int i = 0; i < browserCmd.Length; i++) { if (browserCmd[i] == '"') { inQuote = !inQuote; } if (browserCmd[i] == ' ' && !inQuote) { cmdLine = browserCmd.Substring(0, i); break; } } if (cmdLine == null) { cmdLine = browserCmd; } Process.Start(cmdLine, browserCmd.Substring(cmdLine.Length)); } } private static string GetBrowserHandlerProgId() { try { return (string)Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Explorer").OpenSubKey("FileExts").OpenSubKey(".html").OpenSubKey("UserChoice").GetValue("Progid"); } catch { return (string)Registry.ClassesRoot.OpenSubKey(".html").GetValue(""); } } private int EnsureChiron(string/*!*/ webSiteRoot) { Debug.Assert(!webSiteRoot.EndsWith("\\")); if (_chironDir != webSiteRoot && _chironProcess != null && !_chironProcess.HasExited) { try { _chironProcess.Kill(); } catch { // process already exited } _chironProcess = null; } if (_chironProcess == null || _chironProcess.HasExited) { // start Chiron var chironPath = ChironPath; // Get a free port _chironPort = GetFreePort(); // TODO: race condition - the port might be taked by the time Chiron attempts to open it // TODO: we should wait for Chiron before launching the browser string commandLine = "/w:" + _chironPort + " /notification /d:"; if (webSiteRoot.IndexOf(' ') != -1) { commandLine += "\"" + webSiteRoot + "\""; } else { commandLine += webSiteRoot; } ProcessStartInfo startInfo = new ProcessStartInfo(chironPath, commandLine); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; _chironDir = webSiteRoot; _chironProcess = Process.Start(startInfo); } return _chironPort; } private static int GetFreePort() { return Enumerable.Range(new Random().Next(1200, 2000), 60000).Except( from connection in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections() select connection.LocalEndPoint.Port ).First(); } public string ChironPath { get { string result = GetPythonInstallDir(); if (result != null) { result = Path.Combine(result, @"Silverlight\bin\Chiron.exe"); if (File.Exists(result)) { return result; } } result = Path.Combine(Path.GetDirectoryName(typeof(IronPythonLauncher).Assembly.Location), "Chiron.exe"); if (File.Exists(result)) { return result; } throw new ChironNotFoundException(); } } internal static string GetPythonInstallDir() { using (var ipy = Registry.LocalMachine.OpenSubKey("SOFTWARE\\IronPython")) { if (ipy != null) { using (var twoSeven = ipy.OpenSubKey("2.7")) { if (twoSeven != null) { using (var installPath = twoSeven.OpenSubKey("InstallPath")) { var path = installPath.GetValue("") as string; if (path != null) { return path; } } } } } } var paths = Environment.GetEnvironmentVariable("PATH"); if (paths != null) { foreach (string dir in paths.Split(Path.PathSeparator)) { try { if (IronPythonExistsIn(dir)) { return dir; } } catch { // ignore } } } return null; } private static bool IronPythonExistsIn(string/*!*/ dir) { return File.Exists(Path.Combine(dir, "ipy.exe")); } [Serializable] class ChironNotFoundException : Exception { public ChironNotFoundException() : this("Chiron.exe was not found. Ensure the Silverlight Tools component of IronPython has been installed.") { } public ChironNotFoundException(string message) : base(message) { } public ChironNotFoundException(string message, Exception inner) : base(message, inner) { } protected ChironNotFoundException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } } }
namespace tik4net.Objects.Routing.Bgp { /// <summary> /// Access to the data provided by /// /routing/bgp/peer /// </summary> [TikEntity("/routing/bgp/peer")] public class BgpPeer { /// <summary> /// .id: /// </summary> [TikProperty(".id", IsReadOnly = true, IsMandatory = true)] public string Id { get; private set; } /// <summary> /// Gets or sets the name of the peer. /// </summary> [TikProperty("name", IsMandatory = true)] public string Name { get; set; } /// <summary> /// Gets or sets the BGP instance that this peer belongs to. /// </summary> [TikProperty("instance")] public string Instance { get; set; } /// <summary> /// Gets or sets the remote IP address of the peer. /// </summary> [TikProperty("remote-address")] public string RemoteAddress { get; set; } /// <summary> /// Gets or sets the the remote peer's autonomuous system number. /// </summary> [TikProperty("remote-as")] public long RemoteAs { get; set; } /// <summary> /// Gets or sets the next-hop choice (default, force-self, propagate). /// </summary> [TikProperty("nexthop-choice")] public string NexthopChoice { get; set; } /// <summary> /// Gets or sets a value indicating whether this is a multi-hop peer. /// </summary> [TikProperty("multihop")] public bool Multihop { get; set; } /// <summary> /// Gets or sets a value indicating whether to reflect the route. /// </summary> [TikProperty("route-reflect")] public bool RouteReflect { get; set; } /// <summary> /// Gets or sets the hold-time of this peer. /// </summary> [TikProperty("hold-time")] public string HoldTime { get; set; } /// <summary> /// Gets or sets the time-to-live setting of this peer. /// </summary> [TikProperty("ttl")] public string Ttl { get; set; } /// <summary> /// Gets or sets a comma-separated list of address families (ip, ipv6, l2vpn, vpn4, l2vpn-cisco) that are routed to/by this peer. /// </summary> [TikProperty("address-families")] public string AddressFamilies { get; set; } /// <summary> /// Gets or sets the value whether default originate (never, if-installed, always). /// </summary> [TikProperty("default-originate")] public string DefaultOriginate { get; set; } /// <summary> /// Gets or sets a value indicating whether to remove autonomuous system having private AS numbers. /// </summary> [TikProperty("remove-private-as")] public bool RemovePrivateAs { get; set; } /// <summary> /// Gets or sets a value indicating whether to override the autonomuous system numbers. /// </summary> [TikProperty("as-override")] public bool AsOverride { get; set; } /// <summary> /// Gets or sets a value indicating whether to this peer as passive. /// </summary> [TikProperty("passive")] public bool Passive { get; set; } /// <summary> /// Gets or sets a value indicating whether to use Bidirectional Forwarding Detection with this peer. /// </summary> [TikProperty("use-bfd")] public bool UseBfd { get; set; } /// <summary> /// Gets or sets the peer's remote ID (usually some IP address). /// </summary> [TikProperty("remote-id")] public string RemoteId { get; set; } /// <summary> /// Gets or sets the local IP address that is used to communicate to this peer. /// </summary> [TikProperty("local-address", IsReadOnly = true)] public string LocalAddress { get; private set; } /// <summary> /// Gets the uptime of the link to this peer. /// </summary> [TikProperty("uptime", IsReadOnly = true)] public string Uptime { get; private set; } /// <summary> /// Gets the number of prefixes advertised by this peer. /// </summary> [TikProperty("prefix-count", IsReadOnly = true)] public long PrefixCount { get; private set; } /// <summary> /// Gets the number of updates that have been sent to this peer. /// </summary> [TikProperty("updates-sent", IsReadOnly = true)] public long UpdatesSent { get; private set; } /// <summary> /// Gets the number of updates that have been received from this peer. /// </summary> [TikProperty("updates-received", IsReadOnly = true)] public long UpdatesReceived { get; private set; } /// <summary> /// Gets the number of withdrawals that have been sent to this peer. /// </summary> [TikProperty("withdrawn-sent", IsReadOnly = true)] public long WithdrawnSent { get; private set; } /// <summary> /// Gets the number of withdrawals that have been received form this peer. /// </summary> [TikProperty("withdrawn-received", IsReadOnly = true)] public long WithdrawnReceived { get; private set; } /// <summary> /// remote-hold-time: /// </summary> [TikProperty("remote-hold-time", IsReadOnly = true)] public string RemoteHoldTime { get; private set; } /// <summary> /// Gets the actually used hold-time of the link to this peer. /// </summary> [TikProperty("used-hold-time", IsReadOnly = true)] public string UsedHoldTime { get; private set; } /// <summary> /// Gets the actually used keepalive-time of the link to this peer. /// </summary> [TikProperty("used-keepalive-time", IsReadOnly = true)] public string UsedKeepaliveTime { get; private set; } /// <summary> /// Gets a value indicating whether this peer has the refresh capability. /// </summary> [TikProperty("refresh-capability", IsReadOnly = true)] public bool RefreshCapability { get; private set; } /// <summary> /// Gets a value indicating whether this peer has the AS4 capability. /// </summary> [TikProperty("as4-capability", IsReadOnly = true)] public bool As4Capability { get; private set; } /// <summary> /// Gets the state of the link to this peer. /// </summary> [TikProperty("state", IsReadOnly = true)] public string State { get; private set; } /// <summary> /// Gets a value indicating whether the link to this peer is currently established. /// </summary> [TikProperty("established", IsReadOnly = true)] public bool Established { get; private set; } /// <summary> /// Gets a value indicating whether this peer is disabled. /// </summary> [TikProperty("disabled")] public bool Disabled { get; set; } } }