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.Security.Cryptography.Xml; using System.Security.Cryptography.X509Certificates; using Xunit; using Test.Cryptography; using System.Security.Cryptography.Pkcs.Tests; namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests { public static partial class EdgeCasesTests { public static bool SupportsRc4 { get; } = ContentEncryptionAlgorithmTests.SupportsRc4; [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ImportEdgeCase() { // // Pfx's imported into a certificate collection propagate their "delete on Dispose" behavior to its cloned instances: // a subtle difference from Pfx's created using the X509Certificate2 constructor that can lead to premature or // double key deletion. Since EnvelopeCms.Decrypt() has no legitimate reason to clone the extraStore certs, this shouldn't // be a problem, but this test will verify that it isn't. // byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport()) { X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); byte[] expectedContent = { 1, 2, 3 }; ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(expectedContent, contentInfo.Content); } } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ImportEdgeCaseSki() { byte[] encodedMessage = ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158" + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83" + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46" + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba" + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport()) { X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); byte[] expectedContent = { 1, 2, 3 }; ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(new byte[] { 1, 2, 3 }, contentInfo.Content); Assert.Equal<byte>(expectedContent, contentInfo.Content); } } private static X509Certificate2 LoadPfxUsingCollectionImport(this CertLoader certLoader) { byte[] pfxData = certLoader.PfxData; string password = certLoader.Password; X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Import(pfxData, password, X509KeyStorageFlags.DefaultKeySet); Assert.Equal(1, collection.Count); return collection[0]; } [Fact] public static void ZeroLengthContextUntagged_FixedValue() { // This test ensures that we can handle when the enveloped message has no content inside. This test differs // from "ZeroLengthContent_FixedValue" in that it doesn't have a context specific [0] in the EncryptedContentInfo // section of the DER encoding of the message. // EncryptedContentInfo ::= SEQUENCE { // contentType ContentType, // contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, // encryptedContent[0] IMPLICIT EncryptedContent OPTIONAL } // The input was created with ASN1 editor and verified with .NET framework. It's an enveloped message, version 0, // with one Key Transport recipient and holds data encrypted with 3DES. byte[] content = ("3082010206092A864886F70D010703A081F43081F10201003181C83081C5020100302E301A311830160603550403130F" + "5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D06092A864886F70D0101010500" + "04818009C16B674495C2C3D4763189C3274CF7A9142FBEEC8902ABDC9CE29910D541DF910E029A31443DC9A9F3B05F02" + "DA1C38478C400261C734D6789C4197C20143C4312CEAA99ECB1849718326D4FC3B7FBB2D1D23281E31584A63E99F2C17" + "132BCD8EDDB632967125CD0A4BAA1EFA8CE4C855F7C093339211BDF990CEF5CCE6CD74302106092A864886F70D010701" + "301406082A864886F70D03070408779B3DE045826B18").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(content); int expected = PlatformDetection.IsFullFramework ? 6 : 0; // Desktop bug gives 6 Assert.Equal(expected, ecms.ContentInfo.Content.Length); Assert.Equal(Oids.Pkcs7Data, ecms.ContentInfo.ContentType.Value); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop rejects zero length content: corefx#18724")] public static void ZeroLengthContent_RoundTrip() { ContentInfo contentInfo = new ContentInfo(Array.Empty<byte>()); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); ValidateZeroLengthContent(encodedMessage); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void ZeroLengthContent_FixedValue() { byte[] encodedMessage = ("3082010406092a864886f70d010703a081f63081f30201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818009" + "c16b674495c2c3d4763189c3274cf7a9142fbeec8902abdc9ce29910d541df910e029a31443dc9a9f3b05f02da1c38478c40" + "0261c734d6789c4197c20143c4312ceaa99ecb1849718326d4fc3b7fbb2d1d23281e31584a63e99f2c17132bcd8eddb63296" + "7125cd0a4baa1efa8ce4c855f7c093339211bdf990cef5cce6cd74302306092a864886f70d010701301406082a864886f70d" + "03070408779b3de045826b188000").HexToByteArray(); ValidateZeroLengthContent(encodedMessage); } [ConditionalFact(nameof(SupportsRc4))] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void Rc4AndCngWrappersDontMixTest() { // // Combination of RC4 over a CAPI certificate. // // This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG), // the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG. // byte[] content = { 6, 3, 128, 33, 44 }; AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4)); EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4); CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate())); ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); // In order to actually use the CAPI version of the key, perphemeral loading must be specified. using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.CloneAsPerphemeralLoader().TryGetCertificateWithPrivateKey()) { if (cert == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(); extraStore.Add(cert); ecms.Decrypt(extraStore); } ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(content, contentInfo.Content); } private static void ValidateZeroLengthContent(byte[] encodedMessage) { EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { if (cert == null) return; X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); ContentInfo contentInfo = ecms.ContentInfo; byte[] content = contentInfo.Content; int expected = PlatformDetection.IsFullFramework ? 6 : 0; // Desktop bug gives 6 Assert.Equal(expected, content.Length); } } [Fact] public static void ReuseEnvelopeCmsEncodeThenDecode() { // Test ability to encrypt, encode and decode all in one EnvelopedCms instance. ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void ReuseEnvelopeCmsDecodeThenEncode() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); } [Fact] public static void EnvelopedCmsNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null)); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null, new AlgorithmIdentifier(new Oid(Oids.TripleDesCbc)))); } [Fact] public static void EnvelopedCmsNullAlgorithm() { object ignore; ContentInfo contentInfo = new ContentInfo(new byte[3]); Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(contentInfo, null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipient() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipient)null)); } [Fact] public static void EnvelopedCmsEncryptWithNullRecipients() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipientCollection)null)); } [Fact] // On the desktop, this throws up a UI for the user to select a recipient. We don't support that. [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void EnvelopedCmsEncryptWithZeroRecipients() { EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3])); Assert.Throws<PlatformNotSupportedException>(() => ecms.Encrypt(new CmsRecipientCollection())); } [Fact] public static void EnvelopedCmsNullDecode() { EnvelopedCms ecms = new EnvelopedCms(); Assert.Throws<ArgumentNullException>(() => ecms.Decode(null)); } [Fact] public static void EnvelopedCmsDecryptNullary() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt()); } [Fact] public static void EnvelopedCmsDecryptNullRecipient() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = null; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void EnvelopedCmsDecryptNullExtraStore() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = null; Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(extraStore)); Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void EnvelopedCmsDecryptWithoutMatchingCert() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void EnvelopedCmsDecryptWithoutMatchingCertSki() { // You don't have the private key? No message for you. // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { } byte[] encodedMessage = ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158" + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83" + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46" + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba" + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore)); Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore)); } [Fact] public static void AlgorithmIdentifierNullaryCtor() { AlgorithmIdentifier a = new AlgorithmIdentifier(); Assert.Equal(Oids.TripleDesCbc, a.Oid.Value); Assert.Equal(0, a.KeyLength); } [Fact] public static void CmsRecipient1AryCtor() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassUnknown() { using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient r = new CmsRecipient(SubjectIdentifierType.Unknown, cert); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType); Assert.Same(cert, r.Certificate); } } [Fact] public static void CmsRecipientPassNullCertificate() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(null)); Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, null)); } [Fact] public static void ContentInfoNullOid() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, new byte[3])); } [Fact] public static void ContentInfoNullContent() { object ignore; Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null)); Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, null)); } [Fact] public static void ContentInfoGetContentTypeNull() { Assert.Throws<ArgumentNullException>(() => ContentInfo.GetContentType(null)); } [Fact] public static void ContentInfoGetContentTypeUnknown() { byte[] encodedMessage = ("301A06092A864886F70D010700A00D040B48656C6C6F202E4E455421").HexToByteArray(); Assert.ThrowsAny<CryptographicException>(() => ContentInfo.GetContentType(encodedMessage)); } [Fact] public static void CryptographicAttributeObjectOidCtor() { Oid oid = new Oid(Oids.DocumentDescription); CryptographicAttributeObject cao = new CryptographicAttributeObject(oid); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectPassNullValuesToCtor() { Oid oid = new Oid(Oids.DocumentDescription); // This is legal and equivalent to passing a zero-length AsnEncodedDataCollection. CryptographicAttributeObject cao = new CryptographicAttributeObject(oid, null); Assert.Equal(oid.Value, cao.Oid.Value); Assert.Equal(0, cao.Values.Count); } [Fact] public static void CryptographicAttributeObjectMismatch() { Oid oid = new Oid(Oids.DocumentDescription); Oid wrongOid = new Oid(Oids.DocumentName); AsnEncodedDataCollection col = new AsnEncodedDataCollection(); col.Add(new AsnEncodedData(oid, new byte[3])); object ignore; Assert.Throws<InvalidOperationException>(() => ignore = new CryptographicAttributeObject(wrongOid, col)); } [Fact] public static void EncryptEnvelopedOctetStringWithIncompleteContent() { byte[] content = "04040203".HexToByteArray(); ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content); using (X509Certificate2 certificate = Certificates.RSAKeyTransferCapi1.GetCertificate()) { string certSubjectName = certificate.Subject; AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(Oids.Aes256)); EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg); CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, certificate); Assert.ThrowsAny<CryptographicException>(() => ecms.Encrypt(cmsRecipient)); } } [Fact] public static void EncryptEnvelopedOneByteArray() { byte[] content = "04".HexToByteArray(); ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content); using (X509Certificate2 certificate = Certificates.RSAKeyTransferCapi1.GetCertificate()) { string certSubjectName = certificate.Subject; AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(Oids.Aes256)); EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg); CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, certificate); Assert.ThrowsAny<CryptographicException>(() => ecms.Encrypt(cmsRecipient)); } } } }
// (c) Copyright 2012 Hewlett-Packard Development Company, L.P. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.IO; using System.Xml; using QTObjectModelLib; using Resources = HpToolsLauncher.Properties.Resources; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Win32; namespace HpToolsLauncher { public class GuiTestRunner : IFileSysTestRunner { // Setting keys for mobile private const string MOBILE_HOST_ADDRESS = "ALM_MobileHostAddress"; private const string MOBILE_HOST_PORT = "ALM_MobileHostPort"; private const string MOBILE_USER = "ALM_MobileUserName"; private const string MOBILE_PASSWORD = "ALM_MobilePassword"; private const string MOBILE_USE_SSL = "ALM_MobileUseSSL"; private const string MOBILE_USE_PROXY= "MobileProxySetting_UseProxy"; private const string MOBILE_PROXY_SETTING_ADDRESS = "MobileProxySetting_Address"; private const string MOBILE_PROXY_SETTING_PORT = "MobileProxySetting_Port"; private const string MOBILE_PROXY_SETTING_AUTHENTICATION = "MobileProxySetting_Authentication"; private const string MOBILE_PROXY_SETTING_USERNAME = "MobileProxySetting_UserName"; private const string MOBILE_PROXY_SETTING_PASSWORD = "MobileProxySetting_Password"; private const string MOBILE_INFO = "mobileinfo"; private readonly IAssetRunner _runNotifier; private readonly object _lockObject = new object(); private TimeSpan _timeLeftUntilTimeout = TimeSpan.MaxValue; private readonly string _uftRunMode; private Stopwatch _stopwatch = null; private Application _qtpApplication; private ParameterDefinitions _qtpParamDefs; private Parameters _qtpParameters; private bool _useUFTLicense; private RunCancelledDelegate _runCancelled; private McConnectionInfo _mcConnection; private string _mobileInfo; /// <summary> /// constructor /// </summary> /// <param name="runNotifier"></param> /// <param name="useUftLicense"></param> /// <param name="timeLeftUntilTimeout"></param> public GuiTestRunner(IAssetRunner runNotifier, bool useUftLicense, TimeSpan timeLeftUntilTimeout, string uftRunMode, McConnectionInfo mcConnectionInfo, string mobileInfo) { _timeLeftUntilTimeout = timeLeftUntilTimeout; _uftRunMode = uftRunMode; _stopwatch = Stopwatch.StartNew(); _runNotifier = runNotifier; _useUFTLicense = useUftLicense; _mcConnection = mcConnectionInfo; _mobileInfo = mobileInfo; } #region QTP /// <summary> /// runs the given test and returns resutls /// </summary> /// <param name="testPath"></param> /// <param name="errorReason"></param> /// <param name="runCanclled"></param> /// <returns></returns> public TestRunResults RunTest(TestInfo testinf, ref string errorReason, RunCancelledDelegate runCanclled) { var testPath = testinf.TestPath; TestRunResults runDesc = new TestRunResults(); ConsoleWriter.ActiveTestRun = runDesc; ConsoleWriter.WriteLine(DateTime.Now.ToString(Launcher.DateFormat) + " Running: " + testPath); runDesc.ReportLocation = testPath; runDesc.TestPath = testPath; runDesc.TestState = TestState.Unknown; _runCancelled = runCanclled; if (!Helper.IsQtpInstalled()) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = string.Format(Resources.GeneralQtpNotInstalled, System.Environment.MachineName); ConsoleWriter.WriteErrLine(runDesc.ErrorDesc); Environment.ExitCode = (int)Launcher.ExitCodeEnum.Failed; return runDesc; } string reason = string.Empty; if (!Helper.CanUftProcessStart(out reason)) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = reason; ConsoleWriter.WriteErrLine(runDesc.ErrorDesc); Environment.ExitCode = (int)Launcher.ExitCodeEnum.Failed; return runDesc; } try { ChangeDCOMSettingToInteractiveUser(); var type = Type.GetTypeFromProgID("Quicktest.Application"); lock (_lockObject) { _qtpApplication = Activator.CreateInstance(type) as Application; Version qtpVersion = Version.Parse(_qtpApplication.Version); if (qtpVersion.Equals(new Version(11, 0))) { runDesc.ReportLocation = Path.Combine(testPath, "Report"); if (Directory.Exists(runDesc.ReportLocation)) { Directory.Delete(runDesc.ReportLocation, true); Directory.CreateDirectory(runDesc.ReportLocation); } } // Check for required Addins LoadNeededAddins(testPath); // set Mc connection and other mobile info into rack if neccesary #region Mc connection and other mobile info // Mc Address, username and password if (!string.IsNullOrEmpty(_mcConnection.MobileHostAddress)) { _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_HOST_ADDRESS, _mcConnection.MobileHostAddress); if (!string.IsNullOrEmpty(_mcConnection.MobileHostPort)) { _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_HOST_PORT, _mcConnection.MobileHostPort); } } if (!string.IsNullOrEmpty(_mcConnection.MobileUserName)) { _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_USER, _mcConnection.MobileUserName); } if (!string.IsNullOrEmpty(_mcConnection.MobilePassword)) { string encriptedMcPassword = WinUserNativeMethods.ProtectBSTRToBase64(_mcConnection.MobilePassword); if (encriptedMcPassword == null) { ConsoleWriter.WriteLine("ProtectBSTRToBase64 fail for mcPassword"); throw new Exception("ProtectBSTRToBase64 fail for mcPassword"); } _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_PASSWORD, encriptedMcPassword); } // ssl and proxy info _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_USE_SSL, _mcConnection.MobileUseSSL); if (_mcConnection.MobileUseProxy == 1) { _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_USE_PROXY, _mcConnection.MobileUseProxy); _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_PROXY_SETTING_ADDRESS, _mcConnection.MobileProxySetting_Address); _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_PROXY_SETTING_PORT, _mcConnection.MobileProxySetting_Port); _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_PROXY_SETTING_AUTHENTICATION, _mcConnection.MobileProxySetting_Authentication); _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_PROXY_SETTING_USERNAME, _mcConnection.MobileProxySetting_UserName); string encriptedMcProxyPassword = WinUserNativeMethods.ProtectBSTRToBase64(_mcConnection.MobileProxySetting_Password); if (encriptedMcProxyPassword == null) { ConsoleWriter.WriteLine("ProtectBSTRToBase64 fail for mc proxy Password"); throw new Exception("ProtectBSTRToBase64 fail for mc proxy Password"); } _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_PROXY_SETTING_PASSWORD, encriptedMcProxyPassword); } // Mc info (device, app, launch and terminate data) if (!string.IsNullOrEmpty(_mobileInfo)) { _qtpApplication.TDPierToTulip.SetTestOptionsVal(MOBILE_INFO, _mobileInfo); } #endregion if (!_qtpApplication.Launched) { if (_runCancelled()) { QTPTestCleanup(); KillQtp(); runDesc.TestState = TestState.Error; return runDesc; } // Launch application after set Addins _qtpApplication.Launch(); _qtpApplication.Visible = false; } } } catch (Exception e) { errorReason = Resources.QtpNotLaunchedError; runDesc.TestState = TestState.Error; runDesc.ReportLocation = ""; runDesc.ErrorDesc = e.Message; return runDesc; } if (_qtpApplication.Test != null && _qtpApplication.Test.Modified) { var message = Resources.QtpNotLaunchedError; errorReason = message; runDesc.TestState = TestState.Error; runDesc.ErrorDesc = errorReason; return runDesc; } _qtpApplication.UseLicenseOfType(_useUFTLicense ? tagUnifiedLicenseType.qtUnifiedFunctionalTesting : tagUnifiedLicenseType.qtNonUnified); if (!HandleInputParameters(testPath, ref errorReason, testinf.GetParameterDictionaryForQTP(), testinf.DataTablePath)) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = errorReason; return runDesc; } GuiTestRunResult guiTestRunResult = ExecuteQTPRun(runDesc); runDesc.ReportLocation = guiTestRunResult.ReportPath; if (!guiTestRunResult.IsSuccess) { runDesc.TestState = TestState.Error; return runDesc; } if (!HandleOutputArguments(ref errorReason)) { runDesc.TestState = TestState.Error; runDesc.ErrorDesc = errorReason; return runDesc; } QTPTestCleanup(); return runDesc; } /// <summary> /// performs global cleanup code for this type of runner /// </summary> public void CleanUp() { try { //if we don't have a qtp instance, create one if (_qtpApplication == null) { var type = Type.GetTypeFromProgID("Quicktest.Application"); _qtpApplication = Activator.CreateInstance(type) as Application; } //if the app is running, close it. if (_qtpApplication.Launched) _qtpApplication.Quit(); } catch { //nothing to do. (cleanup code should not throw exceptions, and there is no need to log this as an error in the test) } } static HashSet<string> _colLoadedAddinNames = null; /// <summary> /// Set the test Addins /// </summary> private void LoadNeededAddins(string fileName) { bool blnNeedToLoadAddins = false; //if not launched, we have no addins. if (!_qtpApplication.Launched) _colLoadedAddinNames = null; try { HashSet<string> colCurrentTestAddins = new HashSet<string>(); object erroDescription; var testAddinsObj = _qtpApplication.GetAssociatedAddinsForTest(fileName); object[] testAddins = (object[])testAddinsObj; foreach (string addin in testAddins) { colCurrentTestAddins.Add(addin); } if (_colLoadedAddinNames != null) { //check if we have a missing addin (and need to quit Qtp, and reload with new addins) foreach (string addin in testAddins) { if (!_colLoadedAddinNames.Contains(addin)) { blnNeedToLoadAddins = true; break; } } //check if there is no extra addins that need to be removed if (_colLoadedAddinNames.Count != colCurrentTestAddins.Count) { blnNeedToLoadAddins = true; } } else { //first time = load addins. blnNeedToLoadAddins = true; } _colLoadedAddinNames = colCurrentTestAddins; //the addins need to be refreshed, load new addins if (blnNeedToLoadAddins) { if (_qtpApplication.Launched) _qtpApplication.Quit(); _qtpApplication.SetActiveAddins(ref testAddinsObj, out erroDescription); } } catch (Exception) { // Try anyway to run the test } } /// <summary> /// Activate all Installed Addins /// </summary> private void ActivateAllAddins() { try { // Get Addins collection Addins qtInstalledAddins = _qtpApplication.Addins; if (qtInstalledAddins.Count > 0) { string[] qtAddins = new string[qtInstalledAddins.Count]; // Addins Object is 1 base order for (int idx = 1; idx <= qtInstalledAddins.Count; ++idx) { // Our list is 0 base order qtAddins[idx - 1] = qtInstalledAddins[idx].Name; } object erroDescription; var addinNames = (object)qtAddins; _qtpApplication.SetActiveAddins(ref addinNames, out erroDescription); } } catch (Exception) { // Try anyway to run the test } } /// <summary> /// runs the given test QTP and returns results /// </summary> /// <param name="testResults">the test results object containing test info and also receiving run results</param> /// <returns></returns> private GuiTestRunResult ExecuteQTPRun(TestRunResults testResults) { GuiTestRunResult result = new GuiTestRunResult { IsSuccess = true }; try { Type runResultsOptionstype = Type.GetTypeFromProgID("QuickTest.RunResultsOptions"); var options = (RunResultsOptions)Activator.CreateInstance(runResultsOptionstype); options.ResultsLocation = testResults.ReportLocation; _qtpApplication.Options.Run.RunMode = _uftRunMode; //Check for cancel before executing if (_runCancelled()) { testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.GeneralTestCanceled; ConsoleWriter.WriteLine(Resources.GeneralTestCanceled); result.IsSuccess = false; return result; } ConsoleWriter.WriteLine(string.Format(Resources.FsRunnerRunningTest, testResults.TestPath)); _qtpApplication.Test.Run(options, false, _qtpParameters); result.ReportPath = Path.Combine(testResults.ReportLocation, "Report"); int slept = 0; while ((slept < 20000 && _qtpApplication.GetStatus().Equals("Ready")) || _qtpApplication.GetStatus().Equals("Waiting")) { Thread.Sleep(50); slept += 50; } while (!_runCancelled() && (_qtpApplication.GetStatus().Equals("Running") || _qtpApplication.GetStatus().Equals("Busy"))) { Thread.Sleep(200); if (_timeLeftUntilTimeout - _stopwatch.Elapsed <= TimeSpan.Zero) { _qtpApplication.Test.Stop(); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.GeneralTimeoutExpired; ConsoleWriter.WriteLine(Resources.GeneralTimeoutExpired); result.IsSuccess = false; return result; } } if (_runCancelled()) { QTPTestCleanup(); KillQtp(); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.GeneralTestCanceled; ConsoleWriter.WriteLine(Resources.GeneralTestCanceled); Launcher.ExitCode = Launcher.ExitCodeEnum.Aborted; result.IsSuccess = false; return result; } string lastError = _qtpApplication.Test.LastRunResults.LastError; //read the lastError if (!String.IsNullOrEmpty(lastError)) { testResults.TestState = TestState.Error; testResults.ErrorDesc = lastError; } // the way to check the logical success of the target QTP test is: app.Test.LastRunResults.Status == "Passed". if (_qtpApplication.Test.LastRunResults.Status.Equals("Passed")) { testResults.TestState = TestState.Passed; } else if (_qtpApplication.Test.LastRunResults.Status.Equals("Warning")) { testResults.TestState = TestState.Passed; testResults.HasWarnings = true; if (Launcher.ExitCode != Launcher.ExitCodeEnum.Failed && Launcher.ExitCode != Launcher.ExitCodeEnum.Aborted) Launcher.ExitCode = Launcher.ExitCodeEnum.Unstable; } else { testResults.TestState = TestState.Failed; testResults.FailureDesc = "Test failed"; Launcher.ExitCode = Launcher.ExitCodeEnum.Failed; } } catch (NullReferenceException e) { ConsoleWriter.WriteLine(string.Format(Resources.GeneralErrorWithStack, e.Message, e.StackTrace)); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.QtpRunError; result.IsSuccess = false; return result; } catch (SystemException e) { KillQtp(); ConsoleWriter.WriteLine(string.Format(Resources.GeneralErrorWithStack, e.Message, e.StackTrace)); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.QtpRunError; result.IsSuccess = false; return result; } catch (Exception e2) { ConsoleWriter.WriteLine(string.Format(Resources.GeneralErrorWithStack, e2.Message, e2.StackTrace)); testResults.TestState = TestState.Error; testResults.ErrorDesc = Resources.QtpRunError; result.IsSuccess = false; return result; } return result; } private void KillQtp() { //error during run, process may have crashed (need to cleanup, close QTP and qtpRemote for next test to run correctly) CleanUp(); //kill the qtp automation, to make sure it will run correctly next time Process[] processes = Process.GetProcessesByName("qtpAutomationAgent"); Process qtpAuto = processes.Where(p => p.SessionId == Process.GetCurrentProcess().SessionId).FirstOrDefault(); if (qtpAuto != null) qtpAuto.Kill(); } private bool HandleOutputArguments(ref string errorReason) { try { var outputArguments = new XmlDocument { PreserveWhitespace = true }; outputArguments.LoadXml("<Arguments/>"); for (int i = 1; i <= _qtpParamDefs.Count; ++i) { var pd = _qtpParamDefs[i]; if (pd.InOut == qtParameterDirection.qtParamDirOut) { var node = outputArguments.CreateElement(pd.Name); var value = _qtpParameters[pd.Name].Value; if (value != null) node.InnerText = value.ToString(); outputArguments.DocumentElement.AppendChild(node); } } } catch (Exception e) { errorReason = Resources.QtpNotLaunchedError; return false; } return true; } private bool VerifyParameterValueType(object paramValue, qtParameterType type) { bool legal = false; switch (type) { case qtParameterType.qtParamTypeBoolean: legal = paramValue is bool; break; case qtParameterType.qtParamTypeDate: legal = paramValue is DateTime; break; case qtParameterType.qtParamTypeNumber: legal = ((paramValue is int) || (paramValue is long) || (paramValue is decimal) || (paramValue is float) || (paramValue is double)); break; case qtParameterType.qtParamTypePassword: legal = paramValue is string; break; case qtParameterType.qtParamTypeString: legal = paramValue is string; break; default: legal = true; break; } return legal; } private bool HandleInputParameters(string fileName, ref string errorReason, Dictionary<string, object> inputParams, string dataTablePath) { try { string path = fileName; if (_runCancelled()) { QTPTestCleanup(); KillQtp(); return false; } _qtpApplication.Open(path, true, false); _qtpParamDefs = _qtpApplication.Test.ParameterDefinitions; _qtpParameters = _qtpParamDefs.GetParameters(); // handle all parameters (index starts with 1 !!!) for (int i = 1; i <= _qtpParamDefs.Count; i++) { // input parameters if (_qtpParamDefs[i].InOut == qtParameterDirection.qtParamDirIn) { string paramName = _qtpParamDefs[i].Name; qtParameterType type = _qtpParamDefs[i].Type; // if the caller supplies value for a parameter we set it if (inputParams.ContainsKey(paramName)) { // first verify that the type is correct object paramValue = inputParams[paramName]; if (!VerifyParameterValueType(paramValue, type)) { ConsoleWriter.WriteErrLine(string.Format("Illegal input parameter type (skipped). param: '{0}'. expected type: '{1}'. actual type: '{2}'", paramName, Enum.GetName(typeof(qtParameterType), type), paramValue.GetType())); } else { _qtpParameters[paramName].Value = paramValue; } } } } // specify data table path if (dataTablePath != null) { _qtpApplication.Test.Settings.Resources.DataTablePath = dataTablePath; ConsoleWriter.WriteLine("Using external data table: " + dataTablePath); } } catch (Exception e) { errorReason = Resources.QtpRunError; return false; } return true; } /// <summary> /// stops and closes qtp test, to make sure nothing is left floating after run. /// </summary> private void QTPTestCleanup() { try { lock (_lockObject) { if (_qtpApplication == null) { return; } var qtpTest = _qtpApplication.Test; if (qtpTest != null) { if (_qtpApplication.GetStatus().Equals("Running") || _qtpApplication.GetStatus().Equals("Busy")) { try { _qtpApplication.Test.Stop(); } catch (Exception e) { } finally { } } } } } catch (Exception ex) { } _qtpParameters = null; _qtpParamDefs = null; _qtpApplication = null; } /// <summary> /// Why we need this? If we run jenkins in a master slave node where there is a jenkins service installed in the slave machine, we need to change the DCOM settings as follow: /// dcomcnfg.exe -> My Computer -> DCOM Config -> QuickTest Professional Automation -> Identity -> and select The Interactive User /// </summary> private void ChangeDCOMSettingToInteractiveUser() { string errorMsg = "Unable to change DCOM settings. To chage it manually: " + "run dcomcnfg.exe -> My Computer -> DCOM Config -> QuickTest Professional Automation -> Identity -> and select The Interactive User"; string interactiveUser = "Interactive User"; string runAs = "RunAs"; try { var regKey = GetQuickTestProfessionalAutomationRegKey(RegistryView.Registry32); if (regKey == null) { regKey = GetQuickTestProfessionalAutomationRegKey(RegistryView.Registry64); } if (regKey == null) throw new Exception(@"Unable to find in registry SOFTWARE\Classes\AppID\{A67EB23A-1B8F-487D-8E38-A6A3DD150F0B"); object runAsKey = regKey.GetValue(runAs); if (runAsKey == null || !runAsKey.ToString().Equals(interactiveUser)) { regKey.SetValue(runAs, interactiveUser); } } catch (Exception ex) { throw new Exception(errorMsg + "detailed error is : " + ex.Message); } } private RegistryKey GetQuickTestProfessionalAutomationRegKey(RegistryView registryView) { RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); localKey = localKey.OpenSubKey(@"SOFTWARE\Classes\AppID\{A67EB23A-1B8F-487D-8E38-A6A3DD150F0B}", true); return localKey; } #endregion /// <summary> /// holds the resutls for a GUI test /// </summary> private class GuiTestRunResult { public GuiTestRunResult() { ReportPath = ""; } public bool IsSuccess { get; set; } public string ReportPath { get; set; } } } }
// // assembly.cs: Assembly declaration and specifications // // Authors: // Miguel de Icaza ([email protected]) // Marek Safar ([email protected]) // // Copyright 2001, 2002, 2003 Ximian, Inc. // Copyright 2004-2011 Novell, Inc. // Copyright 2011-2013 Xamarin Inc // using System; using System.IO; using System.Collections.Generic; using System.Globalization; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using Mono.Security.Cryptography; using Mono.CompilerServices.SymbolWriter; using System.Linq; #if STATIC using IKVM.Reflection; using IKVM.Reflection.Emit; using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>; #else using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>; using System.Reflection; using System.Reflection.Emit; #endif namespace Mono.CSharp { public interface IAssemblyDefinition { string FullName { get; } bool IsCLSCompliant { get; } bool IsMissing { get; } string Name { get; } byte[] GetPublicKeyToken (); bool IsFriendAssemblyTo (IAssemblyDefinition assembly); } public class AssemblyReferenceMessageInfo { public AssemblyReferenceMessageInfo (AssemblyName dependencyName, Action<Report> reportMessage) { this.DependencyName = dependencyName; this.ReportMessage = reportMessage; } public AssemblyName DependencyName { get; private set; } public Action<Report> ReportMessage { get; private set; } } public abstract class AssemblyDefinition : IAssemblyDefinition { // TODO: make it private and move all builder based methods here public AssemblyBuilder Builder; protected AssemblyBuilderExtension builder_extra; MonoSymbolFile symbol_writer; bool is_cls_compliant; bool wrap_non_exception_throws; bool wrap_non_exception_throws_custom; bool has_user_debuggable; protected ModuleContainer module; readonly string name; protected readonly string file_name; byte[] public_key, public_key_token; bool delay_sign; // Holds private/public key pair when private key // was available StrongNameKeyPair private_key; Attribute cls_attribute; Method entry_point; protected List<ImportedModuleDefinition> added_modules; SecurityType declarative_security; Dictionary<ITypeDefinition, Attribute> emitted_forwarders; AssemblyAttributesPlaceholder module_target_attrs; // Win32 version info values string vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark; string pa_file_version, pa_assembly_version; protected AssemblyDefinition (ModuleContainer module, string name) { this.module = module; this.name = Path.GetFileNameWithoutExtension (name); wrap_non_exception_throws = true; delay_sign = Compiler.Settings.StrongNameDelaySign; // // Load strong name key early enough for assembly importer to be able to // use the keys for InternalsVisibleTo // This should go somewhere close to ReferencesLoading but don't have the place yet // if (Compiler.Settings.HasKeyFileOrContainer) { LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer); } } protected AssemblyDefinition (ModuleContainer module, string name, string fileName) : this (module, name) { this.file_name = fileName; } #region Properties public Attribute CLSCompliantAttribute { get { return cls_attribute; } } public CompilerContext Compiler { get { return module.Compiler; } } // // Assembly entry point, aka Main method // public Method EntryPoint { get { return entry_point; } set { entry_point = value; } } public string FullName { get { return Builder.FullName; } } public bool HasCLSCompliantAttribute { get { return cls_attribute != null; } } // TODO: This should not exist here but will require more changes public MetadataImporter Importer { get; set; } public bool IsCLSCompliant { get { return is_cls_compliant; } } bool IAssemblyDefinition.IsMissing { get { return false; } } public bool IsSatelliteAssembly { get; private set; } public string Name { get { return name; } } public bool WrapNonExceptionThrows { get { return wrap_non_exception_throws; } } protected Report Report { get { return Compiler.Report; } } public MonoSymbolFile SymbolWriter { get { return symbol_writer; } } #endregion public void AddModule (ImportedModuleDefinition module) { if (added_modules == null) { added_modules = new List<ImportedModuleDefinition> (); added_modules.Add (module); } } public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { if (a.IsValidSecurityAttribute ()) { a.ExtractSecurityPermissionSet (ctor, ref declarative_security); return; } if (a.Type == pa.AssemblyCulture) { string value = a.GetString (); if (value == null || value.Length == 0) return; if (Compiler.Settings.Target == Target.Exe) { Report.Error (7059, a.Location, "Executables cannot be satellite assemblies. Remove the attribute or keep it empty"); return; } if (value == "neutral") value = ""; if (Compiler.Settings.Target == Target.Module) { SetCustomAttribute (ctor, cdata); } else { builder_extra.SetCulture (value, a.Location); } IsSatelliteAssembly = true; return; } if (a.Type == pa.AssemblyVersion) { string value = a.GetString (); if (value == null || value.Length == 0) return; var vinfo = IsValidAssemblyVersion (value, true); if (vinfo == null) { Report.Error (7034, a.Location, "The specified version string `{0}' does not conform to the required format - major[.minor[.build[.revision]]]", value); return; } if (Compiler.Settings.Target == Target.Module) { SetCustomAttribute (ctor, cdata); } else { builder_extra.SetVersion (vinfo, a.Location); pa_assembly_version = vinfo.ToString (); } return; } if (a.Type == pa.AssemblyAlgorithmId) { const int pos = 2; // skip CA header uint alg = (uint) cdata [pos]; alg |= ((uint) cdata [pos + 1]) << 8; alg |= ((uint) cdata [pos + 2]) << 16; alg |= ((uint) cdata [pos + 3]) << 24; if (Compiler.Settings.Target == Target.Module) { SetCustomAttribute (ctor, cdata); } else { builder_extra.SetAlgorithmId (alg, a.Location); } return; } if (a.Type == pa.AssemblyFlags) { const int pos = 2; // skip CA header uint flags = (uint) cdata[pos]; flags |= ((uint) cdata [pos + 1]) << 8; flags |= ((uint) cdata [pos + 2]) << 16; flags |= ((uint) cdata [pos + 3]) << 24; // Ignore set PublicKey flag if assembly is not strongnamed if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null) flags &= ~(uint) AssemblyNameFlags.PublicKey; if (Compiler.Settings.Target == Target.Module) { SetCustomAttribute (ctor, cdata); } else { builder_extra.SetFlags (flags, a.Location); } return; } if (a.Type == pa.TypeForwarder) { TypeSpec t = a.GetArgumentType (); if (t == null || TypeManager.HasElementType (t)) { Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute"); return; } if (emitted_forwarders == null) { emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> (); } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) { Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null); Report.Error (739, a.Location, "A duplicate type forward of type `{0}'", t.GetSignatureForError ()); return; } emitted_forwarders.Add (t.MemberDefinition, a); if (t.MemberDefinition.DeclaringAssembly == this) { Report.SymbolRelatedToPreviousError (t); Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly", t.GetSignatureForError ()); return; } if (t.IsNested) { Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type", t.GetSignatureForError ()); return; } AddTypeForwarders (t, a.Location); return; } if (a.Type == pa.Extension) { a.Error_MisusedExtensionAttribute (); return; } if (a.Type == pa.InternalsVisibleTo) { string assembly_name = a.GetString (); if (assembly_name == null) { Report.Error (7030, a.Location, "Friend assembly reference cannot have `null' value"); return; } if (assembly_name.Length == 0) return; #if STATIC ParsedAssemblyName aname; ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname); if (r != ParseAssemblyResult.OK) { Report.Warning (1700, 3, a.Location, "Friend assembly reference `{0}' is invalid and cannot be resolved", assembly_name); return; } if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) { Report.Error (1725, a.Location, "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified", assembly_name); return; } if (public_key != null && !aname.HasPublicKey) { Report.Error (1726, a.Location, "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations", assembly_name); return; } #endif } else if (a.Type == pa.RuntimeCompatibility) { wrap_non_exception_throws_custom = true; } else if (a.Type == pa.AssemblyFileVersion) { pa_file_version = a.GetString (); if (string.IsNullOrEmpty (pa_file_version) || IsValidAssemblyVersion (pa_file_version, false) == null) { Report.Warning (7035, 1, a.Location, "The specified version string `{0}' does not conform to the recommended format major.minor.build.revision", pa_file_version, a.Name); return; } // File version info decoding from blob is not supported var cab = new CustomAttributeBuilder ((ConstructorInfo)ctor.GetMetaInfo (), new object [] { pa_file_version }); Builder.SetCustomAttribute (cab); return; } else if (a.Type == pa.AssemblyProduct) { vi_product = a.GetString (); } else if (a.Type == pa.AssemblyCompany) { vi_company = a.GetString (); } else if (a.Type == pa.AssemblyCopyright) { vi_copyright = a.GetString (); } else if (a.Type == pa.AssemblyTrademark) { vi_trademark = a.GetString (); } else if (a.Type == pa.Debuggable) { has_user_debuggable = true; } else if (a.Type == pa.AssemblyInformationalVersion) { vi_product_version = a.GetString (); } // // Win32 version info attributes AssemblyDescription and AssemblyTitle cannot be // set using public API and because we have blob like attributes we need to use // special option DecodeVersionInfoAttributeBlobs to support values extraction // SetCustomAttribute (ctor, cdata); } void AddTypeForwarders (TypeSpec type, Location loc) { builder_extra.AddTypeForwarder (type.GetDefinition (), loc); var ntypes = MemberCache.GetDeclaredNestedTypes (type); if (ntypes == null) return; foreach (var nested in ntypes) { if (nested.IsPrivate) continue; AddTypeForwarders (nested, loc); } } // // When using assembly public key attributes InternalsVisibleTo key // was not checked, we have to do it later when we actually know what // our public key token is // void CheckReferencesPublicToken () { var references = builder_extra.GetReferencedAssemblies (); foreach (var an in references) { if (public_key != null && an.GetPublicKey ().Length == 0) { Report.Error (1577, "Referenced assembly `{0}' does not have a strong name", an.FullName); } var ci = an.CultureInfo; if (!ci.Equals (CultureInfo.InvariantCulture)) { Report.Warning (8009, 1, "Referenced assembly `{0}' has different culture setting of `{1}'", an.Name, ci.Name); } var ia = Importer.GetImportedAssemblyDefinition (an); if (ia == null) continue; var an_references = GetNotUnifiedReferences (an); if (an_references != null) { foreach (var r in an_references) { // // Secondary check when assembly references is resolved but not used. For example // due to type-forwarding // if (references.Any (l => l.Name == r.DependencyName.Name)) { r.ReportMessage (Report); } } } if (!ia.IsFriendAssemblyTo (this)) continue; var attr = ia.GetAssemblyVisibleToName (this); var atoken = attr.GetPublicKeyToken (); if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken)) continue; Report.SymbolRelatedToPreviousError (ia.Location); Report.Error (281, "Friend access was granted to `{0}', but the output assembly is named `{1}'. Try adding a reference to `{0}' or change the output assembly name to match it", attr.FullName, FullName); } } protected AssemblyName CreateAssemblyName () { var an = new AssemblyName (name); if (public_key != null && Compiler.Settings.Target != Target.Module) { if (delay_sign) { an.SetPublicKey (public_key); } else { if (public_key.Length == 16) { Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies"); } else if (private_key == null) { Error_AssemblySigning ("The specified key file does not have a private key"); } else { an.KeyPair = private_key; } } } return an; } public virtual ModuleBuilder CreateModuleBuilder () { if (file_name == null) throw new NotSupportedException ("transient module in static assembly"); var module_name = Path.GetFileName (file_name); // Always initialize module without symbolInfo. We could be framework dependent // but returned ISymbolWriter does not have all what we need therefore some // adaptor will be needed for now we alwayas emit MDB format when generating // debug info return Builder.DefineDynamicModule (module_name, module_name, false); } public virtual void Emit () { if (Compiler.Settings.Target == Target.Module) { module_target_attrs = new AssemblyAttributesPlaceholder (module, name); module_target_attrs.CreateContainer (); module_target_attrs.DefineContainer (); module_target_attrs.Define (); module.AddCompilerGeneratedClass (module_target_attrs); } else if (added_modules != null) { ReadModulesAssemblyAttributes (); } if (Compiler.Settings.GenerateDebugInfo) { symbol_writer = new MonoSymbolFile (); } module.EmitContainer (); if (module.HasExtensionMethod) { var pa = module.PredefinedAttributes.Extension; if (pa.IsDefined) { SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty); } } if (!IsSatelliteAssembly) { if (!has_user_debuggable && Compiler.Settings.GenerateDebugInfo) { var pa = module.PredefinedAttributes.Debuggable; if (pa.IsDefined) { var modes = System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints; if (!Compiler.Settings.Optimize) modes |= System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations; pa.EmitAttribute (Builder, modes); } } if (!wrap_non_exception_throws_custom) { PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility; if (pa.IsDefined && pa.ResolveBuilder ()) { var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get (); if (prop != null) { AttributeEncoder encoder = new AttributeEncoder (); encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null)); SetCustomAttribute (pa.Constructor, encoder.ToArray ()); } } } if (declarative_security != null) { #if STATIC foreach (var entry in declarative_security) { Builder.__AddDeclarativeSecurity (entry); } #else throw new NotSupportedException ("Assembly-level security"); #endif } } CheckReferencesPublicToken (); SetEntryPoint (); } public byte[] GetPublicKeyToken () { if (public_key == null || public_key_token != null) return public_key_token; HashAlgorithm ha = SHA1.Create (); byte[] hash = ha.ComputeHash (public_key); // we need the last 8 bytes in reverse order public_key_token = new byte[8]; Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8); Array.Reverse (public_key_token, 0, 8); return public_key_token; } protected virtual List<AssemblyReferenceMessageInfo> GetNotUnifiedReferences (AssemblyName assemblyName) { return null; } // // Either keyFile or keyContainer has to be non-null // void LoadPublicKey (string keyFile, string keyContainer) { if (keyContainer != null) { try { private_key = new StrongNameKeyPair (keyContainer); public_key = private_key.PublicKey; } catch { Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist"); } return; } bool key_file_exists = File.Exists (keyFile); // // For attribute based KeyFile do additional lookup // in output assembly path // if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) { // // The key file can be relative to output assembly // string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile); key_file_exists = File.Exists (test_path); if (key_file_exists) keyFile = test_path; } if (!key_file_exists) { Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist"); return; } using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) { byte[] snkeypair = new byte[fs.Length]; fs.Read (snkeypair, 0, snkeypair.Length); // check for ECMA key if (snkeypair.Length == 16) { public_key = snkeypair; return; } try { // take it, with or without, a private key RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair); // and make sure we only feed the public part to Sys.Ref byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa); // AssemblyName.SetPublicKey requires an additional header byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 }; // Encode public key public_key = new byte[12 + publickey.Length]; Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length); // Length of Public Key (in bytes) int lastPart = public_key.Length - 12; public_key[8] = (byte) (lastPart & 0xFF); public_key[9] = (byte) ((lastPart >> 8) & 0xFF); public_key[10] = (byte) ((lastPart >> 16) & 0xFF); public_key[11] = (byte) ((lastPart >> 24) & 0xFF); Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length); } catch { Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format"); return; } if (delay_sign) return; try { // TODO: Is there better way to test for a private key presence ? CryptoConvert.FromCapiPrivateKeyBlob (snkeypair); private_key = new StrongNameKeyPair (snkeypair); } catch { } } } void ReadModulesAssemblyAttributes () { foreach (var m in added_modules) { var cattrs = m.ReadAssemblyAttributes (); if (cattrs == null) continue; module.OptAttributes.AddAttributes (cattrs); } } public void Resolve () { if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) { // // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)] // when -unsafe option was specified // Location loc = Location.Null; MemberAccess system_security_permissions = new MemberAccess (new MemberAccess ( new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc); var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc); Arguments pos = new Arguments (1); pos.Add (new Argument (req_min.GetConstant (null))); Arguments named = new Arguments (1); named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc))); Attribute g = new Attribute ("assembly", new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"), new Arguments[] { pos, named }, loc, false); g.AttachTo (module, module); // Disable no-location warnings (e.g. obsolete) for compiler generated attribute Compiler.Report.DisableReporting (); try { var ctor = g.Resolve (); if (ctor != null) { g.ExtractSecurityPermissionSet (ctor, ref declarative_security); } } finally { Compiler.Report.EnableReporting (); } } if (module.OptAttributes == null) return; // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types. if (!module.OptAttributes.CheckTargets()) return; cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant); if (cls_attribute != null) { is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue (); } if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) { foreach (var m in added_modules) { if (!m.IsCLSCompliant) { Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", m.Name); } } } Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility); if (a != null) { var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant; if (val != null) wrap_non_exception_throws = val.Value; } } protected void ResolveAssemblySecurityAttributes () { string key_file = null; string key_container = null; if (module.OptAttributes != null) { foreach (Attribute a in module.OptAttributes.Attrs) { // cannot rely on any resolve-based members before you call Resolve if (a.ExplicitTarget != "assembly") continue; // TODO: This code is buggy: comparing Attribute name without resolving is wrong. // However, this is invoked by CodeGen.Init, when none of the namespaces // are loaded yet. // TODO: Does not handle quoted attributes properly switch (a.Name) { case "AssemblyKeyFile": case "AssemblyKeyFileAttribute": case "System.Reflection.AssemblyKeyFileAttribute": if (Compiler.Settings.StrongNameKeyFile != null) { Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ()); Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module", "keyfile", "System.Reflection.AssemblyKeyFileAttribute"); } else { string value = a.GetString (); if (!string.IsNullOrEmpty (value)) { Error_ObsoleteSecurityAttribute (a, "keyfile"); key_file = value; } } break; case "AssemblyKeyName": case "AssemblyKeyNameAttribute": case "System.Reflection.AssemblyKeyNameAttribute": if (Compiler.Settings.StrongNameKeyContainer != null) { Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ()); Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module", "keycontainer", "System.Reflection.AssemblyKeyNameAttribute"); } else { string value = a.GetString (); if (!string.IsNullOrEmpty (value)) { Error_ObsoleteSecurityAttribute (a, "keycontainer"); key_container = value; } } break; case "AssemblyDelaySign": case "AssemblyDelaySignAttribute": case "System.Reflection.AssemblyDelaySignAttribute": bool b = a.GetBoolean (); if (b) { Error_ObsoleteSecurityAttribute (a, "delaysign"); } delay_sign = b; break; } } } // We came here only to report assembly attributes warnings if (public_key != null) return; // // Load the strong key file found in attributes when no // command line key was given // if (key_file != null || key_container != null) { LoadPublicKey (key_file, key_container); } else if (delay_sign) { Report.Warning (1607, 1, "Delay signing was requested but no key file was given"); } } public void EmbedResources () { // // Add Win32 resources // if (Compiler.Settings.Win32ResourceFile != null) { Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile); } else { Builder.DefineVersionInfoResource (vi_product, vi_product_version ?? pa_file_version ?? pa_assembly_version, vi_company, vi_copyright, vi_trademark); } if (Compiler.Settings.Win32IconFile != null) { builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile); } if (Compiler.Settings.Resources != null) { if (Compiler.Settings.Target == Target.Module) { Report.Error (1507, "Cannot link resource file when building a module"); } else { int counter = 0; foreach (var res in Compiler.Settings.Resources) { if (!File.Exists (res.FileName)) { Report.Error (1566, "Error reading resource file `{0}'", res.FileName); continue; } if (res.IsEmbeded) { Stream stream; if (counter++ < 10) { stream = File.OpenRead (res.FileName); } else { // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save // we workaround it by reading everything into memory to compile projects with // many embedded resource (over 3500) references stream = new MemoryStream (File.ReadAllBytes (res.FileName)); } module.Builder.DefineManifestResource (res.Name, stream, res.Attributes); } else { Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes); } } } } } public void Save () { PortableExecutableKinds pekind = PortableExecutableKinds.ILOnly; ImageFileMachine machine; switch (Compiler.Settings.Platform) { case Platform.X86: pekind |= PortableExecutableKinds.Required32Bit; machine = ImageFileMachine.I386; break; case Platform.X64: pekind |= PortableExecutableKinds.PE32Plus; machine = ImageFileMachine.AMD64; break; case Platform.IA64: machine = ImageFileMachine.IA64; break; case Platform.AnyCPU32Preferred: #if STATIC pekind |= PortableExecutableKinds.Preferred32Bit; machine = ImageFileMachine.I386; break; #else throw new NotSupportedException (); #endif case Platform.Arm: #if STATIC machine = ImageFileMachine.ARM; break; #else throw new NotSupportedException (); #endif case Platform.AnyCPU: default: machine = ImageFileMachine.I386; break; } Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave); try { if (Compiler.Settings.Target == Target.Module) { SaveModule (pekind, machine); } else { Builder.Save (module.Builder.ScopeName, pekind, machine); } } catch (ArgumentOutOfRangeException) { Report.Error (16, "Output file `{0}' exceeds the 4GB limit", name); } catch (Exception e) { Report.Error (16, "Could not write to file `{0}'. {1}", name, e.Message); } Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave); // Save debug symbols file if (symbol_writer != null && Compiler.Report.Errors == 0) { // TODO: it should run in parallel Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave); var filename = file_name + ".mdb"; try { // We mmap the file, so unlink the previous version since it may be in use File.Delete (filename); } catch { // We can safely ignore } module.WriteDebugSymbol (symbol_writer); using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) { symbol_writer.CreateSymbolFile (module.Builder.ModuleVersionId, fs); } Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave); } } protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine) { Report.RuntimeMissingSupport (Location.Null, "-target:module"); } void SetCustomAttribute (MethodSpec ctor, byte[] data) { if (module_target_attrs != null) module_target_attrs.AddAssemblyAttribute (ctor, data); else Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data); } void SetEntryPoint () { if (!Compiler.Settings.NeedsEntryPoint) { if (Compiler.Settings.MainClass != null) Report.Error (2017, "Cannot specify -main if building a module or library"); return; } PEFileKinds file_kind; switch (Compiler.Settings.Target) { case Target.Library: case Target.Module: file_kind = PEFileKinds.Dll; break; case Target.WinExe: file_kind = PEFileKinds.WindowApplication; break; default: file_kind = PEFileKinds.ConsoleApplication; break; } if (entry_point == null) { string main_class = Compiler.Settings.MainClass; if (main_class != null) { // TODO: Handle dotted names var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null); if (texpr == null) { Report.Error (1555, "Could not find `{0}' specified for Main method", main_class); return; } var mtype = texpr.MemberDefinition as ClassOrStruct; if (mtype == null) { Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class); return; } Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ()); } else { string pname = file_name == null ? name : Path.GetFileName (file_name); Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point", pname); } return; } Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind); } void Error_ObsoleteSecurityAttribute (Attribute a, string option) { Report.Warning (1699, 1, a.Location, "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute", option, a.Name); } void Error_AssemblySigning (string text) { Report.Error (1548, "Error during assembly signing. " + text); } public bool IsFriendAssemblyTo (IAssemblyDefinition assembly) { return false; } static Version IsValidAssemblyVersion (string version, bool allowGenerated) { string[] parts = version.Split ('.'); if (parts.Length < 1 || parts.Length > 4) return null; var values = new int[4]; for (int i = 0; i < parts.Length; ++i) { if (!int.TryParse (parts[i], out values[i])) { if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) { if (i == 2) { // Nothing can follow * if (parts.Length > 3) return null; // Generate Build value based on days since 1/1/2000 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1); values[i] = System.Math.Max (days.Days, 0); i = 3; } if (i == 3) { // Generate Revision value based on every other second today var seconds = DateTime.Now - DateTime.Today; values[i] = (int) seconds.TotalSeconds / 2; continue; } } return null; } if (values[i] > ushort.MaxValue) return null; } return new Version (values[0], values[1], values[2], values[3]); } } public class AssemblyResource : IEquatable<AssemblyResource> { public AssemblyResource (string fileName, string name) : this (fileName, name, false) { } public AssemblyResource (string fileName, string name, bool isPrivate) { FileName = fileName; Name = name; Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public; } public ResourceAttributes Attributes { get; private set; } public string Name { get; private set; } public string FileName { get; private set; } public bool IsEmbeded { get; set; } #region IEquatable<AssemblyResource> Members public bool Equals (AssemblyResource other) { return Name == other.Name; } #endregion } // // A placeholder class for assembly attributes when emitting module // class AssemblyAttributesPlaceholder : CompilerGeneratedContainer { static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>"; public static readonly string AssemblyFieldName = "attributes"; Field assembly; public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName) : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC | Modifiers.INTERNAL) { assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC, new MemberName (AssemblyFieldName), null); AddField (assembly); } public void AddAssemblyAttribute (MethodSpec ctor, byte[] data) { assembly.SetCustomAttribute (ctor, data); } public static string GetGeneratedName (string outputName) { return string.Format (TypeNamePrefix, outputName); } } // // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible // compiler. This is a default implementation for framework System.Reflection.Emit // which does not implement any of the methods // public class AssemblyBuilderExtension { protected readonly CompilerContext ctx; public AssemblyBuilderExtension (CompilerContext ctx) { this.ctx = ctx; } public virtual System.Reflection.Module AddModule (string module) { ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule"); return null; } public virtual void AddPermissionRequests (PermissionSet[] permissions) { ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security"); } public virtual void AddTypeForwarder (TypeSpec type, Location loc) { ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute"); } public virtual void DefineWin32IconResource (string fileName) { ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon"); } public virtual AssemblyName[] GetReferencedAssemblies () { return null; } public virtual void SetAlgorithmId (uint value, Location loc) { ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute"); } public virtual void SetCulture (string culture, Location loc) { ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute"); } public virtual void SetFlags (uint flags, Location loc) { ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute"); } public virtual void SetVersion (Version version, Location loc) { ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute"); } } abstract class AssemblyReferencesLoader<T> where T : class { protected readonly CompilerContext compiler; protected readonly List<string> paths; protected AssemblyReferencesLoader (CompilerContext compiler) { this.compiler = compiler; paths = new List<string> (); paths.Add (Directory.GetCurrentDirectory ()); paths.AddRange (compiler.Settings.ReferencesLookupPaths); } public abstract T HasObjectType (T assembly); protected abstract string[] GetDefaultReferences (); public abstract T LoadAssemblyFile (string fileName, bool isImplicitReference); public abstract void LoadReferences (ModuleContainer module); protected void Error_FileNotFound (string fileName) { compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName); } protected void Error_FileCorrupted (string fileName) { compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName); } protected void Error_AssemblyIsModule (string fileName) { compiler.Report.Error (1509, "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module", fileName); } protected void Error_ModuleIsAssembly (string fileName) { compiler.Report.Error (1542, "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file", fileName); } protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded) { compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading); loaded = new List<Tuple<RootNamespace, T>> (); // // Load mscorlib.dll as the first // if (module.Compiler.Settings.StdLib) { corlib_assembly = LoadAssemblyFile ("mscorlib.dll", true); } else { corlib_assembly = default (T); } T a; foreach (string r in module.Compiler.Settings.AssemblyReferences) { a = LoadAssemblyFile (r, false); if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly)) continue; var key = Tuple.Create (module.GlobalRootNamespace, a); if (loaded.Contains (key)) continue; loaded.Add (key); } if (corlib_assembly == null) { // // Requires second pass because HasObjectType can trigger assembly load event // for (int i = 0; i < loaded.Count; ++i) { var assembly = loaded [i]; // // corlib assembly is the first referenced assembly which contains System.Object // corlib_assembly = HasObjectType (assembly.Item2); if (corlib_assembly != null) { if (corlib_assembly != assembly.Item2) { var ca = corlib_assembly; i = loaded.FindIndex (l => l.Item2 == ca); } if (i >= 0) loaded.RemoveAt (i); break; } } } foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) { a = LoadAssemblyFile (entry.Item2, false); if (a == null) continue; var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a); if (loaded.Contains (key)) continue; loaded.Add (key); } if (compiler.Settings.LoadDefaultReferences) { foreach (string r in GetDefaultReferences ()) { a = LoadAssemblyFile (r, true); if (a == null) continue; var key = Tuple.Create (module.GlobalRootNamespace, a); if (loaded.Contains (key)) continue; loaded.Add (key); } } compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { [System.Security.SecurityCriticalAttribute] public sealed partial class SafeAccessTokenHandle : System.Runtime.InteropServices.SafeHandle { public SafeAccessTokenHandle(System.IntPtr handle) : base(default(System.IntPtr), default(bool)) { } public static Microsoft.Win32.SafeHandles.SafeAccessTokenHandle InvalidHandle {[System.Security.SecurityCriticalAttribute]get { return default(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle); } } public override bool IsInvalid {[System.Security.SecurityCriticalAttribute]get { return default(bool); } } [System.Security.SecurityCriticalAttribute] protected override bool ReleaseHandle() { return default(bool); } } } namespace System.Security.Principal { public sealed partial class IdentityNotMappedException : System.Exception { public IdentityNotMappedException() { } public IdentityNotMappedException(string message) { } public IdentityNotMappedException(string message, System.Exception inner) { } public System.Security.Principal.IdentityReferenceCollection UnmappedIdentities { get { return default(System.Security.Principal.IdentityReferenceCollection); } } } public abstract partial class IdentityReference { internal IdentityReference() { } public abstract string Value { get; } public abstract override bool Equals(object o); public abstract override int GetHashCode(); public abstract bool IsValidTargetType(System.Type targetType); public static bool operator ==(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { return default(bool); } public static bool operator !=(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { return default(bool); } public abstract override string ToString(); public abstract System.Security.Principal.IdentityReference Translate(System.Type targetType); } public partial class IdentityReferenceCollection : System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>, System.Collections.Generic.IEnumerable<System.Security.Principal.IdentityReference>, System.Collections.IEnumerable { public IdentityReferenceCollection() { } public IdentityReferenceCollection(int capacity) { } public int Count { get { return default(int); } } public System.Security.Principal.IdentityReference this[int index] { get { return default(System.Security.Principal.IdentityReference); } set { } } bool System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>.IsReadOnly { get { return default(bool); } } public void Add(System.Security.Principal.IdentityReference identity) { } public void Clear() { } public bool Contains(System.Security.Principal.IdentityReference identity) { return default(bool); } public void CopyTo(System.Security.Principal.IdentityReference[] array, int offset) { } public System.Collections.Generic.IEnumerator<System.Security.Principal.IdentityReference> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Security.Principal.IdentityReference>); } public bool Remove(System.Security.Principal.IdentityReference identity) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType) { return default(System.Security.Principal.IdentityReferenceCollection); } public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType, bool forceSuccess) { return default(System.Security.Principal.IdentityReferenceCollection); } } public sealed partial class NTAccount : System.Security.Principal.IdentityReference { public NTAccount(string name) { } public NTAccount(string domainName, string accountName) { } public override string Value { get { return default(string); } } public override bool Equals(object o) { return default(bool); } public override int GetHashCode() { return default(int); } public override bool IsValidTargetType(System.Type targetType) { return default(bool); } public static bool operator ==(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { return default(bool); } public static bool operator !=(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { return default(bool); } public override string ToString() { return default(string); } public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { return default(System.Security.Principal.IdentityReference); } } public sealed partial class SecurityIdentifier : System.Security.Principal.IdentityReference, System.IComparable<System.Security.Principal.SecurityIdentifier> { public static readonly int MaxBinaryLength; public static readonly int MinBinaryLength; public SecurityIdentifier(byte[] binaryForm, int offset) { } public SecurityIdentifier(System.IntPtr binaryForm) { } public SecurityIdentifier(System.Security.Principal.WellKnownSidType sidType, System.Security.Principal.SecurityIdentifier domainSid) { } public SecurityIdentifier(string sddlForm) { } public System.Security.Principal.SecurityIdentifier AccountDomainSid { get { return default(System.Security.Principal.SecurityIdentifier); } } public int BinaryLength { get { return default(int); } } public override string Value { get { return default(string); } } public int CompareTo(System.Security.Principal.SecurityIdentifier sid) { return default(int); } public override bool Equals(object o) { return default(bool); } public bool Equals(System.Security.Principal.SecurityIdentifier sid) { return default(bool); } public void GetBinaryForm(byte[] binaryForm, int offset) { } public override int GetHashCode() { return default(int); } public bool IsAccountSid() { return default(bool); } public bool IsEqualDomainSid(System.Security.Principal.SecurityIdentifier sid) { return default(bool); } public override bool IsValidTargetType(System.Type targetType) { return default(bool); } public bool IsWellKnown(System.Security.Principal.WellKnownSidType type) { return default(bool); } public static bool operator ==(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { return default(bool); } public static bool operator !=(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { return default(bool); } public override string ToString() { return default(string); } public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { return default(System.Security.Principal.IdentityReference); } } [System.FlagsAttribute] public enum TokenAccessLevels { AdjustDefault = 128, AdjustGroups = 64, AdjustPrivileges = 32, AdjustSessionId = 256, AllAccess = 983551, AssignPrimary = 1, Duplicate = 2, Impersonate = 4, MaximumAllowed = 33554432, Query = 8, QuerySource = 16, Read = 131080, Write = 131296, } public enum WellKnownSidType { AccountAdministratorSid = 38, AccountCertAdminsSid = 46, AccountComputersSid = 44, AccountControllersSid = 45, AccountDomainAdminsSid = 41, AccountDomainGuestsSid = 43, AccountDomainUsersSid = 42, AccountEnterpriseAdminsSid = 48, AccountGuestSid = 39, AccountKrbtgtSid = 40, AccountPolicyAdminsSid = 49, AccountRasAndIasServersSid = 50, AccountSchemaAdminsSid = 47, AnonymousSid = 13, AuthenticatedUserSid = 17, BatchSid = 10, BuiltinAccountOperatorsSid = 30, BuiltinAdministratorsSid = 26, BuiltinAuthorizationAccessSid = 59, BuiltinBackupOperatorsSid = 33, BuiltinDomainSid = 25, BuiltinGuestsSid = 28, BuiltinIncomingForestTrustBuildersSid = 56, BuiltinNetworkConfigurationOperatorsSid = 37, BuiltinPerformanceLoggingUsersSid = 58, BuiltinPerformanceMonitoringUsersSid = 57, BuiltinPowerUsersSid = 29, BuiltinPreWindows2000CompatibleAccessSid = 35, BuiltinPrintOperatorsSid = 32, BuiltinRemoteDesktopUsersSid = 36, BuiltinReplicatorSid = 34, BuiltinSystemOperatorsSid = 31, BuiltinUsersSid = 27, CreatorGroupServerSid = 6, CreatorGroupSid = 4, CreatorOwnerServerSid = 5, CreatorOwnerSid = 3, DialupSid = 8, DigestAuthenticationSid = 52, EnterpriseControllersSid = 15, InteractiveSid = 11, LocalServiceSid = 23, LocalSid = 2, LocalSystemSid = 22, LogonIdsSid = 21, MaxDefined = 60, NetworkServiceSid = 24, NetworkSid = 9, NTAuthoritySid = 7, NtlmAuthenticationSid = 51, NullSid = 0, OtherOrganizationSid = 55, ProxySid = 14, RemoteLogonIdSid = 20, RestrictedCodeSid = 18, SChannelAuthenticationSid = 53, SelfSid = 16, ServiceSid = 12, TerminalServerSid = 19, ThisOrganizationSid = 54, WinBuiltinTerminalServerLicenseServersSid = 60, WorldSid = 1, } public enum WindowsBuiltInRole { AccountOperator = 548, Administrator = 544, BackupOperator = 551, Guest = 546, PowerUser = 547, PrintOperator = 550, Replicator = 552, SystemOperator = 549, User = 545, } public partial class WindowsIdentity : System.Security.Claims.ClaimsIdentity, System.IDisposable { public new const string DefaultIssuer = "AD AUTHORITY"; public WindowsIdentity(System.IntPtr userToken) { } public WindowsIdentity(System.IntPtr userToken, string type) { } public WindowsIdentity(string sUserPrincipalName) { } public Microsoft.Win32.SafeHandles.SafeAccessTokenHandle AccessToken {[System.Security.SecurityCriticalAttribute]get { return default(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle); } } public sealed override string AuthenticationType { get { return default(string); } } public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } } public System.Security.Principal.IdentityReferenceCollection Groups { get { return default(System.Security.Principal.IdentityReferenceCollection); } } public System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get { return default(System.Security.Principal.TokenImpersonationLevel); } } public virtual bool IsAnonymous { get { return default(bool); } } public override bool IsAuthenticated { get { return default(bool); } } public virtual bool IsGuest { get { return default(bool); } } public virtual bool IsSystem { get { return default(bool); } } public override string Name { get { return default(string); } } public System.Security.Principal.SecurityIdentifier Owner { get { return default(System.Security.Principal.SecurityIdentifier); } } public virtual IntPtr Token { get { return default(System.IntPtr); } } public System.Security.Principal.SecurityIdentifier User { get { return default(System.Security.Principal.SecurityIdentifier); } } public override System.Security.Claims.ClaimsIdentity Clone() { return default(System.Security.Claims.ClaimsIdentity); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public static System.Security.Principal.WindowsIdentity GetAnonymous() { return default(System.Security.Principal.WindowsIdentity); } public static System.Security.Principal.WindowsIdentity GetCurrent() { return default(System.Security.Principal.WindowsIdentity); } public static System.Security.Principal.WindowsIdentity GetCurrent(bool ifImpersonating) { return default(System.Security.Principal.WindowsIdentity); } public static System.Security.Principal.WindowsIdentity GetCurrent(System.Security.Principal.TokenAccessLevels desiredAccess) { return default(System.Security.Principal.WindowsIdentity); } public static void RunImpersonated(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Action action) { } public static T RunImpersonated<T>(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Func<T> func) { return default(T); } } public partial class WindowsPrincipal : System.Security.Claims.ClaimsPrincipal { public WindowsPrincipal(System.Security.Principal.WindowsIdentity ntIdentity) { } public override System.Security.Principal.IIdentity Identity { get { return default(System.Security.Principal.IIdentity); } } public virtual bool IsInRole(int rid) { return default(bool); } public virtual bool IsInRole(System.Security.Principal.SecurityIdentifier sid) { return default(bool); } public virtual bool IsInRole(System.Security.Principal.WindowsBuiltInRole role) { return default(bool); } public override bool IsInRole(string role) { return default(bool); } } }
using System; using System.Collections; using System.IO; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Xml; using Umbraco.Core.Logging; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.businesslogic.Exceptions; using umbraco.cms.businesslogic.media; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.web; using umbraco.presentation.channels.businesslogic; using umbraco.uicontrols; using umbraco.providers; using umbraco.cms.presentation.Trees; using umbraco.IO; using Umbraco.Core; namespace umbraco.cms.presentation.user { /// <summary> /// Summary description for EditUser. /// </summary> public partial class EditUser : UmbracoEnsuredPage { public EditUser() { CurrentApp = BusinessLogic.DefaultApps.users.ToString(); } protected HtmlTable macroProperties; protected TextBox uname = new TextBox(); protected TextBox lname = new TextBox(); protected PlaceHolder passw = new PlaceHolder(); protected CheckBoxList lapps = new CheckBoxList(); protected TextBox email = new TextBox(); protected DropDownList userType = new DropDownList(); protected DropDownList userLanguage = new DropDownList(); protected CheckBox NoConsole = new CheckBox(); protected CheckBox Disabled = new CheckBox(); protected CheckBox DefaultToLiveEditing = new CheckBox(); protected controls.ContentPicker mediaPicker = new umbraco.controls.ContentPicker(); protected controls.ContentPicker contentPicker = new umbraco.controls.ContentPicker(); protected TextBox cName = new TextBox(); protected CheckBox cFulltree = new CheckBox(); protected DropDownList cDocumentType = new DropDownList(); protected DropDownList cDescription = new DropDownList(); protected DropDownList cCategories = new DropDownList(); protected DropDownList cExcerpt = new DropDownList(); protected controls.ContentPicker cMediaPicker = new umbraco.controls.ContentPicker(); protected controls.ContentPicker cContentPicker = new umbraco.controls.ContentPicker(); protected CustomValidator sectionValidator = new CustomValidator(); protected Pane pp = new Pane(); private User u; protected void Page_Load(object sender, EventArgs e) { //if the current user is not an admin they cannot edit a user at all if (CurrentUser.IsAdmin() == false) { throw new UserAuthorizationException("Access denied"); } int UID = int.Parse(Request.QueryString["id"]); u = BusinessLogic.User.GetUser(UID); //the true admin can only edit the true admin if (u.Id == 0 && CurrentUser.Id != 0) { throw new Exception("Only the root user can edit the 'root' user (id:0)"); } //only another admin can edit another admin (who is not the true admin) if (u.IsAdmin() && CurrentUser.IsAdmin() == false) { throw new Exception("Admin users can only be edited by admins"); } // check if canvas editing is enabled DefaultToLiveEditing.Visible = UmbracoSettings.EnableCanvasEditing; // Populate usertype list foreach (UserType ut in UserType.getAll) { if (CurrentUser.IsAdmin() || ut.Alias != "admin") { ListItem li = new ListItem(ui.Text("user", ut.Name.ToLower(), base.getUser()), ut.Id.ToString()); if (ut.Id == u.UserType.Id) li.Selected = true; userType.Items.Add(li); } } // Populate ui language lsit foreach ( string f in Directory.GetFiles(IOHelper.MapPath(SystemDirectories.Umbraco + "/config/lang"), "*.xml") ) { XmlDocument x = new XmlDocument(); x.Load(f); ListItem li = new ListItem(x.DocumentElement.Attributes.GetNamedItem("intName").Value, x.DocumentElement.Attributes.GetNamedItem("alias").Value); if (x.DocumentElement.Attributes.GetNamedItem("alias").Value == u.Language) li.Selected = true; userLanguage.Items.Add(li); } // Console access and disabling NoConsole.Checked = u.NoConsole; Disabled.Checked = u.Disabled; DefaultToLiveEditing.Checked = u.DefaultToLiveEditing; PlaceHolder medias = new PlaceHolder(); mediaPicker.AppAlias = Constants.Applications.Media; mediaPicker.TreeAlias = "media"; if (u.StartMediaId > 0) mediaPicker.Value = u.StartMediaId.ToString(); else mediaPicker.Value = "-1"; medias.Controls.Add(mediaPicker); PlaceHolder content = new PlaceHolder(); contentPicker.AppAlias = Constants.Applications.Content; contentPicker.TreeAlias = "content"; if (u.StartNodeId > 0) contentPicker.Value = u.StartNodeId.ToString(); else contentPicker.Value = "-1"; content.Controls.Add(contentPicker); // Add password changer passw.Controls.Add(new UserControl().LoadControl(SystemDirectories.Umbraco + "/controls/passwordChanger.ascx")); pp.addProperty(ui.Text("user", "username", base.getUser()), uname); pp.addProperty(ui.Text("user", "loginname", base.getUser()), lname); pp.addProperty(ui.Text("user", "password", base.getUser()), passw); pp.addProperty(ui.Text("email", base.getUser()), email); pp.addProperty(ui.Text("user", "usertype", base.getUser()), userType); pp.addProperty(ui.Text("user", "language", base.getUser()), userLanguage); //Media / content root nodes Pane ppNodes = new Pane(); ppNodes.addProperty(ui.Text("user", "startnode", base.getUser()), content); ppNodes.addProperty(ui.Text("user", "mediastartnode", base.getUser()), medias); //Generel umrbaco access Pane ppAccess = new Pane(); if (UmbracoSettings.EnableCanvasEditing) { ppAccess.addProperty(ui.Text("user", "defaultToLiveEditing", base.getUser()), DefaultToLiveEditing); } ppAccess.addProperty(ui.Text("user", "noConsole", base.getUser()), NoConsole); ppAccess.addProperty(ui.Text("user", "disabled", base.getUser()), Disabled); //access to which modules... Pane ppModules = new Pane(); ppModules.addProperty(ui.Text("user", "modules", base.getUser()), lapps); ppModules.addProperty(" ", sectionValidator); TabPage userInfo = UserTabs.NewTabPage(u.Name); userInfo.Controls.Add(pp); userInfo.Controls.Add(ppNodes); userInfo.Controls.Add(ppAccess); userInfo.Controls.Add(ppModules); userInfo.Style.Add("text-align", "center"); userInfo.HasMenu = true; ImageButton save = userInfo.Menu.NewImageButton(); save.ImageUrl = SystemDirectories.Umbraco + "/images/editor/save.gif"; save.Click += new ImageClickEventHandler(saveUser_Click); sectionValidator.ServerValidate += new ServerValidateEventHandler(sectionValidator_ServerValidate); sectionValidator.ControlToValidate = lapps.ID; sectionValidator.ErrorMessage = ui.Text("errorHandling", "errorMandatoryWithoutTab", ui.Text("user", "modules", base.getUser()), base.getUser()); sectionValidator.CssClass = "error"; setupForm(); setupChannel(); ClientTools .SetActiveTreeType(TreeDefinitionCollection.Instance.FindTree<loadUsers>().Tree.Alias) .SyncTree(UID.ToString(), IsPostBack); } void sectionValidator_ServerValidate(object source, ServerValidateEventArgs args) { args.IsValid = false; if (lapps.SelectedIndex >= 0) args.IsValid = true; } private void setupChannel() { Channel userChannel; try { userChannel = new Channel(u.Id); } catch { userChannel = new Channel(); } // Populate dropdowns foreach (DocumentType dt in DocumentType.GetAllAsList()) cDocumentType.Items.Add( new ListItem(dt.Text, dt.Alias) ); // populate fields ArrayList fields = new ArrayList(); cDescription.ID = "cDescription"; cCategories.ID = "cCategories"; cExcerpt.ID = "cExcerpt"; cDescription.Items.Add(new ListItem(ui.Text("choose"), "")); cCategories.Items.Add(new ListItem(ui.Text("choose"), "")); cExcerpt.Items.Add(new ListItem(ui.Text("choose"), "")); foreach (PropertyType pt in PropertyType.GetAll()) { if (!fields.Contains(pt.Alias)) { cDescription.Items.Add(new ListItem(string.Format("{0} ({1})", pt.Name, pt.Alias), pt.Alias)); cCategories.Items.Add(new ListItem(string.Format("{0} ({1})", pt.Name, pt.Alias), pt.Alias)); cExcerpt.Items.Add(new ListItem(string.Format("{0} ({1})", pt.Name, pt.Alias), pt.Alias)); fields.Add(pt.Alias); } } // Handle content and media pickers PlaceHolder medias = new PlaceHolder(); cMediaPicker.AppAlias = Constants.Applications.Media; cMediaPicker.TreeAlias = "media"; if (userChannel.MediaFolder > 0) cMediaPicker.Value = userChannel.MediaFolder.ToString(); else cMediaPicker.Value = "-1"; medias.Controls.Add(cMediaPicker); PlaceHolder content = new PlaceHolder(); cContentPicker.AppAlias = Constants.Applications.Content; cContentPicker.TreeAlias = "content"; if (userChannel.StartNode > 0) cContentPicker.Value = userChannel.StartNode.ToString(); else cContentPicker.Value = "-1"; content.Controls.Add(cContentPicker); // Setup the panes Pane ppInfo = new Pane(); ppInfo.addProperty(ui.Text("name", base.getUser()), cName); ppInfo.addProperty(ui.Text("user", "startnode", base.getUser()), content); ppInfo.addProperty(ui.Text("user", "searchAllChildren", base.getUser()), cFulltree); ppInfo.addProperty(ui.Text("user", "mediastartnode", base.getUser()), medias); Pane ppFields = new Pane(); ppFields.addProperty(ui.Text("user", "documentType", base.getUser()), cDocumentType); ppFields.addProperty(ui.Text("user", "descriptionField", base.getUser()), cDescription); ppFields.addProperty(ui.Text("user", "categoryField", base.getUser()), cCategories); ppFields.addProperty(ui.Text("user", "excerptField", base.getUser()), cExcerpt); TabPage channelInfo = UserTabs.NewTabPage(ui.Text("user", "contentChannel", base.getUser())); channelInfo.Controls.Add(ppInfo); channelInfo.Controls.Add(ppFields); channelInfo.HasMenu = true; ImageButton save = channelInfo.Menu.NewImageButton(); save.ImageUrl = SystemDirectories.Umbraco + "/images/editor/save.gif"; save.Click += new ImageClickEventHandler(saveUser_Click); save.ID = "save"; if (!IsPostBack) { cName.Text = userChannel.Name; cDescription.SelectedValue = userChannel.FieldDescriptionAlias; cCategories.SelectedValue = userChannel.FieldCategoriesAlias; cExcerpt.SelectedValue = userChannel.FieldExcerptAlias; cDocumentType.SelectedValue = userChannel.DocumentTypeAlias; cFulltree.Checked = userChannel.FullTree; } } /// <summary> /// Setups the form. /// </summary> private void setupForm() { if (!IsPostBack) { MembershipUser user = Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].GetUser(u.LoginName, true); uname.Text = u.Name; lname.Text = (user == null) ? u.LoginName : user.UserName; email.Text = (user == null) ? u.Email : user.Email; // Prevent users from changing information if logged in through active directory membership provider // active directory-mapped accounts have empty passwords by default... so set update user fields to read only // this will not be a security issue because empty passwords are not allowed in membership provider. // This might change in version 4.0 if (string.IsNullOrEmpty(u.GetPassword())) { uname.ReadOnly = true; lname.ReadOnly = true; email.ReadOnly = true; passw.Visible = false; } contentPicker.Value = u.StartNodeId.ToString(); mediaPicker.Value = u.StartMediaId.ToString(); // get the current users applications string currentUserApps = ";"; foreach (Application a in CurrentUser.Applications) currentUserApps += a.alias + ";"; Application[] uapps = u.Applications; foreach (Application app in BusinessLogic.Application.getAll()) { if (CurrentUser.IsRoot() || currentUserApps.Contains(";" + app.alias + ";")) { ListItem li = new ListItem(ui.Text("sections", app.alias), app.alias); if (!IsPostBack) foreach (Application tmp in uapps) if (app.alias == tmp.alias) li.Selected = true; lapps.Items.Add(li); } } } } protected override void OnInit(EventArgs e) { base.OnInit(e); //lapps.SelectionMode = ListSelectionMode.Multiple; lapps.RepeatLayout = RepeatLayout.Flow; lapps.RepeatDirection = RepeatDirection.Vertical; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("../webservices/CMSNode.asmx")); // ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("../webservices/legacyAjaxCalls.asmx")); } /// <summary> /// Handles the Click event of the saveUser control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param> private void saveUser_Click(object sender, ImageClickEventArgs e) { if (base.IsValid) { try { MembershipUser user = Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].GetUser(u.LoginName, true); string tempPassword = ((controls.passwordChanger)passw.Controls[0]).Password; if (!string.IsNullOrEmpty(tempPassword.Trim())) { // make sure password is not empty if (string.IsNullOrEmpty(u.Password)) u.Password = "default"; user.ChangePassword(u.Password, tempPassword); } // Is it using the default membership provider if (Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is UsersMembershipProvider) { // Save user in membership provider UsersMembershipUser umbracoUser = user as UsersMembershipUser; umbracoUser.FullName = uname.Text.Trim(); umbracoUser.Language = userLanguage.SelectedValue; umbracoUser.UserType = UserType.GetUserType(int.Parse(userType.SelectedValue)); Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(umbracoUser); // Save user details u.Email = email.Text.Trim(); u.Language = userLanguage.SelectedValue; } else { u.Name = uname.Text.Trim(); u.Language = userLanguage.SelectedValue; u.UserType = UserType.GetUserType(int.Parse(userType.SelectedValue)); if (!(Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is ActiveDirectoryMembershipProvider)) Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(user); } u.LoginName = lname.Text; //u.StartNodeId = int.Parse(startNode.Value); int startNode; if (!int.TryParse(contentPicker.Value, out startNode)) { //set to default if nothing is choosen if (u.StartNodeId > 0) startNode = u.StartNodeId; else startNode = -1; } u.StartNodeId = startNode; u.Disabled = Disabled.Checked; u.DefaultToLiveEditing = DefaultToLiveEditing.Checked; u.NoConsole = NoConsole.Checked; //u.StartMediaId = int.Parse(mediaStartNode.Value); int mstartNode; if (!int.TryParse(mediaPicker.Value, out mstartNode)) { //set to default if nothing is choosen if (u.StartMediaId > 0) mstartNode = u.StartMediaId; else mstartNode = -1; } u.StartMediaId = mstartNode; u.clearApplications(); foreach (ListItem li in lapps.Items) { if (li.Selected) u.addApplication(li.Value); } u.Save(); // save data if (cName.Text != "") { Channel c; try { c = new Channel(u.Id); } catch { c = new Channel(); c.User = u; } c.Name = cName.Text; c.FullTree = cFulltree.Checked; c.StartNode = int.Parse(cContentPicker.Value); c.MediaFolder = int.Parse(cMediaPicker.Value); c.FieldCategoriesAlias = cCategories.SelectedValue; c.FieldDescriptionAlias = cDescription.SelectedValue; c.FieldExcerptAlias = cExcerpt.SelectedValue; c.DocumentTypeAlias = cDocumentType.SelectedValue; // c.MediaTypeAlias = Constants.Conventions.MediaTypes.Image; // [LK:2013-03-22] This was previously lowercase; unsure if using const will cause an issue. c.MediaTypeFileProperty = Constants.Conventions.Media.File; c.ImageSupport = true; c.Save(); } ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editUserSaved", base.getUser()), ""); } catch (Exception ex) { ClientTools.ShowSpeechBubble(speechBubbleIcon.error, ui.Text("speechBubbles", "editUserError", base.getUser()), ""); LogHelper.Error<EditUser>("Exception", ex); } } else { ClientTools.ShowSpeechBubble(speechBubbleIcon.error, ui.Text("speechBubbles", "editUserError", base.getUser()), ""); } } } }
// // Copyright 2012, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; using Xamarin.Utilities; #if PLATFORM_IOS using AuthenticateUIType = MonoTouch.UIKit.UIViewController; #elif PLATFORM_ANDROID using AuthenticateUIType = Android.Content.Intent; using UIContext = Android.Content.Context; #else using AuthenticateUIType = System.Object; #endif namespace Xamarin.Auth { /// <summary> /// A process and user interface to authenticate a user. /// </summary> #if XAMARIN_AUTH_INTERNAL internal abstract class Authenticator #else public abstract class Authenticator #endif { /// <summary> /// Gets or sets the title of any UI elements that need to be presented for this authenticator. /// </summary> /// <value><c>"Authenticate" by default.</c></value> public string Title { get; set; } /// <summary> /// Gets or sets whether to allow user cancellation. /// </summary> /// <value><c>true</c> by default.</value> public bool AllowCancel { get; set; } /// <summary> /// Occurs when authentication has been successfully or unsuccessfully completed. /// Consult the <see cref="AuthenticatorCompletedEventArgs.IsAuthenticated"/> event argument to determine if /// authentication was successful. /// </summary> public event EventHandler<AuthenticatorCompletedEventArgs> Completed; /// <summary> /// Occurs when there an error is encountered when authenticating. /// </summary> public event EventHandler<AuthenticatorErrorEventArgs> Error; /// <summary> /// Gets whether this authenticator has completed its interaction with the user. /// </summary> /// <value><c>true</c> if authorization has been completed, <c>false</c> otherwise.</value> public bool HasCompleted { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.Authenticator"/> class. /// </summary> public Authenticator () { Title = "Authenticate"; HasCompleted = false; AllowCancel = true; } #if PLATFORM_ANDROID UIContext context; public AuthenticateUIType GetUI (UIContext context) { this.context = context; return GetPlatformUI (context); } protected abstract AuthenticateUIType GetPlatformUI (UIContext context); #else /// <summary> /// Gets the UI for this authenticator. /// </summary> /// <returns> /// The UI that needs to be presented. /// </returns> public AuthenticateUIType GetUI () { return GetPlatformUI (); } /// <summary> /// Gets the UI for this authenticator. /// </summary> /// <returns> /// The UI that needs to be presented. /// </returns> protected abstract AuthenticateUIType GetPlatformUI (); #endif /// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='account'> /// The authenticated account. /// </param> public void OnSucceeded (Account account) { if (HasCompleted) return; HasCompleted = true; BeginInvokeOnUIThread (delegate { var ev = Completed; if (ev != null) { ev (this, new AuthenticatorCompletedEventArgs (account)); } }); } /// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='username'> /// User name of the account. /// </param> /// <param name='accountProperties'> /// Additional data, such as access tokens, that need to be stored with the account. This /// information is secured. /// </param> public void OnSucceeded (string username, IDictionary<string, string> accountProperties) { OnSucceeded (new Account (username, accountProperties)); } /// <summary> /// Implementations must call this function when they have cancelled the operation. /// </summary> public void OnCancelled () { if (HasCompleted) return; HasCompleted = true; BeginInvokeOnUIThread (delegate { var ev = Completed; if (ev != null) { ev (this, new AuthenticatorCompletedEventArgs (null)); } }); } /// <summary> /// Implementations must call this function when they have failed to authenticate. /// </summary> /// <param name='message'> /// The reason that this authentication has failed. /// </param> public void OnError (string message) { BeginInvokeOnUIThread (delegate { var ev = Error; if (ev != null) { ev (this, new AuthenticatorErrorEventArgs (message)); } }); } /// <summary> /// Implementations must call this function when they have failed to authenticate. /// </summary> /// <param name='exception'> /// The reason that this authentication has failed. /// </param> public void OnError (Exception exception) { BeginInvokeOnUIThread (delegate { var ev = Error; if (ev != null) { ev (this, new AuthenticatorErrorEventArgs (exception)); } }); } void BeginInvokeOnUIThread (Action action) { #if PLATFORM_IOS MonoTouch.UIKit.UIApplication.SharedApplication.BeginInvokeOnMainThread (delegate { action (); }); #elif PLATFORM_ANDROID var a = context as Android.App.Activity; if (a != null) { a.RunOnUiThread (action); } else { action (); } #else action (); #endif } } /// <summary> /// Authenticator completed event arguments. /// </summary> #if XAMARIN_AUTH_INTERNAL internal class AuthenticatorCompletedEventArgs : EventArgs #else public class AuthenticatorCompletedEventArgs : EventArgs #endif { /// <summary> /// Whether the authentication succeeded and there is a valid <see cref="Account"/>. /// </summary> /// <value> /// <see langword="true"/> if the user is authenticated; otherwise, <see langword="false"/>. /// </value> public bool IsAuthenticated { get { return Account != null; } } /// <summary> /// Gets the account created that represents this authentication. /// </summary> /// <value> /// The account. /// </value> public Account Account { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorCompletedEventArgs"/> class. /// </summary> /// <param name='account'> /// The account created or <see langword="null"/> if authentication failed or was canceled. /// </param> public AuthenticatorCompletedEventArgs (Account account) { Account = account; } } /// <summary> /// Authenticator error event arguments. /// </summary> #if XAMARIN_AUTH_INTERNAL internal class AuthenticatorErrorEventArgs : EventArgs #else public class AuthenticatorErrorEventArgs : EventArgs #endif { /// <summary> /// Gets a message describing the error. /// </summary> /// <value> /// The message. /// </value> public string Message { get; private set; } /// <summary> /// Gets the exception that signaled the error if there was one. /// </summary> /// <value> /// The exception or <see langword="null"/>. /// </value> public Exception Exception { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorErrorEventArgs"/> class /// with a message but no exception. /// </summary> /// <param name='message'> /// A message describing the error. /// </param> public AuthenticatorErrorEventArgs (string message) { Message = message; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.AuthenticatorErrorEventArgs"/> class with an exception. /// </summary> /// <param name='exception'> /// The exception signaling the error. The message of this object is retrieved from this exception or /// its inner exceptions. /// </param> public AuthenticatorErrorEventArgs (Exception exception) { Message = exception.GetUserMessage (); Exception = exception; } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if !PORTABLE using System; namespace NUnit.Framework.Internal { /// <summary> /// PlatformHelper class is used by the PlatformAttribute class to /// determine whether a platform is supported. /// </summary> public class PlatformHelper { private OSPlatform os; private RuntimeFramework rt; // Set whenever we fail to support a list of platforms private string reason = string.Empty; /// <summary> /// Comma-delimited list of all supported OS platform constants /// </summary> public static readonly string OSPlatforms = #if (CLR_2_0 || CLR_4_0) && !NETCF "Win,Win32,Win32S,Win32NT,Win32Windows,WinCE,Win95,Win98,WinMe,NT3,NT4,NT5,NT6,Win2K,WinXP,Win2003Server,Vista,Win2008Server,Win2008ServerR2,Win2012Server,Windows7,Windows8,Unix,Linux,Xbox,MacOSX"; #else "Win,Win32,Win32S,Win32NT,Win32Windows,WinCE,Win95,Win98,WinMe,NT3,NT4,NT5,NT6,Win2K,WinXP,Win2003Server,Vista,Win2008Server,Win2008ServerR2,Win2012Server,Windows7,Windows8,Unix,Linux"; #endif /// <summary> /// Comma-delimited list of all supported Runtime platform constants /// </summary> public static readonly string RuntimePlatforms = "Net,NetCF,SSCLI,Rotor,Mono,MonoTouch"; /// <summary> /// Default constructor uses the operating system and /// common language runtime of the system. /// </summary> public PlatformHelper() { this.os = OSPlatform.CurrentPlatform; this.rt = RuntimeFramework.CurrentFramework; } /// <summary> /// Contruct a PlatformHelper for a particular operating /// system and common language runtime. Used in testing. /// </summary> /// <param name="os">OperatingSystem to be used</param> /// <param name="rt">RuntimeFramework to be used</param> public PlatformHelper( OSPlatform os, RuntimeFramework rt ) { this.os = os; this.rt = rt; } /// <summary> /// Test to determine if one of a collection of platforms /// is being used currently. /// </summary> /// <param name="platforms"></param> /// <returns></returns> public bool IsPlatformSupported( string[] platforms ) { foreach( string platform in platforms ) if ( IsPlatformSupported( platform ) ) return true; return false; } /// <summary> /// Tests to determine if the current platform is supported /// based on a platform attribute. /// </summary> /// <param name="platformAttribute">The attribute to examine</param> /// <returns></returns> public bool IsPlatformSupported( PlatformAttribute platformAttribute ) { string include = platformAttribute.Include; string exclude = platformAttribute.Exclude; try { if (include != null && !IsPlatformSupported(include)) { reason = string.Format("Only supported on {0}", include); return false; } if (exclude != null && IsPlatformSupported(exclude)) { reason = string.Format("Not supported on {0}", exclude); return false; } } catch (Exception ex) { reason = ex.Message; return false; } return true; } /// <summary> /// Test to determine if the a particular platform or comma- /// delimited set of platforms is in use. /// </summary> /// <param name="platform">Name of the platform or comma-separated list of platform names</param> /// <returns>True if the platform is in use on the system</returns> public bool IsPlatformSupported( string platform ) { if ( platform.IndexOf( ',' ) >= 0 ) return IsPlatformSupported( platform.Split( new char[] { ',' } ) ); string platformName = platform.Trim(); bool isSupported = false; // string versionSpecification = null; // // string[] parts = platformName.Split( new char[] { '-' } ); // if ( parts.Length == 2 ) // { // platformName = parts[0]; // versionSpecification = parts[1]; // } switch( platformName.ToUpper() ) { case "WIN": case "WIN32": isSupported = os.IsWindows; break; case "WIN32S": isSupported = os.IsWin32S; break; case "WIN32WINDOWS": isSupported = os.IsWin32Windows; break; case "WIN32NT": isSupported = os.IsWin32NT; break; case "WINCE": isSupported = os.IsWinCE; break; case "WIN95": isSupported = os.IsWin95; break; case "WIN98": isSupported = os.IsWin98; break; case "WINME": isSupported = os.IsWinME; break; case "NT3": isSupported = os.IsNT3; break; case "NT4": isSupported = os.IsNT4; break; case "NT5": isSupported = os.IsNT5; break; case "WIN2K": isSupported = os.IsWin2K; break; case "WINXP": isSupported = os.IsWinXP; break; case "WIN2003SERVER": isSupported = os.IsWin2003Server; break; case "NT6": isSupported = os.IsNT6; break; case "VISTA": isSupported = os.IsVista; break; case "WIN2008SERVER": isSupported = os.IsWin2008Server; break; case "WIN2008SERVERR2": isSupported = os.IsWin2008ServerR2; break; case "WIN2012SERVER": isSupported = os.IsWin2012Server; break; case "WINDOWS7": isSupported = os.IsWindows7; break; case "WINDOWS8": isSupported = os.IsWindows8; break; case "UNIX": case "LINUX": isSupported = os.IsUnix; break; #if (CLR_2_0 || CLR_4_0) && !NETCF case "XBOX": isSupported = os.IsXbox; break; case "MACOSX": isSupported = os.IsMacOSX; break; #endif default: isSupported = IsRuntimeSupported(platformName); break; } if (!isSupported) this.reason = "Only supported on " + platform; return isSupported; } /// <summary> /// Return the last failure reason. Results are not /// defined if called before IsSupported( Attribute ) /// is called. /// </summary> public string Reason { get { return reason; } } private bool IsRuntimeSupported(string platformName) { string versionSpecification = null; string[] parts = platformName.Split(new char[] { '-' }); if (parts.Length == 2) { platformName = parts[0]; versionSpecification = parts[1]; } switch (platformName.ToUpper()) { case "NET": return IsRuntimeSupported(RuntimeType.Net, versionSpecification); case "NETCF": return IsRuntimeSupported(RuntimeType.NetCF, versionSpecification); case "SSCLI": case "ROTOR": return IsRuntimeSupported(RuntimeType.SSCLI, versionSpecification); case "MONO": return IsRuntimeSupported(RuntimeType.Mono, versionSpecification); case "SL": case "SILVERLIGHT": return IsRuntimeSupported(RuntimeType.Silverlight, versionSpecification); case "MONOTOUCH": return IsRuntimeSupported(RuntimeType.MonoTouch, versionSpecification); default: throw new ArgumentException("Invalid platform name", platformName); } } private bool IsRuntimeSupported(RuntimeType runtime, string versionSpecification) { Version version = versionSpecification == null ? RuntimeFramework.DefaultVersion : new Version(versionSpecification); RuntimeFramework target = new RuntimeFramework(runtime, version); return rt.Supports(target); } } } #endif
namespace AutoMapper { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Impl; using Internal; public class TypeMapFactory : ITypeMapFactory { private readonly Internal.IDictionary<Type, TypeInfo> _typeInfos = PlatformAdapter.Resolve<IDictionaryFactory>().CreateDictionary<Type, TypeInfo>(); public TypeMap CreateTypeMap(Type sourceType, Type destinationType, IMappingOptions options, MemberList memberList) { var sourceTypeInfo = GetTypeInfo(sourceType, options); var destTypeInfo = GetTypeInfo(destinationType, options.ShouldMapProperty, options.ShouldMapField, new MethodInfo[0]); var typeMap = new TypeMap(sourceTypeInfo, destTypeInfo, memberList); foreach (var destProperty in destTypeInfo.PublicWriteAccessors) { var members = new LinkedList<MemberInfo>(); if (MapDestinationPropertyToSource(members, sourceTypeInfo, destProperty.Name, options)) { var resolvers = members.Select(mi => mi.ToMemberGetter()); var destPropertyAccessor = destProperty.ToMemberAccessor(); typeMap.AddPropertyMap(destPropertyAccessor, resolvers.Cast<IValueResolver>()); } } if (!destinationType.IsAbstract() && destinationType.IsClass()) { foreach (var destCtor in destTypeInfo.Constructors.OrderByDescending(ci => ci.GetParameters().Length)) { if (MapDestinationCtorToSource(typeMap, destCtor, sourceTypeInfo, options)) { break; } } } return typeMap; } private bool MapDestinationCtorToSource(TypeMap typeMap, ConstructorInfo destCtor, TypeInfo sourceTypeInfo, IMappingOptions options) { var parameters = new List<ConstructorParameterMap>(); var ctorParameters = destCtor.GetParameters(); if (ctorParameters.Length == 0 || !options.ConstructorMappingEnabled) return false; foreach (var parameter in ctorParameters) { var members = new LinkedList<MemberInfo>(); if (!MapDestinationPropertyToSource(members, sourceTypeInfo, parameter.Name, options)) return false; var resolvers = members.Select(mi => mi.ToMemberGetter()); var param = new ConstructorParameterMap(parameter, resolvers.ToArray()); parameters.Add(param); } typeMap.AddConstructorMap(destCtor, parameters); return true; } private TypeInfo GetTypeInfo(Type type, IMappingOptions mappingOptions) { return GetTypeInfo(type, mappingOptions.ShouldMapProperty, mappingOptions.ShouldMapField, mappingOptions.SourceExtensionMethods); } private TypeInfo GetTypeInfo(Type type, Func<PropertyInfo, bool> shouldMapProperty, Func<FieldInfo, bool> shouldMapField, IEnumerable<MethodInfo> extensionMethodsToSearch) { return _typeInfos.GetOrAdd(type, t => new TypeInfo(type, shouldMapProperty, shouldMapField, extensionMethodsToSearch)); } private bool MapDestinationPropertyToSource(LinkedList<MemberInfo> resolvers, TypeInfo sourceType, string nameToSearch, IMappingOptions mappingOptions) { if (string.IsNullOrEmpty(nameToSearch)) return true; var sourceProperties = sourceType.PublicReadAccessors; var sourceNoArgMethods = sourceType.PublicNoArgMethods; var sourceNoArgExtensionMethods = sourceType.PublicNoArgExtensionMethods; MemberInfo resolver = FindTypeMember(sourceProperties, sourceNoArgMethods, sourceNoArgExtensionMethods, nameToSearch, mappingOptions); bool foundMatch = resolver != null; if (foundMatch) { resolvers.AddLast(resolver); } else { string[] matches = mappingOptions.DestinationMemberNamingConvention.SplittingExpression .Matches(nameToSearch) .Cast<Match>() .Select(m => m.Value) .ToArray(); for (int i = 1; (i <= matches.Length) && (!foundMatch); i++) { NameSnippet snippet = CreateNameSnippet(matches, i, mappingOptions); var valueResolver = FindTypeMember(sourceProperties, sourceNoArgMethods, sourceNoArgExtensionMethods, snippet.First, mappingOptions); if (valueResolver != null) { resolvers.AddLast(valueResolver); foundMatch = MapDestinationPropertyToSource(resolvers, GetTypeInfo(valueResolver.GetMemberType(), mappingOptions), snippet.Second, mappingOptions); if (!foundMatch) { resolvers.RemoveLast(); } } } } return foundMatch; } private static MemberInfo FindTypeMember(IEnumerable<MemberInfo> modelProperties, IEnumerable<MethodInfo> getMethods, IEnumerable<MethodInfo> getExtensionMethods, string nameToSearch, IMappingOptions mappingOptions) { MemberInfo pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, nameToSearch, mappingOptions)); if (pi != null) return pi; MethodInfo mi = getMethods.FirstOrDefault(m => NameMatches(m.Name, nameToSearch, mappingOptions)); if (mi != null) return mi; mi = getExtensionMethods.FirstOrDefault(m => NameMatches(m.Name, nameToSearch, mappingOptions)); if (mi != null) return mi; return null; } private static bool NameMatches(string memberName, string nameToMatch, IMappingOptions mappingOptions) { var possibleSourceNames = PossibleNames(memberName, mappingOptions.Aliases, mappingOptions.MemberNameReplacers, mappingOptions.Prefixes, mappingOptions.Postfixes); var possibleDestNames = PossibleNames(nameToMatch, mappingOptions.Aliases, mappingOptions.MemberNameReplacers, mappingOptions.DestinationPrefixes, mappingOptions.DestinationPostfixes); var all = from sourceName in possibleSourceNames from destName in possibleDestNames select new {sourceName, destName}; return all.Any(pair => String.Compare(pair.sourceName, pair.destName, StringComparison.OrdinalIgnoreCase) == 0); } private static IEnumerable<string> PossibleNames(string memberName, IEnumerable<AliasedMember> aliases, IEnumerable<MemberNameReplacer> memberNameReplacers, IEnumerable<string> prefixes, IEnumerable<string> postfixes) { if (string.IsNullOrEmpty(memberName)) yield break; yield return memberName; foreach ( var alias in aliases.Where(alias => String.Equals(memberName, alias.Member, StringComparison.Ordinal))) { yield return alias.Alias; } if (memberNameReplacers.Any()) { string aliasName = memberName; foreach (var nameReplacer in memberNameReplacers) { aliasName = aliasName.Replace(nameReplacer.OriginalValue, nameReplacer.NewValue); } yield return aliasName; } foreach (var prefix in prefixes.Where(prefix => memberName.StartsWith(prefix, StringComparison.Ordinal))) { var withoutPrefix = memberName.Substring(prefix.Length); yield return withoutPrefix; foreach ( var postfix in postfixes.Where(postfix => withoutPrefix.EndsWith(postfix, StringComparison.Ordinal)) ) { yield return withoutPrefix.Remove(withoutPrefix.Length - postfix.Length); } } foreach (var postfix in postfixes.Where(postfix => memberName.EndsWith(postfix, StringComparison.Ordinal))) { yield return memberName.Remove(memberName.Length - postfix.Length); } } private NameSnippet CreateNameSnippet(IEnumerable<string> matches, int i, IMappingOptions mappingOptions) { return new NameSnippet { First = String.Join(mappingOptions.SourceMemberNamingConvention.SeparatorCharacter, matches.Take(i).ToArray()), Second = String.Join(mappingOptions.SourceMemberNamingConvention.SeparatorCharacter, matches.Skip(i).ToArray()) }; } private class NameSnippet { public string First { get; set; } public string Second { get; set; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine.UI.Windows.Extensions; using ME; using UnityEngine.UI.Windows.Audio; using UnityEngine.UI.Windows.Plugins.Flow.Data; namespace UnityEngine.UI.Windows.Plugins.Flow { public enum ModeLayer : byte { Flow, Audio, }; [System.Serializable] public class FlowTag { public int id; public string title; public int color; public bool enabled = true; public FlowTag(int id, string title) { this.id = id; this.title = title; this.color = 0; this.enabled = true; } }; public enum FlowView : byte { None = 0x0, Layout = 0x1, VideoTransitions = 0x2, AudioTransitions = 0x4, Transitions = VideoTransitions | AudioTransitions, }; public enum AuthKeyPermissions : byte { None = 0x0, ABTesting = 0x1, Analytics = 0x2, Ads = 0x4, }; public class FlowData : ScriptableObject { [Header("Version Data")] public string lastModified = "-"; public long lastModifiedUnix = 0; public Version version; #if UNITY_EDITOR [Header("Services Auth")] public string authKey; [HideInInspector] public string editorAuthKey; #endif [HideInInspector] public string buildAuthKey; [HideInInspector] public AuthKeyPermissions authKeyPermissions = AuthKeyPermissions.None; [Header("Compiler Plugin")] public string namespaceName; public bool forceRecompile; public bool minimalScriptsSize; [Header("Flow Data")] [ReadOnly] public float zoom = 1f; [ReadOnly] public Vector2 scrollPos = new Vector2(1f, 1f); [ReadOnly] public int rootWindow; [ReadOnly] public List<int> defaultWindows = new List<int>(); [System.Obsolete("Windows List was deprecated. Use windowAssets List instead.")] [HideInInspector] public List<FlowWindow> windows = new List<FlowWindow>(); [ReadOnly] public List<Data.FlowWindow> windowAssets = new List<Data.FlowWindow>(); [ReadOnly] public List<FlowTag> tags = new List<FlowTag>(); public Audio.Data audio = new Audio.Data(); public ModeLayer modeLayer = ModeLayer.Flow; //private Rect selectionRect; [HideInInspector] private List<int> selected = new List<int>(); [HideInInspector] public FlowView flowView = FlowView.Layout | FlowView.Transitions; [HideInInspector] public bool flowDrawTags = false; [HideInInspector] public float flowWindowWithLayoutScaleFactor = 0f; [ReadOnly] public bool isDirty = false; [ReadOnly] public bool recompileNeeded = false; #if UNITY_EDITOR #region UPGRADES #pragma warning disable 612,618 public bool UpgradeTo105() { this.flowView = FlowView.Layout | FlowView.Transitions; UnityEditor.EditorUtility.SetDirty(this); return true; } public bool UpgradeTo103() { // Need to recompile return true; } public bool UpgradeTo102() { this.modeLayer = ModeLayer.Flow; UnityEditor.EditorUtility.SetDirty(this); return true; } public bool UpgradeTo099() { return true; } #pragma warning restore 612,618 #endregion #endif #if UNITY_EDITOR [ContextMenu("Setup")] public void Setup() { this.audio.Setup(); var screens = this.GetAllScreens(); foreach (var screen in screens) { if (screen != null && screen.window != null) screen.window.Setup(this); } } [ContextMenu("Refresh All Screens")] public void RefreshAllScreens() { foreach (var window in this.windowAssets) { window.RefreshScreen(); } } public void ValidateAuthKey(System.Action<bool> onResult) { var splitted = this.authKey.Split('-'); if (splitted.Length == 2) { this.buildAuthKey = splitted[0]; this.editorAuthKey = splitted[1]; var rnd = Random.Range(0, 3); if (rnd == 0) { this.authKeyPermissions = AuthKeyPermissions.ABTesting; } else if (rnd == 1) { this.authKeyPermissions = AuthKeyPermissions.Analytics; } else { this.authKeyPermissions = AuthKeyPermissions.ABTesting | AuthKeyPermissions.Analytics; } this.authKeyPermissions |= AuthKeyPermissions.Ads; onResult(true); } else { this.buildAuthKey = string.Empty; this.editorAuthKey = string.Empty; this.authKeyPermissions = AuthKeyPermissions.None; onResult(false); } } public string GetAuthKeyEditor() { return this.editorAuthKey; } public bool IsValidAuthKey() { return string.IsNullOrEmpty(this.authKey) == false; } #endif public bool IsCompileDirty() { return this.recompileNeeded; } public void SetCompileDirty(bool state) { this.recompileNeeded = state; } public string GetAuthKeyBuild() { return this.buildAuthKey; } public bool IsValidAuthKey(AuthKeyPermissions permission) { if (permission == AuthKeyPermissions.None) return true; return (this.authKeyPermissions & permission) != 0; } public bool HasView(FlowView view) { return (this.flowView & view) != 0; } /*private void OnEnable() { this.namespaceName = string.IsNullOrEmpty(this.namespaceName) == true ? string.Format("{0}.UI", this.name) : this.namespaceName; }*/ public WindowBase GetRootScreen(bool runtime = false) { var flowWindow = this.windowAssets.FirstOrDefault((w) => w.id == this.rootWindow); if (flowWindow != null) { return flowWindow.GetScreen(runtime).Load<WindowBase>(); } return null; } public List<WindowItem> GetAllScreens(System.Func<Data.FlowWindow, bool> predicate = null, bool runtime = false) { var list = new List<WindowItem>(); foreach (var window in this.windowAssets) { if (runtime == true) { window.FilterRuntimeScreens(); } if (window.IsSmall() == true) continue; if (predicate != null && predicate(window) == false) continue; var screen = window.GetScreen(runtime); if (screen == null) continue; list.Add(screen); } return list; } public List<WindowItem> GetDefaultScreens(bool runtime = false) { return this.GetAllScreens((w) => this.defaultWindows.Contains(w.id), runtime); } public string GetModulesPath() { var modulesPath = string.Empty; var data = this; #if UNITY_EDITOR var dataPath = UnityEditor.AssetDatabase.GetAssetPath(data); var directory = System.IO.Path.GetDirectoryName(dataPath); var projectName = data.name; modulesPath = System.IO.Path.Combine(directory, string.Format("{0}.Modules", projectName)); #endif return modulesPath; } public void Save() { #if UNITY_EDITOR if (this.isDirty == true) { var dateTime = System.DateTime.Now; this.lastModified = dateTime.ToString("dd.MM.yyyy hh:mm"); this.lastModifiedUnix = dateTime.ToUnixTime(); UnityEditor.EditorUtility.SetDirty(this); foreach (var window in this.windowAssets) { this.VerifyRename(window.id); if (window.GetScreen() != null && window.GetScreen().window != null) window.GetScreen().window.Setup(window.id, this); window.isDirty = true; window.Save(); } } #endif this.isDirty = false; } public AttachItem GetAttachItem(int from, int to) { var fromWindow = this.GetWindow(from); var item = fromWindow.attachItems.FirstOrDefault((element) => element.targetId == to); if (item == null) { return AttachItem.Empty; } return item; } #region TAGS public int GetNextTagId() { var maxId = 0; foreach (var tag in this.tags) { if (tag.id > maxId) maxId = tag.id; } return maxId + 1; } public FlowTag GetTag(int id) { return this.tags.FirstOrDefault((t) => t.id == id); } public void AddTag(Data.FlowWindow window, FlowTag tag) { var contains = this.tags.FirstOrDefault((t) => t.title.ToLower() == tag.title.ToLower()); if (contains == null) { this.tags.Add(tag); } else { tag = contains; } window.AddTag(tag); this.isDirty = true; } public void RemoveTag(Data.FlowWindow window, FlowTag tag) { window.RemoveTag(tag); this.isDirty = true; } #endregion #region AUDIO public int GetNextAudioItemId(ClipType clipType) { var maxId = 0; var states = this.audio.GetStates(clipType); foreach (var state in states) { if (state.key > maxId) maxId = state.key; } return maxId + 1; } public void AddAudioItem(ClipType clipType, Audio.Data.State state) { state.key = this.GetNextAudioItemId(clipType); this.audio.Add(clipType, state); } public void RemoveAudioItem(ClipType clipType, int key) { this.audio.Remove(clipType, key); } #endregion public void SetRootWindow(int id) { this.rootWindow = id; this.isDirty = true; } public int GetRootWindow() { return this.rootWindow; } public List<int> GetDefaultWindows() { return this.defaultWindows; } public void SetDefaultWindows(List<int> defaultWindows) { this.defaultWindows = defaultWindows; } public void ResetSelection() { this.selected.Clear(); } public List<int> GetSelected() { return this.selected; } public void SelectWindows(int[] ids) { this.selected.Clear(); foreach (var window in this.windowAssets) { if (window.IsContainer() == false && ids.Contains(window.id) == true) { this.selected.Add(window.id); } } } public void SelectWindowsInRect(Rect rect, System.Func<Data.FlowWindow, bool> predicate = null) { //this.selectionRect = rect; this.selected.Clear(); foreach (var window in this.windowAssets) { if (window.IsContainer() == false && rect.Overlaps(window.rect, true) == true && (predicate == null || predicate(window) == true)) { this.selected.Add(window.id); } } } public Vector2 GetScrollPosition() { return this.scrollPos; } public void SetScrollPosition(Vector2 scrollPos) { this.scrollPos = scrollPos; } #if UNITY_EDITOR public void Attach(int source, int index, int other, bool oneWay, WindowLayoutElement component = null) { var window = this.GetWindow(source); window.Attach(other, index, oneWay, component); this.isDirty = true; } public void Detach(int source, int index, int other, bool oneWay, WindowLayoutElement component = null) { var window = this.GetWindow(source); window.Detach(other, index, oneWay, component); this.isDirty = true; } public bool AlreadyAttached(int source, int index, int other, WindowLayoutElement component = null) { return this.windowAssets.Any((w) => w.id == source && w.AlreadyAttached(other, index, component)); } public void Attach(int source, int other, bool oneWay, WindowLayoutElement component = null) { var window = this.GetWindow(source); window.Attach(other, 0, oneWay, component); this.isDirty = true; } public void Detach(int source, int other, bool oneWay, WindowLayoutElement component = null) { var window = this.GetWindow(source); window.Detach(other, 0, oneWay, component); this.isDirty = true; } public bool AlreadyAttached(int source, int other, WindowLayoutElement component = null) { return this.windowAssets.Any((w) => w.id == source && w.AlreadyAttached(other, 0, component)); } public void DestroyWindow(int id) { // Remove window //this.windows.Remove(this.GetWindow(id)); var data = this.GetWindow(id); this.windowAssets.Remove(data); #if UNITY_EDITOR // Delete any old sub assets inside the prefab. /*var assetPath = UnityEditor.AssetDatabase.GetAssetPath(data); var assets = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(assetPath); for (int i = 0; i < assets.Length; ++i) { var asset = assets[i]; if (UnityEditor.AssetDatabase.IsMainAsset(asset) || asset is GameObject || asset is Component) { continue; } else { Object.DestroyImmediate(asset, allowDestroyingAssets: true); } }*/ Object.DestroyImmediate(data, allowDestroyingAssets: true); #endif this.selected.Remove(id); this.defaultWindows.Remove(id); foreach (var window in this.windowAssets) { window.Detach(id, oneWay: true); } this.ResetCache(); this.isDirty = true; } #endif public Data.FlowWindow CreateWindow(Data.FlowWindow.Flags flags) { return this.CreateWindow_INTERNAL(flags); } public Data.FlowWindow CreateDefaultLink() { var window = this.CreateWindow_INTERNAL( UnityEngine.UI.Windows.Plugins.Flow.Data.FlowWindow.Flags.IsSmall | UnityEngine.UI.Windows.Plugins.Flow.Data.FlowWindow.Flags.CantCompiled | UnityEngine.UI.Windows.Plugins.Flow.Data.FlowWindow.Flags.ShowDefault ); window.title = "Default Link"; window.rect.width = 150f; window.rect.height = 30f; return window; } public Data.FlowWindow CreateContainer() { return this.CreateWindow_INTERNAL(UnityEngine.UI.Windows.Plugins.Flow.Data.FlowWindow.Flags.IsContainer); } public Data.FlowWindow CreateWindow() { return this.CreateWindow_INTERNAL(UnityEngine.UI.Windows.Plugins.Flow.Data.FlowWindow.Flags.Default); } private Data.FlowWindow CreateWindow_INTERNAL(Data.FlowWindow.Flags flags) { var newId = this.AllocateId(); //var window = new Data.FlowWindow(newId, flags); //this.windows.Add(window); var window = Data.FlowWindow.CreateInstance<Data.FlowWindow>(); #if UNITY_EDITOR window.name = window.ToString(); UnityEditor.AssetDatabase.AddObjectToAsset(window, this); #endif window.Setup(newId, flags); this.windowAssets.Add(window); this.windowsCache.Clear(); this.isDirty = true; this.Save(); #if UNITY_EDITOR UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(window), UnityEditor.ImportAssetOptions.ForceUpdate); UnityEditor.AssetDatabase.SaveAssets(); UnityEditor.EditorUtility.SetDirty(window); #endif return window; } public void VerifyRename(int id) { var data = this.GetWindow(id); if (data == null) return; data.name = data.ToString(); } public IEnumerable<Data.FlowWindow> GetWindows() { return this.windowAssets.Where((w) => w.IsContainer() == false && w.IsEnabled()); } public IEnumerable<Data.FlowWindow> GetContainers() { return this.windowAssets.Where((w) => w.IsContainer() == true && w.IsEnabled()); } public IEnumerable<Data.FlowWindow> GetContainersAndWindows() { return this.windowAssets.Where((w) => w.IsEnabled()); } public Data.FlowWindow GetWindow(WindowBase window, bool runtime) { if (window == null) return null; return this.windowAssets.FirstOrDefault((w) => { if (w.GetScreen(runtime) != null) { return w.GetScreen(runtime).Load<WindowBase>().SourceEquals(window); } return window.SourceEquals(null); }); } private Cache windowsCache = new Cache(); public Data.FlowWindow GetWindow(int id) { if (id == 0) return null; if (this.windowsCache.IsEmpty() == true) { this.windowsCache.Fill(this.windowAssets, (w, i) => w.id, (w, i) => i); } var index = this.windowsCache.GetValue(id); if (index == -1) return null; if (index < 0 || index >= this.windowAssets.Count) return null; return this.windowAssets[index]; } public void ResetCache() { this.windowsCache.Clear(); } public int AllocateId() { var maxId = 0; foreach (var window in this.windowAssets) { if (maxId < window.id) maxId = window.id; } return ++maxId; } #if UNITY_EDITOR [UnityEditor.MenuItem("Assets/Create/UI Windows/Flow/Graph")] public static void CreateInstance() { ME.EditorUtilities.CreateAsset<FlowData>(); } #endif } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Palmmedia.ReportGenerator.Core.CodeAnalysis; using Palmmedia.ReportGenerator.Core.Logging; using Palmmedia.ReportGenerator.Core.Parser.Analysis; using Palmmedia.ReportGenerator.Core.Properties; namespace Palmmedia.ReportGenerator.Core.Reporting.Builders.Rendering { /// <summary> /// Latex report renderer. /// </summary> internal class LatexRenderer : IReportRenderer, IDisposable { /// <summary> /// The head of each generated Latex file. /// </summary> private const string LatexStart = @"\documentclass[a4paper,landscape,10pt]{{article}} \usepackage[paper=a4paper,landscape,left=20mm,right=20mm,top=20mm,bottom=20mm]{{geometry}} \usepackage{{longtable}} \usepackage{{fancyhdr}} \usepackage[pdftex]{{color}} \usepackage{{colortbl}} \definecolor{{green}}{{rgb}}{{0.04,0.68,0.04}} \definecolor{{orange}}{{rgb}}{{0.97,0.65,0.12}} \definecolor{{red}}{{rgb}}{{0.75,0.04,0.04}} \definecolor{{gray}}{{rgb}}{{0.86,0.86,0.86}} \usepackage[pdftex, colorlinks=true, linkcolor=red, urlcolor=green, citecolor=red,% raiselinks=true,% bookmarks=true,% bookmarksopenlevel=1,% bookmarksopen=true,% bookmarksnumbered=true,% hyperindex=true,% plainpages=false,% correct hyperlinks pdfpagelabels=true%,% view TeX pagenumber in PDF reader %pdfborder={{0 0 0.5}} ]{{hyperref}} \hypersetup{{pdftitle={{{0}}}, pdfauthor={{ReportGenerator - {1}}} }} \pagestyle{{fancy}} \fancyhead[LE,LO]{{\leftmark}} \fancyhead[R]{{\thepage}} \fancyfoot[C]{{ReportGenerator - {1}}} \begin{{document}} \setcounter{{secnumdepth}}{{-1}}"; /// <summary> /// The end of each generated Latex file. /// </summary> private const string LatexEnd = @"\end{document}"; /// <summary> /// The Logger. /// </summary> private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(LatexRenderer)); /// <summary> /// The current report text writer. /// </summary> private TextWriter reportTextWriter; /// <summary> /// The report text writer for the summary report. /// </summary> private TextWriter summaryReportTextWriter; /// <summary> /// The report text writer for the classes report. /// </summary> private TextWriter classReportTextWriter; /// <summary> /// The underlying stream for the summary report. /// </summary> private Stream summaryReportStream; /// <summary> /// The underlying stream for the classes report. /// </summary> private Stream classReportStream; /// <summary> /// Gets a value indicating whether renderer support rendering of charts. /// </summary> public bool SupportsCharts => false; /// <summary> /// Begins the summary report. /// </summary> /// <param name="targetDirectory">The target directory.</param> /// <param name="fileName">The file name.</param> /// <param name="title">The title.</param> public void BeginSummaryReport(string targetDirectory, string fileName, string title) { this.summaryReportStream = new MemoryStream(); this.reportTextWriter = this.summaryReportTextWriter = new StreamWriter(this.summaryReportStream); string start = string.Format( CultureInfo.InvariantCulture, LatexStart, EscapeLatexChars(ReportResources.CoverageReport), typeof(IReportBuilder).Assembly.GetName().Version); this.reportTextWriter.WriteLine(start); } /// <summary> /// Begins the class report. /// </summary> /// <param name="targetDirectory">The target directory.</param> /// <param name="assembly">The assembly.</param> /// <param name="className">Name of the class.</param> /// <param name="classDisplayName">Display name of the class.</param> /// <param name="additionalTitle">Additional title.</param> public void BeginClassReport(string targetDirectory, Assembly assembly, string className, string classDisplayName, string additionalTitle) { if (this.classReportTextWriter == null) { string targetPath = Path.Combine(targetDirectory, "tmp.tex"); this.classReportStream = new FileStream(targetPath, FileMode.Create); this.classReportTextWriter = new StreamWriter(this.classReportStream); } this.reportTextWriter = this.classReportTextWriter; this.reportTextWriter.WriteLine(@"\newpage"); classDisplayName = string.Format(CultureInfo.InvariantCulture, @"\section{{{0}}}", EscapeLatexChars(classDisplayName)); this.reportTextWriter.WriteLine(classDisplayName); } /// <summary> /// Adds a header to the report. /// </summary> /// <param name="text">The text.</param> public void Header(string text) { text = string.Format( CultureInfo.InvariantCulture, @"\{0}section{{{1}}}", this.reportTextWriter == this.classReportTextWriter ? "sub" : string.Empty, EscapeLatexChars(text)); this.reportTextWriter.WriteLine(text); } /// <summary> /// Adds a header to the report. /// </summary> /// <param name="text">The text.</param> public void HeaderWithGithubLinks(string text) { this.Header(text); } /// <summary> /// Adds a header to the report. /// </summary> /// <param name="text">The text.</param> public void HeaderWithBackLink(string text) { this.Header(text); } /// <summary> /// Adds the test methods to the report. /// </summary> /// <param name="testMethods">The test methods.</param> /// <param name="fileAnalyses">The file analyses that correspond to the class.</param> /// <param name="codeElementsByFileIndex">Code elements by file index.</param> public void TestMethods(IEnumerable<TestMethod> testMethods, IEnumerable<FileAnalysis> fileAnalyses, IDictionary<int, IEnumerable<CodeElement>> codeElementsByFileIndex) { } /// <summary> /// Adds a file of a class to a report. /// </summary> /// <param name="path">The path of the file.</param> public void File(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } if (path.Length > 78) { path = path.Substring(path.Length - 78); } path = string.Format(CultureInfo.InvariantCulture, @"\subsubsection{{{0}}}", EscapeLatexChars(path)); this.reportTextWriter.WriteLine(path); } /// <summary> /// Adds a paragraph to the report. /// </summary> /// <param name="text">The text.</param> public void Paragraph(string text) { this.reportTextWriter.WriteLine(EscapeLatexChars(text)); } /// <summary> /// Adds a table with two columns to the report. /// </summary> public void BeginKeyValueTable() { this.reportTextWriter.WriteLine(@"\begin{longtable}[l]{ll}"); } /// <summary> /// Start of risk summary table section. /// </summary> public void BeginSummaryTable() { } /// <summary> /// End of risk summary table section. /// </summary> public void FinishSummaryTable() { } /// <summary> /// Adds a summary table to the report. /// </summary> /// <param name="branchCoverageAvailable">if set to <c>true</c> branch coverage is available.</param> public void BeginSummaryTable(bool branchCoverageAvailable) { this.reportTextWriter.Write(@"\begin{longtable}[l]{|l|r|r|r|r|r|"); if (branchCoverageAvailable) { this.reportTextWriter.Write("r|"); } this.reportTextWriter.WriteLine("r|}"); this.reportTextWriter.WriteLine(@"\hline"); this.reportTextWriter.Write( "\\textbf{{{0}}} & \\textbf{{{1}}} & \\textbf{{{2}}} & \\textbf{{{3}}} & \\textbf{{{4}}} & \\textbf{{{5}}}", EscapeLatexChars(ReportResources.Name), EscapeLatexChars(ReportResources.Covered), EscapeLatexChars(ReportResources.Uncovered), EscapeLatexChars(ReportResources.Coverable), EscapeLatexChars(ReportResources.Total), EscapeLatexChars(ReportResources.Coverage)); if (branchCoverageAvailable) { this.reportTextWriter.Write( " & \\textbf{{{0}}}", EscapeLatexChars(ReportResources.BranchCoverage)); } this.reportTextWriter.WriteLine(@" & \textbf{{{0}}}\\", EscapeLatexChars(ReportResources.CodeElementCoverageQuota)); this.reportTextWriter.WriteLine(@"\hline"); } /// <summary> /// Adds custom summary elements to the report. /// </summary> /// <param name="assemblies">The assemblies.</param> /// <param name="riskHotspots">The risk hotspots.</param> /// <param name="branchCoverageAvailable">if set to <c>true</c> branch coverage is available.</param> public void CustomSummary(IEnumerable<Assembly> assemblies, IEnumerable<RiskHotspot> riskHotspots, bool branchCoverageAvailable) { } /// <summary> /// Adds a file analysis table to the report. /// </summary> /// <param name="headers">The headers.</param> public void BeginLineAnalysisTable(IEnumerable<string> headers) { this.reportTextWriter.WriteLine(@"\begin{longtable}[l]{lrrll}"); this.reportTextWriter.Write(string.Join(" & ", headers.Select(h => @"\textbf{" + EscapeLatexChars(h) + "}"))); this.reportTextWriter.WriteLine(@"\\"); } /// <summary> /// Adds a table row with two cells to the report. /// </summary> /// <param name="key">The text of the first column.</param> /// <param name="value">The text of the second column.</param> public void KeyValueRow(string key, string value) { string row = string.Format( CultureInfo.InvariantCulture, @"\textbf{{{0}}} & {1}\\", ShortenString(key), EscapeLatexChars(value)); this.reportTextWriter.WriteLine(row); } /// <summary> /// Adds a table row with two cells to the report. /// </summary> /// <param name="key">The text of the first column.</param> /// <param name="files">The files.</param> public void KeyValueRow(string key, IEnumerable<string> files) { files = files.Select(f => { return f.Length > 78 ? f.Substring(f.Length - 78) : f; }); string row = string.Format( CultureInfo.InvariantCulture, @"\textbf{{{0}}} & \begin{{minipage}}[t]{{12cm}}{{{1}}}\end{{minipage}} \\", ShortenString(key), string.Join(@"\\", files.Select(f => EscapeLatexChars(f)))); this.reportTextWriter.WriteLine(row); } /// <summary> /// Adds metrics to the report. /// </summary> /// <param name="class">The class.</param> public void MetricsTable(Class @class) { if (@class == null) { throw new ArgumentNullException(nameof(@class)); } var methodMetrics = @class.Files.SelectMany(f => f.MethodMetrics); this.MetricsTable(methodMetrics); } /// <summary> /// Adds metrics to the report. /// </summary> /// <param name="methodMetrics">The method metrics.</param> public void MetricsTable(IEnumerable<MethodMetric> methodMetrics) { if (methodMetrics == null) { throw new ArgumentNullException(nameof(methodMetrics)); } var metrics = methodMetrics .SelectMany(m => m.Metrics) .Distinct() .OrderBy(m => m.Name); int numberOfTables = (int)Math.Ceiling((double)metrics.Count() / 5); for (int i = 0; i < numberOfTables; i++) { string columns = "|l|" + string.Join("|", metrics.Skip(i * 5).Take(5).Select(m => "r")) + "|"; this.reportTextWriter.WriteLine(@"\begin{longtable}[l]{" + columns + "}"); this.reportTextWriter.WriteLine(@"\hline"); this.reportTextWriter.Write(@"\textbf{" + EscapeLatexChars(ReportResources.Method) + "} & " + string.Join(" & ", metrics.Skip(i * 5).Take(5).Select(m => @"\textbf{" + EscapeLatexChars(m.Name) + "}"))); this.reportTextWriter.WriteLine(@"\\"); this.reportTextWriter.WriteLine(@"\hline"); foreach (var methodMetric in methodMetrics.OrderBy(c => c.Line)) { StringBuilder sb = new StringBuilder(); int counter = 0; foreach (var metric in metrics.Skip(i * 5).Take(5)) { if (counter > 0) { sb.Append(" & "); } var metricValue = methodMetric.Metrics.FirstOrDefault(m => m.Equals(metric)); if (metricValue != null) { if (metricValue.Value.HasValue) { sb.Append(metricValue.Value.Value.ToString(CultureInfo.InvariantCulture)); if (metricValue.MetricType == MetricType.CoveragePercentual) { sb.Append("\\%"); } } else { sb.Append("-"); } } else { sb.Append("-"); } counter++; } string row = string.Format( CultureInfo.InvariantCulture, @"\textbf{{{0}}} & {1}\\", EscapeLatexChars(ShortenString(methodMetric.ShortName, 20)), sb.ToString()); this.reportTextWriter.WriteLine(row); this.reportTextWriter.WriteLine(@"\hline"); } this.reportTextWriter.WriteLine(@"\end{longtable}"); } } /// <summary> /// Adds the coverage information of a single line of a file to the report. /// </summary> /// <param name="fileIndex">The index of the file.</param> /// <param name="analysis">The line analysis.</param> public void LineAnalysis(int fileIndex, LineAnalysis analysis) { if (analysis == null) { throw new ArgumentNullException(nameof(analysis)); } string formattedLine = analysis.LineContent .Replace(((char)11).ToString(), " ") // replace tab .Replace(((char)9).ToString(), " ") // replace tab .Replace("~", " "); // replace '~' since this used for the \verb command formattedLine = ShortenString(formattedLine, 120); formattedLine = StringHelper.ReplaceInvalidXmlChars(formattedLine); string lineVisitStatus; switch (analysis.LineVisitStatus) { case LineVisitStatus.Covered: lineVisitStatus = "green"; break; case LineVisitStatus.NotCovered: lineVisitStatus = "red"; break; case LineVisitStatus.PartiallyCovered: lineVisitStatus = "orange"; break; default: lineVisitStatus = "gray"; break; } string row = string.Format( CultureInfo.InvariantCulture, @"\cellcolor{{{0}}} & {1} & \verb~{2}~ & & \verb~{3}~\\", lineVisitStatus, analysis.LineVisitStatus != LineVisitStatus.NotCoverable ? analysis.LineVisits.ToString(CultureInfo.InvariantCulture) : string.Empty, analysis.LineNumber, formattedLine); this.reportTextWriter.WriteLine(row); } /// <summary> /// Finishes the current table. /// </summary> public void FinishTable() { this.reportTextWriter.WriteLine(@"\end{longtable}"); } /// <summary> /// Renderes a chart with the given historic coverages. /// </summary> /// <param name="historicCoverages">The historic coverages.</param> /// <param name="renderPngFallBackImage">Indicates whether PNG images are rendered as a fallback.</param> public void Chart(IEnumerable<HistoricCoverage> historicCoverages, bool renderPngFallBackImage) { } /// <summary> /// Start of risk hotspots section. /// </summary> public void BeginRiskHotspots() { } /// <summary> /// End of risk hotspots section. /// </summary> public void FinishRiskHotspots() { } /// <summary> /// Summary of risk hotspots. /// </summary> /// <param name="riskHotspots">The risk hotspots.</param> public void RiskHotspots(IEnumerable<RiskHotspot> riskHotspots) { if (riskHotspots == null) { throw new ArgumentNullException(nameof(riskHotspots)); } var codeQualityMetrics = riskHotspots.First().MethodMetric.Metrics .Where(m => m.MetricType == MetricType.CodeQuality) .ToArray(); string columns = "|l|l|l|" + string.Join("|", codeQualityMetrics.Select(m => "r")) + "|"; this.reportTextWriter.WriteLine(@"\begin{longtable}[l]{" + columns + "}"); this.reportTextWriter.WriteLine(@"\hline"); this.reportTextWriter.Write( "\\textbf{{{0}}} & \\textbf{{{1}}} & \\textbf{{{2}}}", EscapeLatexChars(ReportResources.Assembly2), EscapeLatexChars(ReportResources.Class2), EscapeLatexChars(ReportResources.Method)); foreach (var metric in codeQualityMetrics) { this.reportTextWriter.Write(" & \\textbf{{{0}}}", EscapeLatexChars(metric.Name)); } this.reportTextWriter.WriteLine(@"\\"); this.reportTextWriter.WriteLine(@"\hline"); foreach (var riskHotspot in riskHotspots) { this.reportTextWriter.Write( "{0} & {1} & {2}", EscapeLatexChars(riskHotspot.Assembly.ShortName), EscapeLatexChars(riskHotspot.Class.DisplayName), EscapeLatexChars(riskHotspot.MethodMetric.ShortName)); foreach (var statusMetric in riskHotspot.StatusMetrics) { if (statusMetric.Exceeded) { this.reportTextWriter.Write(" & \\textcolor{{red}}{{{0}}}", statusMetric.Metric.Value.HasValue ? statusMetric.Metric.Value.Value.ToString(CultureInfo.InvariantCulture) : "-"); } else { this.reportTextWriter.Write(" & {0}", statusMetric.Metric.Value.HasValue ? statusMetric.Metric.Value.Value.ToString(CultureInfo.InvariantCulture) : "-"); } } this.reportTextWriter.WriteLine(@"\\"); this.reportTextWriter.WriteLine(@"\hline"); } this.reportTextWriter.WriteLine(@"\end{longtable}"); } /// <summary> /// Adds the coverage information of an assembly to the report. /// </summary> /// <param name="assembly">The assembly.</param> /// <param name="branchCoverageAvailable">if set to <c>true</c> branch coverage is available.</param> public void SummaryAssembly(Assembly assembly, bool branchCoverageAvailable) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } string row = string.Format( CultureInfo.InvariantCulture, @"\textbf{{{0}}} & \textbf{{{1}}} & \textbf{{{2}}} & \textbf{{{3}}} & \textbf{{{4}}} & \textbf{{{5}}}", EscapeLatexChars(assembly.Name), assembly.CoveredLines, assembly.CoverableLines - assembly.CoveredLines, assembly.CoverableLines, assembly.TotalLines.GetValueOrDefault(), assembly.CoverageQuota.HasValue ? assembly.CoverageQuota.Value.ToString(CultureInfo.InvariantCulture) + @"\%" : string.Empty); this.reportTextWriter.Write(row); if (branchCoverageAvailable) { row = string.Format( CultureInfo.InvariantCulture, @" & \textbf{{{0}}}", assembly.BranchCoverageQuota.HasValue ? assembly.BranchCoverageQuota.Value.ToString(CultureInfo.InvariantCulture) + @"\%" : string.Empty); this.reportTextWriter.Write(row); } row = string.Format( CultureInfo.InvariantCulture, @" & \textbf{{{0}}}", assembly.CodeElementCoverageQuota.HasValue ? assembly.CodeElementCoverageQuota.Value.ToString(CultureInfo.InvariantCulture) + @"\%" : string.Empty); this.reportTextWriter.Write(row); this.reportTextWriter.WriteLine(@"\\"); this.reportTextWriter.WriteLine(@"\hline"); } /// <summary> /// Adds the coverage information of a class to the report. /// </summary> /// <param name="class">The class.</param> /// <param name="branchCoverageAvailable">if set to <c>true</c> branch coverage is available.</param> public void SummaryClass(Class @class, bool branchCoverageAvailable) { if (@class == null) { throw new ArgumentNullException(nameof(@class)); } string row = string.Format( CultureInfo.InvariantCulture, @"{0} & {1} & {2} & {3} & {4} & {5}", EscapeLatexChars(@class.DisplayName), @class.CoveredLines, @class.CoverableLines - @class.CoveredLines, @class.CoverableLines, @class.TotalLines.GetValueOrDefault(), @class.CoverageQuota.HasValue ? @class.CoverageQuota.Value.ToString(CultureInfo.InvariantCulture) + @"\%" : string.Empty); this.reportTextWriter.Write(row); if (branchCoverageAvailable) { row = string.Format( CultureInfo.InvariantCulture, @" & {0}", @class.BranchCoverageQuota.HasValue ? @class.BranchCoverageQuota.Value.ToString(CultureInfo.InvariantCulture) + @"\%" : string.Empty); this.reportTextWriter.Write(row); } row = string.Format( CultureInfo.InvariantCulture, @" & {0}", @class.CodeElementCoverageQuota.HasValue ? @class.CodeElementCoverageQuota.Value.ToString(CultureInfo.InvariantCulture) + @"\%" : string.Empty); this.reportTextWriter.Write(row); this.reportTextWriter.WriteLine(@"\\"); this.reportTextWriter.WriteLine(@"\hline"); } /// <summary> /// Adds the footer to the report. /// </summary> public void AddFooter() { } /// <summary> /// Saves a summary report. /// </summary> /// <param name="targetDirectory">The target directory.</param> public void SaveSummaryReport(string targetDirectory) { Stream combinedReportStream = null; string targetPath = Path.Combine(targetDirectory, "Summary.tex"); Logger.InfoFormat(Resources.WritingReportFile, targetPath); combinedReportStream = new FileStream(targetPath, FileMode.Create); this.summaryReportTextWriter.Flush(); this.summaryReportStream.Position = 0; this.summaryReportStream.CopyTo(combinedReportStream); this.summaryReportTextWriter.Dispose(); if (this.classReportTextWriter != null) { this.classReportTextWriter.Flush(); this.classReportStream.Position = 0; this.classReportStream.CopyTo(combinedReportStream); this.classReportTextWriter.Dispose(); System.IO.File.Delete(Path.Combine(targetDirectory, "tmp.tex")); } byte[] latexEnd = Encoding.UTF8.GetBytes(LatexEnd); combinedReportStream.Write(latexEnd, 0, latexEnd.Length); combinedReportStream.Flush(); combinedReportStream.Dispose(); this.classReportTextWriter = null; this.summaryReportTextWriter = null; } /// <summary> /// Saves a class report. /// </summary> /// <param name="targetDirectory">The target directory.</param> /// <param name="assemblyName">Name of the assembly.</param> /// <param name="className">Name of the class.</param> public void SaveClassReport(string targetDirectory, string assemblyName, string className) { } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (this.summaryReportTextWriter != null) { this.summaryReportTextWriter.Dispose(); } if (this.classReportTextWriter != null) { this.classReportTextWriter.Dispose(); } if (this.summaryReportStream != null) { this.summaryReportStream.Dispose(); } if (this.classReportStream != null) { this.classReportStream.Dispose(); } } } /// <summary> /// Shortens the given string. /// </summary> /// <param name="text">The text to shorten.</param> /// <returns>The shortened string.</returns> private static string ShortenString(string text) => ShortenString(text, 78); /// <summary> /// Shortens the given string. /// </summary> /// <param name="text">The text to shorten.</param> /// <param name="maxLength">Maximum length.</param> /// <returns>The shortened string.</returns> private static string ShortenString(string text, int maxLength) { if (text.Length > maxLength) { return text.Substring(0, maxLength); } return text; } /// <summary> /// Escapes the latex chars. /// </summary> /// <param name="text">The text.</param> /// <returns>The text with escaped latex chars.</returns> private static string EscapeLatexChars(string text) => text .Replace(@"\", @"\textbackslash ") .Replace("%", @"\%") .Replace("#", @"\#") .Replace("_", @"\_") .Replace("<", "$<$") .Replace(">", "$>$"); } }
using System; using System.Xml; using System.Collections.Generic; using Microsoft.Xna.Framework; using Nano.Engine.Cameras; using Nano.Engine.Graphics.Tileset; using Nano.Engine.Graphics; using Nano.Engine.IO.Import; using System.IO; namespace Nano.Engine.Graphics.Map { public class TileMap { #region member data ISpriteManager m_SpriteManager; List<ITileset> m_Tilesets; List<MapLayer> m_MapLayers; int m_MapWidth; int m_MapHeight; Point m_Origin; int m_TileHeight; int m_TileWidth; TileMapType m_TileMapType; #endregion #region properties public int TileHeight { get { return m_TileHeight; } } public int TileWidth { get { return m_TileWidth; } } public TileMapType TileMapType { get { return m_TileMapType; } } public int WidthInPixels { get { return m_MapWidth * TileWidth; } } public int HeightInPixels { get { return m_MapHeight * TileHeight; } } public Point Origin { get { return m_Origin; } } #endregion #region Constructors public TileMap (ISpriteManager spriteManager, TileMapType mapType, int tileWidth, int tileHeight, List<ITileset> tilesets, List<MapLayer> layers) { m_SpriteManager = spriteManager; m_TileMapType = mapType; m_TileHeight = tileHeight; m_TileWidth = tileWidth; m_Tilesets = tilesets; m_MapLayers = layers; m_MapWidth = m_MapLayers[0].Width; m_MapHeight = m_MapLayers[0].Height; VerifyLayerGeometry(m_MapLayers); SetOrigin(m_TileMapType); } public TileMap(ISpriteManager spriteManager, TileMapType mapType, int tileWidth, int tileHeight, IMapGenerator generator) { m_SpriteManager = spriteManager; var generatedLayers = generator.GenerateLayers(); m_MapLayers = generatedLayers; m_TileMapType = mapType; m_TileHeight = tileHeight; m_TileWidth = tileWidth; m_MapWidth = m_MapLayers[0].Width; m_MapHeight = m_MapLayers[0].Height; VerifyLayerGeometry(m_MapLayers); var generatedTilesets = generator.GenerateTilesets(); m_Tilesets = generatedTilesets; SetOrigin(m_TileMapType); } #endregion private void VerifyLayerGeometry(List<MapLayer> layers) { for (int i = 1; i < layers.Count; i++) { if (m_MapWidth != m_MapLayers[i].Width || m_MapHeight != m_MapLayers[i].Height) throw new Exception("Map layers are not the same size"); } } private void SetOrigin(TileMapType mapType) { if (mapType == TileMapType.Square) m_Origin = new Point(0, 0); else if (mapType == TileMapType.Isometric) m_Origin = new Point(((WidthInPixels / 2) - (TileWidth / 2)), TileHeight); } /// <summary> /// Draw the TileMap using the supplied Camera /// </summary> /// <param name="camera">Camera.</param> public void Draw (ICamera camera) { m_SpriteManager.StartBatch(camera.Transformation); if (TileMapType == TileMapType.Square) { DrawSquareTileMap(camera); } else if (TileMapType == TileMapType.Isometric) { DrawIsometricTileMap(camera); } m_SpriteManager.EndBatch(); } private void DrawSquareTileMap(ICamera camera) { Point cameraPoint = VectorToCell(camera.Position * (1 / camera.Zoom)); Point viewPoint = VectorToCell(new Vector2((camera.Position.X + camera.ViewportRectangle.Width) * (1 / camera.Zoom), (camera.Position.Y + camera.ViewportRectangle.Height) * (1 / camera.Zoom))); Point min = new Point(); Point max = new Point(); min.X = Math.Max(0, cameraPoint.X - 1); min.Y = Math.Max(0, cameraPoint.Y - 1); max.X = Math.Min(viewPoint.X + 1, m_MapWidth); max.Y = Math.Min(viewPoint.Y + 1, m_MapHeight); Rectangle destination = new Rectangle(0, 0, TileWidth, TileHeight); TilesetTile tile; foreach (MapLayer layer in m_MapLayers) { for (int y = min.Y; y < max.Y; y++) { destination.Y = y * TileHeight; for (int x = min.X; x < max.X; x++) { tile = layer.GetTile(x, y); if (tile.TileIndex == -1 || tile.TilesetId == -1) continue; destination.X = x * TileWidth; m_SpriteManager.DrawTexture2D(m_Tilesets[tile.TilesetId].Texture, destination, m_Tilesets[tile.TilesetId].Bounds[tile.TileIndex]); } } } } private void DrawIsometricTileMap(ICamera camera) { Point cameraPoint = VectorToCell(camera.Position * (1 / camera.Zoom)); Point viewPoint = VectorToCell(new Vector2((camera.Position.X + camera.ViewportRectangle.Width) * (1 / camera.Zoom), (camera.Position.Y + camera.ViewportRectangle.Height) * (1 / camera.Zoom))); Point min = new Point(); Point max = new Point(); min.X = 0;//Math.Max(0, cameraPoint.X - 1); min.Y = 0;//Math.Max(0, cameraPoint.Y - 1); max.X = m_MapWidth; //Math.Min(viewPoint.X + 1, m_MapWidth); max.Y = m_MapHeight; //Math.Min(viewPoint.Y + 1, m_MapHeight); Rectangle destination = new Rectangle(0, 0, TileWidth, TileHeight); TilesetTile tile; foreach (MapLayer layer in m_MapLayers) { for (int i = min.X; i < max.X; i++) { for (int j = min.Y; j < max.Y; j++) { tile = layer.GetTile(i, j); if (tile.TileIndex == -1 || tile.TilesetId == -1) continue; Point rowAdjustment = new Point(j * -(TileWidth / 2), j * (TileHeight / 2)); ITileset tset = m_Tilesets[tile.TilesetId]; destination.X = Origin.X + rowAdjustment.X + (i * (TileWidth / 2)) + tset.Offset.X; destination.Y = Origin.Y + rowAdjustment.Y + (i * (TileHeight / 2)) - (tset.Bounds[tile.TileIndex].Height - TileHeight) + tset.Offset.Y; destination.Height = m_Tilesets[tile.TilesetId].Bounds[tile.TileIndex].Height; destination.Width = m_Tilesets[tile.TilesetId].Bounds[tile.TileIndex].Width; m_SpriteManager.DrawTexture2D(m_Tilesets[tile.TilesetId].Texture, destination, m_Tilesets[tile.TilesetId].Bounds[tile.TileIndex]); } } } } public Point VectorToCell(int x, int y) { return VectorToCell(new Vector2((float)x,(float)y)); } public Point VectorToCell(Vector2 position) { if(TileMapType == TileMapType.Square) { return new Point((int)position.X / TileWidth, (int)position.Y / TileHeight); } else { double tw, th, tx, ty; tw = TileWidth; th = TileHeight; tx = Math.Round(( (position.X - Origin.X) / tw) + (position.Y / th)); ty = Math.Round(( (position.X - Origin.X) / tw) + (position.Y / th)); return new Point((int)tx,(int)ty); } } /// <summary> /// Adds a layer to the TileMap. /// Added layers must have the same dimensions as existing layers /// </summary> /// <param name="layer">The Layer to add</param> public void AddLayer(MapLayer layer) { if(layer.Width != m_MapWidth && layer.Height != m_MapHeight) throw new Exception("Added map layer has incorrect size"); m_MapLayers.Add(layer); } /// <summary> /// Loads the TileMap from the specified file. /// Supported file formats : .tmx(partial) /// </summary> /// <returns>A fully initialised TileMap object, or null.</returns> /// <param name="filename">full path to the file including name</param> /// <param name="spriteManager">Sprite manager.</param> public static TileMap FromFile(string filename, ISpriteManager spriteManager) { string ext = Path.GetExtension(filename); if (ext == ".tmx") { TmxFileImporter importer = new TmxFileImporter(filename, spriteManager); return importer.TileMap; } throw new FileLoadException(string.Format("Unsupported file type {0}", ext)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Data.Common; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Data.SqlClient { sealed internal class SqlSequentialTextReader : System.IO.TextReader { private SqlDataReader _reader; // The SqlDataReader that we are reading data from private int _columnIndex; // The index of out column in the table private Encoding _encoding; // Encoding for this character stream private Decoder _decoder; // Decoder based on the encoding (NOTE: Decoders are stateful as they are designed to process streams of data) private byte[] _leftOverBytes; // Bytes leftover from the last Read() operation - this can be null if there were no bytes leftover (Possible optimization: re-use the same array?) private int _peekedChar; // The last character that we peeked at (or -1 if we haven't peeked at anything) private Task _currentTask; // The current async task private CancellationTokenSource _disposalTokenSource; // Used to indicate that a cancellation is requested due to disposal internal SqlSequentialTextReader(SqlDataReader reader, int columnIndex, Encoding encoding) { Debug.Assert(reader != null, "Null reader when creating sequential textreader"); Debug.Assert(columnIndex >= 0, "Invalid column index when creating sequential textreader"); Debug.Assert(encoding != null, "Null encoding when creating sequential textreader"); _reader = reader; _columnIndex = columnIndex; _encoding = encoding; _decoder = encoding.GetDecoder(); _leftOverBytes = null; _peekedChar = -1; _currentTask = null; _disposalTokenSource = new CancellationTokenSource(); } internal int ColumnIndex { get { return _columnIndex; } } public override int Peek() { if (_currentTask != null) { throw ADP.AsyncOperationPending(); } if (IsClosed) { throw ADP.ObjectDisposed(this); } if (!HasPeekedChar) { _peekedChar = Read(); } Debug.Assert(_peekedChar == -1 || ((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue)), string.Format("Bad peeked character: {0}", _peekedChar)); return _peekedChar; } public override int Read() { if (_currentTask != null) { throw ADP.AsyncOperationPending(); } if (IsClosed) { throw ADP.ObjectDisposed(this); } int readChar = -1; // If there is already a peeked char, then return it if (HasPeekedChar) { readChar = _peekedChar; _peekedChar = -1; } // If there is data available try to read a char else { char[] tempBuffer = new char[1]; int charsRead = InternalRead(tempBuffer, 0, 1); if (charsRead == 1) { readChar = tempBuffer[0]; } } Debug.Assert(readChar == -1 || ((readChar >= char.MinValue) && (readChar <= char.MaxValue)), string.Format("Bad read character: {0}", readChar)); return readChar; } public override int Read(char[] buffer, int index, int count) { ValidateReadParameters(buffer, index, count); if (IsClosed) { throw ADP.ObjectDisposed(this); } if (_currentTask != null) { throw ADP.AsyncOperationPending(); } int charsRead = 0; int charsNeeded = count; // Load in peeked char if ((charsNeeded > 0) && (HasPeekedChar)) { Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar)); buffer[index + charsRead] = (char)_peekedChar; charsRead++; charsNeeded--; _peekedChar = -1; } // If we need more data and there is data avaiable, read charsRead += InternalRead(buffer, index + charsRead, charsNeeded); return charsRead; } public override Task<int> ReadAsync(char[] buffer, int index, int count) { ValidateReadParameters(buffer, index, count); TaskCompletionSource<int> completion = new TaskCompletionSource<int>(); if (IsClosed) { completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this))); } else { try { Task original = Interlocked.CompareExchange<Task>(ref _currentTask, completion.Task, null); if (original != null) { completion.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending())); } else { bool completedSynchronously = true; int charsRead = 0; int adjustedIndex = index; int charsNeeded = count; // Load in peeked char if ((HasPeekedChar) && (charsNeeded > 0)) { // Take a copy of _peekedChar in case it is cleared during close int peekedChar = _peekedChar; if (peekedChar >= char.MinValue) { Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar)); buffer[adjustedIndex] = (char)peekedChar; adjustedIndex++; charsRead++; charsNeeded--; _peekedChar = -1; } } int byteBufferUsed; byte[] byteBuffer = PrepareByteBuffer(charsNeeded, out byteBufferUsed); // Permit a 0 byte read in order to advance the reader to the correct column if ((byteBufferUsed < byteBuffer.Length) || (byteBuffer.Length == 0)) { int bytesRead; var reader = _reader; if (reader != null) { Task<int> getBytesTask = reader.GetBytesAsync(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed, Timeout.Infinite, _disposalTokenSource.Token, out bytesRead); if (getBytesTask == null) { byteBufferUsed += bytesRead; } else { // We need more data - setup the callback, and mark this as not completed sync completedSynchronously = false; getBytesTask.ContinueWith((t) => { _currentTask = null; // If we completed but the textreader is closed, then report cancellation if ((t.Status == TaskStatus.RanToCompletion) && (!IsClosed)) { try { int bytesReadFromStream = t.Result; byteBufferUsed += bytesReadFromStream; if (byteBufferUsed > 0) { charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded); } completion.SetResult(charsRead); } catch (Exception ex) { completion.SetException(ex); } } else if (IsClosed) { completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this))); } else if (t.Status == TaskStatus.Faulted) { if (t.Exception.InnerException is SqlException) { // ReadAsync can't throw a SqlException, so wrap it in an IOException completion.SetException(ADP.ExceptionWithStackTrace(ADP.ErrorReadingFromStream(t.Exception.InnerException))); } else { completion.SetException(t.Exception.InnerException); } } else { completion.SetCanceled(); } }, TaskScheduler.Default); } if ((completedSynchronously) && (byteBufferUsed > 0)) { // No more data needed, decode what we have charsRead += DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, adjustedIndex, charsNeeded); } } else { // Reader is null, close must of happened in the middle of this read completion.SetException(ADP.ExceptionWithStackTrace(ADP.ObjectDisposed(this))); } } if (completedSynchronously) { _currentTask = null; if (IsClosed) { completion.SetCanceled(); } else { completion.SetResult(charsRead); } } } } catch (Exception ex) { // In case of any errors, ensure that the completion is completed and the task is set back to null if we switched it completion.TrySetException(ex); Interlocked.CompareExchange(ref _currentTask, null, completion.Task); throw; } } return completion.Task; } protected override void Dispose(bool disposing) { if (disposing) { // Set the textreader as closed SetClosed(); } base.Dispose(disposing); } /// <summary> /// Forces the TextReader to act as if it was closed /// This does not actually close the stream, read off the rest of the data or dispose this /// </summary> internal void SetClosed() { _disposalTokenSource.Cancel(); _reader = null; _peekedChar = -1; // Wait for pending task var currentTask = _currentTask; if (currentTask != null) { ((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne(); } } /// <summary> /// Performs the actual reading and converting /// NOTE: This assumes that buffer, index and count are all valid, we're not closed (!IsClosed) and that there is data left (IsDataLeft()) /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="count"></param> /// <returns></returns> private int InternalRead(char[] buffer, int index, int count) { Debug.Assert(buffer != null, "Null output buffer"); Debug.Assert((index >= 0) && (count >= 0) && (index + count <= buffer.Length), string.Format("Bad count: {0} or index: {1}", count, index)); Debug.Assert(!IsClosed, "Can't read while textreader is closed"); try { int byteBufferUsed; byte[] byteBuffer = PrepareByteBuffer(count, out byteBufferUsed); byteBufferUsed += _reader.GetBytesInternalSequential(_columnIndex, byteBuffer, byteBufferUsed, byteBuffer.Length - byteBufferUsed); if (byteBufferUsed > 0) { return DecodeBytesToChars(byteBuffer, byteBufferUsed, buffer, index, count); } else { // Nothing to read, or nothing read return 0; } } catch (SqlException ex) { // Read can't throw a SqlException - so wrap it in an IOException throw ADP.ErrorReadingFromStream(ex); } } /// <summary> /// Creates a byte array large enough to store all bytes for the characters in the current encoding, then fills it with any leftover bytes /// </summary> /// <param name="numberOfChars">Number of characters that are to be read</param> /// <param name="byteBufferUsed">Number of bytes pre-filled by the leftover bytes</param> /// <returns>A byte array of the correct size, pre-filled with leftover bytes</returns> private byte[] PrepareByteBuffer(int numberOfChars, out int byteBufferUsed) { Debug.Assert(numberOfChars >= 0, "Can't prepare a byte buffer for negative characters"); byte[] byteBuffer; if (numberOfChars == 0) { byteBuffer = new byte[0]; byteBufferUsed = 0; } else { int byteBufferSize = _encoding.GetMaxByteCount(numberOfChars); if (_leftOverBytes != null) { // If we have more leftover bytes than we need for this conversion, then just re-use the leftover buffer if (_leftOverBytes.Length > byteBufferSize) { byteBuffer = _leftOverBytes; byteBufferUsed = byteBuffer.Length; } else { // Otherwise, copy over the leftover buffer byteBuffer = new byte[byteBufferSize]; Array.Copy(_leftOverBytes, byteBuffer, _leftOverBytes.Length); byteBufferUsed = _leftOverBytes.Length; } } else { byteBuffer = new byte[byteBufferSize]; byteBufferUsed = 0; } } return byteBuffer; } /// <summary> /// Decodes the given bytes into characters, and stores the leftover bytes for later use /// </summary> /// <param name="inBuffer">Buffer of bytes to decode</param> /// <param name="inBufferCount">Number of bytes to decode from the inBuffer</param> /// <param name="outBuffer">Buffer to write the characters to</param> /// <param name="outBufferOffset">Offset to start writing to outBuffer at</param> /// <param name="outBufferCount">Maximum number of characters to decode</param> /// <returns>The actual number of characters decoded</returns> private int DecodeBytesToChars(byte[] inBuffer, int inBufferCount, char[] outBuffer, int outBufferOffset, int outBufferCount) { Debug.Assert(inBuffer != null, "Null input buffer"); Debug.Assert((inBufferCount > 0) && (inBufferCount <= inBuffer.Length), string.Format("Bad inBufferCount: {0}", inBufferCount)); Debug.Assert(outBuffer != null, "Null output buffer"); Debug.Assert((outBufferOffset >= 0) && (outBufferCount > 0) && (outBufferOffset + outBufferCount <= outBuffer.Length), string.Format("Bad outBufferCount: {0} or outBufferOffset: {1}", outBufferCount, outBufferOffset)); int charsRead; int bytesUsed; bool completed; _decoder.Convert(inBuffer, 0, inBufferCount, outBuffer, outBufferOffset, outBufferCount, false, out bytesUsed, out charsRead, out completed); // completed may be false and there is no spare bytes if the Decoder has stored bytes to use later if ((!completed) && (bytesUsed < inBufferCount)) { _leftOverBytes = new byte[inBufferCount - bytesUsed]; Array.Copy(inBuffer, bytesUsed, _leftOverBytes, 0, _leftOverBytes.Length); } else { // If Convert() sets completed to true, then it must have used all of the bytes we gave it Debug.Assert(bytesUsed >= inBufferCount, "Converted completed, but not all bytes were used"); _leftOverBytes = null; } Debug.Assert(((_reader == null) || (_reader.ColumnDataBytesRemaining() > 0) || (!completed) || (_leftOverBytes == null)), "Stream has run out of data and the decoder finished, but there are leftover bytes"); Debug.Assert(charsRead > 0, "Converted no chars. Bad encoding?"); return charsRead; } /// <summary> /// True if this TextReader is supposed to be closed /// </summary> private bool IsClosed { get { return (_reader == null); } } /// <summary> /// True if there is a peeked character available /// </summary> private bool HasPeekedChar { get { return (_peekedChar >= char.MinValue); } } /// <summary> /// Checks the the parameters passed into a Read() method are valid /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="count"></param> internal static void ValidateReadParameters(char[] buffer, int index, int count) { if (buffer == null) { throw ADP.ArgumentNull(ADP.ParameterBuffer); } if (index < 0) { throw ADP.ArgumentOutOfRange(ADP.ParameterIndex); } if (count < 0) { throw ADP.ArgumentOutOfRange(ADP.ParameterCount); } try { if (checked(index + count) > buffer.Length) { throw ExceptionBuilder.InvalidOffsetLength(); } } catch (OverflowException) { // If we've overflowed when adding index and count, then they never would have fit into buffer anyway throw ExceptionBuilder.InvalidOffsetLength(); } } } sealed internal class SqlUnicodeEncoding : UnicodeEncoding { private static SqlUnicodeEncoding s_singletonEncoding = new SqlUnicodeEncoding(); private SqlUnicodeEncoding() : base(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false) { } public override Decoder GetDecoder() { return new SqlUnicodeDecoder(); } public override int GetMaxByteCount(int charCount) { // SQL Server never sends a BOM, so we can assume that its 2 bytes per char return charCount * 2; } public static Encoding SqlUnicodeEncodingInstance { get { return s_singletonEncoding; } } sealed private class SqlUnicodeDecoder : Decoder { public override int GetCharCount(byte[] bytes, int index, int count) { // SQL Server never sends a BOM, so we can assume that its 2 bytes per char return count / 2; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // This method is required - simply call Convert() int bytesUsed; int charsUsed; bool completed; Convert(bytes, byteIndex, byteCount, chars, charIndex, chars.Length - charIndex, true, out bytesUsed, out charsUsed, out completed); return charsUsed; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Assume 2 bytes per char and no BOM charsUsed = Math.Min(charCount, byteCount / 2); bytesUsed = charsUsed * 2; completed = (bytesUsed == byteCount); // BlockCopy uses offsets\length measured in bytes, not the actual array index Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * 2, bytesUsed); } } } }
/* * Form.cs - Implementation of the * "System.Windows.Forms.Form" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * Copyright (C) 2003 Neil Cawse. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Windows.Forms { using System.Drawing; using System.Drawing.Toolkit; using System.ComponentModel; using System.Collections; public class Form : ContainerControl { // Internal state. private IButtonControl acceptButton; private IButtonControl defaultButton; private IButtonControl cancelButton; private bool autoScale; private bool keyPreview; private bool topLevel; internal bool dialogResultIsSet; private Size autoScaleBaseSize; private DialogResult dialogResult; private FormBorderStyle borderStyle; private Icon icon; private ToolkitWindowFlags windowFlags; private Size maximumSize; private Size minimumSize; private Form[] mdiChildren; private Form[] ownedForms; private Form mdiParent; private Form owner; private MainMenu menu; private MainMenu mergedMenu; private double opacity; private SizeGripStyle sizeGripStyle; private FormStartPosition formStartPosition; private Color transparencyKey; private FormWindowState windowState; internal static Form activeForm; internal static ArrayList activeForms = new ArrayList(); private bool showInTaskbar; private bool controlBox; private bool loaded; /* whether we have sent OnLoad or not */ private MdiClient mdiClient; // Constructor. public Form() { visible = false; autoScale = true; topLevel = true; loaded=false; borderStyle = FormBorderStyle.Sizable; mdiChildren = new Form [0]; ownedForms = new Form [0]; opacity = 1.0; windowFlags = ToolkitWindowFlags.Default; formStartPosition = FormStartPosition.WindowsDefaultLocation; windowState = FormWindowState.Normal; } // Get or set this control's properties. private IToolkitTopLevelWindow ToolkitWindow { get { return (toolkitWindow as IToolkitTopLevelWindow); } } public IButtonControl AcceptButton { get { return acceptButton; } set { acceptButton = value; } } public static Form ActiveForm { get { return activeForm; } } public Form ActiveMdiChild { get { if(mdiClient != null) { return mdiClient.ActiveChild; } else { return null; } } } [TODO] public bool AllowTransparency { get { // Implement return false; } set { // Implement } } public bool AutoScale { get { return autoScale; } set { autoScale = value; } } public Size AutoScaleBaseSize { get { return autoScaleBaseSize; } set { autoScaleBaseSize = value; } } public override bool AutoScroll { get { return base.AutoScroll; } set { base.AutoScroll = value; } } public override Color BackColor { get { // The base implementation takes care of the default. return base.BackColor; } set { base.BackColor = value; } } public IButtonControl CancelButton { get { return cancelButton; } set { cancelButton = value; } } protected override CreateParams CreateParams { get { return base.CreateParams; } } protected override ImeMode DefaultImeMode { get { return ImeMode.NoControl; } } protected override Size DefaultSize { get { return new Size(300, 300); } } public Rectangle DesktopBounds { get { // Use the ordinary bounds. return Bounds; } set { Bounds = value; } } public Point DesktopLocation { get { // Use the ordinary location. return Location; } set { Location = value; } } public DialogResult DialogResult { get { return dialogResult; } set { dialogResult = value; dialogResultIsSet = true; } } public FormBorderStyle FormBorderStyle { get { return borderStyle; } set { if(borderStyle != value) { Size oldSize = ClientSize; borderStyle = value; SetWindowFlag(0, true); ClientSize = oldSize; } } } public bool HelpButton { get { return GetWindowFlag(ToolkitWindowFlags.Help); } set { SetWindowFlag(ToolkitWindowFlags.Help, value); } } public Icon Icon { get { return icon; } set { if(icon != value) { icon = value; if(ToolkitWindow != null) { ToolkitWindow.SetIcon(value); } } } } public bool IsMdiChild { get { return (MdiParent != null); } } public bool IsMdiContainer { get { return (mdiClient != null); } set { if(value && mdiClient == null) { // Convert the form into MDI mode. mdiClient = new MdiClient(); Controls.Add(mdiClient); } } } public bool KeyPreview { get { return keyPreview; } set { keyPreview = value; } } public bool MaximizeBox { get { return GetWindowFlag(ToolkitWindowFlags.Maximize); } set { SetWindowFlag(ToolkitWindowFlags.Maximize, value); } } [TODO] protected Rectangle MaximizedBounds { get { // Implement return Rectangle.Empty; } set { // Implement } } public Size MaximumSize { get { return maximumSize; } set { if(value.Width < 0) { throw new ArgumentOutOfRangeException ("value.Width", S._("SWF_NonNegative")); } if(value.Height < 0) { throw new ArgumentOutOfRangeException ("value.Height", S._("SWF_NonNegative")); } if(maximumSize != value) { maximumSize = value; if(ToolkitWindow != null) { ToolkitWindow.SetMaximumSize(value); } if (maximumSize.Width > 0 && Width > maximumSize.Width) Width = maximumSize.Width; if (maximumSize.Height > 0 && Height > maximumSize.Height) Height = maximumSize.Height; } } } public Form[] MdiChildren { get { if(mdiClient != null) { return mdiClient.MdiChildren; } else { return new Form [0]; } } } public Form MdiParent { get { return mdiParent; } set { if(mdiParent != null || value == null || Created) { return; } if(value.mdiClient == null) { return; } mdiParent = value; value.mdiClient.Controls.Add(this); Parent = value.mdiClient; } } public bool MinimizeBox { get { return GetWindowFlag(ToolkitWindowFlags.Minimize); } set { SetWindowFlag(ToolkitWindowFlags.Minimize, value); } } public Size MinimumSize { get { return minimumSize; } set { if(value.Width < 0) { throw new ArgumentOutOfRangeException ("value.Width", S._("SWF_NonNegative")); } if(value.Height < 0) { throw new ArgumentOutOfRangeException ("value.Height", S._("SWF_NonNegative")); } if(minimumSize != value) { minimumSize = value; if(ToolkitWindow != null) { ToolkitWindow.SetMinimumSize(value); } if (minimumSize.Width > 0 && Width < minimumSize.Width) Width = minimumSize.Width; if (minimumSize.Height > 0 && Height < minimumSize.Height) Height = minimumSize.Height; } } } public MainMenu Menu { get { return menu; } set { if(menu != value) { if(menu != null) { menu.RemoveFromForm(); menu = null; } if(value != null) { Form other = value.GetForm(); if(other != null) { other.Menu = null; } } // Get the ClientSize before we add the menu. Size clientSize = ClientSize; menu = value; if(menu != null) { menu.AddToForm(this); } // The ClientSize must be the original. ClientSize = clientSize; } } } public MainMenu MergedMenu { get { return mergedMenu; } } public bool Modal { get { return GetWindowFlag(ToolkitWindowFlags.Modal); } } public double Opacity { get { return opacity; } set { opacity = value; IToolkitTopLevelWindow window = (IToolkitTopLevelWindow)ToolkitWindow; if(window != null) { window.SetOpacity(opacity); } } } public Form[] OwnedForms { get { return ownedForms; } } [TODO] public Form Owner { get { return owner; } set { // Fix: update the owned child list owner = value; } } public bool ShowInTaskbar { get { return GetWindowFlag(ToolkitWindowFlags.ShowInTaskbar); } set { if (value != showInTaskbar) { showInTaskbar = value; SetWindowFlag(ToolkitWindowFlags.ShowInTaskbar, value); } } } public new Size Size { get { return base.Size; } set { base.Size = value; } } public SizeGripStyle SizeGripStyle { get { return sizeGripStyle; } set { sizeGripStyle = value; } } public FormStartPosition StartPosition { get { return formStartPosition; } set { formStartPosition = value; } } public bool TopLevel { get { return topLevel; } set { // recreate toolkitwindow, if exists if( value != topLevel ) { topLevel = value; if( null != toolkitWindow ) { Control [] copy = new Control[this.Controls.Count]; this.Controls.CopyTo( copy, 0 ); this.Controls.Clear();; toolkitWindow.Destroy(); toolkitWindow = null; this.CreateHandle(); this.Controls.AddRange( copy ); } } } } public bool TopMost { get { return GetWindowFlag(ToolkitWindowFlags.TopMost); } set { SetWindowFlag(ToolkitWindowFlags.TopMost, value); } } public Color TransparencyKey { get { return transparencyKey; } set { transparencyKey = value; } } public FormWindowState WindowState { get { return windowState; } set { if(windowState != value) { windowState = value; if(ToolkitWindow != null) { if(value == FormWindowState.Normal) { ToolkitWindow.Restore(); } #if !CONFIG_COMPACT_FORMS else if(value == FormWindowState.Minimized) { ToolkitWindow.Iconify(); } #endif else if(value == FormWindowState.Maximized) { ToolkitWindow.Maximize(); } } } } } internal override IToolkitWindow CreateToolkitWindow(IToolkitWindow parent) { // When a Form is reparented to a normal container control // which does work on Win32 unfortunately. if(mdiParent == null && (!TopLevel)) { return base.CreateToolkitWindow(parent); } CreateParams cp = CreateParams; // Create the window and set its initial caption. IToolkitTopLevelWindow window; if(mdiParent == null) { // use ControlToolkitManager to create the window thread safe window = ControlToolkitManager.CreateTopLevelWindow( this, cp.Width - ToolkitDrawSize.Width, cp.Height - ToolkitDrawSize.Height); } else { mdiParent.mdiClient.CreateControl(); IToolkitMdiClient mdi = (mdiParent.mdiClient.toolkitWindow as IToolkitMdiClient); // use ControlToolkitManager to create the window thread safe window = ControlToolkitManager.CreateMdiChildWindow( this, mdi, cp.X, cp.Y, cp.Width - ToolkitDrawSize.Width, cp.Height - ToolkitDrawSize.Height); } window.SetTitle(cp.Caption); // Win32 requires this because if the window is maximized, the windows size needs to be set. toolkitWindow = window; // Adjust the window hints to match our requirements. SetWindowFlags(window); if(icon != null) { window.SetIcon(icon); } window.SetMaximumSize(maximumSize); window.SetMinimumSize(minimumSize); #if !CONFIG_COMPACT_FORMS if(windowState == FormWindowState.Minimized) { window.Iconify(); } else #endif if(windowState == FormWindowState.Maximized) { window.Maximize(); } // Center the window on-screen if necessary. if(formStartPosition == FormStartPosition.CenterScreen) { Size screenSize = ToolkitManager.Toolkit.GetScreenSize(); window.MoveResize ((screenSize.Width - cp.Width) / 2, (screenSize.Height - cp.Height) / 2, window.Dimensions.Width, window.Dimensions.Height); } else if(formStartPosition == FormStartPosition.Manual) { window.MoveResize ( cp.X, cp.Y, window.Dimensions.Width, window.Dimensions.Height ); } if(opacity != 1.0) { window.SetOpacity(opacity); } return window; } // Determine if this is a top-level control which cannot have parents. internal override bool IsTopLevel { get { return ((mdiParent == null) && TopLevel); } } // Get the current state of a window decoration flag. private bool GetWindowFlag(ToolkitWindowFlags flag) { return ((windowFlags & flag) == flag); } // Get the full set of window flags for this window. private ToolkitWindowFlags GetFullFlags() { ToolkitWindowFlags flags = windowFlags; switch(borderStyle) { case FormBorderStyle.None: { bool topMost = ((flags & ToolkitWindowFlags.TopMost) != 0); flags = ToolkitWindowFlags.ShowInTaskbar; if (topMost) flags |= ToolkitWindowFlags.TopMost; } break; case FormBorderStyle.Fixed3D: case FormBorderStyle.FixedSingle: { flags &= ~(ToolkitWindowFlags.Maximize | ToolkitWindowFlags.ResizeHandles | ToolkitWindowFlags.Resize); } break; case FormBorderStyle.FixedDialog: { flags &= ~(ToolkitWindowFlags.Maximize | ToolkitWindowFlags.ResizeHandles | ToolkitWindowFlags.Resize); flags |= ToolkitWindowFlags.Dialog; } break; case FormBorderStyle.FixedToolWindow: { flags &= ~(ToolkitWindowFlags.Maximize | ToolkitWindowFlags.ResizeHandles | ToolkitWindowFlags.Resize | ToolkitWindowFlags.ShowInTaskbar); flags |= ToolkitWindowFlags.ToolWindow; } break; case FormBorderStyle.Sizable: break; case FormBorderStyle.SizableToolWindow: { flags &= ~(ToolkitWindowFlags.ShowInTaskbar); flags |= ToolkitWindowFlags.ToolWindow; } break; } if((flags & ToolkitWindowFlags.Modal) != 0) { flags |= ToolkitWindowFlags.Dialog; } return flags; } // Set the current state of the window decoration flags on a window. private void SetWindowFlags(IToolkitWindow window) { ((IToolkitTopLevelWindow)window).SetWindowFlags(GetFullFlags()); } // Set the current state of a window decoration flag. private void SetWindowFlag(ToolkitWindowFlags flag, bool value) { // Alter the flag setting. if(value) { windowFlags |= flag; } else { windowFlags &= ~flag; } // Pass the flags to the window manager. if(toolkitWindow != null) { SetWindowFlags(toolkitWindow); } } // Activate the form and give it focus. public void Activate() { BringToFront(); } // Add an owned form to this form. public void AddOwnedForm(Form ownedForm) { if(ownedForm != null) { ownedForm.Owner = this; } } // Close this form. public void Close() { CloseRequest(); } // Get the auto scale base size for a particular font. [TODO] public static SizeF GetAutoScaleSize(Font font) { return SizeF.Empty; } // Layout the MDI children of this form. public void LayoutMdi(MdiLayout value) { if(mdiClient != null) { mdiClient.LayoutMdi(value); } } // Remove an owned form from this form. public void RemoveOwnedForm(Form ownedForm) { if(ownedForm != null && ownedForm.Owner == this) { ownedForm.Owner = null; } } #if !CONFIG_COMPACT_FORMS // Set the desktop bounds of this form. public void SetDesktopBounds(int x, int y, int width, int height) { Rectangle workingArea = SystemInformation.WorkingArea; SetBoundsCore(workingArea.X + x, workingArea.Y + y, width, height, BoundsSpecified.All); } // Set the desktop location of this form. public void SetDesktopLocation(int x, int y) { Rectangle workingArea = SystemInformation.WorkingArea; Location = new Point(workingArea.X + x, workingArea.Y + y); } #endif // !CONFIG_COMPACT_FORMS // Show this form as a modal dialog. private DialogResult ShowDialog(Form owner) { // Bail out if this dialog is already displayed modally. if(Modal) { return DialogResult.None; } // Reset the dialog result. dialogResult = DialogResult.None; dialogResultIsSet = false; // Mark this form as modal. SetWindowFlag(ToolkitWindowFlags.Modal, true); try { // Create the control. We must do this before // we set the owner or make the form visible. CreateControl(); // Set the dialog owner. IToolkitTopLevelWindow toolkitWindow = ToolkitWindow; if(toolkitWindow != null) { if(owner != null) { toolkitWindow.SetDialogOwner(owner.ToolkitWindow); } else { toolkitWindow.SetDialogOwner(null); } } // Make the form visible. Visible = true; Activate(); // Enter a message loop until the dialog result is set. Application.InnerMessageLoop(this); Dispose(); // must call Dispose, when closing the dialog } finally { // Make sure that the form is not visible. Visible = false; // The form is no longer modal. SetWindowFlag(ToolkitWindowFlags.Modal, false); } // Return the dialog result. return dialogResult; } public DialogResult ShowDialog() { return ShowDialog(Owner); } public DialogResult ShowDialog(IWin32Window owner) { return ShowDialog(owner as Form); } // Convert this object into a string. public override String ToString() { return base.ToString() + ", Text: " + Text; } // Event that is emitted when this form is activated. public event EventHandler Activated { add { AddHandler(EventId.Activated, value); } remove { RemoveHandler(EventId.Activated, value); } } // Event that is emitted when this form is closed. public event EventHandler Closed { add { AddHandler(EventId.Closed, value); } remove { RemoveHandler(EventId.Closed, value); } } // Event that is emitted when this form is closing. public event CancelEventHandler Closing { add { AddHandler(EventId.Closing, value); } remove { RemoveHandler(EventId.Closing, value); } } // Event that is emitted when this form is deactivated. public event EventHandler Deactivate { add { AddHandler(EventId.Deactivate, value); } remove { RemoveHandler(EventId.Deactivate, value); } } // Event that is emitted when the input language of a form is changed. public event InputLanguageChangedEventHandler InputLanguageChanged { add { AddHandler(EventId.InputLanguageChanged, value); } remove { RemoveHandler(EventId.InputLanguageChanged, value); } } // Event that is emitted when the input language of a form is changing. public event InputLanguageChangingEventHandler InputLanguageChanging { add { AddHandler(EventId.InputLanguageChanging, value); } remove { RemoveHandler(EventId.InputLanguageChanging, value); } } // Event that is emitted when this form is first loaded. public event EventHandler Load { add { AddHandler(EventId.Load, value); } remove { RemoveHandler(EventId.Load, value); } } // Event that is emitted when the maximized bounds change. public event EventHandler MaximizedBoundsChanged { add { AddHandler(EventId.MaximizedBoundsChanged, value); } remove { RemoveHandler(EventId.MaximizedBoundsChanged, value); } } // Event that is emitted when the maximum size changes. public event EventHandler MaximumSizeChanged { add { AddHandler(EventId.MaximumSizeChanged, value); } remove { RemoveHandler(EventId.MaximumSizeChanged, value); } } // Event that is emitted when an MDI child is activated. public event EventHandler MdiChildActivate { add { AddHandler(EventId.MdiChildActivate, value); } remove { RemoveHandler(EventId.MdiChildActivate, value); } } // Event that is emitted at the end of processing a menu item. public event EventHandler MenuComplete { add { AddHandler(EventId.MenuComplete, value); } remove { RemoveHandler(EventId.MenuComplete, value); } } // Event that is emitted at the start of processing a menu item. public event EventHandler MenuStart { add { AddHandler(EventId.MenuStart, value); } remove { RemoveHandler(EventId.MenuStart, value); } } // Event that is emitted when the minimum size changes. public event EventHandler MinimumSizeChanged { add { AddHandler(EventId.MinimumSizeChanged, value); } remove { RemoveHandler(EventId.MinimumSizeChanged, value); } } protected void CenterToScreen() { // Nothing to do here -- Not to be used by App developers } // Create a new control collection for this instance. protected override Control.ControlCollection CreateControlsInstance() { return new ControlCollection(this); } // Create the handle for this control. protected override void CreateHandle() { // Let the base class do the work. base.CreateHandle(); } // Dispose of this control. protected override void Dispose(bool disposing) { acceptButton = null; defaultButton = null; cancelButton = null; mdiClient = null; if( null != owner ) { this.RemoveOwnedForm(owner); owner = null; } if( null != ownedForms ) { int iCount = ownedForms.Length; for( int i = iCount-1; i >= 0; i-- ) { if( null != ownedForms[i] ) { ownedForms[i].Dispose(); } } } if( null != menu ) { menu.ownerForm = null; menu = null; } if( null != mergedMenu ) { if( mergedMenu.ownerForm == this || mergedMenu.ownerForm == null ) { mergedMenu.Dispose(); } mergedMenu = null; } if( activeForm == this ) activeForm = null; base.Dispose(disposing); } // Emit the "Activated" event. protected virtual void OnActivated(EventArgs e) { // This form is currently the active one. activeForm = this; // Dispatch the event to everyone who is listening. EventHandler handler; handler = (EventHandler)(GetHandler(EventId.Activated)); if(handler != null) { handler(this, e); } } // Emit the "Closed" event. protected virtual void OnClosed(EventArgs e) { EventHandler handler; handler = (EventHandler)(GetHandler(EventId.Closed)); if(handler != null) { handler(this, e); } } // Emit the "Closing" event. protected virtual void OnClosing(CancelEventArgs e) { CancelEventHandler handler; handler = (CancelEventHandler)(GetHandler(EventId.Closing)); if(handler != null) { handler(this, e); } } // Handle initial control creation. protected override void OnCreateControl() { base.OnCreateControl(); if(loaded == false && toolkitWindow.IsMapped) { loaded = true; OnLoad(EventArgs.Empty); } if( menu != null ) { // Workaround for fixing that menu is dispayed correct when form is shown. Height = Height+1; Height = Height-1; } } // Emit the "Deactivate" event. protected virtual void OnDeactivate(EventArgs e) { // None of the application's forms are currently active. activeForm = null; // Dispatch the event to everyone who is listening. EventHandler handler; handler = (EventHandler)(GetHandler(EventId.Deactivate)); if(handler != null) { handler(this, e); } } // Override the "FontChanged" event. protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); } // Override the "HandleCreated" event. protected override void OnHandleCreated(EventArgs e) { // we have to add a reference to the form if the form is created and shown without a reference // to avoid the form beeing collected, even it is shown. if( !activeForms.Contains(this) ) activeForms.Add(this); base.OnHandleCreated(e); } // Override the "HandleDestroyed" event. protected override void OnHandleDestroyed(EventArgs e) { activeForms.Remove(this); base.OnHandleDestroyed(e); } // Emit the "InputLanguageChanged" event. protected virtual void OnInputLanguageChanged (InputLanguageChangedEventArgs e) { InputLanguageChangedEventHandler handler; handler = (InputLanguageChangedEventHandler) (GetHandler(EventId.InputLanguageChanged)); if(handler != null) { handler(this, e); } } // Emit the "InputLanguageChanging" event. protected virtual void OnInputLanguageChanging (InputLanguageChangingEventArgs e) { InputLanguageChangingEventHandler handler; handler = (InputLanguageChangingEventHandler) (GetHandler(EventId.InputLanguageChanging)); if(handler != null) { handler(this, e); } } // Emit the "Load" event. protected virtual void OnLoad(EventArgs e) { EventHandler handler; handler = (EventHandler)(GetHandler(EventId.Load)); if(handler != null) { handler(this, e); } } // Emit the "MaximizedBoundsChanged" event. protected virtual void OnMaximizedBoundsChanged(EventArgs e) { EventHandler handler; handler = (EventHandler) (GetHandler(EventId.MaximizedBoundsChanged)); if(handler != null) { handler(this, e); } } // Emit the "MaximumSizeChanged" event. protected virtual void OnMaximumSizeChanged(EventArgs e) { EventHandler handler; handler = (EventHandler) (GetHandler(EventId.MaximumSizeChanged)); if(handler != null) { handler(this, e); } } // Emit the "MdiChildActivate" event. protected virtual void OnMdiChildActivate(EventArgs e) { EventHandler handler; handler = (EventHandler)(GetHandler(EventId.MdiChildActivate)); if(handler != null) { handler(this, e); } } // Emit the "MenuComplete" event. protected virtual void OnMenuComplete(EventArgs e) { EventHandler handler; handler = (EventHandler)(GetHandler(EventId.MenuComplete)); if(handler != null) { handler(this, e); } } // Emit the "MenuStart" event. protected virtual void OnMenuStart(EventArgs e) { EventHandler handler; handler = (EventHandler)(GetHandler(EventId.MenuStart)); if(handler != null) { handler(this, e); } } // Emit the "MinimumSizeChanged" event. protected virtual void OnMinimumSizeChanged(EventArgs e) { EventHandler handler; handler = (EventHandler) (GetHandler(EventId.MinimumSizeChanged)); if(handler != null) { handler(this, e); } } // Override the "Paint" event. protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (menu != null) menu.OnPaint(); } // Override the "PrimaryEnter" event. internal override void OnPrimaryEnter(EventArgs e) { OnActivated(e); } // Override the "PrimaryLeave" event. internal override void OnPrimaryLeave(EventArgs e) { OnDeactivate(e); } // Override the "Resize" event. protected override void OnResize(EventArgs e) { base.OnResize(e); } // Override the "StyleChanged" event. protected override void OnStyleChanged(EventArgs e) { base.OnStyleChanged(e); } // Override the "TextChanged" event. protected override void OnTextChanged(EventArgs e) { if(ToolkitWindow != null) { ToolkitWindow.SetTitle(Text); } base.OnTextChanged(e); } // Override the "VisibleChanged" event. protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); if(loaded == false && toolkitWindow != null && toolkitWindow.IsMapped) { loaded = true; OnLoad(EventArgs.Empty); } } // Process a command key. protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (base.ProcessCmdKey(ref msg, keyData)) return true; if (menu != null) return menu.ProcessCmdKey(ref msg, keyData); return false; } // Process a dialog key. protected override bool ProcessDialogKey(Keys keyData) { if ((keyData & (Keys.Control | Keys.Alt)) == 0) { Keys key = keyData & Keys.KeyCode; if (key == Keys.Return) { if (acceptButton != null) { acceptButton.PerformClick(); return true; } } else if (key == Keys.Escape) { if (cancelButton != null) { cancelButton.PerformClick(); return true; } } } return base.ProcessDialogKey(keyData); } // Preview a keyboard message. protected override bool ProcessKeyPreview(ref Message msg) { if(keyPreview) { // The form wants first crack at the key message. if(ProcessKeyEventArgs(ref msg)) { return true; } } return base.ProcessKeyPreview(ref msg); } // Process the tab key. protected override bool ProcessTabKey(bool forward) { return SelectNextControl(ActiveControl, forward, true, true, true); } protected override bool ProcessDialogChar(char charCode) { if (GetTopLevel() && ProcessMnemonic(charCode)) return true; return base.ProcessDialogChar(charCode); } // Inner core of "Scale". [TODO] protected override void ScaleCore(float dx, float dy) { base.ScaleCore(dx, dy); } // Select this control. protected override void Select(bool directed, bool forward) { if (directed) base.SelectNextControl(null, forward, true, true, false); if (TopLevel) toolkitWindow.Focus(); Form parent = ParentForm; if (parent != null) parent.ActiveControl = this; } protected override void UpdateDefaultButton() { // Find the bottom active control. ContainerControl c = this; while (true) { ContainerControl nextActive = c.ActiveControl as ContainerControl; if (nextActive == null) { break; } c = nextActive; } IButtonControl newDefaultButton = c as IButtonControl; if (c == null) { newDefaultButton = acceptButton; } if (newDefaultButton != defaultButton) { // Notify the previous button that it is not the default. if (defaultButton != null) { defaultButton.NotifyDefault(false); } defaultButton = newDefaultButton; if (defaultButton != null) { defaultButton.NotifyDefault(true); } } } // Inner core of "SetBounds". protected override void SetBoundsCore (int x, int y, int width, int height, BoundsSpecified specified) { base.SetBoundsCore(x, y, width, height, specified); } public override Point ClientOrigin { get { if (menu != null) return ToolkitDrawOrigin + new Size(0, SystemInformation.MenuHeight); else return ToolkitDrawOrigin; } } protected override Point ToolkitDrawOrigin { get { int leftAdjust, topAdjust, rightAdjust, bottomAdjust; if(FormBorderStyle != FormBorderStyle.None) { ToolkitManager.Toolkit.GetWindowAdjust (out leftAdjust, out topAdjust, out rightAdjust, out bottomAdjust, GetFullFlags()); return new Point(leftAdjust, topAdjust); } else { return Point.Empty; } } } protected override Size ToolkitDrawSize { get { if(FormBorderStyle != FormBorderStyle.None) { int leftAdjust, topAdjust, rightAdjust, bottomAdjust; ToolkitManager.Toolkit.GetWindowAdjust (out leftAdjust, out topAdjust, out rightAdjust, out bottomAdjust, GetFullFlags()); return new Size(leftAdjust + rightAdjust, topAdjust + bottomAdjust); } else { return Size.Empty; } } } // Convert a client size into a window bounds size. internal override Size ClientToBounds(Size size) { int leftAdjust = 0, topAdjust = 0, rightAdjust = 0, bottomAdjust = 0; if (FormBorderStyle != FormBorderStyle.None) { ToolkitManager.Toolkit.GetWindowAdjust (out leftAdjust, out topAdjust, out rightAdjust, out bottomAdjust, GetFullFlags()); } if (Menu != null) topAdjust += SystemInformation.MenuHeight; return new Size(size.Width + leftAdjust + rightAdjust, size.Height + topAdjust + bottomAdjust); } // Inner core of setting the visibility state. protected override void SetVisibleCore(bool value) { base.SetVisibleCore(value); } // Close request received from "Control.ToolkitClose". internal override void CloseRequest() { if( IsDisposed ) return; // irgnore CloseRequest, if form was destroyed CancelEventArgs args = new CancelEventArgs(); OnClosing(args); if(!(args.Cancel)) { dialogResultIsSet = true; // must be set here, or Application.InnerMessageLoop won't end OnClosed(EventArgs.Empty); Dispose(); } } // Window state change request received. internal override void WindowStateChanged(FormWindowState state) { windowState = state; } // Event that is called when an MDI child is activated or deactivated. internal override void MdiActivate(IToolkitWindow child) { if(mdiClient != null) { mdiClient.Activate(child); } OnMdiChildActivate(EventArgs.Empty); } #if !CONFIG_COMPACT_FORMS // Default window procedure for this control class. protected override void DefWndProc(ref Message msg) { base.DefWndProc(ref msg); } // Process a message. protected override void WndProc(ref Message m) { base.WndProc(ref m); } #endif // !CONFIG_COMPACT_FORMS // Collection of child controls. public new class ControlCollection : Control.ControlCollection { // Internal state. private Form formOwner; // Constructor. public ControlCollection(Form owner) : base(owner) { this.formOwner = owner; } // Override the "Add" and "Remove" behavior. [TODO] public override void Add(Control control) { base.Add(control); } [TODO] public override void Remove(Control control) { base.Remove(control); } }; // class ControlCollection protected override void OnMouseDown(MouseEventArgs e) { // If the mouse is in the non client area, // it must be over the menu if (e.Y < 0 && menu != null) menu.OnMouseDown(e); base.OnMouseDown (e); } protected override void OnMouseLeave(EventArgs e) { // The menu needs to remove the highlighting if (menu != null) menu.OnMouseLeave(); base.OnMouseLeave (e); } protected override void OnMouseMove(MouseEventArgs e) { // If the mouse is in the non client area, // it must be over the menu if (e.Y < 0 && menu != null) menu.OnMouseMove(e); base.OnMouseMove (e); } [TODO] public bool ControlBox { get { return controlBox; } set { if (value != controlBox) { controlBox = value; // Implement } } } }; // class Form }; // namespace System.Windows.Forms
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// SchemaVersionResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Events.V1.Schema { public class SchemaVersionResource : Resource { private static Request BuildReadRequest(ReadSchemaVersionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Events, "/v1/Schemas/" + options.PathId + "/Versions", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a paginated list of versions of the schema. /// </summary> /// <param name="options"> Read SchemaVersion parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SchemaVersion </returns> public static ResourceSet<SchemaVersionResource> Read(ReadSchemaVersionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<SchemaVersionResource>.FromJson("schema_versions", response.Content); return new ResourceSet<SchemaVersionResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a paginated list of versions of the schema. /// </summary> /// <param name="options"> Read SchemaVersion parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SchemaVersion </returns> public static async System.Threading.Tasks.Task<ResourceSet<SchemaVersionResource>> ReadAsync(ReadSchemaVersionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<SchemaVersionResource>.FromJson("schema_versions", response.Content); return new ResourceSet<SchemaVersionResource>(page, options, client); } #endif /// <summary> /// Retrieve a paginated list of versions of the schema. /// </summary> /// <param name="pathId"> The unique identifier of the schema. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SchemaVersion </returns> public static ResourceSet<SchemaVersionResource> Read(string pathId, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSchemaVersionOptions(pathId){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a paginated list of versions of the schema. /// </summary> /// <param name="pathId"> The unique identifier of the schema. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SchemaVersion </returns> public static async System.Threading.Tasks.Task<ResourceSet<SchemaVersionResource>> ReadAsync(string pathId, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSchemaVersionOptions(pathId){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<SchemaVersionResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<SchemaVersionResource>.FromJson("schema_versions", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<SchemaVersionResource> NextPage(Page<SchemaVersionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Events) ); var response = client.Request(request); return Page<SchemaVersionResource>.FromJson("schema_versions", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<SchemaVersionResource> PreviousPage(Page<SchemaVersionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Events) ); var response = client.Request(request); return Page<SchemaVersionResource>.FromJson("schema_versions", response.Content); } private static Request BuildFetchRequest(FetchSchemaVersionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Events, "/v1/Schemas/" + options.PathId + "/Versions/" + options.PathSchemaVersion + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch a specific schema and version. /// </summary> /// <param name="options"> Fetch SchemaVersion parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SchemaVersion </returns> public static SchemaVersionResource Fetch(FetchSchemaVersionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch a specific schema and version. /// </summary> /// <param name="options"> Fetch SchemaVersion parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SchemaVersion </returns> public static async System.Threading.Tasks.Task<SchemaVersionResource> FetchAsync(FetchSchemaVersionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch a specific schema and version. /// </summary> /// <param name="pathId"> The unique identifier of the schema. </param> /// <param name="pathSchemaVersion"> The version of the schema </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SchemaVersion </returns> public static SchemaVersionResource Fetch(string pathId, int? pathSchemaVersion, ITwilioRestClient client = null) { var options = new FetchSchemaVersionOptions(pathId, pathSchemaVersion); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch a specific schema and version. /// </summary> /// <param name="pathId"> The unique identifier of the schema. </param> /// <param name="pathSchemaVersion"> The version of the schema </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SchemaVersion </returns> public static async System.Threading.Tasks.Task<SchemaVersionResource> FetchAsync(string pathId, int? pathSchemaVersion, ITwilioRestClient client = null) { var options = new FetchSchemaVersionOptions(pathId, pathSchemaVersion); return await FetchAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a SchemaVersionResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> SchemaVersionResource object represented by the provided JSON </returns> public static SchemaVersionResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<SchemaVersionResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique identifier of the schema. /// </summary> [JsonProperty("id")] public string Id { get; private set; } /// <summary> /// The version of this schema. /// </summary> [JsonProperty("schema_version")] public int? SchemaVersion { get; private set; } /// <summary> /// The date the schema version was created. /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The URL of this resource. /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The raw /// </summary> [JsonProperty("raw")] public Uri Raw { get; private set; } private SchemaVersionResource() { } } }
/*============================================================================ * Copyright (C) Microsoft Corporation, All rights reserved. *============================================================================ */ #region Using directives using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// The command returns zero, one or more CimSession objects that represent /// connections with remote computers established from the current PS Session. /// </summary> [Cmdlet(VerbsCommon.Get, "CimSession", DefaultParameterSetName = ComputerNameSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227966")] [OutputType(typeof(CimSession))] public sealed class GetCimSessionCommand : CimBaseCommand { #region constructor /// <summary> /// constructor /// </summary> public GetCimSessionCommand() : base(parameters, parameterSets) { DebugHelper.WriteLogEx(); } #endregion #region parameters /// <summary> /// <para> /// The following is the definition of the input parameter "ComputerName". /// Specifies one or more connections by providing their ComputerName(s). The /// Cmdlet then gets CimSession(s) opened with those connections. This parameter /// is an alternative to using CimSession(s) that also identifies the remote /// computer(s). /// </para> /// <para> /// This is the only optional parameter of the Cmdlet. If not provided, the /// Cmdlet returns all CimSession(s) live/active in the runspace. /// </para> /// <para> /// If an instance of CimSession is pipelined to Get-CimSession, the /// ComputerName property of the instance is bound by name with this parameter. /// </para> /// </summary> [Alias(AliasCN, AliasServerName)] [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ComputerNameSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] ComputerName { get { return computername;} set { computername = value; base.SetParameter(value, nameComputerName); } } private String[] computername; /// <summary> /// The following is the definition of the input parameter "Id". /// Specifies one or more numeric Id(s) for which to get CimSession(s). /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = SessionIdSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public UInt32[] Id { get { return id;} set { id = value; base.SetParameter(value, nameId); } } private UInt32[] id; /// <summary> /// The following is the definition of the input parameter "InstanceID". /// Specifies one or Session Instance IDs /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = InstanceIdSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Guid[] InstanceId { get { return instanceid;} set { instanceid = value; base.SetParameter(value, nameInstanceId); } } private Guid[] instanceid; /// <summary> /// The following is the definition of the input parameter "Name". /// Specifies one or more session Name(s) for which to get CimSession(s). The /// argument may contain wildcard characters. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = NameSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] Name { get { return name;} set { name = value; base.SetParameter(value, nameName); } } private String[] name; #endregion #region cmdlet processing methods /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { cimGetSession = new CimGetSession(); this.AtBeginProcess = false; }//End BeginProcessing() /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { base.CheckParameterSet(); cimGetSession.GetCimSession(this); }//End ProcessRecord() #endregion #region private members /// <summary> /// <see cref="CimGetSession"/> object used to search CimSession from cache /// </summary> private CimGetSession cimGetSession; #region const string of parameter names internal const string nameComputerName = "ComputerName"; internal const string nameId = "Id"; internal const string nameInstanceId = "InstanceId"; internal const string nameName = "Name"; #endregion /// <summary> /// static parameter definition entries /// </summary> static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>> { { nameComputerName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ComputerNameSet, false), } }, { nameId, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.SessionIdSet, true), } }, { nameInstanceId, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.InstanceIdSet, true), } }, { nameName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.NameSet, true), } }, }; /// <summary> /// static parameter set entries /// </summary> static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry> { { CimBaseCommand.ComputerNameSet, new ParameterSetEntry(0, true) }, { CimBaseCommand.SessionIdSet, new ParameterSetEntry(1) }, { CimBaseCommand.InstanceIdSet, new ParameterSetEntry(1) }, { CimBaseCommand.NameSet, new ParameterSetEntry(1) }, }; #endregion }//End Class }//End namespace
// (c) Copyright 2012 Hewlett-Packard Development Company, L.P. // 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.Diagnostics; using System.IO; using System.Reflection; using HpToolsLauncher.Properties; using HpToolsLauncher.TestRunners; namespace HpToolsLauncher { public class FileSystemTestsRunner : RunnerBase, IDisposable { #region Members Dictionary<string, string> _jenkinsEnvVariables; private List<TestInfo> _tests; private static string _uftViewerPath; private int _errors, _fail; private bool _useUFTLicense; private TimeSpan _timeout = TimeSpan.MaxValue; private Stopwatch _stopwatch = null; private string _abortFilename = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\stop" + Launcher.UniqueTimeStamp + ".txt"; //LoadRunner Arguments private int _pollingInterval; private TimeSpan _perScenarioTimeOutMinutes; private List<string> _ignoreErrorStrings; //saves runners for cleaning up at the end. private Dictionary<TestType, IFileSysTestRunner> _colRunnersForCleanup = new Dictionary<TestType, IFileSysTestRunner>(); public const string UftJUnitRportName = "uftRunnerRoot"; private McConnectionInfo _mcConnection; private string _mobileInfoForAllGuiTests; #endregion /// <summary> /// creates instance of the runner given a source. /// </summary> /// <param name="sources"></param> /// <param name="timeout"></param> /// <param name="backgroundWorker"></param> /// <param name="useUFTLicense"></param> public FileSystemTestsRunner(List<string> sources, TimeSpan timeout, int ControllerPollingInterval, TimeSpan perScenarioTimeOutMinutes, List<string> ignoreErrorStrings, Dictionary<string, string> jenkinsEnvVariables, McConnectionInfo mcConnection, string mobileInfo, bool useUFTLicense = false ) { _jenkinsEnvVariables = jenkinsEnvVariables; //search if we have any testing tools installed if (!Helper.IsTestingToolsInstalled(TestStorageType.FileSystem)) { ConsoleWriter.WriteErrLine(string.Format(Resources.FileSystemTestsRunner_No_HP_testing_tool_is_installed_on, System.Environment.MachineName)); Environment.Exit((int)Launcher.ExitCodeEnum.Failed); } _timeout = timeout; ConsoleWriter.WriteLine("FileSystemTestRunner timeout is " + _timeout ); _stopwatch = Stopwatch.StartNew(); _pollingInterval = ControllerPollingInterval; _perScenarioTimeOutMinutes = perScenarioTimeOutMinutes; _ignoreErrorStrings = ignoreErrorStrings; _useUFTLicense = useUFTLicense; _tests = new List<TestInfo>(); _mcConnection = mcConnection; _mobileInfoForAllGuiTests = mobileInfo; ConsoleWriter.WriteLine("Mc connection info is - " + _mcConnection.ToString()); //go over all sources, and create a list of all tests foreach (string source in sources) { List<TestInfo> testGroup = new List<TestInfo>(); try { //--handle directories which contain test subdirectories (recursively) if (Helper.IsDirectory(source)) { var testsLocations = Helper.GetTestsLocations(source); foreach (var loc in testsLocations) { var test = new TestInfo(loc, loc, source); testGroup.Add(test); } } //--handle mtb files (which contain links to tests) else //file might be LoadRunner scenario or //mtb file (which contain links to tests) //other files are dropped { testGroup = new List<TestInfo>(); FileInfo fi = new FileInfo(source); if (fi.Extension == Helper.LoadRunnerFileExtention) testGroup.Add(new TestInfo(source, source, source)); else if (fi.Extension == ".mtb") //if (source.TrimEnd().EndsWith(".mtb", StringComparison.CurrentCultureIgnoreCase)) { MtbManager manager = new MtbManager(); var paths = manager.Parse(source); foreach (var p in paths) { testGroup.Add(new TestInfo(p, p, source)); } } else if (fi.Extension == ".mtbx") //if (source.TrimEnd().EndsWith(".mtb", StringComparison.CurrentCultureIgnoreCase)) { testGroup = MtbxManager.Parse(source, _jenkinsEnvVariables, source); } } } catch (Exception) { testGroup = new List<TestInfo>(); } //--handle single test dir, add it with no group if (testGroup.Count == 1) { testGroup[0].TestGroup = "<None>"; } _tests.AddRange(testGroup); } if (_tests == null || _tests.Count == 0) { ConsoleWriter.WriteLine(Resources.FsRunnerNoValidTests); Environment.Exit((int)Launcher.ExitCodeEnum.Failed); } ConsoleWriter.WriteLine(string.Format(Resources.FsRunnerTestsFound, _tests.Count)); _tests.ForEach(t => ConsoleWriter.WriteLine("" + t.TestName)); ConsoleWriter.WriteLine(Resources.GeneralDoubleSeperator); } /// <summary> /// runs all tests given to this runner and returns a suite of run resutls /// </summary> /// <returns>The rest run results for each test</returns> public override TestSuiteRunResults Run() { //create a new Run Results object TestSuiteRunResults activeRunDesc = new TestSuiteRunResults(); double totalTime = 0; try { var start = DateTime.Now; foreach (var test in _tests) { if (RunCancelled()) break; var testStart = DateTime.Now; string errorReason = string.Empty; TestRunResults runResult = null; try { runResult = RunHPToolsTest(test, ref errorReason); } catch (Exception ex) { runResult = new TestRunResults(); runResult.TestState = TestState.Error; runResult.ErrorDesc = ex.Message; runResult.TestName = test.TestName; } //get the original source for this test, for grouping tests under test classes runResult.TestGroup = test.TestGroup; activeRunDesc.TestRuns.Add(runResult); //if fail was terminated before this step, continue if (runResult.TestState != TestState.Failed) { if (runResult.TestState != TestState.Error) { Helper.GetTestStateFromReport(runResult); } else { if (string.IsNullOrEmpty(runResult.ErrorDesc)) { if (RunCancelled()) { runResult.ErrorDesc = HpToolsLauncher.Properties.Resources.ExceptionUserCancelled; } else { runResult.ErrorDesc = HpToolsLauncher.Properties.Resources.ExceptionExternalProcess; } } runResult.ReportLocation = null; runResult.TestState = TestState.Error; } } if (runResult.TestState == TestState.Passed && runResult.HasWarnings) { runResult.TestState = TestState.Warning; ConsoleWriter.WriteLine(Resources.FsRunnerTestDoneWarnings); } else { ConsoleWriter.WriteLine(string.Format(Resources.FsRunnerTestDone, runResult.TestState)); } ConsoleWriter.WriteLine(DateTime.Now.ToString(Launcher.DateFormat) + " Test complete: " + runResult.TestPath + "\n-------------------------------------------------------------------------------------------------------"); UpdateCounters(runResult.TestState); var testTotalTime = (DateTime.Now - testStart).TotalSeconds; } totalTime = (DateTime.Now - start).TotalSeconds; } finally { activeRunDesc.NumTests = _tests.Count; activeRunDesc.NumErrors = _errors; activeRunDesc.TotalRunTime = TimeSpan.FromSeconds(totalTime); activeRunDesc.NumFailures = _fail; foreach (IFileSysTestRunner cleanupRunner in _colRunnersForCleanup.Values) { cleanupRunner.CleanUp(); } } return activeRunDesc; } /// <summary> /// checks if timeout has expired /// </summary> /// <returns></returns> private bool CheckTimeout() { TimeSpan timeleft = _timeout - _stopwatch.Elapsed; return (timeleft > TimeSpan.Zero); } /// <summary> /// creates a correct type of runner and runs a single test. /// </summary> /// <param name="testPath"></param> /// <param name="errorReason"></param> /// <returns></returns> private TestRunResults RunHPToolsTest(TestInfo testinf, ref string errorReason) { var testPath = testinf.TestPath; var type = Helper.GetTestType(testPath); IFileSysTestRunner runner = null; switch (type) { case TestType.ST: runner = new ApiTestRunner(this, _timeout - _stopwatch.Elapsed); break; case TestType.QTP: runner = new GuiTestRunner(this, _useUFTLicense, _timeout - _stopwatch.Elapsed, _mcConnection, _mobileInfoForAllGuiTests); break; case TestType.LoadRunner: AppDomain.CurrentDomain.AssemblyResolve += Helper.HPToolsAssemblyResolver; runner = new PerformanceTestRunner(this, _timeout, _pollingInterval, _perScenarioTimeOutMinutes, _ignoreErrorStrings); break; } if (runner != null) { if (!_colRunnersForCleanup.ContainsKey(type)) _colRunnersForCleanup.Add(type, runner); Stopwatch s = Stopwatch.StartNew(); var results = runner.RunTest(testinf, ref errorReason, RunCancelled); results.Runtime = s.Elapsed; if (type == TestType.LoadRunner) AppDomain.CurrentDomain.AssemblyResolve -= Helper.HPToolsAssemblyResolver; return results; } //check for abortion if (System.IO.File.Exists(_abortFilename)) { ConsoleWriter.WriteLine(Resources.GeneralStopAborted); //stop working Environment.Exit((int)Launcher.ExitCodeEnum.Aborted); } return new TestRunResults { ErrorDesc = "Unknown TestType", TestState = TestState.Error }; } /// <summary> /// checks if run was cancelled/aborted /// </summary> /// <returns></returns> public bool RunCancelled() { //if timeout has passed if (_stopwatch.Elapsed > _timeout && !_blnRunCancelled) { ConsoleWriter.WriteLine(Resources.GeneralTimedOut); Launcher.ExitCode = Launcher.ExitCodeEnum.Aborted; _blnRunCancelled = true; } return _blnRunCancelled; } /// <summary> /// sums errors and failed tests /// </summary> /// <param name="testState"></param> private void UpdateCounters(TestState testState) { switch (testState) { case TestState.Error: _errors += 1; break; case TestState.Failed: _fail += 1; break; } } /// <summary> /// Opens the report viewer for the given report directory /// </summary> /// <param name="reportDirectory"></param> public static void OpenReport(string reportDirectory) { Helper.OpenReport(reportDirectory, ref _uftViewerPath); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// UserBindingResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Chat.V2.Service.User { public class UserBindingResource : Resource { public sealed class BindingTypeEnum : StringEnum { private BindingTypeEnum(string value) : base(value) {} public BindingTypeEnum() {} public static implicit operator BindingTypeEnum(string value) { return new BindingTypeEnum(value); } public static readonly BindingTypeEnum Gcm = new BindingTypeEnum("gcm"); public static readonly BindingTypeEnum Apn = new BindingTypeEnum("apn"); public static readonly BindingTypeEnum Fcm = new BindingTypeEnum("fcm"); } private static Request BuildReadRequest(ReadUserBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Bindings", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static ResourceSet<UserBindingResource> Read(ReadUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<UserBindingResource>.FromJson("bindings", response.Content); return new ResourceSet<UserBindingResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<ResourceSet<UserBindingResource>> ReadAsync(ReadUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<UserBindingResource>.FromJson("bindings", response.Content); return new ResourceSet<UserBindingResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resource from </param> /// <param name="pathUserSid"> The SID of the User with the User Bindings to read </param> /// <param name="bindingType"> The push technology used by the User Binding resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static ResourceSet<UserBindingResource> Read(string pathServiceSid, string pathUserSid, List<UserBindingResource.BindingTypeEnum> bindingType = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadUserBindingOptions(pathServiceSid, pathUserSid){BindingType = bindingType, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resource from </param> /// <param name="pathUserSid"> The SID of the User with the User Bindings to read </param> /// <param name="bindingType"> The push technology used by the User Binding resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<ResourceSet<UserBindingResource>> ReadAsync(string pathServiceSid, string pathUserSid, List<UserBindingResource.BindingTypeEnum> bindingType = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadUserBindingOptions(pathServiceSid, pathUserSid){BindingType = bindingType, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<UserBindingResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<UserBindingResource>.FromJson("bindings", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<UserBindingResource> NextPage(Page<UserBindingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Chat) ); var response = client.Request(request); return Page<UserBindingResource>.FromJson("bindings", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<UserBindingResource> PreviousPage(Page<UserBindingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Chat) ); var response = client.Request(request); return Page<UserBindingResource>.FromJson("bindings", response.Content); } private static Request BuildFetchRequest(FetchUserBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Bindings/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static UserBindingResource Fetch(FetchUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<UserBindingResource> FetchAsync(FetchUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathUserSid"> The SID of the User with the binding </param> /// <param name="pathSid"> The SID of the User Binding resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static UserBindingResource Fetch(string pathServiceSid, string pathUserSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchUserBindingOptions(pathServiceSid, pathUserSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param> /// <param name="pathUserSid"> The SID of the User with the binding </param> /// <param name="pathSid"> The SID of the User Binding resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<UserBindingResource> FetchAsync(string pathServiceSid, string pathUserSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchUserBindingOptions(pathServiceSid, pathUserSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteUserBindingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Chat, "/v2/Services/" + options.PathServiceSid + "/Users/" + options.PathUserSid + "/Bindings/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static bool Delete(DeleteUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete UserBinding parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteUserBindingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathUserSid"> The SID of the User of the User Bindings to delete </param> /// <param name="pathSid"> The SID of the User Binding resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UserBinding </returns> public static bool Delete(string pathServiceSid, string pathUserSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteUserBindingOptions(pathServiceSid, pathUserSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathUserSid"> The SID of the User of the User Bindings to delete </param> /// <param name="pathSid"> The SID of the User Binding resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UserBinding </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathUserSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteUserBindingOptions(pathServiceSid, pathUserSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a UserBindingResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> UserBindingResource object represented by the provided JSON </returns> public static UserBindingResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<UserBindingResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Service that the resource is associated with /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The unique endpoint identifier for the User Binding /// </summary> [JsonProperty("endpoint")] public string Endpoint { get; private set; } /// <summary> /// The string that identifies the resource's User /// </summary> [JsonProperty("identity")] public string Identity { get; private set; } /// <summary> /// The SID of the User with the binding /// </summary> [JsonProperty("user_sid")] public string UserSid { get; private set; } /// <summary> /// The SID of the Credential for the binding /// </summary> [JsonProperty("credential_sid")] public string CredentialSid { get; private set; } /// <summary> /// The push technology to use for the binding /// </summary> [JsonProperty("binding_type")] [JsonConverter(typeof(StringEnumConverter))] public UserBindingResource.BindingTypeEnum BindingType { get; private set; } /// <summary> /// The Programmable Chat message types the binding is subscribed to /// </summary> [JsonProperty("message_types")] public List<string> MessageTypes { get; private set; } /// <summary> /// The absolute URL of the User Binding resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private UserBindingResource() { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdigEngine.Extensions { using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using Markdig.Syntax; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Plugins; public class MarkdownValidatorBuilder { private readonly List<RuleWithId<MarkdownValidationRule>> _validators = new List<RuleWithId<MarkdownValidationRule>>(); private readonly List<RuleWithId<MarkdownTagValidationRule>> _tagValidators = new List<RuleWithId<MarkdownTagValidationRule>>(); private readonly Dictionary<string, MarkdownValidationRule> _globalValidators = new Dictionary<string, MarkdownValidationRule>(); private readonly List<MarkdownValidationSetting> _settings = new List<MarkdownValidationSetting>(); private List<IMarkdownObjectValidatorProvider> _validatorProviders = new List<IMarkdownObjectValidatorProvider>(); public const string DefaultValidatorName = "default"; public const string MarkdownValidatePhaseName = "Markdown style"; public ICompositionContainer Container { get; } public MarkdownValidatorBuilder(ICompositionContainer container) { Container = container; } public static MarkdownValidatorBuilder Create( MarkdownServiceParameters parameters, ICompositionContainer container) { var builder = new MarkdownValidatorBuilder(container); if (parameters != null) { LoadValidatorConfig(parameters.BasePath, parameters.TemplateDir, builder); } if (container != null) { builder.LoadEnabledRulesProvider(); } return builder; } public IMarkdownObjectRewriter CreateRewriter() { var tagValidator = new TagValidator(GetEnabledTagRules().ToImmutableList()); var validators = from vp in _validatorProviders from p in vp.GetValidators() select p; return new MarkdownTokenRewriteWithScope( MarkdownObjectRewriterFactory.FromValidators( validators.Concat( new[] { MarkdownObjectValidatorFactory.FromLambda<IMarkdownObject>(tagValidator.Validate) })), MarkdownValidatePhaseName); } public void AddValidators(MarkdownValidationRule[] rules) { if (rules == null) { return; } foreach (var rule in rules) { if (string.IsNullOrEmpty(rule.ContractName)) { continue; } _globalValidators[rule.ContractName] = rule; } } public void AddValidators(string category, Dictionary<string, MarkdownValidationRule> validators) { if (validators == null) { return; } foreach (var pair in validators) { if (string.IsNullOrEmpty(pair.Value.ContractName)) { continue; } _validators.Add(new RuleWithId<MarkdownValidationRule> { Category = category, Id = pair.Key, Rule = pair.Value, }); } } public void AddTagValidators(MarkdownTagValidationRule[] validators) { if (validators == null) { return; } foreach (var item in validators) { _tagValidators.Add(new RuleWithId<MarkdownTagValidationRule> { Category = null, Id = null, Rule = item }); } } public void AddTagValidators(string category, Dictionary<string, MarkdownTagValidationRule> validators) { if (validators == null) { return; } foreach (var pair in validators) { _tagValidators.Add(new RuleWithId<MarkdownTagValidationRule> { Category = category, Id = pair.Key, Rule = pair.Value, }); } } public void AddSettings(MarkdownValidationSetting[] settings) { if (settings == null) { return; } foreach (var setting in settings) { _settings.Add(setting); } } public void EnsureDefaultValidator() { if (!_globalValidators.ContainsKey(DefaultValidatorName)) { _globalValidators[DefaultValidatorName] = new MarkdownValidationRule { ContractName = DefaultValidatorName }; } } private static void LoadValidatorConfig(string baseDir, string templateDir, MarkdownValidatorBuilder builder) { if (string.IsNullOrEmpty(baseDir)) { return; } if (templateDir != null) { var configFolder = Path.Combine(templateDir, MarkdownSytleDefinition.MarkdownStyleDefinitionFolderName); if (Directory.Exists(configFolder)) { LoadValidatorDefinition(configFolder, builder); } } var configFile = Path.Combine(baseDir, MarkdownSytleConfig.MarkdownStyleFileName); if (EnvironmentContext.FileAbstractLayer.Exists(configFile)) { var config = JsonUtility.Deserialize<MarkdownSytleConfig>(configFile); builder.AddValidators(config.Rules); builder.AddTagValidators(config.TagRules); builder.AddSettings(config.Settings); } builder.EnsureDefaultValidator(); } private static void LoadValidatorDefinition(string mdStyleDefPath, MarkdownValidatorBuilder builder) { if (Directory.Exists(mdStyleDefPath)) { foreach (var configFile in Directory.GetFiles(mdStyleDefPath, "*" + MarkdownSytleDefinition.MarkdownStyleDefinitionFilePostfix)) { var fileName = Path.GetFileName(configFile); var category = fileName.Remove(fileName.Length - MarkdownSytleDefinition.MarkdownStyleDefinitionFilePostfix.Length); var config = JsonUtility.Deserialize<MarkdownSytleDefinition>(configFile); builder.AddTagValidators(category, config.TagRules); builder.AddValidators(category, config.Rules); } } } public void LoadEnabledRulesProvider() { HashSet<string> enabledContractName = new HashSet<string>(); foreach (var item in _validators) { if (IsDisabledBySetting(item) ?? item.Rule.Disable) { enabledContractName.Remove(item.Rule.ContractName); } else { enabledContractName.Add(item.Rule.ContractName); } } foreach (var pair in _globalValidators) { if (pair.Value.Disable) { enabledContractName.Remove(pair.Value.ContractName); } else { enabledContractName.Add(pair.Value.ContractName); } } _validatorProviders = (from name in enabledContractName from vp in Container?.GetExports<IMarkdownObjectValidatorProvider>(name) select vp).ToList(); } private IEnumerable<MarkdownTagValidationRule> GetEnabledTagRules() { foreach (var item in _tagValidators) { if (IsDisabledBySetting(item) ?? item.Rule.Disable) { continue; } yield return item.Rule; } } private bool? IsDisabledBySetting<T>(RuleWithId<T> item) { bool? categoryDisable = null; bool? idDisable = null; if (item.Category != null) { foreach (var setting in _settings) { if (setting.Category == item.Category) { if (setting.Id == null) { categoryDisable = setting.Disable; } else if (setting.Id == item.Id) { idDisable = setting.Disable; } } } } return idDisable ?? categoryDisable; } #region Nested Classes private sealed class RuleWithId<T> { public T Rule { get; set; } public string Category { get; set; } public string Id { get; set; } } #endregion } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security; using System.Text; using System.Threading; using System.Web; using System.Web.Caching; using ASC.Common.Caching; using ASC.Core; using ASC.Core.Users; using ASC.Files.Core; using ASC.Web.Core.Files; using ASC.Web.Files.Api; using ASC.Web.Files.Classes; using ASC.Web.Files.Core; using ASC.Web.Files.Helpers; using ASC.Web.Files.Resources; using ASC.Web.Files.Services.DocumentService; using ASC.Web.Files.ThirdPartyApp; using ASC.Web.Studio.Core; using Newtonsoft.Json.Linq; using File = ASC.Files.Core.File; using FileShare = ASC.Files.Core.Security.FileShare; using SecurityContext = ASC.Core.SecurityContext; namespace ASC.Web.Files.Utils { public class EntryManager { private const string UPDATE_LIST = "filesUpdateList"; private static readonly ICache cache = AscCache.Default; public static IEnumerable<FileEntry> GetEntries(IFolderDao folderDao, IFileDao fileDao, Folder parent, int from, int count, FilterType filter, bool subjectGroup, Guid subjectId, String searchText, bool searchInContent, bool withSubfolders, OrderBy orderBy, out int total) { total = 0; if (parent == null) throw new ArgumentNullException("parent", FilesCommonResource.ErrorMassage_FolderNotFound); if (parent.ProviderEntry && !FilesSettings.EnableThirdParty) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFolder); if (parent.RootFolderType == FolderType.Privacy && (!PrivacyRoomSettings.Available || !PrivacyRoomSettings.Enabled)) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFolder); var fileSecurity = Global.GetFilesSecurity(); var entries = Enumerable.Empty<FileEntry>(); searchInContent = searchInContent && filter != FilterType.ByExtension && !Equals(parent.ID, Global.FolderTrash); if (parent.FolderType == FolderType.Projects && parent.ID.Equals(Global.FolderProjects)) { var apiServer = new ASC.Api.ApiServer(); var apiUrl = string.Format("{0}project/maxlastmodified.json", SetupInfo.WebApiBaseUrl); var responseBody = apiServer.GetApiResponse(apiUrl, "GET"); if (responseBody != null) { var responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(responseBody))); var projectLastModified = responseApi["response"].Value<String>(); const string projectLastModifiedCacheKey = "documents/projectFolders/projectLastModified"; if (HttpRuntime.Cache.Get(projectLastModifiedCacheKey) == null || !HttpRuntime.Cache.Get(projectLastModifiedCacheKey).Equals(projectLastModified)) { HttpRuntime.Cache.Remove(projectLastModifiedCacheKey); HttpRuntime.Cache.Insert(projectLastModifiedCacheKey, projectLastModified); } var projectListCacheKey = string.Format("documents/projectFolders/{0}", SecurityContext.CurrentAccount.ID); var folderIDProjectTitle = (Dictionary<object, KeyValuePair<int, string>>)HttpRuntime.Cache.Get(projectListCacheKey); if (folderIDProjectTitle == null) { apiUrl = string.Format("{0}project/filter.json?sortBy=title&sortOrder=ascending&status=open&fields=id,title,security,projectFolder", SetupInfo.WebApiBaseUrl); responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET")))); var responseData = responseApi["response"]; if (!(responseData is JArray)) return entries.ToList(); folderIDProjectTitle = new Dictionary<object, KeyValuePair<int, string>>(); foreach (JObject projectInfo in responseData.Children()) { var projectID = projectInfo["id"].Value<int>(); var projectTitle = Global.ReplaceInvalidCharsAndTruncate(projectInfo["title"].Value<String>()); JToken projectSecurityJToken; if (projectInfo.TryGetValue("security", out projectSecurityJToken)) { var projectSecurity = projectInfo["security"].Value<JObject>(); JToken projectCanFileReadJToken; if (projectSecurity.TryGetValue("canReadFiles", out projectCanFileReadJToken)) { if (!projectSecurity["canReadFiles"].Value<bool>()) { continue; } } } int projectFolderID; JToken projectFolderIDjToken; if (projectInfo.TryGetValue("projectFolder", out projectFolderIDjToken)) projectFolderID = projectFolderIDjToken.Value<int>(); else projectFolderID = (int)FilesIntegration.RegisterBunch("projects", "project", projectID.ToString()); if (!folderIDProjectTitle.ContainsKey(projectFolderID)) folderIDProjectTitle.Add(projectFolderID, new KeyValuePair<int, string>(projectID, projectTitle)); AscCache.Default.Remove("documents/folders/" + projectFolderID); AscCache.Default.Insert("documents/folders/" + projectFolderID, projectTitle, TimeSpan.FromMinutes(30)); } HttpRuntime.Cache.Remove(projectListCacheKey); HttpRuntime.Cache.Insert(projectListCacheKey, folderIDProjectTitle, new CacheDependency(null, new[] { projectLastModifiedCacheKey }), Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(15)); } var rootKeys = folderIDProjectTitle.Keys.ToList(); if (filter == FilterType.None || filter == FilterType.FoldersOnly) { var folders = folderDao.GetFolders(rootKeys, filter, subjectGroup, subjectId, searchText, withSubfolders, false); var emptyFilter = string.IsNullOrEmpty(searchText) && filter == FilterType.None && subjectId == Guid.Empty; if (!emptyFilter) { var projectFolderIds = folderIDProjectTitle .Where(projectFolder => string.IsNullOrEmpty(searchText) || (projectFolder.Value.Value ?? "").ToLower().Trim().Contains(searchText.ToLower().Trim())) .Select(projectFolder => projectFolder.Key) .ToList(); folders.RemoveAll(folder => rootKeys.Contains(folder.ID)); var projectFolders = folderDao.GetFolders(projectFolderIds, filter, subjectGroup, subjectId, null, false, false); folders.AddRange(projectFolders); } folders.ForEach(x => { x.Title = folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID].Value : x.Title; x.FolderUrl = folderIDProjectTitle.ContainsKey(x.ID) ? PathProvider.GetFolderUrl(x, folderIDProjectTitle[x.ID].Key) : string.Empty; }); if (withSubfolders) { folders = fileSecurity.FilterRead(folders); } entries = entries.Concat(folders); } if (filter != FilterType.FoldersOnly && withSubfolders) { var files = fileDao.GetFiles(rootKeys, filter, subjectGroup, subjectId, searchText, searchInContent); files = fileSecurity.FilterRead(files); entries = entries.Concat(files); } } parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1)); parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalSubFolders + 1 : 0)); } else if (parent.FolderType == FolderType.SHARE) { //share var shared = (IEnumerable<FileEntry>)fileSecurity.GetSharesForMe(filter, subjectGroup, subjectId, searchText, searchInContent, withSubfolders); entries = entries.Concat(shared); parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1)); parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalSubFolders + 1 : 0)); } else if (parent.FolderType == FolderType.Recent) { var files = GetRecent(folderDao, fileDao, filter, subjectGroup, subjectId, searchText, searchInContent); entries = entries.Concat(files); parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1)); } else if (parent.FolderType == FolderType.Favorites) { List<Folder> folders; List<File> files; GetFavorites(folderDao, fileDao, filter, subjectGroup, subjectId, searchText, searchInContent, out folders, out files); entries = entries.Concat(folders); entries = entries.Concat(files); parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1)); parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalSubFolders + 1 : 0)); } else if (parent.FolderType == FolderType.Templates) { var files = GetTemplates(folderDao, fileDao, filter, subjectGroup, subjectId, searchText, searchInContent); entries = entries.Concat(files); parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1)); parent.TotalSubFolders = 0; } else if (parent.FolderType == FolderType.Privacy) { var folders = folderDao.GetFolders(parent.ID, orderBy, filter, subjectGroup, subjectId, searchText, withSubfolders); folders = fileSecurity.FilterRead(folders); entries = entries.Concat(folders); var files = fileDao.GetFiles(parent.ID, orderBy, filter, subjectGroup, subjectId, searchText, searchInContent, withSubfolders); files = fileSecurity.FilterRead(files); entries = entries.Concat(files); //share var shared = (IEnumerable<FileEntry>)fileSecurity.GetPrivacyForMe(filter, subjectGroup, subjectId, searchText, searchInContent, withSubfolders); entries = entries.Concat(shared); parent.TotalFiles = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1)); parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalSubFolders + 1 : 0)); } else { if (parent.FolderType == FolderType.TRASH) withSubfolders = false; var folders = folderDao.GetFolders(parent.ID, orderBy, filter, subjectGroup, subjectId, searchText, withSubfolders); folders = fileSecurity.FilterRead(folders); entries = entries.Concat(folders); var files = fileDao.GetFiles(parent.ID, orderBy, filter, subjectGroup, subjectId, searchText, searchInContent, withSubfolders); files = fileSecurity.FilterRead(files); entries = entries.Concat(files); if (filter == FilterType.None || filter == FilterType.FoldersOnly) { var folderList = GetThirpartyFolders(parent, searchText); var thirdPartyFolder = FilterEntries(folderList, filter, subjectGroup, subjectId, searchText, searchInContent); entries = entries.Concat(thirdPartyFolder); } } if (orderBy.SortedBy != SortedByType.New) { if (parent.FolderType != FolderType.Recent) { entries = SortEntries(entries, orderBy); } total = entries.Count(); if (0 < from) entries = entries.Skip(from); if (0 < count) entries = entries.Take(count); } entries = FileMarker.SetTagsNew(folderDao, parent, entries); //sorting after marking if (orderBy.SortedBy == SortedByType.New) { entries = SortEntries(entries, orderBy); total = entries.Count(); if (0 < from) entries = entries.Skip(from); if (0 < count) entries = entries.Take(count); } SetFileStatus(entries.Where(r => r != null && r.ID != null && r.FileEntryType == FileEntryType.File).Select(r => r as File).ToList()); return entries; } public static IEnumerable<File> GetTemplates(IFolderDao folderDao, IFileDao fileDao, FilterType filter, bool subjectGroup, Guid subjectId, String searchText, bool searchInContent) { using (var tagDao = Global.DaoFactory.GetTagDao()) { var tags = tagDao.GetTags(SecurityContext.CurrentAccount.ID, TagType.Template); var fileIds = tags.Where(tag => tag.EntryType == FileEntryType.File).Select(tag => tag.EntryId).ToList(); var files = fileDao.GetFilesFiltered(fileIds, filter, subjectGroup, subjectId, searchText, searchInContent); files = files.Where(file => file.RootFolderType != FolderType.TRASH).ToList(); files = Global.GetFilesSecurity().FilterRead(files); CheckFolderId(folderDao, files); return files; } } public static IEnumerable<Folder> GetThirpartyFolders(Folder parent, string searchText = null) { var folderList = new List<Folder>(); if ((parent.ID.Equals(Global.FolderMy) || parent.ID.Equals(Global.FolderCommon)) && ThirdpartyConfiguration.SupportInclusion && (FilesSettings.EnableThirdParty || CoreContext.Configuration.Personal)) { using (var providerDao = Global.DaoFactory.GetProviderDao()) { if (providerDao == null) return folderList; var fileSecurity = Global.GetFilesSecurity(); var providers = providerDao.GetProvidersInfo(parent.RootFolderType, searchText); folderList = providers .Select(providerInfo => GetFakeThirdpartyFolder(providerInfo, parent.ID)) .Where(fileSecurity.CanRead).ToList(); } if (folderList.Any()) using (var securityDao = Global.DaoFactory.GetSecurityDao()) { securityDao.GetPureShareRecords(folderList) //.Where(x => x.Owner == SecurityContext.CurrentAccount.ID) .Select(x => x.EntryId).Distinct().ToList() .ForEach(id => { folderList.First(y => y.ID.Equals(id)).Shared = true; }); } } return folderList; } public static IEnumerable<File> GetRecent(IFolderDao folderDao, IFileDao fileDao, FilterType filter, bool subjectGroup, Guid subjectId, String searchText, bool searchInContent) { using (var tagDao = Global.DaoFactory.GetTagDao()) { var tags = tagDao.GetTags(SecurityContext.CurrentAccount.ID, TagType.Recent).ToList(); var fileIds = tags.Where(tag => tag.EntryType == FileEntryType.File).Select(tag => tag.EntryId).ToList(); var files = fileDao.GetFilesFiltered(fileIds, filter, subjectGroup, subjectId, searchText, searchInContent); files = files.Where(file => file.RootFolderType != FolderType.TRASH).ToList(); files = Global.GetFilesSecurity().FilterRead(files); CheckFolderId(folderDao, files); var listFileIds = fileIds.ToList(); files = files.OrderBy(file => listFileIds.IndexOf(file.ID)).ToList(); return files; } } public static void GetFavorites(IFolderDao folderDao, IFileDao fileDao, FilterType filter, bool subjectGroup, Guid subjectId, String searchText, bool searchInContent, out List<Folder> folders, out List<File> files) { folders = new List<Folder>(); files = new List<File>(); var fileSecurity = Global.GetFilesSecurity(); using (var tagDao = Global.DaoFactory.GetTagDao()) { var tags = tagDao.GetTags(SecurityContext.CurrentAccount.ID, TagType.Favorite); if (filter == FilterType.None || filter == FilterType.FoldersOnly) { var folderIds = tags.Where(tag => tag.EntryType == FileEntryType.Folder).Select(tag => tag.EntryId).ToList(); folders = folderDao.GetFolders(folderIds, filter, subjectGroup, subjectId, searchText, false, false); folders = folders.Where(folder => folder.RootFolderType != FolderType.TRASH).ToList(); folders = fileSecurity.FilterRead(folders); CheckFolderId(folderDao, folders); } if (filter != FilterType.FoldersOnly) { var fileIds = tags.Where(tag => tag.EntryType == FileEntryType.File).Select(tag => tag.EntryId).ToList(); files = fileDao.GetFilesFiltered(fileIds, filter, subjectGroup, subjectId, searchText, searchInContent); files = files.Where(file => file.RootFolderType != FolderType.TRASH).ToList(); files = fileSecurity.FilterRead(files); CheckFolderId(folderDao, files); } } } public static IEnumerable<FileEntry> FilterEntries(IEnumerable<FileEntry> entries, FilterType filter, bool subjectGroup, Guid subjectId, String searchText, bool searchInContent) { if (entries == null || !entries.Any()) return entries; if (subjectId != Guid.Empty) { entries = entries.Where(f => subjectGroup ? CoreContext.UserManager.GetUsersByGroup(subjectId).Any(s => s.ID == f.CreateBy) : f.CreateBy == subjectId ) .ToList(); } Func<FileEntry, bool> where = null; switch (filter) { case FilterType.SpreadsheetsOnly: case FilterType.PresentationsOnly: case FilterType.ImagesOnly: case FilterType.DocumentsOnly: case FilterType.ArchiveOnly: case FilterType.FilesOnly: case FilterType.MediaOnly: where = f => f.FileEntryType == FileEntryType.File && (((File)f).FilterType == filter || filter == FilterType.FilesOnly); break; case FilterType.FoldersOnly: where = f => f.FileEntryType == FileEntryType.Folder; break; case FilterType.ByExtension: var filterExt = (searchText ?? string.Empty).ToLower().Trim(); where = f => !string.IsNullOrEmpty(filterExt) && f.FileEntryType == FileEntryType.File && FileUtility.GetFileExtension(f.Title).Equals(filterExt); break; } if (where != null) { entries = entries.Where(where).ToList(); } if ((!searchInContent || filter == FilterType.ByExtension) && !string.IsNullOrEmpty(searchText = (searchText ?? string.Empty).ToLower().Trim())) { entries = entries.Where(f => f.Title.ToLower().Contains(searchText)).ToList(); } return entries; } public static IEnumerable<FileEntry> SortEntries(IEnumerable<FileEntry> entries, OrderBy orderBy) { if (entries == null || !entries.Any()) return entries; Comparison<FileEntry> sorter; if (orderBy == null) { orderBy = FilesSettings.DefaultOrder; } var c = orderBy.IsAsc ? 1 : -1; switch (orderBy.SortedBy) { case SortedByType.Type: sorter = (x, y) => { var cmp = 0; if (x.FileEntryType == FileEntryType.File && y.FileEntryType == FileEntryType.File) cmp = c * (FileUtility.GetFileExtension((x.Title)).CompareTo(FileUtility.GetFileExtension(y.Title))); return cmp == 0 ? x.Title.EnumerableComparer(y.Title) : cmp; }; break; case SortedByType.Author: sorter = (x, y) => { var cmp = c * string.Compare(x.CreateByString, y.CreateByString); return cmp == 0 ? x.Title.EnumerableComparer(y.Title) : cmp; }; break; case SortedByType.Size: sorter = (x, y) => { var cmp = 0; if (x.FileEntryType == FileEntryType.File && y.FileEntryType == FileEntryType.File) cmp = c * ((File)x).ContentLength.CompareTo(((File)y).ContentLength); return cmp == 0 ? x.Title.EnumerableComparer(y.Title) : cmp; }; break; case SortedByType.AZ: sorter = (x, y) => c * x.Title.EnumerableComparer(y.Title); break; case SortedByType.DateAndTime: sorter = (x, y) => { var cmp = c * DateTime.Compare(x.ModifiedOn, y.ModifiedOn); return cmp == 0 ? x.Title.EnumerableComparer(y.Title) : cmp; }; break; case SortedByType.DateAndTimeCreation: sorter = (x, y) => { var cmp = c * DateTime.Compare(x.CreateOn, y.CreateOn); return cmp == 0 ? x.Title.EnumerableComparer(y.Title) : cmp; }; break; case SortedByType.New: sorter = (x, y) => { var isNewSortResult = x.IsNew.CompareTo(y.IsNew); return c * (isNewSortResult == 0 ? DateTime.Compare(x.ModifiedOn, y.ModifiedOn) : isNewSortResult); }; break; default: sorter = (x, y) => c * x.Title.EnumerableComparer(y.Title); break; } if (orderBy.SortedBy != SortedByType.New) { // folders on top var folders = entries.Where(r => r.FileEntryType == FileEntryType.Folder).ToList(); var files = entries.Where(r => r.FileEntryType == FileEntryType.File).ToList(); folders.Sort(sorter); files.Sort(sorter); return folders.Concat(files); } var result = entries.ToList(); result.Sort(sorter); return result; } public static Folder GetFakeThirdpartyFolder(IProviderInfo providerInfo, object parentFolderId = null) { //Fake folder. Don't send request to third party return new Folder { ParentFolderID = parentFolderId, ID = providerInfo.RootFolderId, CreateBy = providerInfo.Owner, CreateOn = providerInfo.CreateOn, FolderType = FolderType.DEFAULT, ModifiedBy = providerInfo.Owner, ModifiedOn = providerInfo.CreateOn, ProviderId = providerInfo.ID, ProviderKey = providerInfo.ProviderKey, RootFolderCreator = providerInfo.Owner, RootFolderId = providerInfo.RootFolderId, RootFolderType = providerInfo.RootFolderType, Shareable = false, Title = providerInfo.CustomerTitle, TotalFiles = 0, TotalSubFolders = 0 }; } public static List<Folder> GetBreadCrumbs(object folderId) { using (var folderDao = Global.DaoFactory.GetFolderDao()) { return GetBreadCrumbs(folderId, folderDao); } } public static List<Folder> GetBreadCrumbs(object folderId, IFolderDao folderDao) { if (folderId == null) return new List<Folder>(); var breadCrumbs = Global.GetFilesSecurity().FilterRead(folderDao.GetParentFolders(folderId)); var firstVisible = breadCrumbs.ElementAtOrDefault(0); object rootId = null; if (firstVisible == null) { rootId = Global.FolderShare; } else { switch (firstVisible.FolderType) { case FolderType.DEFAULT: if (!firstVisible.ProviderEntry) { rootId = Global.FolderShare; } else { switch (firstVisible.RootFolderType) { case FolderType.USER: rootId = SecurityContext.CurrentAccount.ID == firstVisible.RootFolderCreator ? Global.FolderMy : Global.FolderShare; break; case FolderType.COMMON: rootId = Global.FolderCommon; break; } } break; case FolderType.BUNCH: rootId = Global.FolderProjects; break; } } if (rootId != null) { breadCrumbs.Insert(0, folderDao.GetFolder(rootId)); } return breadCrumbs; } public static void CheckFolderId(IFolderDao folderDao, IEnumerable<FileEntry> entries) { var fileSecurity = Global.GetFilesSecurity(); foreach (var entry in entries) { if (entry.RootFolderType == FolderType.USER && entry.RootFolderCreator != SecurityContext.CurrentAccount.ID) { var folderId = entry is File ? ((File)entry).FolderID : ((Folder)entry).ParentFolderID; var folder = folderDao.GetFolder(folderId); if (!fileSecurity.CanRead(folder)) { entry.FolderIdDisplay = Global.FolderShare; } } } } public static void SetFileStatus(File file) { if (file == null || file.ID == null) return; SetFileStatus(new List<File>(1) { file }); } public static void SetFileStatus(IEnumerable<File> files) { using (var tagDao = Global.DaoFactory.GetTagDao()) { var tagsFavorite = tagDao.GetTags(SecurityContext.CurrentAccount.ID, TagType.Favorite, files); var tagsTemplate = tagDao.GetTags(SecurityContext.CurrentAccount.ID, TagType.Template, files); var tagsNew = tagDao.GetNewTags(SecurityContext.CurrentAccount.ID, files); var tagsLocked = tagDao.GetTags(TagType.Locked, files.ToArray()); foreach (var file in files) { if (tagsFavorite.Any(r => r.EntryId.Equals(file.ID))) { file.IsFavorite = true; } if (tagsTemplate.Any(r => r.EntryId.Equals(file.ID))) { file.IsTemplate = true; } if (tagsNew.Any(r => r.EntryId.Equals(file.ID))) { file.IsNew = true; } var tagLocked = tagsLocked.FirstOrDefault(t => t.EntryId.Equals(file.ID)); var lockedBy = tagLocked != null ? tagLocked.Owner : Guid.Empty; file.Locked = lockedBy != Guid.Empty; file.LockedBy = lockedBy != Guid.Empty && lockedBy != SecurityContext.CurrentAccount.ID ? Global.GetUserName(lockedBy) : null; } } } public static bool FileLockedForMe(object fileId, Guid userId = default(Guid)) { var app = ThirdPartySelector.GetAppByFileId(fileId.ToString()); if (app != null) { return false; } userId = userId == default(Guid) ? SecurityContext.CurrentAccount.ID : userId; using (var tagDao = Global.DaoFactory.GetTagDao()) { var lockedBy = FileLockedBy(fileId, tagDao); return lockedBy != Guid.Empty && lockedBy != userId; } } public static Guid FileLockedBy(object fileId, ITagDao tagDao) { var tagLock = tagDao.GetTags(fileId, FileEntryType.File, TagType.Locked).FirstOrDefault(); return tagLock != null ? tagLock.Owner : Guid.Empty; } public static File GetFillFormDraft(File sourceFile, out Folder folderIfNew) { folderIfNew = null; if (sourceFile == null) return null; File linkedFile = null; using (var linkDao = Global.GetLinkDao()) using (var fileDao = Global.DaoFactory.GetFileDao()) { var fileSecurity = Global.GetFilesSecurity(); var linkedId = linkDao.GetLinked(sourceFile.ID); if (linkedId != null) { linkedFile = fileDao.GetFile(linkedId); if (linkedFile == null || !fileSecurity.CanFillForms(linkedFile) || FileLockedForMe(linkedFile.ID) || linkedFile.RootFolderType == FolderType.TRASH) { linkDao.DeleteLink(sourceFile.ID); linkedFile = null; } } if (linkedFile == null) { var folderId = Global.FolderMy.ToString(); using (var folderDao = Global.DaoFactory.GetFolderDao()) { folderIfNew = folderDao.GetFolder(folderId); } if (folderIfNew == null) throw new Exception(FilesCommonResource.ErrorMassage_FolderNotFound); if (!fileSecurity.CanCreate(folderIfNew)) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create); linkedFile = new File { Title = sourceFile.Title, FolderID = folderIfNew.ID, FileStatus = sourceFile.FileStatus, ConvertedType = sourceFile.ConvertedType, Comment = FilesCommonResource.CommentCreateFillFormDraft, Encrypted = sourceFile.Encrypted, }; using (var stream = fileDao.GetFileStream(sourceFile)) { linkedFile.ContentLength = stream.CanSeek ? stream.Length : sourceFile.ContentLength; linkedFile = fileDao.SaveFile(linkedFile, stream); } FileMarker.MarkAsNew(linkedFile); linkDao.AddLink(sourceFile.ID, linkedFile.ID); } } return linkedFile; } public static bool CheckFillFormDraft(File linkedFile) { if (linkedFile == null) return false; using (var linkDao = Global.GetLinkDao()) using (var fileDao = Global.DaoFactory.GetFileDao()) { var sourceId = linkDao.GetSource(linkedFile.ID); var sourceFile = fileDao.GetFile(sourceId); var fileSecurity = Global.GetFilesSecurity(); if (sourceFile == null || !fileSecurity.CanFillForms(sourceFile) || sourceFile.Access != FileShare.FillForms) { linkDao.DeleteLink(sourceId); return false; } } return true; } public static File SaveEditing(String fileId, string fileExtension, string downloadUri, Stream stream, String doc, string comment = null, bool checkRight = true, bool encrypted = false, ForcesaveType? forcesave = null, bool keepLink = false) { var newExtension = string.IsNullOrEmpty(fileExtension) ? FileUtility.GetFileExtension(downloadUri) : fileExtension; var app = ThirdPartySelector.GetAppByFileId(fileId); if (app != null) { app.SaveFile(fileId, newExtension, downloadUri, stream); return null; } File file; using (var fileDao = Global.DaoFactory.GetFileDao()) { var editLink = FileShareLink.Check(doc, false, fileDao, out file); if (file == null) { file = fileDao.GetFile(fileId); } if (file == null) throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); var fileSecurity = Global.GetFilesSecurity(); if (checkRight && !editLink && (!fileSecurity.CanEdit(file) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile); if (checkRight && FileLockedForMe(file.ID)) throw new Exception(FilesCommonResource.ErrorMassage_LockedFile); if (checkRight && (!forcesave.HasValue || forcesave.Value == ForcesaveType.None) && FileTracker.IsEditing(file.ID)) throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile); if (file.RootFolderType == FolderType.TRASH) throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); var currentExt = file.ConvertedExtension; if (string.IsNullOrEmpty(newExtension)) newExtension = FileUtility.GetFileExtension(file.Title); var replaceVersion = false; if (file.Forcesave != ForcesaveType.None) { if (file.Forcesave == ForcesaveType.User && FilesSettings.StoreForcesave || encrypted) { file.Version++; } else { replaceVersion = true; } } else { if (file.Version != 1) { file.VersionGroup++; } else { var storeTemplate = Global.GetStoreTemplate(); var path = FileConstant.NewDocPath + Thread.CurrentThread.CurrentCulture + "/"; if (!storeTemplate.IsDirectory(path)) { path = FileConstant.NewDocPath + "en-US/"; } var fileExt = currentExt != FileUtility.MasterFormExtension ? FileUtility.GetInternalExtension(file.Title) : currentExt; path += "new" + fileExt; //todo: think about the criteria for saving after creation if (file.ContentLength != storeTemplate.GetFileSize("", path)) { file.VersionGroup++; } } file.Version++; } file.Forcesave = forcesave.HasValue ? forcesave.Value : ForcesaveType.None; if (string.IsNullOrEmpty(comment)) comment = FilesCommonResource.CommentEdit; file.Encrypted = encrypted; file.ConvertedType = FileUtility.GetFileExtension(file.Title) != newExtension ? newExtension : null; file.ThumbnailStatus = encrypted ? Thumbnail.NotRequired : Thumbnail.Waiting; if (file.ProviderEntry && !newExtension.Equals(currentExt)) { if (FileUtility.ExtsConvertible.Keys.Contains(newExtension) && FileUtility.ExtsConvertible[newExtension].Contains(currentExt)) { if (stream != null) { downloadUri = PathProvider.GetTempUrl(stream, newExtension); downloadUri = DocumentServiceConnector.ReplaceCommunityAdress(downloadUri); } var key = DocumentServiceConnector.GenerateRevisionId(downloadUri); DocumentServiceConnector.GetConvertedUri(downloadUri, newExtension, currentExt, key, null, null, null, false, out downloadUri); stream = null; } else { file.ID = null; file.Title = FileUtility.ReplaceFileExtension(file.Title, newExtension); } file.ConvertedType = null; } using (var tmpStream = new MemoryStream()) { if (stream != null) { stream.CopyTo(tmpStream); } else { // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } var req = (HttpWebRequest)WebRequest.Create(downloadUri); using (var editedFileStream = new ResponseStream(req.GetResponse())) { editedFileStream.CopyTo(tmpStream); } } tmpStream.Position = 0; file.ContentLength = tmpStream.Length; file.Comment = string.IsNullOrEmpty(comment) ? null : comment; if (replaceVersion) { file = fileDao.ReplaceFileVersion(file, tmpStream); } else { file = fileDao.SaveFile(file, tmpStream); } if (!keepLink || file.CreateBy != SecurityContext.CurrentAccount.ID || !file.IsFillFormDraft) { using (var linkDao = Global.GetLinkDao()) { linkDao.DeleteAllLink(file.ID); } } } } FileMarker.MarkAsNew(file); FileMarker.RemoveMarkAsNew(file); return file; } public static void TrackEditing(string fileId, Guid tabId, Guid userId, string doc, bool editingAlone = false) { bool checkRight; if (FileTracker.GetEditingBy(fileId).Contains(userId)) { checkRight = FileTracker.ProlongEditing(fileId, tabId, userId, editingAlone); if (!checkRight) return; } File file; bool editLink; using (var fileDao = Global.DaoFactory.GetFileDao()) { editLink = FileShareLink.Check(doc, false, fileDao, out file); if (file == null) file = fileDao.GetFile(fileId); } if (file == null) throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); var fileSecurity = Global.GetFilesSecurity(); if (!editLink && (!fileSecurity.CanEdit(file, userId) && !fileSecurity.CanCustomFilterEdit(file, userId) && !fileSecurity.CanReview(file, userId) && !fileSecurity.CanFillForms(file, userId) && !fileSecurity.CanComment(file, userId) || CoreContext.UserManager.GetUsers(userId).IsVisitor())) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile); } if (FileLockedForMe(file.ID, userId)) throw new Exception(FilesCommonResource.ErrorMassage_LockedFile); if (file.RootFolderType == FolderType.TRASH) throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); checkRight = FileTracker.ProlongEditing(fileId, tabId, userId, editingAlone); if (checkRight) { FileTracker.ChangeRight(fileId, userId, false); } } public static File UpdateToVersionFile(object fileId, int version, String doc = null, bool checkRight = true) { using (var fileDao = Global.DaoFactory.GetFileDao()) { if (version < 1) throw new ArgumentNullException("version"); File fromFile; var editLink = FileShareLink.Check(doc, false, fileDao, out fromFile); if (fromFile == null) fromFile = fileDao.GetFile(fileId); if (fromFile == null) throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); if (fromFile.Version != version) fromFile = fileDao.GetFile(fromFile.ID, Math.Min(fromFile.Version, version)); if (fromFile == null) throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); if (checkRight && !editLink && (!Global.GetFilesSecurity().CanEdit(fromFile) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile); if (FileLockedForMe(fromFile.ID)) throw new Exception(FilesCommonResource.ErrorMassage_LockedFile); if (checkRight && FileTracker.IsEditing(fromFile.ID)) throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile); if (fromFile.RootFolderType == FolderType.TRASH) throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); if (fromFile.ProviderEntry) throw new Exception(FilesCommonResource.ErrorMassage_BadRequest); if (fromFile.Encrypted) throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat); var exists = cache.Get<string>(UPDATE_LIST + fileId.ToString()) != null; if (exists) { throw new Exception(FilesCommonResource.ErrorMassage_UpdateEditingFile); } else { cache.Insert(UPDATE_LIST + fileId.ToString(), fileId.ToString(), TimeSpan.FromMinutes(2)); } try { var currFile = fileDao.GetFile(fileId); var newFile = new File { ID = fromFile.ID, Version = currFile.Version + 1, VersionGroup = currFile.VersionGroup, Title = FileUtility.ReplaceFileExtension(currFile.Title, FileUtility.GetFileExtension(fromFile.Title)), FileStatus = currFile.FileStatus, FolderID = currFile.FolderID, CreateBy = currFile.CreateBy, CreateOn = currFile.CreateOn, ModifiedBy = fromFile.ModifiedBy, ModifiedOn = fromFile.ModifiedOn, ConvertedType = fromFile.ConvertedType, Comment = string.Format(FilesCommonResource.CommentRevert, fromFile.ModifiedOnString), Encrypted = fromFile.Encrypted }; using (var stream = fileDao.GetFileStream(fromFile)) { newFile.ContentLength = stream.CanSeek ? stream.Length : fromFile.ContentLength; newFile = fileDao.SaveFile(newFile, stream); } if (fromFile.ThumbnailStatus == Thumbnail.Created) { using (var thumb = fileDao.GetThumbnail(fromFile)) { fileDao.SaveThumbnail(newFile, thumb); } newFile.ThumbnailStatus = Thumbnail.Created; } using (var linkDao = Global.GetLinkDao()) { linkDao.DeleteAllLink(newFile.ID); } FileMarker.MarkAsNew(newFile); SetFileStatus(newFile); newFile.Access = fromFile.Access; if (newFile.IsTemplate && !FileUtility.ExtsWebTemplate.Contains(FileUtility.GetFileExtension(newFile.Title), StringComparer.CurrentCultureIgnoreCase)) { var tagTemplate = Tag.Template(SecurityContext.CurrentAccount.ID, newFile); using (var tagDao = Global.DaoFactory.GetTagDao()) { tagDao.RemoveTags(tagTemplate); } newFile.IsTemplate = false; } return newFile; } catch (Exception e) { Global.Logger.Error(string.Format("Error on update {0} to version {1}", fileId, version), e); throw new Exception(e.Message, e); } finally { cache.Remove(UPDATE_LIST + fromFile.ID); } } } public static File CompleteVersionFile(object fileId, int version, bool continueVersion, bool checkRight = true) { using (var fileDao = Global.DaoFactory.GetFileDao()) { var fileVersion = version > 0 ? fileDao.GetFile(fileId, version) : fileDao.GetFile(fileId); if (fileVersion == null) throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); if (checkRight && (!Global.GetFilesSecurity().CanEdit(fileVersion) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile); if (FileLockedForMe(fileVersion.ID)) throw new Exception(FilesCommonResource.ErrorMassage_LockedFile); if (fileVersion.RootFolderType == FolderType.TRASH) throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); if (fileVersion.ProviderEntry) throw new Exception(FilesCommonResource.ErrorMassage_BadRequest); var lastVersionFile = fileDao.GetFile(fileVersion.ID); if (continueVersion) { if (lastVersionFile.VersionGroup > 1) { fileDao.ContinueVersion(fileVersion.ID, fileVersion.Version); lastVersionFile.VersionGroup--; } } else { if (!FileTracker.IsEditing(lastVersionFile.ID)) { if (fileVersion.Version == lastVersionFile.Version) { lastVersionFile = UpdateToVersionFile(fileVersion.ID, fileVersion.Version, null, checkRight); } fileDao.CompleteVersion(fileVersion.ID, fileVersion.Version); lastVersionFile.VersionGroup++; } } SetFileStatus(lastVersionFile); return lastVersionFile; } } public static bool FileRename(object fileId, String title, out File file) { using (var fileDao = Global.DaoFactory.GetFileDao()) { file = fileDao.GetFile(fileId); if (file == null) throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); if (!Global.GetFilesSecurity().CanEdit(file)) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_RenameFile); if (!Global.GetFilesSecurity().CanDelete(file) && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_RenameFile); if (FileLockedForMe(file.ID)) throw new Exception(FilesCommonResource.ErrorMassage_LockedFile); if (file.ProviderEntry && FileTracker.IsEditing(file.ID)) throw new Exception(FilesCommonResource.ErrorMassage_UpdateEditingFile); if (file.RootFolderType == FolderType.TRASH) throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); title = Global.ReplaceInvalidCharsAndTruncate(title); var ext = FileUtility.GetFileExtension(file.Title); if (string.Compare(ext, FileUtility.GetFileExtension(title), true) != 0) { title += ext; } var fileAccess = file.Access; var renamed = false; if (String.Compare(file.Title, title, false) != 0) { var newFileID = fileDao.FileRename(file, title); file = fileDao.GetFile(newFileID); file.Access = fileAccess; DocumentServiceHelper.RenameFile(file, fileDao); renamed = true; } SetFileStatus(file); return renamed; } } public static void MarkAsRecent(FileEntry fileEntry) { using (var tagDao = Global.DaoFactory.GetTagDao()) { var userID = SecurityContext.CurrentAccount.ID; var tag = Tag.Recent(userID, fileEntry); tagDao.SaveTags(tag); } } //Long operation public static void DeleteSubitems(object parentId, IFolderDao folderDao, IFileDao fileDao, ILinkDao linkDao) { var folders = folderDao.GetFolders(parentId); foreach (var folder in folders) { DeleteSubitems(folder.ID, folderDao, fileDao, linkDao); Global.Logger.InfoFormat("Delete folder {0} in {1}", folder.ID, parentId); folderDao.DeleteFolder(folder.ID); } var files = fileDao.GetFiles(parentId, null, FilterType.None, false, Guid.Empty, string.Empty, true); foreach (var file in files) { Global.Logger.InfoFormat("Delete file {0} in {1}", file.ID, parentId); fileDao.DeleteFile(file.ID); linkDao.DeleteAllLink(file.ID); } } public static void MoveSharedItems(object parentId, object toId, IFolderDao folderDao, IFileDao fileDao) { var fileSecurity = Global.GetFilesSecurity(); var folders = folderDao.GetFolders(parentId); foreach (var folder in folders) { var shared = folder.Shared && fileSecurity.GetShares(folder).Any(record => record.Share != FileShare.Restrict); if (shared) { Global.Logger.InfoFormat("Move shared folder {0} from {1} to {2}", folder.ID, parentId, toId); folderDao.MoveFolder(folder.ID, toId, null); } else { MoveSharedItems(folder.ID, toId, folderDao, fileDao); } } var files = fileDao.GetFiles(parentId, null, FilterType.None, false, Guid.Empty, string.Empty, true); foreach (var file in files.Where(file => file.Shared && fileSecurity.GetShares(file) .Any(record => record.Subject != FileConstant.ShareLinkId && record.Share != FileShare.Restrict))) { Global.Logger.InfoFormat("Move shared file {0} from {1} to {2}", file.ID, parentId, toId); fileDao.MoveFile(file.ID, toId); } } public static void ReassignItems(object parentId, Guid fromUserId, Guid toUserId, IFolderDao folderDao, IFileDao fileDao) { var fileIds = fileDao.GetFiles(parentId, new OrderBy(SortedByType.AZ, true), FilterType.ByUser, false, fromUserId, null, true, true) .Where(file => file.CreateBy == fromUserId) .Select(file => file.ID); fileDao.ReassignFiles(fileIds.ToList(), toUserId); var folderIds = folderDao.GetFolders(parentId, new OrderBy(SortedByType.AZ, true), FilterType.ByUser, false, fromUserId, null, true) .Where(folder => folder.CreateBy == fromUserId).Select(folder => folder.ID); folderDao.ReassignFolders(folderIds.ToList(), toUserId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { internal static class ILGen { internal static void Emit(this ILGenerator il, OpCode opcode, MethodBase methodBase) { Debug.Assert(methodBase is MethodInfo || methodBase is ConstructorInfo); var ctor = methodBase as ConstructorInfo; if ((object)ctor != null) { il.Emit(opcode, ctor); } else { il.Emit(opcode, (MethodInfo)methodBase); } } #region Instruction helpers internal static void EmitLoadArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); switch (index) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (index <= Byte.MaxValue) { il.Emit(OpCodes.Ldarg_S, (byte)index); } else { il.Emit(OpCodes.Ldarg, index); } break; } } internal static void EmitLoadArgAddress(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= Byte.MaxValue) { il.Emit(OpCodes.Ldarga_S, (byte)index); } else { il.Emit(OpCodes.Ldarga, index); } } internal static void EmitStoreArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= Byte.MaxValue) { il.Emit(OpCodes.Starg_S, (byte)index); } else { il.Emit(OpCodes.Starg, index); } } /// <summary> /// Emits a Ldind* instruction for the appropriate type /// </summary> internal static void EmitLoadValueIndirect(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); if (type.GetTypeInfo().IsValueType) { if (type == typeof(int)) { il.Emit(OpCodes.Ldind_I4); } else if (type == typeof(uint)) { il.Emit(OpCodes.Ldind_U4); } else if (type == typeof(short)) { il.Emit(OpCodes.Ldind_I2); } else if (type == typeof(ushort)) { il.Emit(OpCodes.Ldind_U2); } else if (type == typeof(long) || type == typeof(ulong)) { il.Emit(OpCodes.Ldind_I8); } else if (type == typeof(char)) { il.Emit(OpCodes.Ldind_I2); } else if (type == typeof(bool)) { il.Emit(OpCodes.Ldind_I1); } else if (type == typeof(float)) { il.Emit(OpCodes.Ldind_R4); } else if (type == typeof(double)) { il.Emit(OpCodes.Ldind_R8); } else { il.Emit(OpCodes.Ldobj, type); } } else { il.Emit(OpCodes.Ldind_Ref); } } /// <summary> /// Emits a Stind* instruction for the appropriate type. /// </summary> internal static void EmitStoreValueIndirect(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); if (type.GetTypeInfo().IsValueType) { if (type == typeof(int)) { il.Emit(OpCodes.Stind_I4); } else if (type == typeof(short)) { il.Emit(OpCodes.Stind_I2); } else if (type == typeof(long) || type == typeof(ulong)) { il.Emit(OpCodes.Stind_I8); } else if (type == typeof(char)) { il.Emit(OpCodes.Stind_I2); } else if (type == typeof(bool)) { il.Emit(OpCodes.Stind_I1); } else if (type == typeof(float)) { il.Emit(OpCodes.Stind_R4); } else if (type == typeof(double)) { il.Emit(OpCodes.Stind_R8); } else { il.Emit(OpCodes.Stobj, type); } } else { il.Emit(OpCodes.Stind_Ref); } } // Emits the Ldelem* instruction for the appropriate type internal static void EmitLoadElement(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); if (!type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Ldelem_Ref); } else if (type.GetTypeInfo().IsEnum) { il.Emit(OpCodes.Ldelem, type); } else { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: il.Emit(OpCodes.Ldelem_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Ldelem_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Ldelem_I2); break; case TypeCode.Char: case TypeCode.UInt16: il.Emit(OpCodes.Ldelem_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Ldelem_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Ldelem_U4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Ldelem_R8); break; default: il.Emit(OpCodes.Ldelem, type); break; } } } /// <summary> /// Emits a Stelem* instruction for the appropriate type. /// </summary> internal static void EmitStoreElement(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); if (type.GetTypeInfo().IsEnum) { il.Emit(OpCodes.Stelem, type); return; } switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: il.Emit(OpCodes.Stelem_I1); break; case TypeCode.Char: case TypeCode.Int16: case TypeCode.UInt16: il.Emit(OpCodes.Stelem_I2); break; case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Stelem_I4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Stelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Stelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Stelem_R8); break; default: if (type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Stelem, type); } else { il.Emit(OpCodes.Stelem_Ref); } break; } } internal static void EmitType(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, nameof(type)); il.Emit(OpCodes.Ldtoken, type); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); } #endregion #region Fields, properties and methods internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, nameof(fi)); if (fi.IsStatic) { il.Emit(OpCodes.Ldsflda, fi); } else { il.Emit(OpCodes.Ldflda, fi); } } internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, nameof(fi)); if (fi.IsStatic) { il.Emit(OpCodes.Ldsfld, fi); } else { il.Emit(OpCodes.Ldfld, fi); } } internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, nameof(fi)); if (fi.IsStatic) { il.Emit(OpCodes.Stsfld, fi); } else { il.Emit(OpCodes.Stfld, fi); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, ConstructorInfo ci) { ContractUtils.RequiresNotNull(ci, nameof(ci)); if (ci.DeclaringType.GetTypeInfo().ContainsGenericParameters) { throw Error.IllegalNewGenericParams(ci.DeclaringType); } il.Emit(OpCodes.Newobj, ci); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, Type type, Type[] paramTypes) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(paramTypes, nameof(paramTypes)); ConstructorInfo ci = type.GetConstructor(paramTypes); if (ci == null) throw Error.TypeDoesNotHaveConstructorForTheSignature(); il.EmitNew(ci); } #endregion #region Constants internal static void EmitNull(this ILGenerator il) { il.Emit(OpCodes.Ldnull); } internal static void EmitString(this ILGenerator il, string value) { ContractUtils.RequiresNotNull(value, nameof(value)); il.Emit(OpCodes.Ldstr, value); } internal static void EmitBoolean(this ILGenerator il, bool value) { if (value) { il.Emit(OpCodes.Ldc_I4_1); } else { il.Emit(OpCodes.Ldc_I4_0); } } internal static void EmitChar(this ILGenerator il, char value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U2); } internal static void EmitByte(this ILGenerator il, byte value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U1); } internal static void EmitSByte(this ILGenerator il, sbyte value) { il.EmitInt(value); il.Emit(OpCodes.Conv_I1); } internal static void EmitShort(this ILGenerator il, short value) { il.EmitInt(value); il.Emit(OpCodes.Conv_I2); } internal static void EmitUShort(this ILGenerator il, ushort value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U2); } internal static void EmitInt(this ILGenerator il, int value) { OpCode c; switch (value) { case -1: c = OpCodes.Ldc_I4_M1; break; case 0: c = OpCodes.Ldc_I4_0; break; case 1: c = OpCodes.Ldc_I4_1; break; case 2: c = OpCodes.Ldc_I4_2; break; case 3: c = OpCodes.Ldc_I4_3; break; case 4: c = OpCodes.Ldc_I4_4; break; case 5: c = OpCodes.Ldc_I4_5; break; case 6: c = OpCodes.Ldc_I4_6; break; case 7: c = OpCodes.Ldc_I4_7; break; case 8: c = OpCodes.Ldc_I4_8; break; default: if (value >= -128 && value <= 127) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } return; } il.Emit(c); } internal static void EmitUInt(this ILGenerator il, uint value) { il.EmitInt((int)value); il.Emit(OpCodes.Conv_U4); } internal static void EmitLong(this ILGenerator il, long value) { il.Emit(OpCodes.Ldc_I8, value); // // Now, emit convert to give the constant type information. // // Otherwise, it is treated as unsigned and overflow is not // detected if it's used in checked ops. // il.Emit(OpCodes.Conv_I8); } internal static void EmitULong(this ILGenerator il, ulong value) { il.Emit(OpCodes.Ldc_I8, (long)value); il.Emit(OpCodes.Conv_U8); } internal static void EmitDouble(this ILGenerator il, double value) { il.Emit(OpCodes.Ldc_R8, value); } internal static void EmitSingle(this ILGenerator il, float value) { il.Emit(OpCodes.Ldc_R4, value); } // matches TryEmitConstant internal static bool CanEmitConstant(object value, Type type) { if (value == null || CanEmitILConstant(type)) { return true; } Type t = value as Type; if (t != null && ShouldLdtoken(t)) { return true; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { return true; } return false; } // matches TryEmitILConstant private static bool CanEmitILConstant(Type type) { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Char: case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.String: return true; } return false; } internal static void EmitConstant(this ILGenerator il, object value) { Debug.Assert(value != null); EmitConstant(il, value, value.GetType()); } // // Note: we support emitting more things as IL constants than // Linq does internal static void EmitConstant(this ILGenerator il, object value, Type type) { if (value == null) { // Smarter than the Linq implementation which uses the initobj // pattern for all value types (works, but requires a local and // more IL) il.EmitDefault(type); return; } // Handle the easy cases if (il.TryEmitILConstant(value, type)) { return; } // Check for a few more types that we support emitting as constants Type t = value as Type; if (t != null && ShouldLdtoken(t)) { il.EmitType(t); if (type != typeof(Type)) { il.Emit(OpCodes.Castclass, type); } return; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { il.Emit(OpCodes.Ldtoken, mb); Type dt = mb.DeclaringType; if (dt != null && dt.GetTypeInfo().IsGenericType) { il.Emit(OpCodes.Ldtoken, dt); il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) })); } else { il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle) })); } if (type != typeof(MethodBase)) { il.Emit(OpCodes.Castclass, type); } return; } throw ContractUtils.Unreachable; } internal static bool ShouldLdtoken(Type t) { return t.GetTypeInfo() is TypeBuilder || t.IsGenericParameter || t.GetTypeInfo().IsVisible; } internal static bool ShouldLdtoken(MethodBase mb) { // Can't ldtoken on a DynamicMethod if (mb is DynamicMethod) { return false; } Type dt = mb.DeclaringType; return dt == null || ShouldLdtoken(dt); } private static bool TryEmitILConstant(this ILGenerator il, object value, Type type) { switch (type.GetTypeCode()) { case TypeCode.Boolean: il.EmitBoolean((bool)value); return true; case TypeCode.SByte: il.EmitSByte((sbyte)value); return true; case TypeCode.Int16: il.EmitShort((short)value); return true; case TypeCode.Int32: il.EmitInt((int)value); return true; case TypeCode.Int64: il.EmitLong((long)value); return true; case TypeCode.Single: il.EmitSingle((float)value); return true; case TypeCode.Double: il.EmitDouble((double)value); return true; case TypeCode.Char: il.EmitChar((char)value); return true; case TypeCode.Byte: il.EmitByte((byte)value); return true; case TypeCode.UInt16: il.EmitUShort((ushort)value); return true; case TypeCode.UInt32: il.EmitUInt((uint)value); return true; case TypeCode.UInt64: il.EmitULong((ulong)value); return true; case TypeCode.Decimal: il.EmitDecimal((decimal)value); return true; case TypeCode.String: il.EmitString((string)value); return true; default: return false; } } #endregion #region Linq Conversions internal static void EmitConvertToType(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { if (TypeUtils.AreEquivalent(typeFrom, typeTo)) { return; } if (typeFrom == typeof(void) || typeTo == typeof(void)) { throw ContractUtils.Unreachable; } bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom); bool isTypeToNullable = TypeUtils.IsNullableType(typeTo); Type nnExprType = TypeUtils.GetNonNullableType(typeFrom); Type nnType = TypeUtils.GetNonNullableType(typeTo); if (typeFrom.GetTypeInfo().IsInterface || // interface cast typeTo.GetTypeInfo().IsInterface || typeFrom == typeof(object) || // boxing cast typeTo == typeof(object) || typeFrom == typeof(System.Enum) || typeFrom == typeof(System.ValueType) || TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo)) { il.EmitCastToType(typeFrom, typeTo); } else if (isTypeFromNullable || isTypeToNullable) { il.EmitNullableConversion(typeFrom, typeTo, isChecked); } else if (!(TypeUtils.IsConvertible(typeFrom) && TypeUtils.IsConvertible(typeTo)) // primitive runtime conversion && (nnExprType.IsAssignableFrom(nnType) || // down cast nnType.IsAssignableFrom(nnExprType))) // up cast { il.EmitCastToType(typeFrom, typeTo); } else if (typeFrom.IsArray && typeTo.IsArray) { // See DevDiv Bugs #94657. il.EmitCastToType(typeFrom, typeTo); } else { il.EmitNumericConversion(typeFrom, typeTo, isChecked); } } private static void EmitCastToType(this ILGenerator il, Type typeFrom, Type typeTo) { if (!typeFrom.GetTypeInfo().IsValueType && typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Unbox_Any, typeTo); } else if (typeFrom.GetTypeInfo().IsValueType && !typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Box, typeFrom); if (typeTo != typeof(object)) { il.Emit(OpCodes.Castclass, typeTo); } } else if (!typeFrom.GetTypeInfo().IsValueType && !typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Castclass, typeTo); } else { throw Error.InvalidCast(typeFrom, typeTo); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static void EmitNumericConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { bool isFromUnsigned = TypeUtils.IsUnsigned(typeFrom); bool isFromFloatingPoint = TypeUtils.IsFloatingPoint(typeFrom); if (typeTo == typeof(Single)) { if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); il.Emit(OpCodes.Conv_R4); } else if (typeTo == typeof(Double)) { if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); il.Emit(OpCodes.Conv_R8); } else { TypeCode tc = typeTo.GetTypeCode(); if (isChecked) { // Overflow checking needs to know if the source value on the IL stack is unsigned or not. if (isFromUnsigned) { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_Ovf_I1_Un); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_Ovf_I2_Un); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_Ovf_I4_Un); break; case TypeCode.Int64: il.Emit(OpCodes.Conv_Ovf_I8_Un); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_Ovf_U1_Un); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_Ovf_U2_Un); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_Ovf_U4_Un); break; case TypeCode.UInt64: il.Emit(OpCodes.Conv_Ovf_U8_Un); break; default: throw Error.UnhandledConvert(typeTo); } } else { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_Ovf_I1); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_Ovf_I2); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_Ovf_I4); break; case TypeCode.Int64: il.Emit(OpCodes.Conv_Ovf_I8); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_Ovf_U1); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_Ovf_U2); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_Ovf_U4); break; case TypeCode.UInt64: il.Emit(OpCodes.Conv_Ovf_U8); break; default: throw Error.UnhandledConvert(typeTo); } } } else { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_I2); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_U4); break; case TypeCode.Int64: if (isFromUnsigned) { il.Emit(OpCodes.Conv_U8); } else { il.Emit(OpCodes.Conv_I8); } break; case TypeCode.UInt64: if (isFromUnsigned || isFromFloatingPoint) { il.Emit(OpCodes.Conv_U8); } else { il.Emit(OpCodes.Conv_I8); } break; default: throw Error.UnhandledConvert(typeTo); } } } } private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(TypeUtils.IsNullableType(typeTo)); Label labIfNull = default(Label); Label labEnd = default(Label); LocalBuilder locFrom = null; LocalBuilder locTo = null; locFrom = il.DeclareLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); locTo = il.DeclareLocal(typeTo); // test for null il.Emit(OpCodes.Ldloca, locFrom); il.EmitHasValue(typeFrom); labIfNull = il.DefineLabel(); il.Emit(OpCodes.Brfalse_S, labIfNull); il.Emit(OpCodes.Ldloca, locFrom); il.EmitGetValueOrDefault(typeFrom); Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom); Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo); il.EmitConvertToType(nnTypeFrom, nnTypeTo, isChecked); // construct result type ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); labEnd = il.DefineLabel(); il.Emit(OpCodes.Br_S, labEnd); // if null then create a default one il.MarkLabel(labIfNull); il.Emit(OpCodes.Ldloca, locTo); il.Emit(OpCodes.Initobj, typeTo); il.MarkLabel(labEnd); il.Emit(OpCodes.Ldloc, locTo); } private static void EmitNonNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(!TypeUtils.IsNullableType(typeFrom)); Debug.Assert(TypeUtils.IsNullableType(typeTo)); LocalBuilder locTo = null; locTo = il.DeclareLocal(typeTo); Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo); il.EmitConvertToType(typeFrom, nnTypeTo, isChecked); ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); il.Emit(OpCodes.Ldloc, locTo); } private static void EmitNullableToNonNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(!TypeUtils.IsNullableType(typeTo)); if (typeTo.GetTypeInfo().IsValueType) il.EmitNullableToNonNullableStructConversion(typeFrom, typeTo, isChecked); else il.EmitNullableToReferenceConversion(typeFrom); } private static void EmitNullableToNonNullableStructConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(!TypeUtils.IsNullableType(typeTo)); Debug.Assert(typeTo.GetTypeInfo().IsValueType); LocalBuilder locFrom = null; locFrom = il.DeclareLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); il.Emit(OpCodes.Ldloca, locFrom); il.EmitGetValue(typeFrom); Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom); il.EmitConvertToType(nnTypeFrom, typeTo, isChecked); } private static void EmitNullableToReferenceConversion(this ILGenerator il, Type typeFrom) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); // We've got a conversion from nullable to Object, ValueType, Enum, etc. Just box it so that // we get the nullable semantics. il.Emit(OpCodes.Box, typeFrom); } private static void EmitNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom); bool isTypeToNullable = TypeUtils.IsNullableType(typeTo); Debug.Assert(isTypeFromNullable || isTypeToNullable); if (isTypeFromNullable && isTypeToNullable) il.EmitNullableToNullableConversion(typeFrom, typeTo, isChecked); else if (isTypeFromNullable) il.EmitNullableToNonNullableConversion(typeFrom, typeTo, isChecked); else il.EmitNonNullableToNullableConversion(typeFrom, typeTo, isChecked); } internal static void EmitHasValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_HasValue", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("GetValueOrDefault", System.Type.EmptyTypes); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } #endregion #region Arrays /// <summary> /// Emits an array of constant values provided in the given list. /// The array is strongly typed. /// </summary> internal static void EmitArray<T>(this ILGenerator il, IList<T> items) { ContractUtils.RequiresNotNull(items, nameof(items)); il.EmitInt(items.Count); il.Emit(OpCodes.Newarr, typeof(T)); for (int i = 0; i < items.Count; i++) { il.Emit(OpCodes.Dup); il.EmitInt(i); il.EmitConstant(items[i], typeof(T)); il.EmitStoreElement(typeof(T)); } } /// <summary> /// Emits an array of values of count size. The items are emitted via the callback /// which is provided with the current item index to emit. /// </summary> internal static void EmitArray(this ILGenerator il, Type elementType, int count, Action<int> emit) { ContractUtils.RequiresNotNull(elementType, nameof(elementType)); ContractUtils.RequiresNotNull(emit, nameof(emit)); Debug.Assert(count >= 0); il.EmitInt(count); il.Emit(OpCodes.Newarr, elementType); for (int i = 0; i < count; i++) { il.Emit(OpCodes.Dup); il.EmitInt(i); emit(i); il.EmitStoreElement(elementType); } } /// <summary> /// Emits an array construction code. /// The code assumes that bounds for all dimensions /// are already emitted. /// </summary> internal static void EmitArray(this ILGenerator il, Type arrayType) { ContractUtils.RequiresNotNull(arrayType, nameof(arrayType)); Debug.Assert(arrayType.IsArray); if (arrayType.IsVector()) { il.Emit(OpCodes.Newarr, arrayType.GetElementType()); } else { int rank = arrayType.GetArrayRank(); Type[] types = new Type[rank]; for (int i = 0; i < rank; i++) { types[i] = typeof(int); } il.EmitNew(arrayType, types); } } #endregion #region Support for emitting constants internal static void EmitDecimal(this ILGenerator il, decimal value) { if (Decimal.Truncate(value) == value) { if (Int32.MinValue <= value && value <= Int32.MaxValue) { int intValue = Decimal.ToInt32(value); il.EmitInt(intValue); il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(int) })); } else if (Int64.MinValue <= value && value <= Int64.MaxValue) { long longValue = Decimal.ToInt64(value); il.EmitLong(longValue); il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(long) })); } else { il.EmitDecimalBits(value); } } else { il.EmitDecimalBits(value); } } private static void EmitDecimalBits(this ILGenerator il, decimal value) { int[] bits = Decimal.GetBits(value); il.EmitInt(bits[0]); il.EmitInt(bits[1]); il.EmitInt(bits[2]); il.EmitBoolean((bits[3] & 0x80000000) != 0); il.EmitByte((byte)(bits[3] >> 16)); il.EmitNew(typeof(decimal).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) })); } /// <summary> /// Emits default(T) /// Semantics match C# compiler behavior /// </summary> internal static void EmitDefault(this ILGenerator il, Type type) { switch (type.GetTypeCode()) { case TypeCode.Object: case TypeCode.DateTime: if (type.GetTypeInfo().IsValueType) { // Type.GetTypeCode on an enum returns the underlying // integer TypeCode, so we won't get here. Debug.Assert(!type.GetTypeInfo().IsEnum); // This is the IL for default(T) if T is a generic type // parameter, so it should work for any type. It's also // the standard pattern for structs. LocalBuilder lb = il.DeclareLocal(type); il.Emit(OpCodes.Ldloca, lb); il.Emit(OpCodes.Initobj, type); il.Emit(OpCodes.Ldloc, lb); } else { il.Emit(OpCodes.Ldnull); } break; case TypeCode.Empty: case TypeCode.String: il.Emit(OpCodes.Ldnull); break; case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Ldc_I4_0); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Conv_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldc_R4, default(Single)); break; case TypeCode.Double: il.Emit(OpCodes.Ldc_R8, default(Double)); break; case TypeCode.Decimal: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Newobj, typeof(Decimal).GetConstructor(new Type[] { typeof(int) })); break; default: throw ContractUtils.Unreachable; } } #endregion } }
//--------------------------------------------------------------------------- // // <copyright file="BackgroundFormatInfo.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Background format information // // History: // 10/28/04 : ghermann - Created // //--------------------------------------------------------------------------- using System; using MS.Internal.Documents; // FlowDocumentFormatter using System.Windows.Threading; // DispatcherTimer namespace MS.Internal.PtsHost { internal sealed class BackgroundFormatInfo { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Structural Cache contructor /// </summary> internal BackgroundFormatInfo(StructuralCache structuralCache) { _structuralCache = structuralCache; } #endregion Constructors //------------------------------------------------------------------- // // Internal Methods // //------------------------------------------------------------------- #region Internal Methods /// <summary> /// Updates background layout information from a structuralCache /// </summary> internal void UpdateBackgroundFormatInfo() { _cpInterrupted = -1; _lastCPUninterruptible = 0; _doesFinalDTRCoverRestOfText = false; _cchAllText = _structuralCache.TextContainer.SymbolCount; if(_structuralCache.DtrList != null) { int positionsAdded = 0; // Sum for all dtrs but the last for(int dtrIndex = 0; dtrIndex < _structuralCache.DtrList.Length - 1; dtrIndex++) { positionsAdded += _structuralCache.DtrList[dtrIndex].PositionsAdded - _structuralCache.DtrList[dtrIndex].PositionsRemoved; } DirtyTextRange dtrLast = _structuralCache.DtrList[_structuralCache.DtrList.Length - 1]; if((dtrLast.StartIndex + positionsAdded + dtrLast.PositionsAdded) >= _cchAllText) { _doesFinalDTRCoverRestOfText = true; _lastCPUninterruptible = dtrLast.StartIndex + positionsAdded; } } else { _doesFinalDTRCoverRestOfText = true; } // And set a good stop time for formatting _backgroundFormatStopTime = DateTime.UtcNow.AddMilliseconds(_stopTimeDelta); } /// <summary> /// This method is called after user input. /// Temporarily disable background layout to cut down on ui latency. /// </summary> internal void ThrottleBackgroundFormatting() { if (_throttleBackgroundTimer == null) { // Start up a timer. Until the timer fires, we'll disable // all background layout. This leaves the control responsive // to user input. _throttleBackgroundTimer = new DispatcherTimer(DispatcherPriority.Background); _throttleBackgroundTimer.Interval = new TimeSpan(0, 0, (int)_throttleBackgroundSeconds); _throttleBackgroundTimer.Tick += new EventHandler(OnThrottleBackgroundTimeout); } else { // Reset the timer. _throttleBackgroundTimer.Stop(); } _throttleBackgroundTimer.Start(); } /// <summary> /// Run one iteration of background formatting. Currently that simply requires /// that we invalidate the content. /// </summary> internal void BackgroundFormat(IFlowDocumentFormatter formatter, bool ignoreThrottle) { if (_throttleBackgroundTimer == null) { formatter.OnContentInvalidated(true); } else if (ignoreThrottle) { OnThrottleBackgroundTimeout(null, EventArgs.Empty); } else { // If we had recent user input, wait until the timeout passes // to invalidate. _pendingBackgroundFormatter = formatter; } } #endregion Internal Methods //------------------------------------------------------------------- // // Internal Properties // //------------------------------------------------------------------- #region Internal Properties /// <summary> /// Last CP Uninterruptible /// </summary> internal int LastCPUninterruptible { get { return _lastCPUninterruptible; } } /// <summary> /// Stop time for background formatting timeslice /// </summary> internal DateTime BackgroundFormatStopTime { get { return _backgroundFormatStopTime; } } /// <summary> /// Cch of all text in container /// </summary> internal int CchAllText { get { return _cchAllText; } } /// <summary> /// Whether background layout is globally enabled /// </summary> static internal bool IsBackgroundFormatEnabled { get { return _isBackgroundFormatEnabled; } } /// <summary> /// Does the final dtr extend through the sum of the text /// </summary> internal bool DoesFinalDTRCoverRestOfText { get { return _doesFinalDTRCoverRestOfText; } } /// <summary> /// Current last cp formatted /// </summary> internal int CPInterrupted { get { return _cpInterrupted; } set { _cpInterrupted = value; } } /// <summary> /// Height of the viewport /// </summary> internal double ViewportHeight { get { return _viewportHeight; } set { _viewportHeight = value; } } #endregion Internal Properties //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods // Callback for the background layout throttle timer. // Resumes backgound layout. private void OnThrottleBackgroundTimeout(object sender, EventArgs e) { _throttleBackgroundTimer.Stop(); _throttleBackgroundTimer = null; if (_pendingBackgroundFormatter != null) { BackgroundFormat(_pendingBackgroundFormatter, true /* ignoreThrottle */); _pendingBackgroundFormatter = null; } } #endregion Private Methods //------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------- #region Private Fields //------------------------------------------------------------------- // Height of the viewport. //------------------------------------------------------------------- private double _viewportHeight; //------------------------------------------------------------------- // Does the final DTR cover the entirety of the range? //------------------------------------------------------------------- private bool _doesFinalDTRCoverRestOfText; //------------------------------------------------------------------- // What is the last uninterruptible cp ? //------------------------------------------------------------------- private int _lastCPUninterruptible; //------------------------------------------------------------------- // Stop time for background layout // Used for background layout //------------------------------------------------------------------- private DateTime _backgroundFormatStopTime; //------------------------------------------------------------------- // Cch of all text in container //------------------------------------------------------------------- private int _cchAllText; //------------------------------------------------------------------- // Cp Interrupted // Used for background layout //------------------------------------------------------------------- private int _cpInterrupted; //------------------------------------------------------------------- // Global enabling flag for whether background format is enabled. //------------------------------------------------------------------- private static bool _isBackgroundFormatEnabled = true; //------------------------------------------------------------------- // Structural cache //------------------------------------------------------------------- private StructuralCache _structuralCache; //------------------------------------------------------------------- // Time after a user input until which we use a minimal time slice // to remain responsive to future input. //------------------------------------------------------------------- private DateTime _throttleTimeout = DateTime.UtcNow; //------------------------------------------------------------------- // Timer used to disable background layout during user interaction. //------------------------------------------------------------------- private DispatcherTimer _throttleBackgroundTimer; //------------------------------------------------------------------- // Holds the formatter to invalidate when _throttleBackgroundTimer // fires. //------------------------------------------------------------------- IFlowDocumentFormatter _pendingBackgroundFormatter; //------------------------------------------------------------------- // Number of seconds to disable background layout after receiving // user input. //------------------------------------------------------------------- private const uint _throttleBackgroundSeconds = 2; //------------------------------------------------------------------- // Max time slice (ms) for one background format iteration. //------------------------------------------------------------------- private const uint _stopTimeDelta = 200; #endregion Private Fields } }
using Lucene.Net.Diagnostics; using System.Diagnostics; using System.IO; namespace Lucene.Net.Codecs { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using IndexOutput = Lucene.Net.Store.IndexOutput; using MathUtil = Lucene.Net.Util.MathUtil; using RAMOutputStream = Lucene.Net.Store.RAMOutputStream; /// <summary> /// This abstract class writes skip lists with multiple levels. /// /// <code> /// /// Example for skipInterval = 3: /// c (skip level 2) /// c c c (skip level 1) /// x x x x x x x x x x (skip level 0) /// d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d (posting list) /// 3 6 9 12 15 18 21 24 27 30 (df) /// /// d - document /// x - skip data /// c - skip data with child pointer /// /// Skip level i contains every skipInterval-th entry from skip level i-1. /// Therefore the number of entries on level i is: floor(df / ((skipInterval ^ (i + 1))). /// /// Each skip entry on a level i>0 contains a pointer to the corresponding skip entry in list i-1. /// this guarantees a logarithmic amount of skips to find the target document. /// /// While this class takes care of writing the different skip levels, /// subclasses must define the actual format of the skip data. /// </code> /// <para/> /// @lucene.experimental /// </summary> public abstract class MultiLevelSkipListWriter { /// <summary> /// Number of levels in this skip list. </summary> protected internal int m_numberOfSkipLevels; /// <summary> /// The skip interval in the list with level = 0. </summary> private int skipInterval; /// <summary> /// SkipInterval used for level &gt; 0. </summary> private int skipMultiplier; /// <summary> /// For every skip level a different buffer is used. </summary> private RAMOutputStream[] skipBuffer; /// <summary> /// Creates a <see cref="MultiLevelSkipListWriter"/>. </summary> protected MultiLevelSkipListWriter(int skipInterval, int skipMultiplier, int maxSkipLevels, int df) { this.skipInterval = skipInterval; this.skipMultiplier = skipMultiplier; // calculate the maximum number of skip levels for this document frequency if (df <= skipInterval) { m_numberOfSkipLevels = 1; } else { m_numberOfSkipLevels = 1 + MathUtil.Log(df / skipInterval, skipMultiplier); } // make sure it does not exceed maxSkipLevels if (m_numberOfSkipLevels > maxSkipLevels) { m_numberOfSkipLevels = maxSkipLevels; } } /// <summary> /// Creates a <see cref="MultiLevelSkipListWriter"/>, where /// <see cref="skipInterval"/> and <see cref="skipMultiplier"/> are /// the same. /// </summary> protected MultiLevelSkipListWriter(int skipInterval, int maxSkipLevels, int df) : this(skipInterval, skipInterval, maxSkipLevels, df) { } /// <summary> /// Allocates internal skip buffers. </summary> protected virtual void Init() { skipBuffer = new RAMOutputStream[m_numberOfSkipLevels]; for (int i = 0; i < m_numberOfSkipLevels; i++) { skipBuffer[i] = new RAMOutputStream(); } } /// <summary> /// Creates new buffers or empties the existing ones. </summary> public virtual void ResetSkip() { if (skipBuffer == null) { Init(); } else { for (int i = 0; i < skipBuffer.Length; i++) { skipBuffer[i].Reset(); } } } /// <summary> /// Subclasses must implement the actual skip data encoding in this method. /// </summary> /// <param name="level"> The level skip data shall be writing for. </param> /// <param name="skipBuffer"> The skip buffer to write to. </param> protected abstract void WriteSkipData(int level, IndexOutput skipBuffer); /// <summary> /// Writes the current skip data to the buffers. The current document frequency determines /// the max level is skip data is to be written to. /// </summary> /// <param name="df"> The current document frequency. </param> /// <exception cref="IOException"> If an I/O error occurs. </exception> public virtual void BufferSkip(int df) { if (Debugging.AssertsEnabled) Debugging.Assert(df % skipInterval == 0); int numLevels = 1; df /= skipInterval; // determine max level while ((df % skipMultiplier) == 0 && numLevels < m_numberOfSkipLevels) { numLevels++; df /= skipMultiplier; } long childPointer = 0; for (int level = 0; level < numLevels; level++) { WriteSkipData(level, skipBuffer[level]); long newChildPointer = skipBuffer[level].GetFilePointer(); if (level != 0) { // store child pointers for all levels except the lowest skipBuffer[level].WriteVInt64(childPointer); } //remember the childPointer for the next level childPointer = newChildPointer; } } /// <summary> /// Writes the buffered skip lists to the given output. /// </summary> /// <param name="output"> The <see cref="IndexOutput"/> the skip lists shall be written to. </param> /// <returns> The pointer the skip list starts. </returns> public virtual long WriteSkip(IndexOutput output) { long skipPointer = output.GetFilePointer(); //System.out.println("skipper.writeSkip fp=" + skipPointer); if (skipBuffer == null || skipBuffer.Length == 0) { return skipPointer; } for (int level = m_numberOfSkipLevels - 1; level > 0; level--) { long length = skipBuffer[level].GetFilePointer(); if (length > 0) { output.WriteVInt64(length); skipBuffer[level].WriteTo(output); } } skipBuffer[0].WriteTo(output); return skipPointer; } } }
using System; using System.IO; using System.Timers; using System.Xml.Serialization; using Android.Content; using Kaboom.Serializer; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; using Microsoft.Xna.Framework.Media; namespace Kaboom.Sources { class MainGame : Game { class CurrentElement { public Point Coord; public VirtualBomb Entity; public CurrentElement() { Coord = new Point(-1, -1); Entity = null; } } private readonly GraphicsDeviceManager graphics_; private SpriteBatch spriteBatch_; private readonly string level_; private readonly Event em_; private Map map_; private Hud hud_; private readonly CurrentElement currentBomb_; private bool ended_; private readonly Ladder ladder_; private bool lose_; private bool explosionMode_; private readonly ScoreManager score_ = ScoreManager.Instance; private bool isTuto_; private readonly List<string> mapName_; private readonly List<string> tutoName_; private bool onHelp_; private readonly SelecterAnimation selecterAnimation_; private Vector2 selecterCoord_; /// <summary> /// Create the game instance /// </summary> public MainGame(string level) { currentBomb_ = new CurrentElement(); this.graphics_ = new GraphicsDeviceManager(this) { IsFullScreen = true, SupportedOrientations = DisplayOrientation.LandscapeLeft, PreferMultiSampling = true }; this.level_ = level; ended_ = false; lose_ = false; this.em_ = new Event(); this.ladder_ = new Ladder(); this.selecterAnimation_ = new SelecterAnimation(); #region mapNameInit mapName_ = new List<string> { "NumbaWan", "DidUCheckTuto", "It's Something", "Versus", "CombisTheG", "InTheRedCorner", "TheBreach", "OppositeForces", "XFactor", "ChooseYourSide", "DynamiteWarehouse", "FaceToFace", "OneStepAway", "FindYourWayOut", "Corporate", "Unreachable", "Tetris", "Life", "Invasion", "A-Maze-Me" }; tutoName_ = new List<string> { "TutoNormalBomb", "TutoLineBomb", "TutoConeBomb", "TutoXBomb", "TutoCheckpointBS", "TutoHBomb", "TutoUltimateBomb", "TutoBonusTNT" }; #endregion isTuto_ = tutoName_.Contains(this.level_); Content.RootDirectory = "Content"; } /// <summary> /// Load a MapElements /// </summary> /// <param name="filename">filename to fetch</param> /// <returns>Map description</returns> private MapElements LoadLevel(string filename) { var serializer = new XmlSerializer(typeof(MapElements)); using (var fs = TitleContainer.OpenStream(Path.Combine(Content.RootDirectory, filename + ".xml"))) { return (MapElements)serializer.Deserialize(fs); } } /// <summary> /// Load heavy content and resources that shouldn't be copied /// </summary> protected override void LoadContent() { base.LoadContent(); this.spriteBatch_ = new SpriteBatch(GraphicsDevice); #region Load KaboomResources.Textures["background1"] = Content.Load<Texture2D>("background1"); KaboomResources.Textures["background2"] = Content.Load<Texture2D>("background2"); KaboomResources.Textures["background3"] = Content.Load<Texture2D>("background3"); KaboomResources.Textures["background4"] = Content.Load<Texture2D>("background4"); KaboomResources.Textures["BombSheetSquare"] = Content.Load<Texture2D>("BombSheetSquare"); KaboomResources.Textures["BombSheetLine"] = Content.Load<Texture2D>("BombSheetLine"); KaboomResources.Textures["BombSheetAngle"] = Content.Load<Texture2D>("BombSheetAngle"); KaboomResources.Textures["BombSheetH"] = Content.Load<Texture2D>("BombSheetH"); KaboomResources.Textures["BombSheetX"] = Content.Load<Texture2D>("BombSheetX"); KaboomResources.Textures["BombSheetTNT"] = Content.Load<Texture2D>("BombSheetTNT"); KaboomResources.Textures["BombSheetUltimate"] = Content.Load<Texture2D>("BombSheetUltimate"); KaboomResources.Textures["BombSheetBigSquare"] = Content.Load<Texture2D>("BombSheetBigSquare"); KaboomResources.Textures["hud"] = Content.Load<Texture2D>("hud"); KaboomResources.Textures["hud_active"] = Content.Load<Texture2D>("hud_active"); KaboomResources.Textures["highlight"] = Content.Load<Texture2D>("HighLight"); KaboomResources.Textures["highlight2"] = Content.Load<Texture2D>("HighLight2"); KaboomResources.Textures["goal"] = Content.Load<Texture2D>("GoalSheet"); KaboomResources.Textures["checkpoint"] = Content.Load<Texture2D>("CheckPoint"); KaboomResources.Textures["endScreen"] = Content.Load<Texture2D>("endScreen"); KaboomResources.Textures["endScreen2"] = Content.Load<Texture2D>("endScreen2"); KaboomResources.Textures["endScreen3"] = Content.Load<Texture2D>("endScreen3"); KaboomResources.Textures["failScreen"] = Content.Load<Texture2D>("failScreen"); KaboomResources.Textures["ladderScreen"] = Content.Load<Texture2D>("ladderScreen"); KaboomResources.Textures["help"] = Content.Load<Texture2D>("question-mark"); KaboomResources.Textures["selecter"] = Content.Load<Texture2D>("Selecter"); if (isTuto_) KaboomResources.Textures["Tuto"] = Content.Load<Texture2D>(level_); KaboomResources.Textures["helpScreen"] = Content.Load<Texture2D>("helpScreen"); KaboomResources.Sprites["BombUltimate"] = new SpriteSheet(KaboomResources.Textures["BombSheetUltimate"], new[] { 14, 14 }, 2, 20); KaboomResources.Sprites["BombSquare"] = new SpriteSheet(KaboomResources.Textures["BombSheetSquare"], new[] { 14, 14 }, 2, 20); KaboomResources.Sprites["BombAngle"] = new SpriteSheet(KaboomResources.Textures["BombSheetAngle"], new[] { 14, 14 }, 2, 20); KaboomResources.Sprites["BombBigSquare"] = new SpriteSheet(KaboomResources.Textures["BombSheetBigSquare"], new[] { 14, 14 }, 2, 20); KaboomResources.Sprites["BombLine"] = new SpriteSheet(KaboomResources.Textures["BombSheetLine"], new[] { 14, 14 }, 2, 20); KaboomResources.Sprites["BombSheetTNT"] = new SpriteSheet(KaboomResources.Textures["BombSheetTNT"], new[] { 1, 14 }, 2, 20); KaboomResources.Sprites["BombH"] = new SpriteSheet(KaboomResources.Textures["BombSheetH"], new[] { 14, 14 }, 2, 20); KaboomResources.Sprites["BombX"] = new SpriteSheet(KaboomResources.Textures["BombSheetX"], new[] { 14, 14 }, 2, 20); KaboomResources.Sprites["background2"] = new SpriteSheet(KaboomResources.Textures["background2"], new[] { 1, 15 }, 2, 20); KaboomResources.Sprites["background3"] = new SpriteSheet(KaboomResources.Textures["background3"], new[] { 1, 8 }, 2, 20); KaboomResources.Sprites["Ground"] = new SpriteSheet(KaboomResources.Textures["background1"], new[] { 1 }, 1); KaboomResources.Sprites["checkpoint"] = new SpriteSheet(KaboomResources.Textures["checkpoint"], new[] { 1, 14 }, 2); KaboomResources.Sprites["goal"] = new SpriteSheet(KaboomResources.Textures["goal"], new[] { 14, 14 }, 2); KaboomResources.Fonts["default"] = Content.Load<SpriteFont>("defaultFont"); KaboomResources.Fonts["end"] = Content.Load<SpriteFont>("endFont"); KaboomResources.Effects["DropBomb"] = Content.Load<SoundEffect>("Drop"); KaboomResources.Effects["Explode"] = Content.Load<SoundEffect>("Explosion"); KaboomResources.Effects["Detonate"] = Content.Load<SoundEffect>("Detonate"); KaboomResources.Musics["InGame"] = Content.Load<Song>("InGame"); KaboomResources.Level = LoadLevel(level_); #endregion } /// <summary> /// Initialise game /// </summary> protected override void Initialize() { base.Initialize(); this.hud_ = new Hud(this, this.spriteBatch_); hud_.GameInfos.Round = 10; score_.Restart(10); this.map_ = new Map(this, this.spriteBatch_, KaboomResources.Level); this.ladder_.AddEntry(KaboomResources.Level.Score.Score1, "King"); this.ladder_.AddEntry(KaboomResources.Level.Score.Score2, "Prince"); this.ladder_.AddEntry(KaboomResources.Level.Score.Score3, "Champion"); this.hud_.GameInfos.Round = KaboomResources.Level.Score.Turn; this.map_.EndGameManager += ManageEndGame; Viewport.Instance.Initialize(GraphicsDevice, this.map_); this.Components.Add(this.map_); this.Components.Add(this.hud_); MediaPlayer.Play(KaboomResources.Musics["InGame"]); MediaPlayer.IsRepeating = true; MediaPlayer.Volume = 0.5f; } private void UpdateEnd(Action ret) { if (ret.ActionType == Action.Type.Tap) { var hudEvent = this.hud_.GetHudEndEvent(ret.Pos); switch (hudEvent) { case Hud.EHudEndAction.Menu: MediaPlayer.IsRepeating = false; MediaPlayer.Stop(); Activity.Finish(); Activity.StartActivity(new Intent(Activity, typeof (MenuActivity))); break; case Hud.EHudEndAction.Ladder: if (!lose_) ladder_.IsDisplay = true; break; case Hud.EHudEndAction.Score: if (!lose_) ladder_.IsDisplay = false; break; case Hud.EHudEndAction.Reload: MediaPlayer.IsRepeating = false; MediaPlayer.Stop(); Activity.Finish(); Activity.StartActivity(new Intent(Activity, typeof (MainActivity)).PutExtra("level", this.level_)); break; case Hud.EHudEndAction.Next: MediaPlayer.IsRepeating = false; MediaPlayer.Stop(); Activity.Finish(); int idx; if ((idx = mapName_.IndexOf(level_)) != -1) { idx++; if (idx >= mapName_.Count) Activity.StartActivity(new Intent(Activity, typeof (MenuActivity))); else Activity.StartActivity(new Intent(Activity, typeof (MainActivity)).PutExtra("level", mapName_[ idx])); } else { idx = tutoName_.IndexOf(level_) + 1; if (idx >= tutoName_.Count) Activity.StartActivity(new Intent(Activity, typeof (MainActivity)).PutExtra("level", mapName_[0])); else Activity.StartActivity(new Intent(Activity, typeof (MainActivity)).PutExtra("level", tutoName_[ idx])); } break; } } } private void UpdateSplash(Action ret) { if (ret.ActionType == Action.Type.Tap) { if (isTuto_) isTuto_ = false; else onHelp_ = false; } } /// <summary> /// Update game and game components /// </summary> /// <param name="gameTime">Game clock</param> protected override void Update(GameTime gameTime) { base.Update(gameTime); Viewport.Instance.Update(); if (explosionMode_) { if (map_.NbExplosions == 0) { explosionMode_ = false; score_.EndOfTurn(hud_.TotalBombsNumber()); } } else if (!ended_) { if (hud_.GameInfos.Round <= 0) { ended_ = true; lose_ = true; } } Action ret; while ((ret = this.em_.GetEvents()).ActionType != Action.Type.NoEvent) { if (ended_) { UpdateEnd(ret); } else if (isTuto_ || onHelp_) { UpdateSplash(ret); } else { switch (ret.ActionType) { case Action.Type.NoEvent: break;/* case Action.Type.Drag: Viewport.Instance.AdjustPos(this.map_, ref ret.DeltaX, ref ret.DeltaY); Camera.Instance.OffX += ret.DeltaX; Camera.Instance.OffY += ret.DeltaY; break; case Action.Type.Pinch: { Viewport.Instance.HandlePinch(ret); break; }*/ case Action.Type.DragComplete: if (this.Selecter) this.Selecter = false; break; case Action.Type.Drag: {/* var hudEvent = this.hud_.GetHudEvent(ret.Pos); if (explosionMode_) continue; if (hudEvent != Hud.EHudAction.NoAction) { if (hudEvent == Hud.EHudAction.BombDetonation) { if (currentBomb_.Coord.X != -1) { this.map_.AddNewEntity(currentBomb_.Entity.ToBomb(), currentBomb_.Coord); currentBomb_.Coord.X = -1; currentBomb_.Coord.Y = -1; } map_.ActivateDetonators(); hud_.GameInfos.Round -= 1; if (hud_.GameInfos.Round <= 0) hud_.GameInfos.Round = 0; this.hud_.ResetBombset(); this.hud_.UnselectAll(); explosionMode_ = true; } else if (hudEvent == Hud.EHudAction.BombLock) { if (currentBomb_.Coord.X != -1) { var pattern = hud_.SelectedBombType(); this.map_.AddNewEntity(currentBomb_.Entity.ToBomb(), currentBomb_.Coord); hud_.RemoveBombOfType(pattern); currentBomb_.Coord.X = -1; currentBomb_.Coord.Y = -1; KaboomResources.Effects["DropBomb"].Play(); } } else if (hudEvent == Hud.EHudAction.Help) { onHelp_ = true; } else if (hudEvent == Hud.EHudAction.BombSelection) { if (currentBomb_.Coord.X != -1) map_.RemoveEntity(currentBomb_.Coord); currentBomb_.Coord.X = -1; currentBomb_.Coord.Y = -1; } } else { try { var pattern = hud_.SelectedBombType(); if (this.map_.GetCoordByPos(ret.Pos) == currentBomb_.Coord) { if (pattern != Pattern.Type.NoPattern && currentBomb_.Coord.X != -1) { currentBomb_.Entity.NextOrientation(); this.map_.AddNewEntity(currentBomb_.Entity, currentBomb_.Coord); } } else if (pattern != Pattern.Type.NoPattern) { if (currentBomb_.Coord.X != -1) map_.RemoveEntity(currentBomb_.Coord); currentBomb_.Coord = this.map_.GetCoordByPos(ret.Pos); currentBomb_.Entity = new VirtualBomb(pattern, KaboomResources.Sprites[ hud_.SelectedBombName()].Clone ()); if ( !(this.map_.AddNewEntity(currentBomb_.Entity, currentBomb_.Coord))) { currentBomb_.Coord.X = -1; currentBomb_.Coord.Y = -1; } } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { } }*/ try { if (this.Selecter == false) { var s = this.map_.GetCoordByPos(ret.Pos); this.selecterCoord_ = new Vector2( (s.X * Camera.Instance.DimX) + (Camera.Instance.DimX / 2), (s.Y * Camera.Instance.DimY) + (Camera.Instance.DimY / 2)); this.Selecter = true; } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { } break; } } } } if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { MediaPlayer.IsRepeating = false; MediaPlayer.Stop(); this.Exit(); } } protected bool Selecter { get { return selecterAnimation_.Enabled || this.selecterAnimation_.IsFading(); } set { this.selecterAnimation_.Enabled = value; if (value) this.selecterAnimation_.Start(); else this.selecterAnimation_.Stop(); } } /// <summary> /// Draw game components (Map) /// </summary> /// <param name="gameTime">Game clock</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); this.spriteBatch_.Begin(); this.spriteBatch_.Draw(KaboomResources.Textures["background4"], new Rectangle(0, 0, this.graphics_.PreferredBackBufferWidth, this.graphics_.PreferredBackBufferHeight), KaboomResources.Textures["background4"].Bounds, Color.White); this.spriteBatch_.End(); base.Draw(gameTime); if (this.Selecter) { this.spriteBatch_.Begin(); this.selecterAnimation_.Update(); this.spriteBatch_.Draw(KaboomResources.Textures["selecter"], new Vector2( this.selecterCoord_.X - (KaboomResources.Textures["selecter"].Bounds.Width * this.selecterAnimation_.Size / 2.0f) + Camera.Instance.OffX, this.selecterCoord_.Y - (KaboomResources.Textures["selecter"].Bounds.Height * this.selecterAnimation_.Size / 2.0f) + Camera.Instance.OffY), KaboomResources.Textures["selecter"].Bounds, Color.White, 0f, Vector2.Zero, this.selecterAnimation_.Size, SpriteEffects.None, 1); this.spriteBatch_.End(); } if (isTuto_) { this.spriteBatch_.Begin(); this.spriteBatch_.Draw(KaboomResources.Textures["Tuto"], new Rectangle((int)(this.graphics_.PreferredBackBufferWidth * 0.05), (int)(this.graphics_.PreferredBackBufferHeight * 0.05), (int)(this.graphics_.PreferredBackBufferWidth * 0.9), (int)(this.graphics_.PreferredBackBufferHeight * 0.9)), KaboomResources.Textures["Tuto"].Bounds, Color.White); this.spriteBatch_.End(); } else if (onHelp_) { this.spriteBatch_.Begin(); this.spriteBatch_.Draw(KaboomResources.Textures["helpScreen"], new Rectangle((int)(this.graphics_.PreferredBackBufferWidth * 0.05), (int)(this.graphics_.PreferredBackBufferHeight * 0.05), (int)(this.graphics_.PreferredBackBufferWidth * 0.9), (int)(this.graphics_.PreferredBackBufferHeight * 0.9)), KaboomResources.Textures["helpScreen"].Bounds, Color.White); this.spriteBatch_.End(); } if (ended_) { if (ladder_.IsDisplay) hud_.DrawLadder(gameTime, ladder_.GetLadder()); else hud_.DrawEnd(gameTime, lose_, ladder_.GetIdxOf("Player")); } } /// <summary> /// Handle the end of the game /// </summary> /// <param name="sender"></param> /// <param name="ea"></param> public void ManageEndGame(object sender, EventArgs ea) { score_.EndReached(hud_.RemainingTurns); if (ended_ == false) this.ladder_.AddEntry(this.hud_.GameInfos.Score.Score, "Player"); ended_ = true; } /// <summary> /// Activate Bombset in checkpoint /// </summary> public void BombSet(List<Hud.BombInfo> value) { this.hud_.BombSet = value; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>AssetGroupProductGroupView</c> resource.</summary> public sealed partial class AssetGroupProductGroupViewName : gax::IResourceName, sys::IEquatable<AssetGroupProductGroupViewName> { /// <summary>The possible contents of <see cref="AssetGroupProductGroupViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c>. /// </summary> CustomerAssetGroupListingGroupFilter = 1, } private static gax::PathTemplate s_customerAssetGroupListingGroupFilter = new gax::PathTemplate("customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id_listing_group_filter_id}"); /// <summary> /// Creates a <see cref="AssetGroupProductGroupViewName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AssetGroupProductGroupViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AssetGroupProductGroupViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AssetGroupProductGroupViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AssetGroupProductGroupViewName"/> with the pattern /// <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="listingGroupFilterId"> /// The <c>ListingGroupFilter</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// A new instance of <see cref="AssetGroupProductGroupViewName"/> constructed from the provided ids. /// </returns> public static AssetGroupProductGroupViewName FromCustomerAssetGroupListingGroupFilter(string customerId, string assetGroupId, string listingGroupFilterId) => new AssetGroupProductGroupViewName(ResourceNameType.CustomerAssetGroupListingGroupFilter, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)), listingGroupFilterId: gax::GaxPreconditions.CheckNotNullOrEmpty(listingGroupFilterId, nameof(listingGroupFilterId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AssetGroupProductGroupViewName"/> with /// pattern <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="listingGroupFilterId"> /// The <c>ListingGroupFilter</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="AssetGroupProductGroupViewName"/> with pattern /// <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c>. /// </returns> public static string Format(string customerId, string assetGroupId, string listingGroupFilterId) => FormatCustomerAssetGroupListingGroupFilter(customerId, assetGroupId, listingGroupFilterId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AssetGroupProductGroupViewName"/> with /// pattern <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c> /// . /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="listingGroupFilterId"> /// The <c>ListingGroupFilter</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="AssetGroupProductGroupViewName"/> with pattern /// <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c>. /// </returns> public static string FormatCustomerAssetGroupListingGroupFilter(string customerId, string assetGroupId, string listingGroupFilterId) => s_customerAssetGroupListingGroupFilter.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(listingGroupFilterId, nameof(listingGroupFilterId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="AssetGroupProductGroupViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="assetGroupProductGroupViewName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="AssetGroupProductGroupViewName"/> if successful.</returns> public static AssetGroupProductGroupViewName Parse(string assetGroupProductGroupViewName) => Parse(assetGroupProductGroupViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AssetGroupProductGroupViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="assetGroupProductGroupViewName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AssetGroupProductGroupViewName"/> if successful.</returns> public static AssetGroupProductGroupViewName Parse(string assetGroupProductGroupViewName, bool allowUnparsed) => TryParse(assetGroupProductGroupViewName, allowUnparsed, out AssetGroupProductGroupViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AssetGroupProductGroupViewName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="assetGroupProductGroupViewName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AssetGroupProductGroupViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string assetGroupProductGroupViewName, out AssetGroupProductGroupViewName result) => TryParse(assetGroupProductGroupViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AssetGroupProductGroupViewName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="assetGroupProductGroupViewName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AssetGroupProductGroupViewName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string assetGroupProductGroupViewName, bool allowUnparsed, out AssetGroupProductGroupViewName result) { gax::GaxPreconditions.CheckNotNull(assetGroupProductGroupViewName, nameof(assetGroupProductGroupViewName)); gax::TemplatedResourceName resourceName; if (s_customerAssetGroupListingGroupFilter.TryParseName(assetGroupProductGroupViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAssetGroupListingGroupFilter(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(assetGroupProductGroupViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AssetGroupProductGroupViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetGroupId = null, string customerId = null, string listingGroupFilterId = null) { Type = type; UnparsedResource = unparsedResourceName; AssetGroupId = assetGroupId; CustomerId = customerId; ListingGroupFilterId = listingGroupFilterId; } /// <summary> /// Constructs a new instance of a <see cref="AssetGroupProductGroupViewName"/> class from the component parts /// of pattern <c>customers/{customer_id}/assetGroupProductGroupViews/{asset_group_id}~{listing_group_filter_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetGroupId">The <c>AssetGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="listingGroupFilterId"> /// The <c>ListingGroupFilter</c> ID. Must not be <c>null</c> or empty. /// </param> public AssetGroupProductGroupViewName(string customerId, string assetGroupId, string listingGroupFilterId) : this(ResourceNameType.CustomerAssetGroupListingGroupFilter, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), assetGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetGroupId, nameof(assetGroupId)), listingGroupFilterId: gax::GaxPreconditions.CheckNotNullOrEmpty(listingGroupFilterId, nameof(listingGroupFilterId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AssetGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AssetGroupId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>ListingGroupFilter</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string ListingGroupFilterId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAssetGroupListingGroupFilter: return s_customerAssetGroupListingGroupFilter.Expand(CustomerId, $"{AssetGroupId}~{ListingGroupFilterId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AssetGroupProductGroupViewName); /// <inheritdoc/> public bool Equals(AssetGroupProductGroupViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AssetGroupProductGroupViewName a, AssetGroupProductGroupViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AssetGroupProductGroupViewName a, AssetGroupProductGroupViewName b) => !(a == b); } public partial class AssetGroupProductGroupView { /// <summary> /// <see cref="AssetGroupProductGroupViewName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal AssetGroupProductGroupViewName ResourceNameAsAssetGroupProductGroupViewName { get => string.IsNullOrEmpty(ResourceName) ? null : AssetGroupProductGroupViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
using System; using System.Xml; using System.Xml.Serialization; using dk.nita.saml20.Schema.XmlDSig; using dk.nita.saml20.Utils; namespace dk.nita.saml20.Schema.Metadata { /// <summary> /// The &lt;RoleDescriptor&gt; element is an abstract extension point that contains common descriptive /// information intended to provide processing commonality across different roles. New roles can be defined /// by extending its abstract RoleDescriptorType complex type /// </summary> [XmlInclude(typeof(AttributeAuthorityDescriptor))] [XmlInclude(typeof(PDPDescriptor))] [XmlInclude(typeof(AuthnAuthorityDescriptor))] [XmlInclude(typeof(SSODescriptor))] [XmlInclude(typeof(SPSSODescriptor))] [XmlInclude(typeof(IDPSSODescriptor))] [Serializable] [XmlType(Namespace=Saml20Constants.METADATA)] [XmlRoot(ELEMENT_NAME, Namespace=Saml20Constants.METADATA, IsNullable=false)] public abstract class RoleDescriptor { /// <summary> /// The XML Element name of this class /// </summary> public const string ELEMENT_NAME = "RoleDescriptor"; private Signature signatureField; private ExtensionsType1 extensionsField; private KeyDescriptor[] keyDescriptorField; private Organization organizationField; private Contact[] contactPersonField; private string idField; private DateTime? validUntilField; private string cacheDurationField; private string[] protocolSupportEnumerationField; private string errorURLField; private XmlAttribute[] anyAttrField; /// <summary> /// Gets or sets the signature. /// An XML signature that authenticates the containing element and its contents /// </summary> /// <value>The signature.</value> [XmlElementAttribute(Namespace=Saml20Constants.XMLDSIG)] public Signature Signature { get { return signatureField; } set { signatureField = value; } } /// <summary> /// Gets or sets the extensions. /// This contains optional metadata extensions that are agreed upon between a metadata publisher /// and consumer. Extension elements MUST be namespace-qualified by a non-SAML-defined /// namespace. /// </summary> /// <value>The extensions.</value> public ExtensionsType1 Extensions { get { return extensionsField; } set { extensionsField = value; } } /// <summary> /// Gets or sets the key descriptor. /// Optional sequence of elements that provides information about the cryptographic keys that the /// entity uses when acting in this role. /// </summary> /// <value>The key descriptor.</value> [XmlElementAttribute("KeyDescriptor")] public KeyDescriptor[] KeyDescriptor { get { return keyDescriptorField; } set { keyDescriptorField = value; } } /// <summary> /// Gets or sets the organization. /// Optional element specifies the organization associated with this role. Identical to the element used /// within the &lt;EntityDescriptor&gt; element. /// </summary> /// <value>The organization.</value> public Organization Organization { get { return organizationField; } set { organizationField = value; } } /// <summary> /// Gets or sets the contact person. /// Optional sequence of elements specifying contacts associated with this role. Identical to the /// element used within the &lt;EntityDescriptor&gt; element. /// </summary> /// <value>The contact person.</value> [XmlElementAttribute("ContactPerson")] public Contact[] ContactPerson { get { return contactPersonField; } set { contactPersonField = value; } } /// <summary> /// Gets or sets the ID. /// A document-unique identifier for the element, typically used as a reference point when signing. /// </summary> /// <value>The ID.</value> [XmlAttributeAttribute(DataType="ID")] public string ID { get { return idField; } set { idField = value; } } /// <summary> /// Gets or sets the valid until. /// Optional attribute indicates the expiration time of the metadata contained in the element and any /// contained elements. /// </summary> /// <value>The valid until.</value> [XmlIgnore] public DateTime? validUntil { get { return validUntilField; } set { validUntilField = value; } } /// <summary> /// Gets or sets the valid until string. /// </summary> /// <value>The valid until string.</value> [XmlAttribute("validUntil")] public string validUntilString { get { if (validUntilField.HasValue) return Saml20Utils.ToUTCString(validUntilField.Value); else return null; } set { if (string.IsNullOrEmpty(value)) validUntilField = null; else validUntilField = Saml20Utils.FromUTCString(value); } } /// <summary> /// Gets or sets the cache duration. /// Optional attribute indicates the maximum length of time a consumer should cache the metadata /// contained in the element and any contained elements. /// </summary> /// <value>The cache duration.</value> [XmlAttributeAttribute(DataType="duration")] public string cacheDuration { get { return cacheDurationField; } set { cacheDurationField = value; } } /// <summary> /// Gets or sets the protocol support enumeration. /// A whitespace-delimited set of URIs that identify the set of protocol specifications supported by the /// role element. For SAML V2.0 entities, this set MUST include the SAML protocol namespace URI, /// urn:oasis:names:tc:SAML:2.0:protocol. Note that future SAML specifications might /// share the same namespace URI, but SHOULD provide alternate "protocol support" identifiers to /// ensure discrimination when necessary. /// </summary> /// <value>The protocol support enumeration.</value> [XmlAttributeAttribute(DataType="anyURI")] public string[] protocolSupportEnumeration { get { return protocolSupportEnumerationField; } set { protocolSupportEnumerationField = value; } } /// <summary> /// Gets or sets the error URL. /// Optional URI attribute that specifies a location to direct a user for problem resolution and /// additional support related to this role. /// </summary> /// <value>The error URL.</value> [XmlAttributeAttribute(DataType="anyURI")] public string errorURL { get { return errorURLField; } set { errorURLField = value; } } /// <summary> /// Gets or sets any attr. /// </summary> /// <value>Any attr.</value> [XmlAnyAttributeAttribute] public XmlAttribute[] AnyAttr { get { return anyAttrField; } set { anyAttrField = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Collections.ObjectModel; namespace Eto.Forms { /// <summary> /// Control to present multiple pages with a tab selection /// </summary> /// <remarks> /// Some platforms (e.g. OS X) have limitations on how many tabs are visible. /// It is advised to utilize different methods (e.g. a listbox or combo box) to switch between many sections /// if there are too many tabs. /// </remarks> [ContentProperty("Pages")] [Handler(typeof(TabControl.IHandler))] public class TabControl : Container { TabPageCollection pages; new IHandler Handler { get { return (IHandler)base.Handler; } } /// <summary> /// Gets an enumeration of controls that are directly contained by this container /// </summary> /// <value>The contained controls.</value> public override IEnumerable<Control> Controls { get { return pages ?? Enumerable.Empty<Control>(); } } static readonly object SelectedIndexChangedEvent = new object(); /// <summary> /// Occurs when the <see cref="SelectedIndex"/> is changed. /// </summary> public event EventHandler<EventArgs> SelectedIndexChanged { add { Properties.AddEvent(SelectedIndexChangedEvent, value); } remove { Properties.RemoveEvent(SelectedIndexChangedEvent, value); } } /// <summary> /// Raises the <see cref="SelectedIndexChanged"/> event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnSelectedIndexChanged(EventArgs e) { Properties.TriggerEvent(SelectedIndexChangedEvent, this, e); var page = SelectedPage; if (page != null) page.TriggerClick(e); } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.TabControl"/> class. /// </summary> public TabControl() { } /// <summary> /// Initializes a new instance of the <see cref="Eto.Forms.TabControl"/> class with the specified handler. /// </summary> /// <param name="handler">Handler for the implementation of the tab control.</param> protected TabControl(IHandler handler) : base(handler) { } /// <summary> /// Gets or sets the index of the selected tab. /// </summary> /// <value>The index of the selected tab.</value> public int SelectedIndex { get { return Handler.SelectedIndex; } set { Handler.SelectedIndex = value; } } /// <summary> /// Gets or sets the currently selected page. /// </summary> /// <value>The selected page.</value> public TabPage SelectedPage { get { return SelectedIndex < 0 ? null : Pages[SelectedIndex]; } set { SelectedIndex = pages.IndexOf(value); } } /// <summary> /// Gets the collection of tab pages. /// </summary> /// <value>The pages.</value> public Collection<TabPage> Pages { get { return pages ?? (pages = new TabPageCollection(this)); } } /// <summary> /// Remove the specified child from the container. /// </summary> /// <param name="child">Child to remove.</param> public override void Remove(Control child) { var page = child as TabPage; if (page != null) { Pages.Remove(page); } } /// <summary> /// Gets or sets the position of the tabs relative to the content. /// </summary> /// <remarks> /// Note that on some platforms the text is rotated when using Left or Right (e.g. OS X). /// This means that is is not suitable when you have a lot of tabs. /// Some platforms (mobile) may ignore this hint and display the tabs according to the platform. /// </remarks> public DockPosition TabPosition { get { return Handler.TabPosition; } set { Handler.TabPosition = value; } } /// <summary> /// Gets the binding for the <see cref="SelectedIndex"/> property. /// </summary> /// <value>The selected index binding.</value> public BindableBinding<TabControl, int> SelectedIndexBinding { get { return new BindableBinding<TabControl, int>( this, c => c.SelectedIndex, (c, v) => c.SelectedIndex = v, (c, h) => c.SelectedIndexChanged += h, (c, h) => c.SelectedIndexChanged -= h ); } } class TabPageCollection : Collection<TabPage> { readonly TabControl control; internal TabPageCollection(TabControl control) { this.control = control; } protected override void InsertItem(int index, TabPage item) { base.InsertItem(index, item); control.SetParent(item, () => control.Handler.InsertTab(index, item)); } protected override void ClearItems() { var pages = this.ToArray(); for (int i = 0; i < pages.Length; i++) { control.Handler.RemoveTab(i, pages[i]); control.RemoveParent(pages[i]); } base.ClearItems(); } protected override void RemoveItem(int index) { var page = this[index]; control.Handler.RemoveTab(index, page); control.RemoveParent(page); base.RemoveItem(index); } } #region Callback static readonly object callback = new Callback(); /// <summary> /// Gets an instance of an object used to perform callbacks to the widget from handler implementations /// </summary> /// <returns>The callback instance to use for this widget</returns> protected override object GetCallback() { return callback; } /// <summary> /// Callback interface for the <see cref="TabControl"/> /// </summary> public new interface ICallback : Control.ICallback { /// <summary> /// Raises the selected index changed event. /// </summary> void OnSelectedIndexChanged(TabControl widget, EventArgs e); } /// <summary> /// Callback implementation for handlers of the <see cref="TabControl"/> /// </summary> protected new class Callback : Control.Callback, ICallback { /// <summary> /// Raises the selected index changed event. /// </summary> public void OnSelectedIndexChanged(TabControl widget, EventArgs e) { widget.Platform.Invoke(() => widget.OnSelectedIndexChanged(e)); } } #endregion #region Handler /// <summary> /// Handler interface for the <see cref="TabControl"/> /// </summary> public new interface IHandler : Container.IHandler { /// <summary> /// Gets or sets the index of the selected tab. /// </summary> /// <value>The index of the selected tab.</value> int SelectedIndex { get; set; } /// <summary> /// Inserts a tab at the specified index. /// </summary> /// <param name="index">Index to insert the tab.</param> /// <param name="page">Page to insert.</param> void InsertTab(int index, TabPage page); /// <summary> /// Removes all tabs from the control. /// </summary> void ClearTabs(); /// <summary> /// Removes the specified tab. /// </summary> /// <param name="index">Index of the page to remove.</param> /// <param name="page">Page to remove.</param> void RemoveTab(int index, TabPage page); /// <summary> /// Gets or sets the position of the tabs relative to the content. /// </summary> DockPosition TabPosition { get; set; } } #endregion } }
// 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.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature { [ExportLanguageService(typeof(AbstractChangeSignatureService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureService { private static readonly ImmutableArray<SyntaxKind> _invokableAncestorKinds = ImmutableArray.Create( SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.NameMemberCref, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.DelegateDeclaration); private static readonly ImmutableArray<SyntaxKind> _invokableAncestorInDeclarationKinds = _invokableAncestorKinds.AddRange( ImmutableArray.Create(SyntaxKind.Block, SyntaxKind.ArrowExpressionClause)); public override async Task<ISymbol> GetInvocationSymbolAsync( Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position != tree.Length ? position : Math.Max(0, position - 1)); // Allow the user to invoke Change-Sig if they've written: Foo(a, b, c);$$ if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent is StatementSyntax) { token = token.GetPreviousToken(); position = token.Span.End; } var ancestorDeclarationKinds = restrictToDeclarations ? _invokableAncestorInDeclarationKinds : _invokableAncestorKinds; var matchingNode = token.Parent.AncestorsAndSelf().FirstOrDefault(n => ancestorDeclarationKinds.Contains(n.Kind())); // If we walked up and we hit a block/expression-body, then we didn't find anything // viable to reorder. Just bail here. This helps prevent Change-sig from appearing // too aggressively inside method bodies. if (matchingNode == null || matchingNode.IsKind(SyntaxKind.Block) || matchingNode.IsKind(SyntaxKind.ArrowExpressionClause)) { return null; } // Don't show change-signature in the random whitespace/trivia for code. if (!matchingNode.Span.IntersectsWith(position)) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = semanticModel.GetDeclaredSymbol(matchingNode, cancellationToken); if (symbol != null) { // If we're actually on the declaration of some symbol, ensure that we're // in a good location for that symbol (i.e. not in the attributes/constraints). return restrictToDeclarations && !InSymbolHeader(matchingNode, position) ? null : symbol; } if (matchingNode.IsKind(SyntaxKind.ObjectCreationExpression)) { var objectCreation = matchingNode as ObjectCreationExpressionSyntax; if (token.Parent.AncestorsAndSelf().Any(a => a == objectCreation.Type)) { var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol; if (typeSymbol != null && typeSymbol.IsKind(SymbolKind.NamedType) && (typeSymbol as ITypeSymbol).TypeKind == TypeKind.Delegate) { return typeSymbol; } } } var symbolInfo = semanticModel.GetSymbolInfo(matchingNode, cancellationToken); return symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault(); } private bool InSymbolHeader(SyntaxNode matchingNode, int position) { // Caret has to be after the attributes if the symbol has any. var lastAttributes = matchingNode.ChildNodes().LastOrDefault(n => n is AttributeListSyntax); var start = lastAttributes?.GetLastToken().GetNextToken().SpanStart ?? matchingNode.SpanStart; if (position < start) { return false; } // If the symbol has a parameter list, then the caret shouldn't be past the end of it. var parameterList = matchingNode.ChildNodes().LastOrDefault(n => n is ParameterListSyntax); if (parameterList != null) { return position <= parameterList.FullSpan.End; } // Case we haven't handled yet. Just assume we're in the header. return true; } private ImmutableArray<SyntaxKind> _updatableAncestorKinds = new[] { SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.DelegateDeclaration, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.NameMemberCref }.ToImmutableArray(); private ImmutableArray<SyntaxKind> _updatableNodeKinds = new[] { SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.DelegateDeclaration, SyntaxKind.NameMemberCref, SyntaxKind.AnonymousMethodExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.SimpleLambdaExpression }.ToImmutableArray(); public override SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node) { if (_updatableNodeKinds.Contains(node.Kind())) { return node; } // TODO: file bug about this: var invocation = csnode.Ancestors().FirstOrDefault(a => a.Kind == SyntaxKind.InvocationExpression); var matchingNode = node.AncestorsAndSelf().FirstOrDefault(n => _updatableAncestorKinds.Contains(n.Kind())); if (matchingNode == null) { return null; } var nodeContainingOriginal = GetNodeContainingTargetNode(matchingNode); if (nodeContainingOriginal == null) { return null; } return node.AncestorsAndSelf().Any(n => n == nodeContainingOriginal) ? matchingNode : null; } private SyntaxNode GetNodeContainingTargetNode(SyntaxNode matchingNode) { switch (matchingNode.Kind()) { case SyntaxKind.InvocationExpression: return (matchingNode as InvocationExpressionSyntax).Expression; case SyntaxKind.ElementAccessExpression: return (matchingNode as ElementAccessExpressionSyntax).ArgumentList; case SyntaxKind.ObjectCreationExpression: return (matchingNode as ObjectCreationExpressionSyntax).Type; case SyntaxKind.ConstructorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.Attribute: case SyntaxKind.DelegateDeclaration: case SyntaxKind.NameMemberCref: return matchingNode; default: return null; } } public override SyntaxNode ChangeSignature( Document document, ISymbol declarationSymbol, SyntaxNode potentiallyUpdatedNode, SyntaxNode originalNode, SignatureChange signaturePermutation, CancellationToken cancellationToken) { var updatedNode = potentiallyUpdatedNode as CSharpSyntaxNode; // Update <param> tags. if (updatedNode.IsKind(SyntaxKind.MethodDeclaration) || updatedNode.IsKind(SyntaxKind.ConstructorDeclaration) || updatedNode.IsKind(SyntaxKind.IndexerDeclaration) || updatedNode.IsKind(SyntaxKind.DelegateDeclaration)) { var updatedLeadingTrivia = UpdateParamTagsInLeadingTrivia(updatedNode, declarationSymbol, signaturePermutation); if (updatedLeadingTrivia != null) { updatedNode = updatedNode.WithLeadingTrivia(updatedLeadingTrivia); } } // Update declarations parameter lists if (updatedNode.IsKind(SyntaxKind.MethodDeclaration)) { var method = updatedNode as MethodDeclarationSyntax; var updatedParameters = PermuteDeclaration(method.ParameterList.Parameters, signaturePermutation); return method.WithParameterList(method.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = updatedNode as ConstructorDeclarationSyntax; var updatedParameters = PermuteDeclaration(constructor.ParameterList.Parameters, signaturePermutation); return constructor.WithParameterList(constructor.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.IndexerDeclaration)) { var indexer = updatedNode as IndexerDeclarationSyntax; var updatedParameters = PermuteDeclaration(indexer.ParameterList.Parameters, signaturePermutation); return indexer.WithParameterList(indexer.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.DelegateDeclaration)) { var delegateDeclaration = updatedNode as DelegateDeclarationSyntax; var updatedParameters = PermuteDeclaration(delegateDeclaration.ParameterList.Parameters, signaturePermutation); return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.AnonymousMethodExpression)) { var anonymousMethod = updatedNode as AnonymousMethodExpressionSyntax; // Delegates may omit parameters in C# if (anonymousMethod.ParameterList == null) { return anonymousMethod; } var updatedParameters = PermuteDeclaration(anonymousMethod.ParameterList.Parameters, signaturePermutation); return anonymousMethod.WithParameterList(anonymousMethod.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.SimpleLambdaExpression)) { var lambda = updatedNode as SimpleLambdaExpressionSyntax; if (signaturePermutation.UpdatedConfiguration.ToListOfParameters().Any()) { Debug.Assert(false, "Updating a simple lambda expression without removing its parameter"); } else { // No parameters. Change to a parenthesized lambda expression var emptyParameterList = SyntaxFactory.ParameterList() .WithLeadingTrivia(lambda.Parameter.GetLeadingTrivia()) .WithTrailingTrivia(lambda.Parameter.GetTrailingTrivia()); return SyntaxFactory.ParenthesizedLambdaExpression(lambda.AsyncKeyword, emptyParameterList, lambda.ArrowToken, lambda.Body); } } if (updatedNode.IsKind(SyntaxKind.ParenthesizedLambdaExpression)) { var lambda = updatedNode as ParenthesizedLambdaExpressionSyntax; var updatedParameters = PermuteDeclaration(lambda.ParameterList.Parameters, signaturePermutation); return lambda.WithParameterList(lambda.ParameterList.WithParameters(updatedParameters)); } // Update reference site argument lists if (updatedNode.IsKind(SyntaxKind.InvocationExpression)) { var invocation = updatedNode as InvocationExpressionSyntax; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var symbolInfo = semanticModel.GetSymbolInfo(originalNode as InvocationExpressionSyntax, cancellationToken); var methodSymbol = symbolInfo.Symbol as IMethodSymbol; var isReducedExtensionMethod = false; if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ReducedExtension) { isReducedExtensionMethod = true; } var newArguments = PermuteArgumentList(document, declarationSymbol, invocation.ArgumentList.Arguments, signaturePermutation, isReducedExtensionMethod); return invocation.WithArgumentList(invocation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ObjectCreationExpression)) { var objCreation = updatedNode as ObjectCreationExpressionSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation); return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ThisConstructorInitializer) || updatedNode.IsKind(SyntaxKind.BaseConstructorInitializer)) { var objCreation = updatedNode as ConstructorInitializerSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation); return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ElementAccessExpression)) { var elementAccess = updatedNode as ElementAccessExpressionSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, elementAccess.ArgumentList.Arguments, signaturePermutation); return elementAccess.WithArgumentList(elementAccess.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.Attribute)) { var attribute = updatedNode as AttributeSyntax; var newArguments = PermuteAttributeArgumentList(document, declarationSymbol, attribute.ArgumentList.Arguments, signaturePermutation); return attribute.WithArgumentList(attribute.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } // Handle references in crefs if (updatedNode.IsKind(SyntaxKind.NameMemberCref)) { var nameMemberCref = updatedNode as NameMemberCrefSyntax; if (nameMemberCref.Parameters == null || !nameMemberCref.Parameters.Parameters.Any()) { return nameMemberCref; } var newParameters = PermuteDeclaration(nameMemberCref.Parameters.Parameters, signaturePermutation); var newCrefParameterList = nameMemberCref.Parameters.WithParameters(newParameters); return nameMemberCref.WithParameters(newCrefParameterList); } Debug.Assert(false, "Unknown reference location"); return null; } private SeparatedSyntaxList<T> PermuteDeclaration<T>(SeparatedSyntaxList<T> list, SignatureChange updatedSignature) where T : SyntaxNode { var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var newParameters = new List<T>(); foreach (var newParam in reorderedParameters) { var pos = originalParameters.IndexOf(newParam); var param = list[pos]; newParameters.Add(param); } var numSeparatorsToSkip = originalParameters.Count - reorderedParameters.Count; return SyntaxFactory.SeparatedList(newParameters, GetSeparators(list, numSeparatorsToSkip)); } private static SeparatedSyntaxList<AttributeArgumentSyntax> PermuteAttributeArgumentList( Document document, ISymbol declarationSymbol, SeparatedSyntaxList<AttributeArgumentSyntax> arguments, SignatureChange updatedSignature) { var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature); var numSeparatorsToSkip = arguments.Count - newArguments.Count; return SyntaxFactory.SeparatedList(newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip)); } private static SeparatedSyntaxList<ArgumentSyntax> PermuteArgumentList( Document document, ISymbol declarationSymbol, SeparatedSyntaxList<ArgumentSyntax> arguments, SignatureChange updatedSignature, bool isReducedExtensionMethod = false) { var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature, isReducedExtensionMethod); var numSeparatorsToSkip = arguments.Count - newArguments.Count; return SyntaxFactory.SeparatedList(newArguments.Select(a => (ArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip)); } private List<SyntaxTrivia> UpdateParamTagsInLeadingTrivia(CSharpSyntaxNode node, ISymbol declarationSymbol, SignatureChange updatedSignature) { if (!node.HasLeadingTrivia) { return null; } var paramNodes = node .DescendantNodes(descendIntoTrivia: true) .OfType<XmlElementSyntax>() .Where(e => e.StartTag.Name.ToString() == DocumentationCommentXmlNames.ParameterElementName); var permutedParamNodes = VerifyAndPermuteParamNodes(paramNodes, declarationSymbol, updatedSignature); if (permutedParamNodes == null) { return null; } return GetPermutedTrivia(node, permutedParamNodes); } private List<XmlElementSyntax> VerifyAndPermuteParamNodes(IEnumerable<XmlElementSyntax> paramNodes, ISymbol declarationSymbol, SignatureChange updatedSignature) { // Only reorder if count and order match originally. var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var declaredParameters = declarationSymbol.GetParameters(); if (paramNodes.Count() != declaredParameters.Count()) { return null; } var dictionary = new Dictionary<string, XmlElementSyntax>(); int i = 0; foreach (var paramNode in paramNodes) { var nameAttribute = paramNode.StartTag.Attributes.FirstOrDefault(a => a.Name.ToString().Equals("name", StringComparison.OrdinalIgnoreCase)); if (nameAttribute == null) { return null; } var identifier = nameAttribute.DescendantNodes(descendIntoTrivia: true).OfType<IdentifierNameSyntax>().FirstOrDefault(); if (identifier == null || identifier.ToString() != declaredParameters.ElementAt(i).Name) { return null; } dictionary.Add(originalParameters[i].Name.ToString(), paramNode); i++; } // Everything lines up, so permute them. var permutedParams = new List<XmlElementSyntax>(); foreach (var parameter in reorderedParameters) { permutedParams.Add(dictionary[parameter.Name]); } return permutedParams; } private List<SyntaxTrivia> GetPermutedTrivia(CSharpSyntaxNode node, List<XmlElementSyntax> permutedParamNodes) { var updatedLeadingTrivia = new List<SyntaxTrivia>(); var index = 0; foreach (var trivia in node.GetLeadingTrivia()) { if (!trivia.HasStructure) { updatedLeadingTrivia.Add(trivia); continue; } var structuredTrivia = trivia.GetStructure() as DocumentationCommentTriviaSyntax; if (structuredTrivia == null) { updatedLeadingTrivia.Add(trivia); continue; } var updatedNodeList = new List<XmlNodeSyntax>(); var structuredContent = structuredTrivia.Content.ToList(); for (int i = 0; i < structuredContent.Count; i++) { var content = structuredContent[i]; if (!content.IsKind(SyntaxKind.XmlElement)) { updatedNodeList.Add(content); continue; } var xmlElement = content as XmlElementSyntax; if (xmlElement.StartTag.Name.ToString() != DocumentationCommentXmlNames.ParameterElementName) { updatedNodeList.Add(content); continue; } // Found a param tag, so insert the next one from the reordered list if (index < permutedParamNodes.Count) { updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia())); index++; } else { // Inspecting a param element that we are deleting but not replacing. } } var newDocComments = SyntaxFactory.DocumentationCommentTrivia(structuredTrivia.Kind(), SyntaxFactory.List(updatedNodeList.AsEnumerable())); newDocComments = newDocComments.WithEndOfComment(structuredTrivia.EndOfComment); newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia()); var newTrivia = SyntaxFactory.Trivia(newDocComments); updatedLeadingTrivia.Add(newTrivia); } return updatedLeadingTrivia; } private static List<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip = 0) where T : SyntaxNode { var separators = new List<SyntaxToken>(); for (int i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++) { separators.Add(arguments.GetSeparator(i)); } return separators; } public override async Task<ImmutableArray<SymbolAndProjectId>> DetermineCascadedSymbolsFromDelegateInvoke( SymbolAndProjectId<IMethodSymbol> symbolAndProjectId, Document document, CancellationToken cancellationToken) { var symbol = symbolAndProjectId.Symbol; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var nodes = root.DescendantNodes().ToImmutableArray(); var convertedMethodGroups = nodes .WhereAsArray( n => { if (!n.IsKind(SyntaxKind.IdentifierName) || !semanticModel.GetMemberGroup(n, cancellationToken).Any()) { return false; } ISymbol convertedType = semanticModel.GetTypeInfo(n, cancellationToken).ConvertedType; if (convertedType != null) { convertedType = convertedType.OriginalDefinition; } if (convertedType != null) { convertedType = SymbolFinder.FindSourceDefinitionAsync(convertedType, document.Project.Solution, cancellationToken).WaitAndGetResult(cancellationToken) ?? convertedType; } return convertedType == symbol.ContainingType; }) .SelectAsArray(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol); return convertedMethodGroups.SelectAsArray(symbolAndProjectId.WithSymbol); } protected override IEnumerable<IFormattingRule> GetFormattingRules(Document document) { return new[] { new ChangeSignatureFormattingRule() }.Concat(Formatter.GetDefaultFormattingRules(document)); } } }
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.IrDAAddress // // Copyright (c) 2003-2020 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License using System; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Diagnostics.CodeAnalysis; namespace InTheHand.Net { /// <summary> /// Represents an IrDA device address. /// </summary> public sealed class IrDAAddress : IComparable, IFormattable { const int AddressBytesLength = 4; // Currently there are no Properties that change the content of this type // so currently it is non-mutable. If we wanted a mutable type, then we // have to be careful of the 'const' "None" value, as a user could change // it, and then other uses would *not* be None... readonly byte[] data; internal IrDAAddress() { data = new byte[AddressBytesLength]; } /// <summary> /// Initializes a new instance of the <see cref="IrDAAddress"/> class with the specified address. /// </summary> /// <param name="address">Address as 4 byte array.</param> /// <exception cref="ArgumentNullException"><paramref name="address"/> was null.</exception> /// <exception cref="ArgumentException"><paramref name="address"/> was not a 4 byte array.</exception> public IrDAAddress(byte[] address) { if (address == null) { throw new ArgumentNullException("address"); } if (address.Length != AddressBytesLength) { throw new ArgumentException("Address bytes array must be four bytes in size."); } data = (byte[])address.Clone(); } /// <summary> /// Initializes a new instance of the <see cref="IrDAAddress"/> class with the specified address. /// </summary> /// <param name="address"><see cref="int"/> representation of the address.</param> public IrDAAddress(int address) { data = new byte[4]; BitConverter.GetBytes(address).CopyTo(data,0); } /// <summary> /// Returns the IrDA address as an integer. /// </summary> /// - /// <returns>An <see cref="int"/>.</returns> public int ToInt32() { return BitConverter.ToInt32(data, 0); } /// <summary> /// Returns the internal byte array. /// </summary> /// - /// <returns>An array of <see cref="T:System.Byte"/>.</returns> public byte[] ToByteArray() { return (byte[])data.Clone(); } /// <summary> /// Converts the string representation of an address to it's <see cref="IrDAAddress"/> equivalent. /// A return value indicates whether the operation succeeded. /// </summary> /// <param name="s">A string containing an address to convert.</param> /// <param name="result">When this method returns, contains the <see cref="IrDAAddress"/> equivalent to the address contained in s, if the conversion succeeded, or null (Nothing in Visual Basic) if the conversion failed. /// The conversion fails if the s parameter is null or is not of the correct format.</param> /// <returns>true if s is a valid IrDA address; otherwise, false.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "TrParse pattern.")] public static bool TryParse(string s, out IrDAAddress result) { try { result = Parse(s); return true; } catch { result = null; return false; } } /// <summary> /// Converts the string representation of an IrDA address to a new <see cref="IrDAAddress"/> instance. /// </summary> /// <param name="irdaString">A string containing an address to convert.</param> /// <returns>New <see cref="IrDAAddress"/> instance.</returns> /// <remarks>Address must be specified in hex format optionally separated by the colon or period character e.g. 00000000, 00:00:00:00 or 00.00.00.00.</remarks> /// <exception cref="T:System.ArgumentNullException">irdaString is null.</exception> /// <exception cref="T:System.FormatException">irdaString is not a valid IrDA address.</exception> public static IrDAAddress Parse(string irdaString) { if (irdaString == null) { throw new ArgumentNullException("irdaString"); } IrDAAddress ia; if (irdaString.IndexOf(":", StringComparison.Ordinal) > -1) { // assume address in colon separated hex format 00:00:00:00 // check length if (irdaString.Length != 11) { throw new FormatException("irdaString is not a valid IrDA address."); } byte[] iabytes = new byte[AddressBytesLength]; // split on colons string[] sbytes = irdaString.Split(':'); for (int ibyte = 0; ibyte < iabytes.Length; ibyte++) { // parse hex byte in reverse order iabytes[ibyte] = byte.Parse(sbytes[3 - ibyte], NumberStyles.HexNumber); } ia = new IrDAAddress(iabytes); } else if (irdaString.IndexOf(".", StringComparison.Ordinal) > -1) { // assume address in uri hex format 00.00.00.00 // check length if (irdaString.Length != 11) { throw new FormatException("irdaString is not a valid IrDA address."); } byte[] iabytes = new byte[AddressBytesLength]; // split on colons string[] sbytes = irdaString.Split('.'); for (int ibyte = 0; ibyte < iabytes.Length; ibyte++) { // parse hex byte in reverse order iabytes[ibyte] = byte.Parse(sbytes[3 - ibyte], NumberStyles.HexNumber, CultureInfo.InvariantCulture); } ia = new IrDAAddress(iabytes); } else { // assume specified as integer // check length if ((irdaString.Length < 4) | (irdaString.Length > 8)) { throw new FormatException("irdaString is not a valid IrDA address."); } ia = new IrDAAddress(int.Parse(irdaString, NumberStyles.HexNumber, CultureInfo.InvariantCulture)); } return ia; } /// <summary> /// Converts the address to its equivalent string representation. /// </summary> /// <returns>The string representation of this instance.</returns> public override string ToString() { return ToString("N"); } /// <summary> /// Returns a <see cref="string"/> representation of the value of this <see cref="IrDAAddress"/> instance, according to the provided format specifier. /// </summary> /// <param name="format">A single format specifier that indicates how to format the value of this Guid. The format parameter can be "N", "C" or "P". If format is null or the empty string (""), "N" is used.</param> /// <returns>A <see cref="string"/> representation of the value of this <see cref="BluetoothAddress"/>.</returns> /// <remarks><list type="table"> /// <listheader><term>Specifier</term><term>Format of Return Value </term></listheader> /// <item><term>N</term><term>8 digits: <para>XXXXXXXX</para></term></item> /// <item><term>C</term><term>8 digits separated by colons: <para>XX:XX:XX:XX</para></term></item> /// <item><term>P</term><term>8 digits separated by periods: <para>XX.XX.XX.XX</para></term></item> /// </list></remarks> public string ToString(string format) { string separator; if (string.IsNullOrEmpty(format)) { separator = string.Empty; } else { // FxCop notes: "Warning, Avoid unnecessary string creation" due to this. // It is compiled as a series of if/else statments... switch(format.ToUpper()) { case "N": separator = string.Empty; break; case "C": separator = ":"; break; case "P": separator = "."; break; default: throw new FormatException("Invalid format specified - must be either \"N\", \"C\", \"P\", \"\" or null."); } } System.Text.StringBuilder result = new System.Text.StringBuilder(18); result.Append(data[3].ToString("X2") + separator); result.Append(data[2].ToString("X2") + separator); result.Append(data[1].ToString("X2") + separator); result.Append(data[0].ToString("X2")); return result.ToString(); } /// <summary> /// Compares two <see cref="IrDAAddress"/> instances for equality. /// </summary> /// - /// <param name="obj">The <see cref="IrDAAddress"/> /// to compare with the current instance. /// </param> /// - /// <returns><c>true</c> if <paramref name="obj"/> /// is a <see cref="IrDAAddress"/> and equal to the current instance; /// otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { IrDAAddress ira = obj as IrDAAddress; if (ira != null) { return (this == ira); } return base.Equals(obj); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { return ToInt32().GetHashCode(); } /// <summary> /// Returns an indication whether the values of two specified <see cref="IrDAAddress"/> objects are equal. /// </summary> /// - /// <param name="x">A <see cref="IrDAAddress"/> or <see langword="null"/>.</param> /// <param name="y">A <see cref="IrDAAddress"/> or <see langword="null"/>.</param> /// - /// <returns><c>true</c> if the values of the two instance are equal; /// otherwise, <c>false</c>. /// </returns> public static bool operator ==(IrDAAddress x, IrDAAddress y) { if ((x is null) && (y is null)) { return true; } if ((x is object) && (y is object)) { if(x.ToInt32() == y.ToInt32()) { return true; } } return false; } /// <summary> /// Returns an indication whether the values of two specified <see cref="IrDAAddress"/> objects are not equal. /// </summary> /// - /// <param name="x">A <see cref="IrDAAddress"/> or <see langword="null"/>.</param> /// <param name="y">A <see cref="IrDAAddress"/> or <see langword="null"/>.</param> /// - /// <returns><c>true</c> if the value of the two instance is different; /// otherwise, <c>false</c>. /// </returns> public static bool operator !=(IrDAAddress x, IrDAAddress y) { return !(x == y); } /// <summary> /// Provides a null IrDA address. /// </summary> #if CODE_ANALYSIS [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Is now immutable.")] #endif public static readonly IrDAAddress None = new IrDAAddress(); /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> int IComparable.CompareTo(object obj) { IrDAAddress irda = obj as IrDAAddress; if (irda != null) { return ToInt32().CompareTo(irda.ToInt32()); } return -1; } /// <summary> /// Returns a <see cref="string"/> representation of the value of this <see cref="IrDAAddress"/> instance, according to the provided format specifier. /// </summary> /// <param name="format">A single format specifier that indicates how to format the value of this Guid. /// The format parameter can be "N", "C" or "P". If format is null or the empty string (""), "N" is used.</param> /// <param name="formatProvider">Ignored.</param> /// - /// <returns>A <see cref="string"/> representation of the value of this <see cref="IrDAAddress"/>.</returns> /// - /// <remarks>See <see cref="M:InTheHand.Net.IrDAAddress.ToString(System.String)"/> /// for the possible format strings and their output. /// </remarks> public string ToString(string format, IFormatProvider formatProvider) { return ToString(format); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Runtime; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics; using Internal.Reflection.Augments; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; namespace System { // WARNING: Bartok hard-codes offsets to the delegate fields, so it's notion of where fields are may // differ from the runtime's notion. Bartok honors sequential and explicit layout directives, so I've // ordered the fields in such a way as to match the runtime's layout and then just tacked on this // sequential layout directive so that Bartok matches it. [StructLayout(LayoutKind.Sequential)] [DebuggerDisplay("Target method(s) = {GetTargetMethodsDescriptionForDebugger()}")] public abstract partial class Delegate : ICloneable, ISerializable { // This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a // "protected-and-internal" rather than "internal" but C# has no keyword for the former. internal Delegate() { // ! Do NOT put any code here. Delegate constructers are not guaranteed to be executed. } // V1 API: Create closed instance delegates. Method name matching is case sensitive. protected Delegate(Object target, String method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal // implementation of CreateDelegate below, and does not invoke this constructor. // The constructor is just for API compatibility with the public contract of the Delegate class. throw new PlatformNotSupportedException(); } // V1 API: Create open static delegates. Method name matching is case insensitive. protected Delegate(Type target, String method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal // implementation of CreateDelegate below, and does not invoke this constructor. // The constructor is just for API compatibility with the public contract of the Delegate class. throw new PlatformNotSupportedException(); } // New Delegate Implementation protected internal object m_firstParameter; protected internal object m_helperObject; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")] protected internal IntPtr m_extraFunctionPointerOrData; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")] protected internal IntPtr m_functionPointer; [ThreadStatic] protected static string s_DefaultValueString; // WARNING: These constants are also declared in System.Private.TypeLoader\Internal\Runtime\TypeLoader\CallConverterThunk.cs // Do not change their values without updating the values in the calling convention converter component protected const int MulticastThunk = 0; protected const int ClosedStaticThunk = 1; protected const int OpenStaticThunk = 2; protected const int ClosedInstanceThunkOverGenericMethod = 3; // This may not exist protected const int DelegateInvokeThunk = 4; protected const int OpenInstanceThunk = 5; // This may not exist protected const int ReversePinvokeThunk = 6; // This may not exist protected const int ObjectArrayThunk = 7; // This may not exist // // If the thunk does not exist, the function will return IntPtr.Zero. protected virtual IntPtr GetThunk(int whichThunk) { #if DEBUG // The GetThunk function should be overriden on all delegate types, except for universal // canonical delegates which use calling convention converter thunks to marshal arguments // for the delegate call. If we execute this version of GetThunk, we can at least assert // that the current delegate type is a generic type. Debug.Assert(this.EETypePtr.IsGeneric); #endif return TypeLoaderExports.GetDelegateThunk(this, whichThunk); } // // If there is a default value string, the overridden function should set the // s_DefaultValueString field and return true. protected virtual bool LoadDefaultValueString() { return false; } /// <summary> /// Used by various parts of the runtime as a replacement for Delegate.Method /// /// The Interop layer uses this to distinguish between different methods on a /// single type, and to get the function pointer for delegates to static functions /// /// The reflection apis use this api to figure out what MethodInfo is related /// to a delegate. /// /// </summary> /// <param name="typeOfFirstParameterIfInstanceDelegate"> /// This value indicates which type an delegate's function pointer is associated with /// This value is ONLY set for delegates where the function pointer points at an instance method /// </param> /// <param name="isOpenResolver"> /// This value indicates if the returned pointer is an open resolver structure. /// </param> /// <returns></returns> unsafe internal IntPtr GetFunctionPointer(out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate, out bool isOpenResolver) { typeOfFirstParameterIfInstanceDelegate = default(RuntimeTypeHandle); isOpenResolver = false; if (GetThunk(MulticastThunk) == m_functionPointer) { return IntPtr.Zero; } else if (m_extraFunctionPointerOrData != IntPtr.Zero) { if (GetThunk(OpenInstanceThunk) == m_functionPointer) { typeOfFirstParameterIfInstanceDelegate = ((OpenMethodResolver*)m_extraFunctionPointerOrData)->DeclaringType; isOpenResolver = true; } return m_extraFunctionPointerOrData; } else { if (m_firstParameter != null) typeOfFirstParameterIfInstanceDelegate = new RuntimeTypeHandle(m_firstParameter.EETypePtr); // TODO! Implementation issue for generic invokes here ... we need another IntPtr for uniqueness. return m_functionPointer; } } // @todo: Not an api but some NativeThreadPool code still depends on it. internal IntPtr GetNativeFunctionPointer() { if (GetThunk(ReversePinvokeThunk) != m_functionPointer) { throw new InvalidOperationException("GetNativeFunctionPointer may only be used on a reverse pinvoke delegate"); } return m_extraFunctionPointerOrData; } // This function is known to the IL Transformer. protected void InitializeClosedInstance(object firstParameter, IntPtr functionPointer) { if (firstParameter == null) throw new ArgumentException(SR.Arg_DlgtNullInst); m_functionPointer = functionPointer; m_firstParameter = firstParameter; } // This function is known to the IL Transformer. protected void InitializeClosedInstanceSlow(object firstParameter, IntPtr functionPointer) { // This method is like InitializeClosedInstance, but it handles ALL cases. In particular, it handles generic method with fun function pointers. if (firstParameter == null) throw new ArgumentException(SR.Arg_DlgtNullInst); if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer)) { m_functionPointer = functionPointer; m_firstParameter = firstParameter; } else { m_firstParameter = this; m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod); m_extraFunctionPointerOrData = functionPointer; m_helperObject = firstParameter; } } // This function is known to the compiler. protected void InitializeClosedInstanceWithGVMResolution(object firstParameter, RuntimeMethodHandle tokenOfGenericVirtualMethod) { if (firstParameter == null) throw new ArgumentException(SR.Arg_DlgtNullInst); IntPtr functionResolution = TypeLoaderExports.GVMLookupForSlot(firstParameter, tokenOfGenericVirtualMethod); if (functionResolution == IntPtr.Zero) { // TODO! What to do when GVM resolution fails. Should never happen throw new InvalidOperationException(); } if (!FunctionPointerOps.IsGenericMethodPointer(functionResolution)) { m_functionPointer = functionResolution; m_firstParameter = firstParameter; } else { m_firstParameter = this; m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod); m_extraFunctionPointerOrData = functionResolution; m_helperObject = firstParameter; } return; } private void InitializeClosedInstanceToInterface(object firstParameter, IntPtr dispatchCell) { if (firstParameter == null) throw new ArgumentException(SR.Arg_DlgtNullInst); m_functionPointer = RuntimeImports.RhpResolveInterfaceMethod(firstParameter, dispatchCell); m_firstParameter = firstParameter; } // This is used to implement MethodInfo.CreateDelegate() in a desktop-compatible way. Yes, the desktop really // let you use that api to invoke an instance method with a null 'this'. private void InitializeClosedInstanceWithoutNullCheck(object firstParameter, IntPtr functionPointer) { if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer)) { m_functionPointer = functionPointer; m_firstParameter = firstParameter; } else { m_firstParameter = this; m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod); m_extraFunctionPointerOrData = functionPointer; m_helperObject = firstParameter; } } // This function is known to the compiler backend. protected void InitializeClosedStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { m_extraFunctionPointerOrData = functionPointer; m_helperObject = firstParameter; m_functionPointer = functionPointerThunk; m_firstParameter = this; } // This function is known to the compiler backend. protected void InitializeClosedStaticWithoutThunk(object firstParameter, IntPtr functionPointer) { m_extraFunctionPointerOrData = functionPointer; m_helperObject = firstParameter; m_functionPointer = GetThunk(ClosedStaticThunk); m_firstParameter = this; } // This function is known to the compiler backend. protected void InitializeOpenStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = functionPointerThunk; m_extraFunctionPointerOrData = functionPointer; } // This function is known to the compiler backend. protected void InitializeOpenStaticWithoutThunk(object firstParameter, IntPtr functionPointer) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = GetThunk(OpenStaticThunk); m_extraFunctionPointerOrData = functionPointer; } // This function is known to the compiler backend. protected void InitializeReversePInvokeThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = functionPointerThunk; m_extraFunctionPointerOrData = functionPointer; } // This function is known to the compiler backend. protected void InitializeReversePInvokeWithoutThunk(object firstParameter, IntPtr functionPointer) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = GetThunk(ReversePinvokeThunk); m_extraFunctionPointerOrData = functionPointer; } // This function is known to the compiler backend. protected void InitializeOpenInstanceThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = functionPointerThunk; OpenMethodResolver instanceMethodResolver = new OpenMethodResolver(default(RuntimeTypeHandle), functionPointer, default(GCHandle), 0); m_extraFunctionPointerOrData = instanceMethodResolver.ToIntPtr(); } // This function is known to the compiler backend. protected void InitializeOpenInstanceWithoutThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = GetThunk(OpenInstanceThunk); OpenMethodResolver instanceMethodResolver = new OpenMethodResolver(default(RuntimeTypeHandle), functionPointer, default(GCHandle), 0); m_extraFunctionPointerOrData = instanceMethodResolver.ToIntPtr(); } protected void InitializeOpenInstanceThunkDynamic(IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = functionPointerThunk; m_extraFunctionPointerOrData = functionPointer; } internal void SetClosedStaticFirstParameter(object firstParameter) { // Closed static delegates place a value in m_helperObject that they pass to the target method. Debug.Assert(m_functionPointer == GetThunk(ClosedStaticThunk)); m_helperObject = firstParameter; } // This function is only ever called by the open instance method thunk, and in that case, // m_extraFunctionPointerOrData always points to an OpenMethodResolver [MethodImpl(MethodImplOptions.NoInlining)] protected IntPtr GetActualTargetFunctionPointer(object thisObject) { return OpenMethodResolver.ResolveMethod(m_extraFunctionPointerOrData, thisObject); } public override int GetHashCode() { return GetType().GetHashCode(); } private bool IsDynamicDelegate() { if (this.GetThunk(MulticastThunk) == IntPtr.Zero) { return true; } return false; } [DebuggerGuidedStepThroughAttribute] protected virtual object DynamicInvokeImpl(object[] args) { if (IsDynamicDelegate()) { // DynamicDelegate case object result = ((Func<object[], object>)m_helperObject)(args); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); return result; } else { IntPtr invokeThunk = this.GetThunk(DelegateInvokeThunk); object result = System.InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, this, invokeThunk, IntPtr.Zero, this, args, binderBundle: null); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); return result; } } [DebuggerGuidedStepThroughAttribute] public object DynamicInvoke(params object[] args) { object result = DynamicInvokeImpl(args); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); return result; } public static unsafe Delegate Combine(Delegate a, Delegate b) { if (a == null) return b; if (b == null) return a; return a.CombineImpl(b); } public static Delegate Remove(Delegate source, Delegate value) { if (source == null) return null; if (value == null) return source; if (!InternalEqualTypes(source, value)) throw new ArgumentException(SR.Arg_DlgtTypeMis); return source.RemoveImpl(value); } public static Delegate RemoveAll(Delegate source, Delegate value) { Delegate newDelegate = null; do { newDelegate = source; source = Remove(source, value); } while (newDelegate != source); return newDelegate; } // Used to support the C# compiler in implementing the "+" operator for delegates public static Delegate Combine(params Delegate[] delegates) { if ((delegates == null) || (delegates.Length == 0)) return null; Delegate d = delegates[0]; for (int i = 1; i < delegates.Length; i++) { d = Combine(d, delegates[i]); } return d; } private MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount, bool thisIsMultiCastAlready) { // First, allocate a new multicast delegate just like this one, i.e. same type as the this object MulticastDelegate result = (MulticastDelegate)RuntimeImports.RhNewObject(this.EETypePtr); // Performance optimization - if this already points to a true multicast delegate, // copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them if (thisIsMultiCastAlready) { result.m_functionPointer = this.m_functionPointer; } else { result.m_functionPointer = GetThunk(MulticastThunk); } result.m_firstParameter = result; result.m_helperObject = invocationList; result.m_extraFunctionPointerOrData = (IntPtr)invocationCount; return result; } internal MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount) { return NewMulticastDelegate(invocationList, invocationCount, false); } private bool TrySetSlot(Delegate[] a, int index, Delegate o) { if (a[index] == null && System.Threading.Interlocked.CompareExchange<Delegate>(ref a[index], o, null) == null) return true; // The slot may be already set because we have added and removed the same method before. // Optimize this case, because it's cheaper than copying the array. if (a[index] != null) { MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)a[index]; if (Object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) && Object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) && dd.m_extraFunctionPointerOrData == d.m_extraFunctionPointerOrData && dd.m_functionPointer == d.m_functionPointer) { return true; } } return false; } // This method will combine this delegate with the passed delegate // to form a new delegate. protected virtual Delegate CombineImpl(Delegate follow) { if ((Object)follow == null) // cast to object for a more efficient test return this; // Verify that the types are the same... if (!InternalEqualTypes(this, follow)) throw new ArgumentException(); if (IsDynamicDelegate() && follow.IsDynamicDelegate()) { throw new InvalidOperationException(); } MulticastDelegate dFollow = (MulticastDelegate)follow; Delegate[] resultList; int followCount = 1; Delegate[] followList = dFollow.m_helperObject as Delegate[]; if (followList != null) followCount = (int)dFollow.m_extraFunctionPointerOrData; int resultCount; Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList == null) { resultCount = 1 + followCount; resultList = new Delegate[resultCount]; resultList[0] = this; if (followList == null) { resultList[1] = dFollow; } else { for (int i = 0; i < followCount; i++) resultList[1 + i] = followList[i]; } return NewMulticastDelegate(resultList, resultCount); } else { int invocationCount = (int)m_extraFunctionPointerOrData; resultCount = invocationCount + followCount; resultList = null; if (resultCount <= invocationList.Length) { resultList = invocationList; if (followList == null) { if (!TrySetSlot(resultList, invocationCount, dFollow)) resultList = null; } else { for (int i = 0; i < followCount; i++) { if (!TrySetSlot(resultList, invocationCount + i, followList[i])) { resultList = null; break; } } } } if (resultList == null) { int allocCount = invocationList.Length; while (allocCount < resultCount) allocCount *= 2; resultList = new Delegate[allocCount]; for (int i = 0; i < invocationCount; i++) resultList[i] = invocationList[i]; if (followList == null) { resultList[invocationCount] = dFollow; } else { for (int i = 0; i < followCount; i++) resultList[invocationCount + i] = followList[i]; } } return NewMulticastDelegate(resultList, resultCount, true); } } private Delegate[] DeleteFromInvocationList(Delegate[] invocationList, int invocationCount, int deleteIndex, int deleteCount) { Delegate[] thisInvocationList = m_helperObject as Delegate[]; int allocCount = thisInvocationList.Length; while (allocCount / 2 >= invocationCount - deleteCount) allocCount /= 2; Delegate[] newInvocationList = new Delegate[allocCount]; for (int i = 0; i < deleteIndex; i++) newInvocationList[i] = invocationList[i]; for (int i = deleteIndex + deleteCount; i < invocationCount; i++) newInvocationList[i - deleteCount] = invocationList[i]; return newInvocationList; } private bool EqualInvocationLists(Delegate[] a, Delegate[] b, int start, int count) { for (int i = 0; i < count; i++) { if (!(a[start + i].Equals(b[i]))) return false; } return true; } // This method currently looks backward on the invocation list // for an element that has Delegate based equality with value. (Doesn't // look at the invocation list.) If this is found we remove it from // this list and return a new delegate. If its not found a copy of the // current list is returned. protected virtual Delegate RemoveImpl(Delegate value) { // There is a special case were we are removing using a delegate as // the value we need to check for this case // MulticastDelegate v = value as MulticastDelegate; if (v == null) return this; if (v.m_helperObject as Delegate[] == null) { Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList == null) { // they are both not real Multicast if (this.Equals(value)) return null; } else { int invocationCount = (int)m_extraFunctionPointerOrData; for (int i = invocationCount; --i >= 0;) { if (value.Equals(invocationList[i])) { if (invocationCount == 2) { // Special case - only one value left, either at the beginning or the end return invocationList[1 - i]; } else { Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1); return NewMulticastDelegate(list, invocationCount - 1, true); } } } } } else { Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList != null) { int invocationCount = (int)m_extraFunctionPointerOrData; int vInvocationCount = (int)v.m_extraFunctionPointerOrData; for (int i = invocationCount - vInvocationCount; i >= 0; i--) { if (EqualInvocationLists(invocationList, v.m_helperObject as Delegate[], i, vInvocationCount)) { if (invocationCount - vInvocationCount == 0) { // Special case - no values left return null; } else if (invocationCount - vInvocationCount == 1) { // Special case - only one value left, either at the beginning or the end return invocationList[i != 0 ? 0 : invocationCount - 1]; } else { Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount); return NewMulticastDelegate(list, invocationCount - vInvocationCount, true); } } } } } return this; } public virtual Delegate[] GetInvocationList() { Delegate[] del; Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList == null) { del = new Delegate[1]; del[0] = this; } else { // Create an array of delegate copies and each // element into the array int invocationCount = (int)m_extraFunctionPointerOrData; del = new Delegate[invocationCount]; for (int i = 0; i < del.Length; i++) del[i] = invocationList[i]; } return del; } public MethodInfo Method { get { return GetMethodImpl(); } } protected virtual MethodInfo GetMethodImpl() { return RuntimeAugments.Callbacks.GetDelegateMethod(this); } public override bool Equals(Object obj) { // It is expected that all real uses of the Equals method will hit the MulticastDelegate.Equals logic instead of this // therefore, instead of duplicating the desktop behavior where direct calls to this Equals function do not behave // correctly, we'll just throw here. throw new PlatformNotSupportedException(); } public static bool operator ==(Delegate d1, Delegate d2) { if ((Object)d1 == null) return (Object)d2 == null; return d1.Equals(d2); } public static bool operator !=(Delegate d1, Delegate d2) { if ((Object)d1 == null) return (Object)d2 != null; return !d1.Equals(d2); } public Object Target { get { // Multi-cast delegates return the Target of the last delegate in the list if (m_functionPointer == GetThunk(MulticastThunk)) { Delegate[] invocationList = (Delegate[])m_helperObject; int invocationCount = (int)m_extraFunctionPointerOrData; return invocationList[invocationCount - 1].Target; } // Closed static delegates place a value in m_helperObject that they pass to the target method. if (m_functionPointer == GetThunk(ClosedStaticThunk) || m_functionPointer == GetThunk(ClosedInstanceThunkOverGenericMethod) || m_functionPointer == GetThunk(ObjectArrayThunk)) return m_helperObject; // Other non-closed thunks can be identified as the m_firstParameter field points at this. if (Object.ReferenceEquals(m_firstParameter, this)) { return null; } // Closed instance delegates place a value in m_firstParameter, and we've ruled out all other types of delegates return m_firstParameter; } } // V2 api: Creates open or closed delegates to static or instance methods - relaxed signature checking allowed. public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method) => CreateDelegate(type, firstArgument, method, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, firstArgument, method, throwOnBindFailure); // V1 api: Creates open delegates to static or instance methods - relaxed signature checking allowed. public static Delegate CreateDelegate(Type type, MethodInfo method) => CreateDelegate(type, method, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, method, throwOnBindFailure); // V1 api: Creates closed delegates to instance methods only, relaxed signature checking disallowed. public static Delegate CreateDelegate(Type type, object target, string method) => CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase) => CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure); // V1 api: Creates open delegates to static methods only, relaxed signature checking disallowed. public static Delegate CreateDelegate(Type type, Type target, string method) => CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase) => CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure); public virtual object Clone() { return MemberwiseClone(); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(); } internal bool IsOpenStatic { get { return GetThunk(OpenStaticThunk) == m_functionPointer; } } internal static bool InternalEqualTypes(object a, object b) { return a.EETypePtr == b.EETypePtr; } // Returns a new delegate of the specified type whose implementation is provied by the // provided delegate. internal static Delegate CreateObjectArrayDelegate(Type t, Func<object[], object> handler) { EETypePtr delegateEEType; if (!t.TryGetEEType(out delegateEEType)) { throw new InvalidOperationException(); } if (!delegateEEType.IsDefType || delegateEEType.IsGenericTypeDefinition) { throw new InvalidOperationException(); } Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType)); IntPtr objArrayThunk = del.GetThunk(Delegate.ObjectArrayThunk); if (objArrayThunk == IntPtr.Zero) { throw new InvalidOperationException(); } del.m_helperObject = handler; del.m_functionPointer = objArrayThunk; del.m_firstParameter = del; return del; } // // Internal (and quite unsafe) helper to create delegates of an arbitrary type. This is used to support Reflection invoke. // // Note that delegates constructed the normal way do not come through here. The IL transformer generates the equivalent of // this code customized for each delegate type. // internal static Delegate CreateDelegate(EETypePtr delegateEEType, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isOpen) { Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType)); // What? No constructor call? That's right, and it's not an oversight. All "construction" work happens in // the Initialize() methods. This helper has a hard dependency on this invariant. if (isStatic) { if (isOpen) { IntPtr thunk = del.GetThunk(Delegate.OpenStaticThunk); del.InitializeOpenStaticThunk(null, ldftnResult, thunk); } else { IntPtr thunk = del.GetThunk(Delegate.ClosedStaticThunk); del.InitializeClosedStaticThunk(thisObject, ldftnResult, thunk); } } else { if (isOpen) { IntPtr thunk = del.GetThunk(Delegate.OpenInstanceThunk); del.InitializeOpenInstanceThunkDynamic(ldftnResult, thunk); } else { del.InitializeClosedInstanceWithoutNullCheck(thisObject, ldftnResult); } } return del; } private string GetTargetMethodsDescriptionForDebugger() { if (m_functionPointer == GetThunk(MulticastThunk)) { // Multi-cast delegates return the Target of the last delegate in the list Delegate[] invocationList = (Delegate[])m_helperObject; int invocationCount = (int)m_extraFunctionPointerOrData; StringBuilder builder = new StringBuilder(); for (int c = 0; c < invocationCount; c++) { if (c != 0) builder.Append(", "); builder.Append(invocationList[c].GetTargetMethodsDescriptionForDebugger()); } return builder.ToString(); } else { RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate; bool isOpenThunk; IntPtr functionPointer = GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out isOpenThunk); if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer)) { return DebuggerFunctionPointerFormattingHook(functionPointer, typeOfFirstParameterIfInstanceDelegate); } else { unsafe { GenericMethodDescriptor* pointerDef = FunctionPointerOps.ConvertToGenericDescriptor(functionPointer); return DebuggerFunctionPointerFormattingHook(pointerDef->InstantiationArgument, typeOfFirstParameterIfInstanceDelegate); } } } } private static string DebuggerFunctionPointerFormattingHook(IntPtr functionPointer, RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate) { // This method will be hooked by the debugger and the debugger will cause it to return a description for the function pointer throw new NotSupportedException(); } } }
//BSD, 2014-present, WinterDev //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // [email protected] // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: [email protected] // [email protected] // http://www.antigrain.com //---------------------------------------------------------------------------- // // class bspline // //---------------------------------------------------------------------------- namespace PixelFarm.CpuBlit.VertexProcessing { //----------------------------------------------------------------bspline // A very simple class of Bi-cubic Spline interpolation. // First call init(num, x[], y[]) where num - number of source points, // x, y - arrays of X and Y values respectively. Here Y must be a function // of X. It means that all the X-coordinates must be arranged in the ascending // order. // Then call get(x) that calculates a value Y for the respective X. // The class supports extrapolation, i.e. you can call get(x) where x is // outside the given with init() X-range. Extrapolation is a simple linear // function. //------------------------------------------------------------------------ public sealed class BSpline { int _max; int _num; int _xOffset; int _yOffset; double[] _am = new double[16]; int _last_idx; //------------------------------------------------------------------------ public BSpline() { _max = (0); _num = (0); _xOffset = (0); _yOffset = (0); _last_idx = -1; } //------------------------------------------------------------------------ public BSpline(int num) { _max = (0); _num = (0); _xOffset = (0); _yOffset = (0); _last_idx = -1; Init(num); } //------------------------------------------------------------------------ public BSpline(int num, double[] x, double[] y) { _max = (0); _num = (0); _xOffset = (0); _yOffset = (0); _last_idx = -1; Init(num, x, y); } //------------------------------------------------------------------------ void Init(int max) { if (max > 2 && max > _max) { _am = new double[max * 3]; _max = max; _xOffset = _max; _yOffset = _max * 2; } _num = 0; _last_idx = -1; } //------------------------------------------------------------------------ public void AddPoint(double x, double y) { if (_num < _max) { _am[_xOffset + _num] = x; _am[_yOffset + _num] = y; ++_num; } } //------------------------------------------------------------------------ public void Prepare() { if (_num > 2) { int i, k; int r; int s; double h, p, d, f, e; for (k = 0; k < _num; k++) { _am[k] = 0.0; } int n1 = 3 * _num; double[] al = new double[n1]; for (k = 0; k < n1; k++) { al[k] = 0.0; } r = _num; s = _num * 2; n1 = _num - 1; d = _am[_xOffset + 1] - _am[_xOffset + 0]; e = (_am[_yOffset + 1] - _am[_yOffset + 0]) / d; for (k = 1; k < n1; k++) { h = d; d = _am[_xOffset + k + 1] - _am[_xOffset + k]; f = e; e = (_am[_yOffset + k + 1] - _am[_yOffset + k]) / d; al[k] = d / (d + h); al[r + k] = 1.0 - al[k]; al[s + k] = 6.0 * (e - f) / (h + d); } for (k = 1; k < n1; k++) { p = 1.0 / (al[r + k] * al[k - 1] + 2.0); al[k] *= -p; al[s + k] = (al[s + k] - al[r + k] * al[s + k - 1]) * p; } _am[n1] = 0.0; al[n1 - 1] = al[s + n1 - 1]; _am[n1 - 1] = al[n1 - 1]; for (k = n1 - 2, i = 0; i < _num - 2; i++, k--) { al[k] = al[k] * al[k + 1] + al[s + k]; _am[k] = al[k]; } } _last_idx = -1; } //------------------------------------------------------------------------ void Init(int num, double[] x, double[] y) { if (num > 2) { Init(num); int i; for (i = 0; i < num; i++) { AddPoint(x[i], y[i]); } Prepare(); } _last_idx = -1; } //------------------------------------------------------------------------ void BSearch(int n, int xOffset, double x0, out int i) { int j = n - 1; int k; for (i = 0; (j - i) > 1;) { k = (i + j) >> 1; if (x0 < _am[xOffset + k]) j = k; else i = k; } } //------------------------------------------------------------------------ double Interpolate(double x, int i) { int j = i + 1; double d = _am[_xOffset + i] - _am[_xOffset + j]; double h = x - _am[_xOffset + j]; double r = _am[_xOffset + i] - x; double p = d * d / 6.0; return (_am[j] * r * r * r + _am[i] * h * h * h) / 6.0 / d + ((_am[_yOffset + j] - _am[j] * p) * r + (_am[_yOffset + i] - _am[i] * p) * h) / d; } //------------------------------------------------------------------------ double ExtrapolateLeft(double x) { double d = _am[_xOffset + 1] - _am[_xOffset + 0]; return (-d * _am[1] / 6 + (_am[_yOffset + 1] - _am[_yOffset + 0]) / d) * (x - _am[_xOffset + 0]) + _am[_yOffset + 0]; } //------------------------------------------------------------------------ double ExtrapolateRight(double x) { double d = _am[_xOffset + _num - 1] - _am[_xOffset + _num - 2]; return (d * _am[_num - 2] / 6 + (_am[_yOffset + _num - 1] - _am[_yOffset + _num - 2]) / d) * (x - _am[_xOffset + _num - 1]) + _am[_yOffset + _num - 1]; } //------------------------------------------------------------------------ public double Get(double x) { if (_num > 2) { int i; // Extrapolation on the left if (x < _am[_xOffset + 0]) return ExtrapolateLeft(x); // Extrapolation on the right if (x >= _am[_xOffset + _num - 1]) return ExtrapolateRight(x); // Interpolation BSearch(_num, _xOffset, x, out i); return Interpolate(x, i); } return 0.0; } //------------------------------------------------------------------------ public double GetStateful(double x) { if (_num > 2) { // Extrapolation on the left if (x < _am[_xOffset + 0]) return ExtrapolateLeft(x); // Extrapolation on the right if (x >= _am[_xOffset + _num - 1]) return ExtrapolateRight(x); if (_last_idx >= 0) { // Check if x is not in current range if (x < _am[_xOffset + _last_idx] || x > _am[_xOffset + _last_idx + 1]) { // Check if x between next points (most probably) if (_last_idx < _num - 2 && x >= _am[_xOffset + _last_idx + 1] && x <= _am[_xOffset + _last_idx + 2]) { ++_last_idx; } else if (_last_idx > 0 && x >= _am[_xOffset + _last_idx - 1] && x <= _am[_xOffset + _last_idx]) { // x is between pevious points --_last_idx; } else { // Else perform full search BSearch(_num, _xOffset, x, out _last_idx); } } return Interpolate(x, _last_idx); } else { // Interpolation BSearch(_num, _xOffset, x, out _last_idx); return Interpolate(x, _last_idx); } } return 0.0; } } }
// *********************************************************************** // Copyright (c) 2014-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Reflection; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Builders { /// <summary> /// NUnitTestFixtureBuilder is able to build a fixture given /// a class marked with a TestFixtureAttribute or an unmarked /// class containing test methods. In the first case, it is /// called by the attribute and in the second directly by /// NUnitSuiteBuilder. /// </summary> public class NUnitTestFixtureBuilder { #region Static Fields static readonly string NO_TYPE_ARGS_MSG = "Fixture type contains generic parameters. You must either provide " + "Type arguments or specify constructor arguments that allow NUnit " + "to deduce the Type arguments."; #endregion #region Instance Fields private ITestCaseBuilder _testBuilder = new DefaultTestCaseBuilder(); #endregion #region Public Methods /// <summary> /// Build a TestFixture from type provided. A non-null TestSuite /// must always be returned, since the method is generally called /// because the user has marked the target class as a fixture. /// If something prevents the fixture from being used, it should /// be returned nonetheless, labelled as non-runnable. /// </summary> /// <param name="typeInfo">An ITypeInfo for the fixture to be used.</param> /// <returns>A TestSuite object or one derived from TestSuite.</returns> // TODO: This should really return a TestFixture, but that requires changes to the Test hierarchy. public TestSuite BuildFrom(ITypeInfo typeInfo) { var fixture = new TestFixture(typeInfo); if (fixture.RunState != RunState.NotRunnable) CheckTestFixtureIsValid(fixture); fixture.ApplyAttributesToTest(typeInfo.Type); AddTestCasesToFixture(fixture); return fixture; } /// <summary> /// Overload of BuildFrom called by tests that have arguments. /// Builds a fixture using the provided type and information /// in the ITestFixtureData object. /// </summary> /// <param name="typeInfo">The TypeInfo for which to construct a fixture.</param> /// <param name="testFixtureData">An object implementing ITestFixtureData or null.</param> /// <returns></returns> public TestSuite BuildFrom(ITypeInfo typeInfo, ITestFixtureData testFixtureData) { Guard.ArgumentNotNull(testFixtureData, "testFixtureData"); object[] arguments = testFixtureData.Arguments; if (typeInfo.ContainsGenericParameters) { Type[] typeArgs = testFixtureData.TypeArgs; if (typeArgs.Length == 0) { int cnt = 0; foreach (object o in arguments) if (o is Type) cnt++; else break; typeArgs = new Type[cnt]; for (int i = 0; i < cnt; i++) typeArgs[i] = (Type)arguments[i]; if (cnt > 0) { object[] args = new object[arguments.Length - cnt]; for (int i = 0; i < args.Length; i++) args[i] = arguments[cnt + i]; arguments = args; } } if (typeArgs.Length > 0 || TypeHelper.CanDeduceTypeArgsFromArgs(typeInfo.Type, arguments, ref typeArgs)) { typeInfo = typeInfo.MakeGenericType(typeArgs); } } var fixture = new TestFixture(typeInfo); if (arguments != null && arguments.Length > 0) { string name = fixture.Name = typeInfo.GetDisplayName(arguments); string nspace = typeInfo.Namespace; fixture.FullName = nspace != null && nspace != "" ? nspace + "." + name : name; fixture.Arguments = arguments; } if (fixture.RunState != RunState.NotRunnable) fixture.RunState = testFixtureData.RunState; foreach (string key in testFixtureData.Properties.Keys) foreach (object val in testFixtureData.Properties[key]) fixture.Properties.Add(key, val); if (fixture.RunState != RunState.NotRunnable) CheckTestFixtureIsValid(fixture); fixture.ApplyAttributesToTest(typeInfo.Type); AddTestCasesToFixture(fixture); return fixture; } #endregion #region Helper Methods /// <summary> /// Method to add test cases to the newly constructed fixture. /// </summary> /// <param name="fixture">The fixture to which cases should be added</param> private void AddTestCasesToFixture(TestFixture fixture) { // TODO: Check this logic added from Neil's build. if (fixture.TypeInfo.ContainsGenericParameters) { fixture.RunState = RunState.NotRunnable; fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG); return; } var methods = fixture.TypeInfo.GetMethods( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (IMethodInfo method in methods) { Test test = BuildTestCase(method, fixture); if (test != null) { fixture.Add(test); } } } /// <summary> /// Method to create a test case from a MethodInfo and add /// it to the fixture being built. It first checks to see if /// any global TestCaseBuilder addin wants to build the /// test case. If not, it uses the internal builder /// collection maintained by this fixture builder. /// /// The default implementation has no test case builders. /// Derived classes should add builders to the collection /// in their constructor. /// </summary> /// <param name="method">The method for which a test is to be created</param> /// <param name="suite">The test suite being built.</param> /// <returns>A newly constructed Test</returns> private Test BuildTestCase(IMethodInfo method, TestSuite suite) { return _testBuilder.CanBuildFrom(method, suite) ? _testBuilder.BuildFrom(method, suite) : null; } private static void CheckTestFixtureIsValid(TestFixture fixture) { if (fixture.TypeInfo.ContainsGenericParameters) { fixture.RunState = RunState.NotRunnable; fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG); } else if (!fixture.TypeInfo.IsStaticClass) { object[] args = fixture.Arguments; Type[] argTypes; // Note: This could be done more simply using // Type.EmptyTypes and Type.GetTypeArray() but // they don't exist in all runtimes we support. argTypes = new Type[args.Length]; int index = 0; foreach (object arg in args) argTypes[index++] = arg.GetType(); if (!fixture.TypeInfo.HasConstructor(argTypes)) { fixture.RunState = RunState.NotRunnable; fixture.Properties.Set(PropertyNames.SkipReason, "No suitable constructor was found"); } } } private static bool IsStaticClass(Type type) { return type.IsAbstract && type.IsSealed; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed partial class ExpressionBinder { //////////////////////////////////////////////////////////////////////////////// // This table is used to implement the last set of 'better' conversion rules // when there are no implicit conversions between T1(down) and T2 (across) // Use all the simple types plus 1 more for Object // See CLR section 7.4.1.3 private static readonly byte[][] s_betterConversionTable = { // BYTE SHORT INT LONG FLOAT DOUBLE DECIMAL CHAR BOOL SBYTE USHORT UINT ULONG IPTR UIPTR OBJECT new byte[] /* BYTE*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0}, new byte[] /* SHORT*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, new byte[] /* INT*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0}, new byte[] /* LONG*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, new byte[] /* FLOAT*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new byte[] /* DOUBLE*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new byte[] /* DECIMAL*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new byte[] /* CHAR*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new byte[] /* BOOL*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new byte[] /* SBYTE*/ {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, new byte[] /* USHORT*/ {0, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0}, new byte[] /* UINT*/ {0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0}, new byte[] /* ULONG*/ {0, 2, 2, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0}, new byte[] /* IPTR*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new byte[] /* UIPTR*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new byte[] /* OBJECT*/ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; private BetterType WhichMethodIsBetterTieBreaker( CandidateFunctionMember node1, CandidateFunctionMember node2, CType pTypeThrough, ArgInfos args) { MethPropWithInst mpwi1 = node1.mpwi; MethPropWithInst mpwi2 = node2.mpwi; // Same signatures. If they have different lifting numbers, the smaller number wins. // Otherwise, if one is generic and the other isn't then the non-generic wins. // Otherwise, if one is expanded and the other isn't then the non-expanded wins. // Otherwise, if one has fewer modopts than the other then it wins. if (node1.ctypeLift != node2.ctypeLift) { return node1.ctypeLift < node2.ctypeLift ? BetterType.Left : BetterType.Right; } // Non-generic wins. if (mpwi1.TypeArgs.Count != 0) { if (mpwi2.TypeArgs.Count == 0) { return BetterType.Right; } } else if (mpwi2.TypeArgs.Count != 0) { return BetterType.Left; } // Non-expanded wins if (node1.fExpanded) { if (!node2.fExpanded) { return BetterType.Right; } } else if (node2.fExpanded) { return BetterType.Left; } // See if one's parameter types (un-instantiated) are more specific. BetterType nT = GetGlobalSymbols().CompareTypes( RearrangeNamedArguments(mpwi1.MethProp().Params, mpwi1, pTypeThrough, args), RearrangeNamedArguments(mpwi2.MethProp().Params, mpwi2, pTypeThrough, args)); if (nT == BetterType.Left || nT == BetterType.Right) { return nT; } // Fewer modopts wins. if (mpwi1.MethProp().modOptCount != mpwi2.MethProp().modOptCount) { return mpwi1.MethProp().modOptCount < mpwi2.MethProp().modOptCount ? BetterType.Left : BetterType.Right; } // Bona-fide tie. return BetterType.Neither; } //////////////////////////////////////////////////////////////////////////////// // Find the index of a name on a list. // There is no failure case; we require that the name actually // be on the list private static int FindName(List<Name> names, Name name) { int index = names.IndexOf(name); Debug.Assert(index != -1); return index; } //////////////////////////////////////////////////////////////////////////////// // We need to rearange the method parameters so that the type of any specified named argument // appears in the same place as the named argument. Consider the example below: // Foo(int x = 4, string y = "", long l = 4) // Foo(string y = "", string x="", long l = 5) // and the call site: // Foo(y:"a") // After rearranging the parameter types we will have: // (string, int, long) and (string, string, long) // By rearranging the arguments as such we make sure that any specified named arguments appear in the same position for both // methods and we also maintain the relative order of the other parameters (the type long appears after int in the above example) private TypeArray RearrangeNamedArguments(TypeArray pta, MethPropWithInst mpwi, CType pTypeThrough, ArgInfos args) { if (!args.fHasExprs) { return pta; } #if DEBUG // We never have a named argument that is in a position in the argument // list past the end of what would be the formal parameter list. for (int i = pta.Count; i < args.carg; i++) { Debug.Assert(!(args.prgexpr[i] is ExprNamedArgumentSpecification)); } #endif CType type = pTypeThrough != null ? pTypeThrough : mpwi.GetType(); CType[] typeList = new CType[pta.Count]; MethodOrPropertySymbol methProp = GroupToArgsBinder.FindMostDerivedMethod(GetSymbolLoader(), mpwi.MethProp(), type); // We initialize the new type array with the parameters for the method. for (int iParam = 0; iParam < pta.Count; iParam++) { typeList[iParam] = pta[iParam]; } var prgexpr = args.prgexpr; // We then go over the specified arguments and put the type for any named argument in the right position in the array. for (int iParam = 0; iParam < args.carg; iParam++) { if (prgexpr[iParam] is ExprNamedArgumentSpecification named) { // We find the index of the type of the argument in the method parameter list and store that in a temp int index = FindName(methProp.ParameterNames, named.Name); CType tempType = pta[index]; // Starting from the current position in the type list up until the location of the type of the optional argument // We shift types by one: // before: (int, string, long) // after: (string, int, long) // We only touch the types between the current position and the position of the type we need to move for (int iShift = iParam; iShift < index; iShift++) { typeList[iShift + 1] = typeList[iShift]; } typeList[iParam] = tempType; } } return GetSymbolLoader().getBSymmgr().AllocParams(pta.Count, typeList); } //////////////////////////////////////////////////////////////////////////////// // Determine which method is better for the purposes of overload resolution. // Better means: as least as good in all params, and better in at least one param. // Better w/r to a param means is an ordering, from best down: // 1) same type as argument // 2) implicit conversion from argument to formal type // Because of user defined conversion opers this relation is not transitive. // // If there is a tie because of identical signatures, the tie may be broken by the // following rules: // 1) If one is generic and the other isn't, the non-generic wins. // 2) Otherwise if one is expanded (params) and the other isn't, the non-expanded wins. // 3) Otherwise if one has more specific parameter types (at the declaration) it wins: // This occurs if at least on parameter type is more specific and no parameter type is // less specific. //* A type parameter is less specific than a non-type parameter. //* A constructed type is more specific than another constructed type if at least // one type argument is more specific and no type argument is less specific than // the corresponding type args in the other. // 4) Otherwise if one has more modopts than the other does, the smaller number of modopts wins. // // Returns Left if m1 is better, Right if m2 is better, or Neither/Same private BetterType WhichMethodIsBetter( CandidateFunctionMember node1, CandidateFunctionMember node2, CType pTypeThrough, ArgInfos args) { MethPropWithInst mpwi1 = node1.mpwi; MethPropWithInst mpwi2 = node2.mpwi; // Substitutions should have already been done on these! TypeArray pta1 = RearrangeNamedArguments(node1.@params, mpwi1, pTypeThrough, args); TypeArray pta2 = RearrangeNamedArguments(node2.@params, mpwi2, pTypeThrough, args); // If the parameter types for both candidate methods are identical, // use the tie breaking rules. if (pta1 == pta2) { return WhichMethodIsBetterTieBreaker(node1, node2, pTypeThrough, args); } // Otherwise, do a parameter-by-parameter comparison: // // Given an argument list A with a set of argument expressions {E1, ... En} and // two applicable function members Mp and Mq with parameter types {P1,... Pn} and // {Q1, ... Qn}, Mp is defined to be a better function member than Mq if: //* for each argument the implicit conversion from Ex to Qx is not better than // the implicit conversion from Ex to Px. //* for at least one argument, the conversion from Ex to Px is better than the // conversion from Ex to Qx. BetterType betterMethod = BetterType.Neither; CType type1 = pTypeThrough != null ? pTypeThrough : mpwi1.GetType(); CType type2 = pTypeThrough != null ? pTypeThrough : mpwi2.GetType(); MethodOrPropertySymbol methProp1 = GroupToArgsBinder.FindMostDerivedMethod(GetSymbolLoader(), mpwi1.MethProp(), type1); MethodOrPropertySymbol methProp2 = GroupToArgsBinder.FindMostDerivedMethod(GetSymbolLoader(), mpwi2.MethProp(), type2); List<Name> names1 = methProp1.ParameterNames; List<Name> names2 = methProp2.ParameterNames; for (int i = 0; i < args.carg; i++) { Expr arg = args.fHasExprs ? args.prgexpr[i] : null; CType argType = args.types[i]; CType p1 = pta1[i]; CType p2 = pta2[i]; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // We need to consider conversions from the actual runtime type // since we could have private interfaces that we are converting if (arg.RuntimeObjectActualType != null) { argType = arg.RuntimeObjectActualType; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // END RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BetterType betterConversion = WhichConversionIsBetter(arg, argType, p1, p2); if (betterMethod == BetterType.Right && betterConversion == BetterType.Left) { betterMethod = BetterType.Neither; break; } else if (betterMethod == BetterType.Left && betterConversion == BetterType.Right) { betterMethod = BetterType.Neither; break; } else if (betterMethod == BetterType.Neither) { if (betterConversion == BetterType.Right || betterConversion == BetterType.Left) { betterMethod = betterConversion; } } } // We may have different sizes if we had optional parameters. If thats the case, // the one with fewer parameters wins (ie less optional parameters) unless it is // expanded. If so, the one with more parameters wins (ie option beats expanded). if (pta1.Count != pta2.Count && betterMethod == BetterType.Neither) { if (node1.fExpanded && !node2.fExpanded) { return BetterType.Right; } else if (node2.fExpanded && !node1.fExpanded) { return BetterType.Left; } // Here, if both methods needed to use optionals to fill in the signatures, // then we are ambiguous. Otherwise, take the one that didn't need any // optionals. if (pta1.Count == args.carg) { return BetterType.Left; } else if (pta2.Count == args.carg) { return BetterType.Right; } return BetterType.Neither; } return betterMethod; } private BetterType WhichConversionIsBetter(Expr arg, CType argType, CType p1, CType p2) { Debug.Assert(argType != null); Debug.Assert(p1 != null); Debug.Assert(p2 != null); // 7.4.2.3 Better Conversion From Expression // // Given an implicit conversion C1 that converts from an expression E to a type T1 // and an implicit conversion C2 that converts from an expression E to a type T2, the // better conversion of the two conversions is determined as follows: //* if T1 and T2 are the same type, neither conversion is better. //* If E has a type S and the conversion from S to T1 is better than the conversion from // S to T2 then C1 is the better conversion. //* If E has a type S and the conversion from S to T2 is better than the conversion from // S to T1 then C2 is the better conversion. //* If E is a lambda expression or anonymous method for which an inferred return type X // exists and T1 is a delegate type and T2 is a delegate type and T1 and T2 have identical // parameter lists: // * If T1 is a delegate of return type Y1 and T2 is a delegate of return type Y2 and the // conversion from X to Y1 is better than the conversion from X to Y2, then C1 is the // better return type. // * If T1 is a delegate of return type Y1 and T2 is a delegate of return type Y2 and the // conversion from X to Y2 is better than the conversion from X to Y1, then C2 is the // better return type. if (p1 == p2) { return BetterType.Same; } return WhichConversionIsBetter(argType, p1, p2); } private BetterType WhichConversionIsBetter(CType argType, CType p1, CType p2) { // 7.4.2.4 Better conversion from type // // Given a conversion C1 that converts from a type S to a type T1 and a conversion C2 // that converts from a type S to a type T2, the better conversion of the two conversions // is determined as follows: //* If T1 and T2 are the same type, neither conversion is better //* If S is T1, C1 is the better conversion. //* If S is T2, C2 is the better conversion. //* If an implicit conversion from T1 to T2 exists and no implicit conversion from T2 to // T1 exists, C1 is the better conversion. //* If an implicit conversion from T2 to T1 exists and no implicit conversion from T1 to // T2 exists, C2 is the better conversion. // // [Otherwise, see table above for better integral type conversions.] if (p1 == p2) { return BetterType.Same; } if (argType == p1) { return BetterType.Left; } if (argType == p2) { return BetterType.Right; } bool a2b = canConvert(p1, p2); bool b2a = canConvert(p2, p1); if (a2b && !b2a) { return BetterType.Left; } if (b2a && !a2b) { return BetterType.Right; } Debug.Assert(b2a == a2b); if (p1.isPredefined() && p2.isPredefined() && p1.getPredefType() <= PredefinedType.PT_OBJECT && p2.getPredefType() <= PredefinedType.PT_OBJECT) { int c = s_betterConversionTable[(int)p1.getPredefType()][(int)p2.getPredefType()]; if (c == 1) { return BetterType.Left; } else if (c == 2) { return BetterType.Right; } } return BetterType.Neither; } //////////////////////////////////////////////////////////////////////////////// // Determine best method for overload resolution. Returns null if no best // method, in which case two tying methods are returned for error reporting. private CandidateFunctionMember FindBestMethod( List<CandidateFunctionMember> list, CType pTypeThrough, ArgInfos args, out CandidateFunctionMember methAmbig1, out CandidateFunctionMember methAmbig2) { Debug.Assert(list.Any()); Debug.Assert(list.First().mpwi != null); Debug.Assert(list.Count > 0); // select the best method: /* Effectively, we pick the best item from a set using a non-transitive ranking function So, pick the first item (candidate) and compare against next (contender), if there is no next, goto phase 2 If first is better, move to next contender, if none proceed to phase 2 If second is better, make the contender the candidate and make the item following contender into the new contender, if there is none, goto phase 2 If neither, make contender+1 into candidate and contender+2 into contender, if possible, otherwise, if contender was last, return null, otherwise if new candidate is last, goto phase 2 Phase 2: compare all items before candidate to candidate If candidate always better, return it, otherwise return null */ // Record two method that are ambiguous for error reporting. CandidateFunctionMember ambig1 = null; CandidateFunctionMember ambig2 = null; bool ambiguous = false; CandidateFunctionMember candidate = list[0]; for (int i = 1; i < list.Count; i++) { CandidateFunctionMember contender = list[i]; Debug.Assert(candidate != contender); BetterType result = WhichMethodIsBetter(candidate, contender, pTypeThrough, args); if (result == BetterType.Left) { ambiguous = false; continue; // (meaning m1 is better...) } else if (result == BetterType.Right) { ambiguous = false; candidate = contender; } else { // in case of tie we don't want to bother with the contender who tied... ambig1 = candidate; ambig2 = contender; i++; if (i < list.Count) { contender = list[i]; candidate = contender; } else { ambiguous = true; } } } if (ambiguous) goto AMBIG; // Now, compare the candidate with items previous to it... foreach (CandidateFunctionMember contender in list) { if (contender == candidate) { // We hit our winner, so its good enough... methAmbig1 = null; methAmbig2 = null; return candidate; } BetterType result = WhichMethodIsBetter(contender, candidate, pTypeThrough, args); if (result == BetterType.Right) { // meaning m2 is better continue; } else if (result == BetterType.Same || result == BetterType.Neither) { ambig1 = candidate; ambig2 = contender; } break; } AMBIG: // an ambig call. Return two of the ambiguous set. if (ambig1 != null && ambig2 != null) { methAmbig1 = ambig1; methAmbig2 = ambig2; } else { // For some reason, we have an ambiguity but never had a tie. // This can easily happen in a circular graph of candidate methods. methAmbig1 = list.First(); methAmbig2 = list.Skip(1).First(); } return null; } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Data; using System.Windows.Forms; using System.IO; using System.Reflection; using System.Data.OleDb; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.DB.Architecture; using Autodesk.Revit.DB.Events; using Autodesk.Revit.Collections; namespace Revit.SDK.Samples.RoomSchedule { /// <summary> /// Room Schedule form, used to retrieve data from .xls data source and create new rooms. /// </summary> public partial class RoomScheduleForm : System.Windows.Forms.Form { #region Class Member Variables // Reserve name of data source private String m_dataBaseName; // Revit external command data private ExternalCommandData m_commandData; // Current active document private Document m_document; // Room data information private RoomsData m_roomData; // All levels in Revit document. private List<Level> m_allLevels = new List<Level>(); // All available phases in Revit document. private List<Phase> m_allPhases = new List<Phase>(); // Room work sheet name private String m_roomTableName; // All rooms data from spread sheet private DataTable m_spreadRoomsTable; #endregion #region Class Constructor Method /// <summary> /// Class constructor /// </summary> /// <param name="commandData">Revit external command data</param> public RoomScheduleForm(ExternalCommandData commandData) { // UI initialization InitializeComponent(); // reserve Revit command data and get rooms information, // and then display rooms information in DataGrideView m_commandData = commandData; m_document = m_commandData.Application.ActiveUIDocument.Document; m_roomData = new RoomsData(commandData.Application.ActiveUIDocument.Document); // bind levels and phases data to level and phase ComboBox controls GetAllLevelsAndPhases(); // list all levels and phases this.levelComboBox.DisplayMember = "Name"; this.levelComboBox.DataSource = m_allLevels; this.levelComboBox.SelectedIndex = 0; this.phaseComboBox.DisplayMember = "Name"; this.phaseComboBox.DataSource = m_allPhases; this.phaseComboBox.SelectedIndex = 0; // if there is no phase, newRoomButton will be disabled. if (m_allPhases.Count == 0) { newRoomButton.Enabled = false; } // check to see whether current Revit document was mapped to spreadsheet. UpdateRoomMapSheetInfo(); } #endregion #region Class Implementations /// <summary> /// Get all available levels and phases from current document /// </summary> private void GetAllLevelsAndPhases() { // get all levels which can place rooms foreach (PlanTopology planTopology in m_document.PlanTopologies) { m_allLevels.Add(planTopology.Level); } // get all phases by filter type FilteredElementCollector collector = new FilteredElementCollector(m_document); ICollection<Element> allPhases = collector.OfClass(typeof(Phase)).ToElements(); foreach (Phase phs in allPhases) { m_allPhases.Add(phs); } } /// <summary> /// Create shared parameter for Rooms category /// </summary> /// <returns>True, shared parameter exists; false, doesn't exist</returns> private bool CreateMyRoomSharedParameter() { // Create Room Shared Parameter Routine: --> // 1: Check whether the Room shared parameter("External Room ID") has been defined. // 2: Share parameter file locates under sample directory of this .dll module. // 3: Add a group named "SDKSampleRoomScheduleGroup". // 4: Add a shared parameter named "External Room ID" to "Rooms" category, which is visible. // The "External Room ID" parameter will be used to map to spreadsheet based room ID(which is unique) try { // check whether shared parameter exists if (ShareParameterExists(RoomsData.SharedParam)) { return true; } // create shared parameter file String modulePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); String paramFile = modulePath + "\\RoomScheduleSharedParameters.txt"; if (File.Exists(paramFile)) { File.Delete(paramFile); } FileStream fs = File.Create(paramFile); fs.Close(); // cache application handle Autodesk.Revit.ApplicationServices.Application revitApp = m_commandData.Application.Application; // prepare shared parameter file m_commandData.Application.Application.SharedParametersFilename = paramFile; // open shared parameter file DefinitionFile parafile = revitApp.OpenSharedParameterFile(); // create a group DefinitionGroup apiGroup = parafile.Groups.Create("SDKSampleRoomScheduleGroup"); // create a visible "External Room ID" of text type. Definition roomSharedParamDef = apiGroup.Definitions.Create(RoomsData.SharedParam, ParameterType.Text, true); // get Rooms category Category roomCat = m_commandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item("Rooms"); CategorySet categories = revitApp.Create.NewCategorySet(); categories.Insert(roomCat); // insert the new parameter InstanceBinding binding = revitApp.Create.NewInstanceBinding(categories); m_commandData.Application.ActiveUIDocument.Document.ParameterBindings.Insert(roomSharedParamDef, binding); return false; } catch (Exception ex) { throw new Exception("Failed to create shared parameter: " + ex.Message); } } /// <summary> /// Test if the Room binds a specified shared parameter /// </summary> /// <param name="paramName">Parameter name to be checked</param> /// <returns>true, the definition exists, false, doesn't exist.</returns> private bool ShareParameterExists(String paramName) { BindingMap bindingMap = m_document.ParameterBindings; DefinitionBindingMapIterator iter = bindingMap.ForwardIterator(); iter.Reset(); while (iter.MoveNext()) { Definition tempDefinition = iter.Key; // find the definition of which the name is the appointed one if (String.Compare(tempDefinition.Name, paramName) != 0) { continue; } // get the category which is bound ElementBinding binding = bindingMap.get_Item(tempDefinition) as ElementBinding; CategorySet bindCategories = binding.Categories; foreach (Category category in bindCategories) { if (category.Name == "Rooms") { // the definition with appointed name was bound to Rooms, return true return true; } } } // // return false if shared parameter doesn't exist return false; } /// <summary> /// My custom message box /// </summary> /// <param name="strMsg">message to be popped up</param> /// <param name="icon">icon to be displayed</param> public static void MyMessageBox(String strMsg, MessageBoxIcon icon) { MessageBox.Show(strMsg, "Room Schedule", MessageBoxButtons.OK, icon); } /// <summary> /// Update control display of form /// call this method when create new rooms or switch the room show(show all or show by level) /// </summary> /// <param name="bUpdateAllRooms">whether retrieve all rooms from Revit project once more</param> private void UpdateFormDisplay(bool bUpdateAllRooms) { // update Revit Rooms data when there is room creation if (bUpdateAllRooms) { m_roomData.UpdateRoomsData(); } revitRoomDataGridView.DataSource = null; if (showAllRoomsCheckBox.Checked) { // show all rooms in Revit project revitRoomDataGridView.DataSource = new DataView(m_roomData.GenRoomsDataTable(null)); } else { // show all rooms in specified level levelComboBox_SelectedIndexChanged(null, null); } // update this DataGridView revitRoomDataGridView.Update(); } /// <summary> /// Display current Room sheet information: Excel path /// </summary> private void UpdateRoomMapSheetInfo() { int hashCode = m_document.GetHashCode(); SheetInfo xlsAndTable = new SheetInfo("", ""); if (CrtlApplication.EventReactor.DocMappedSheetInfo(hashCode, ref xlsAndTable)) { roomExcelTextBox.Text = "Mapped Sheet: " + xlsAndTable.FileName + ": " + xlsAndTable.SheetName; } } /// <summary> /// Some preparation and check before creating room. /// </summary> /// <param name="curPhase">Current phase used to create room, all rooms will be created in this phase.</param> /// <returns>Number indicates how many new rooms were created.</returns> private int RoomCreationStart() { int nNewRoomsSize = 0; // transaction is used to cancel room creation when exception occurs SubTransaction myTransaction = new SubTransaction(m_document); try { // Preparation before room creation starts Phase curPhase = null; if (!RoomCreationPreparation(ref curPhase)) { return 0; } // get all existing rooms which have mapped to spreadsheet rooms. // we should skip the creation for those spreadsheet rooms which have been mapped by Revit rooms. Dictionary<int, string> existingRooms = new Dictionary<int, string>(); foreach (Room room in m_roomData.Rooms) { Parameter sharedParameter = room.get_Parameter(RoomsData.SharedParam); if (null != sharedParameter && false == String.IsNullOrEmpty(sharedParameter.AsString())) { existingRooms.Add(room.Id.IntegerValue, sharedParameter.AsString()); } } #region Rooms Creation and Set myTransaction.Start(); // create rooms with spread sheet based rooms data for (int row = 0; row < m_spreadRoomsTable.Rows.Count; row++) { // get the ID column value and use it to check whether this spreadsheet room is mapped by Revit room. String externaId = m_spreadRoomsTable.Rows[row][RoomsData.RoomID].ToString(); if (existingRooms.ContainsValue(externaId)) { // skip the spreadsheet room creation if it's mapped by Revit room continue; } // create rooms in specified phase, but without placing them. Room newRoom = m_document.Create.NewRoom(curPhase); if (null == newRoom) { // abort the room creation and pop up failure message myTransaction.RollBack(); MyMessageBox("Create room failed.", MessageBoxIcon.Warning); return 0; } // set the shared parameter's value of Revit room Parameter sharedParam = newRoom.get_Parameter(RoomsData.SharedParam); if (null == sharedParam) { // abort the room creation and pop up failure message myTransaction.RollBack(); MyMessageBox("Failed to get shared parameter, please try again.", MessageBoxIcon.Warning); return 0; } else { sharedParam.Set(externaId); } // Update this new room with values of spreadsheet UpdateNewRoom(newRoom, row); // remember how many new rooms were created, based on spread sheet data nNewRoomsSize++; } // end this transaction if create all rooms successfully. myTransaction.Commit(); #endregion } catch (Exception ex) { // cancel this time transaction when exception occurs if (myTransaction.HasStarted()) { myTransaction.RollBack(); } MyMessageBox(ex.Message, MessageBoxIcon.Warning); return 0; } // output unplaced rooms creation message String strMessage = string.Empty; int nSkippedRooms = m_spreadRoomsTable.Rows.Count - nNewRoomsSize; if (nSkippedRooms > 0) { strMessage = string.Format("{0} unplaced {1} created successfully.\r\n{2} skipped, {3}", nNewRoomsSize, (nNewRoomsSize > 1) ? ("rooms were") : ("room was"), nSkippedRooms.ToString() + ((nSkippedRooms > 1) ? (" were") : (" was")), (nSkippedRooms > 1) ? ("because they were already mapped by Revit rooms.") : ("because it was already mapped by Revit rooms.")); } else { strMessage = string.Format("{0} unplaced {1} created successfully.", nNewRoomsSize, (nNewRoomsSize > 1) ? ("rooms were") : ("room was")); } // output creation message MyMessageBox(strMessage, MessageBoxIcon.Information); return nNewRoomsSize; } /// <summary> /// Some preparation and check before creating room. /// </summary> /// <param name="curPhase">Current phase used to create room, all rooms will be created in this phase.</param> /// <returns></returns> private bool RoomCreationPreparation(ref Phase curPhase) { // check to see whether there is available spread sheet based rooms to create if (null == m_spreadRoomsTable || null == m_spreadRoomsTable.Rows || m_spreadRoomsTable.Rows.Count == 0) { MyMessageBox("There is no available spread sheet based room to create.", MessageBoxIcon.Warning); return false; } // create shared parameter for "Room" category elements CreateMyRoomSharedParameter(); // create Revit rooms by using spread sheet based rooms // add "ID" data of spread sheet to Room element's share parameter: "External Room ID" DataColumn column = m_spreadRoomsTable.Columns[RoomsData.RoomID]; if (column == null) { MyMessageBox("Failed to get ID data of spread sheet rooms.", MessageBoxIcon.Warning); return false; } // get phase used to create room foreach (Phase phase in m_allPhases) { if (String.Compare(phase.Name, phaseComboBox.Text) == 0) { curPhase = phase; break; } } if (null == curPhase) { MyMessageBox("No available phase used to create room.", MessageBoxIcon.Warning); return false; } return true; } /// <summary> /// Update new room with values in spreadsheet, currently there are three columns need to be set. /// </summary> /// <param name="newRoom">New room to be updated.</param> /// <param name="index">The index of row in spreadsheet, use values of this row to update the new room.</param> private void UpdateNewRoom(Room newRoom, int row) { String[] constantColumns = { RoomsData.RoomName, RoomsData.RoomNumber, RoomsData.RoomComments }; for (int col = 0; col < constantColumns.Length; col++) { // check to see whether the column exists in table if (m_spreadRoomsTable.Columns.IndexOf(constantColumns[col]) != -1) { // if value is not null or empty, set new rooms related parameter. String colValue = m_spreadRoomsTable.Rows[row][constantColumns[col]].ToString(); if (String.IsNullOrEmpty(colValue)) { continue; } switch (constantColumns[col]) { case RoomsData.RoomName: newRoom.Name = colValue; break; case RoomsData.RoomNumber: newRoom.Number = colValue; break; case RoomsData.RoomComments: Parameter commentParam = newRoom.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS); if (null != commentParam) { commentParam.Set(colValue); } break; default: // no action for other parameter break; } } } } #endregion #region Class Events Implmentation /// <summary> /// Import room spread sheet and display them in form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void importRoomButton_Click(object sender, EventArgs e) { using (OpenFileDialog sfdlg = new OpenFileDialog()) { // file dialog initialization sfdlg.Title = "Import Excel File"; sfdlg.Filter = "Excel File(*.xls)|*.xls"; sfdlg.RestoreDirectory = true; // // initialize the default file name int hashCode = m_document.GetHashCode(); SheetInfo xlsAndTable = new SheetInfo(String.Empty, String.Empty); if (CrtlApplication.EventReactor.DocMappedSheetInfo(hashCode, ref xlsAndTable)) { sfdlg.FileName = xlsAndTable.FileName; } // // import the select if (DialogResult.OK == sfdlg.ShowDialog()) { try { // create xls data source connector and retrieve data from it m_dataBaseName = sfdlg.FileName; XlsDBConnector xlsCon = new XlsDBConnector(m_dataBaseName); // bind table data to grid view and ComboBox control tablesComboBox.DataSource = xlsCon.RetrieveAllTables(); // close the connection xlsCon.Dispose(); } catch (Exception ex) { tablesComboBox.DataSource = null; MyMessageBox(ex.Message, MessageBoxIcon.Warning); } } } } /// <summary> /// Select one table(work sheet) and display its data to DataGridView control. /// after selection, generate data table from data source /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tablesComboBox_SelectedIndexChanged(object sender, EventArgs e) { // update spread sheet based rooms sheetDataGridView.DataSource = null; m_roomTableName = tablesComboBox.SelectedValue as String; XlsDBConnector xlsCon = null; try { if (null != m_spreadRoomsTable) { m_spreadRoomsTable.Clear(); } // get all rooms table then close this connection immediately xlsCon = new XlsDBConnector(m_dataBaseName); // generate room data table from room work sheet. m_spreadRoomsTable = xlsCon.GenDataTable(m_roomTableName); newRoomButton.Enabled = (0 == m_spreadRoomsTable.Rows.Count) ? false : true; // close connection xlsCon.Dispose(); // update data source of DataGridView sheetDataGridView.DataSource = new DataView(m_spreadRoomsTable); } catch (Exception ex) { // close connection and update data source xlsCon.Dispose(); sheetDataGridView.DataSource = null; MyMessageBox(ex.Message, MessageBoxIcon.Warning); return; } // update the static s_DocMapDict variable when user changes the Excel and room table int hashCode = m_document.GetHashCode(); if (CrtlApplication.EventReactor.DocMonitored(hashCode)) { // update spread sheet to which document is being mapped. CrtlApplication.EventReactor.UpdateSheeInfo(hashCode, new SheetInfo(m_dataBaseName, m_roomTableName)); // update current mapped room sheet information, only show this when Revit rooms were mapped to Excel sheet. UpdateRoomMapSheetInfo(); } } /// <summary> /// Filter rooms by specified level. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void levelComboBox_SelectedIndexChanged(object sender, EventArgs e) { // get the selected level, by comparing its name and ComboBox selected item's name Level selLevel = null; foreach (Level level in m_allLevels) { if (0 == String.Compare(level.Name, levelComboBox.Text)) { selLevel = level; break; } } if (selLevel == null) { MyMessageBox("There is no available level to get rooms.", MessageBoxIcon.Warning); return; } // update data source of DataGridView this.revitRoomDataGridView.DataSource = null; this.revitRoomDataGridView.DataSource = new DataView(m_roomData.GenRoomsDataTable(selLevel)); } /// <summary> /// Create new rooms according to spreadsheet based rooms data and specified phase. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void newRoomButton_Click(object sender, EventArgs e) { // Create room process: // 1: Create shared parameter for "Room" category elements if it doesn't exist. // 2: Create rooms by using spread sheet's data: // a: We should make sure that each of spreadsheet room is mapped by only one Revit room; // if not, many Revit rooms map to one spreadsheet room will confuse user; // b: Set Name, Number and comment values of new rooms by spreadsheet relative data. // 3: Subscribe document Save, SaveAs and Close event handlers. // 4: Update all rooms data and pop up message // Create rooms now int nNewRoomsSize = RoomCreationStart(); if (nNewRoomsSize <= 0) { return; } // Reserve this document by its hash code, this document will be updated when it's about to be saved. int hashCode = m_document.GetHashCode(); if (!CrtlApplication.EventReactor.DocMonitored(hashCode)) { // reserves this document and current .xls file and table. CrtlApplication.EventReactor.UpdateSheeInfo(hashCode, new SheetInfo(m_dataBaseName, m_roomTableName)); // show current Excel and sheet name sample is mapped to, only show them after unplaced rooms were created. UpdateRoomMapSheetInfo(); } // update Revit rooms data and display of controls. UpdateFormDisplay(true); } /// <summary> /// Show all rooms in current document /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void showAllRoomsCheckBox_CheckedChanged(object sender, EventArgs e) { // disable and enable some controls levelComboBox.Enabled = !showAllRoomsCheckBox.Checked; // update room display, there is no new creation, so it's not necessary to retrieve all rooms UpdateFormDisplay(false); } /// <summary> /// Close the form. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void closeButton_Click(object sender, EventArgs e) { this.Close(); } /// <summary> /// Clear all values of shared parameters /// Allow user to create more unplaced rooms and update map relationships between Revit and spreadsheet rooms. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void clearIDButton_Click(object sender, EventArgs e) { int nCount = 0; foreach (Room room in m_roomData.Rooms) { Parameter param = null; bool bExist = RoomsData.ShareParameterExists(room, RoomsData.SharedParam, ref param); if (bExist && null != param && false == String.IsNullOrEmpty(param.AsString())) { param.Set(String.Empty); nCount++; } } // update Revit rooms display if (nCount > 0) { UpdateFormDisplay(false); } } #endregion } }
using YAF.Lucene.Net.Diagnostics; using System; namespace YAF.Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ArrayUtil = YAF.Lucene.Net.Util.ArrayUtil; using ByteBlockPool = YAF.Lucene.Net.Util.ByteBlockPool; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using BytesRefHash = YAF.Lucene.Net.Util.BytesRefHash; using IndexReader = YAF.Lucene.Net.Index.IndexReader; using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator; using Term = YAF.Lucene.Net.Index.Term; using TermContext = YAF.Lucene.Net.Index.TermContext; using TermsEnum = YAF.Lucene.Net.Index.TermsEnum; using TermState = YAF.Lucene.Net.Index.TermState; /// <summary> /// A rewrite method that tries to pick the best /// constant-score rewrite method based on term and /// document counts from the query. If both the number of /// terms and documents is small enough, then /// <see cref="MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE"/> is used. /// Otherwise, <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is /// used. /// </summary> // LUCENENET specific: made this class public. In Lucene there was a derived class // with the same name that was nested within MultiTermQuery, but in .NET it is // more intuitive if our classes are not nested. public class ConstantScoreAutoRewrite : TermCollectingRewrite<BooleanQuery> { /// <summary> /// Defaults derived from rough tests with a 20.0 million /// doc Wikipedia index. With more than 350 terms in the /// query, the filter method is fastest: /// </summary> public static int DEFAULT_TERM_COUNT_CUTOFF = 350; /// <summary> /// If the query will hit more than 1 in 1000 of the docs /// in the index (0.1%), the filter method is fastest: /// </summary> public static double DEFAULT_DOC_COUNT_PERCENT = 0.1; private int termCountCutoff = DEFAULT_TERM_COUNT_CUTOFF; private double docCountPercent = DEFAULT_DOC_COUNT_PERCENT; /// <summary> /// If the number of terms in this query is equal to or /// larger than this setting then /// <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is used. /// </summary> public virtual int TermCountCutoff { get => termCountCutoff; set => termCountCutoff = value; } /// <summary> /// If the number of documents to be visited in the /// postings exceeds this specified percentage of the /// <see cref="Index.IndexReader.MaxDoc"/> for the index, then /// <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is used. /// Value may be 0.0 to 100.0. /// </summary> public virtual double DocCountPercent { get => docCountPercent; set => docCountPercent = value; } protected override BooleanQuery GetTopLevelQuery() { return new BooleanQuery(true); } protected override void AddClause(BooleanQuery topLevel, Term term, int docFreq, float boost, TermContext states) //ignored { topLevel.Add(new TermQuery(term, states), Occur.SHOULD); } public override Query Rewrite(IndexReader reader, MultiTermQuery query) { // Get the enum and start visiting terms. If we // exhaust the enum before hitting either of the // cutoffs, we use ConstantBooleanQueryRewrite; else, // ConstantFilterRewrite: int docCountCutoff = (int)((docCountPercent / 100.0) * reader.MaxDoc); int termCountLimit = Math.Min(BooleanQuery.MaxClauseCount, termCountCutoff); CutOffTermCollector col = new CutOffTermCollector(docCountCutoff, termCountLimit); CollectTerms(reader, query, col); int size = col.pendingTerms.Count; if (col.hasCutOff) { return MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE.Rewrite(reader, query); } else { BooleanQuery bq = GetTopLevelQuery(); if (size > 0) { BytesRefHash pendingTerms = col.pendingTerms; int[] sort = pendingTerms.Sort(col.termsEnum.Comparer); for (int i = 0; i < size; i++) { int pos = sort[i]; // docFreq is not used for constant score here, we pass 1 // to explicitely set a fake value, so it's not calculated AddClause(bq, new Term(query.m_field, pendingTerms.Get(pos, new BytesRef())), 1, 1.0f, col.array.termState[pos]); } } // Strip scores Query result = new ConstantScoreQuery(bq); result.Boost = query.Boost; return result; } } internal sealed class CutOffTermCollector : TermCollector { internal CutOffTermCollector(int docCountCutoff, int termCountLimit) { pendingTerms = new BytesRefHash(new ByteBlockPool(new ByteBlockPool.DirectAllocator()), 16, array); this.docCountCutoff = docCountCutoff; this.termCountLimit = termCountLimit; } public override void SetNextEnum(TermsEnum termsEnum) { this.termsEnum = termsEnum; } public override bool Collect(BytesRef bytes) { int pos = pendingTerms.Add(bytes); docVisitCount += termsEnum.DocFreq; if (pendingTerms.Count >= termCountLimit || docVisitCount >= docCountCutoff) { hasCutOff = true; return false; } TermState termState = termsEnum.GetTermState(); if (Debugging.AssertsEnabled) Debugging.Assert(termState != null); if (pos < 0) { pos = (-pos) - 1; array.termState[pos].Register(termState, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); } else { array.termState[pos] = new TermContext(m_topReaderContext, termState, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); } return true; } internal int docVisitCount = 0; internal bool hasCutOff = false; internal TermsEnum termsEnum; internal readonly int docCountCutoff, termCountLimit; internal readonly TermStateByteStart array = new TermStateByteStart(16); internal BytesRefHash pendingTerms; } public override int GetHashCode() { const int prime = 1279; return (int)(prime * termCountCutoff + J2N.BitConversion.DoubleToInt64Bits(docCountPercent)); } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj is null) { return false; } if (this.GetType() != obj.GetType()) { return false; } ConstantScoreAutoRewrite other = (ConstantScoreAutoRewrite)obj; if (other.termCountCutoff != termCountCutoff) { return false; } if (J2N.BitConversion.DoubleToInt64Bits(other.docCountPercent) != J2N.BitConversion.DoubleToInt64Bits(docCountPercent)) { return false; } return true; } /// <summary> /// Special implementation of <see cref="BytesRefHash.BytesStartArray"/> that keeps parallel arrays for <see cref="TermContext"/> </summary> internal sealed class TermStateByteStart : BytesRefHash.DirectBytesStartArray { internal TermContext[] termState; public TermStateByteStart(int initSize) : base(initSize) { } public override int[] Init() { int[] ord = base.Init(); termState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; if (Debugging.AssertsEnabled) Debugging.Assert(termState.Length >= ord.Length); return ord; } public override int[] Grow() { int[] ord = base.Grow(); if (termState.Length < ord.Length) { TermContext[] tmpTermState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(termState, 0, tmpTermState, 0, termState.Length); termState = tmpTermState; } if (Debugging.AssertsEnabled) Debugging.Assert(termState.Length >= ord.Length); return ord; } public override int[] Clear() { termState = null; return base.Clear(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Tests for ProjectInstance public members</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using ForwardingLoggerRecord = Microsoft.Build.Logging.ForwardingLoggerRecord; using Microsoft.Build.BackEnd; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Build.UnitTests.OM.Instance { /// <summary> /// Tests for ProjectInstance public members /// </summary> [TestClass] public class ProjectInstance_Tests { /// <summary> /// Verify that a cloned off project instance can see environment variables /// </summary> [TestMethod] public void CreateProjectInstancePassesEnvironment() { Project p = new Project(); ProjectInstance i = p.CreateProjectInstance(); Assert.AreEqual(true, i.GetPropertyValue("username") != null); } /// <summary> /// Read off properties /// </summary> [TestMethod] public void PropertiesAccessors() { ProjectInstance p = GetSampleProjectInstance(); Assert.AreEqual("v1", p.GetPropertyValue("p1")); Assert.AreEqual("v2X", p.GetPropertyValue("p2")); } /// <summary> /// Read off items /// </summary> [TestMethod] public void ItemsAccessors() { ProjectInstance p = GetSampleProjectInstance(); IList<ProjectItemInstance> items = Helpers.MakeList(p.GetItems("i")); Assert.AreEqual(3, items.Count); Assert.AreEqual("i", items[0].ItemType); Assert.AreEqual("i0", items[0].EvaluatedInclude); Assert.AreEqual(String.Empty, items[0].GetMetadataValue("m")); Assert.AreEqual(null, items[0].GetMetadata("m")); Assert.AreEqual("i1", items[1].EvaluatedInclude); Assert.AreEqual("m1", items[1].GetMetadataValue("m")); Assert.AreEqual("m1", items[1].GetMetadata("m").EvaluatedValue); Assert.AreEqual("v1", items[2].EvaluatedInclude); } /// <summary> /// Add item /// </summary> [TestMethod] public void AddItemWithoutMetadata() { ProjectInstance p = GetEmptyProjectInstance(); ProjectItemInstance returned = p.AddItem("i", "i1"); Assert.AreEqual("i", returned.ItemType); Assert.AreEqual("i1", returned.EvaluatedInclude); Assert.AreEqual(false, returned.Metadata.GetEnumerator().MoveNext()); foreach (ProjectItemInstance item in p.Items) { Assert.AreEqual("i1", item.EvaluatedInclude); Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext()); } } /// <summary> /// Add item /// </summary> [TestMethod] public void AddItemWithoutMetadata_Escaped() { ProjectInstance p = GetEmptyProjectInstance(); ProjectItemInstance returned = p.AddItem("i", "i%3b1"); Assert.AreEqual("i", returned.ItemType); Assert.AreEqual("i;1", returned.EvaluatedInclude); Assert.AreEqual(false, returned.Metadata.GetEnumerator().MoveNext()); foreach (ProjectItemInstance item in p.Items) { Assert.AreEqual("i;1", item.EvaluatedInclude); Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext()); } } /// <summary> /// Add item with metadata /// </summary> [TestMethod] public void AddItemWithMetadata() { ProjectInstance p = GetEmptyProjectInstance(); var metadata = new List<KeyValuePair<string, string>>(); metadata.Add(new KeyValuePair<string, string>("m", "m1")); metadata.Add(new KeyValuePair<string, string>("n", "n1")); metadata.Add(new KeyValuePair<string, string>("o", "o%40")); ProjectItemInstance returned = p.AddItem("i", "i1", metadata); Assert.Same(returned, Helpers.MakeList(p.GetItems("i"))[0]); foreach (ProjectItemInstance item in p.Items) { Assert.Same(returned, item); Assert.AreEqual("i1", item.EvaluatedInclude); var metadataOut = Helpers.MakeList(item.Metadata); Assert.AreEqual(3, metadataOut.Count); Assert.AreEqual("m1", item.GetMetadataValue("m")); Assert.AreEqual("n1", item.GetMetadataValue("n")); Assert.AreEqual("o@", item.GetMetadataValue("o")); } } /// <summary> /// Add item null item type /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void AddItemInvalidNullItemType() { ProjectInstance p = GetEmptyProjectInstance(); p.AddItem(null, "i1"); } /// <summary> /// Add item empty item type /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentException))] public void AddItemInvalidEmptyItemType() { ProjectInstance p = GetEmptyProjectInstance(); p.AddItem(String.Empty, "i1"); } /// <summary> /// Add item null include /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void AddItemInvalidNullInclude() { ProjectInstance p = GetEmptyProjectInstance(); p.AddItem("i", null); } /// <summary> /// Add item null metadata /// </summary> [TestMethod] public void AddItemNullMetadata() { ProjectInstance p = GetEmptyProjectInstance(); ProjectItemInstance item = p.AddItem("i", "i1", null); Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext()); } /// <summary> /// It's okay to set properties that are also global properties, masking their value /// </summary> [TestMethod] public void SetGlobalPropertyOnInstance() { Dictionary<string, string> globals = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "p", "p1" } }; Project p = new Project(ProjectRootElement.Create(), globals, null); ProjectInstance instance = p.CreateProjectInstance(); instance.SetProperty("p", "p2"); Assert.AreEqual("p2", instance.GetPropertyValue("p")); // And clearing it should not expose the original global property value instance.SetProperty("p", ""); Assert.AreEqual("", instance.GetPropertyValue("p")); } /// <summary> /// ProjectInstance itself is cloned properly /// </summary> [TestMethod] public void CloneProjectItself() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Assert.IsTrue(!Object.ReferenceEquals(first, second)); } /// <summary> /// Properties are cloned properly /// </summary> [TestMethod] public void CloneProperties() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Assert.IsTrue(!Object.ReferenceEquals(first.GetProperty("p1"), second.GetProperty("p1"))); ProjectPropertyInstance newProperty = first.SetProperty("p1", "v1b"); Assert.AreEqual(true, Object.ReferenceEquals(newProperty, first.GetProperty("p1"))); Assert.AreEqual("v1b", first.GetPropertyValue("p1")); Assert.AreEqual("v1", second.GetPropertyValue("p1")); } /// <summary> /// Passing an item list into another list should copy the metadata too /// </summary> [TestMethod] public void ItemEvaluationCopiesMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m>m1</m> <n>n%3b%3b</n> </i> <j Include='@(i)'/> </ItemGroup> </Project>"; ProjectInstance project = GetProjectInstance(content); Assert.AreEqual(1, Helpers.MakeList(project.GetItems("j")).Count); Assert.AreEqual("i1", Helpers.MakeList(project.GetItems("j"))[0].EvaluatedInclude); Assert.AreEqual("m1", Helpers.MakeList(project.GetItems("j"))[0].GetMetadataValue("m")); Assert.AreEqual("n;;", Helpers.MakeList(project.GetItems("j"))[0].GetMetadataValue("n")); } /// <summary> /// Wildcards are expanded in item groups inside targets, and the evaluatedinclude /// is not the wildcard itself! /// </summary> [TestMethod] [TestCategory("serialize")] public void WildcardsInsideTargets() { string directory = null; string file1 = null; string file2 = null; string file3 = null; try { directory = Path.Combine(Path.GetTempPath(), "WildcardsInsideTargets"); Directory.CreateDirectory(directory); file1 = Path.Combine(directory, "a.exe"); file2 = Path.Combine(directory, "b.exe"); file3 = Path.Combine(directory, "c.bat"); File.WriteAllText(file1, String.Empty); File.WriteAllText(file2, String.Empty); File.WriteAllText(file3, String.Empty); string path = Path.Combine(directory, "*.exe"); string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'> <ItemGroup> <i Include='" + path + @"'/> </ItemGroup> </Target> </Project>"; ProjectInstance projectInstance = GetProjectInstance(content); projectInstance.Build(); Assert.AreEqual(2, Helpers.MakeList(projectInstance.GetItems("i")).Count); Assert.AreEqual(file1, Helpers.MakeList(projectInstance.GetItems("i"))[0].EvaluatedInclude); Assert.AreEqual(file2, Helpers.MakeList(projectInstance.GetItems("i"))[1].EvaluatedInclude); } finally { File.Delete(file1); File.Delete(file2); File.Delete(file3); Directory.Delete(directory); } } /// <summary> /// Items are cloned properly /// </summary> [TestMethod] public void CloneItems() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Assert.IsTrue(!Object.ReferenceEquals(Helpers.MakeList(first.GetItems("i"))[0], Helpers.MakeList(second.GetItems("i"))[0])); first.AddItem("i", "i3"); Assert.AreEqual(4, Helpers.MakeList(first.GetItems("i")).Count); Assert.AreEqual(3, Helpers.MakeList(second.GetItems("i")).Count); } /// <summary> /// Null target in array should give ArgumentNullException /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void BuildNullTargetInArray() { ProjectInstance instance = new ProjectInstance(ProjectRootElement.Create()); instance.Build(new string[] { null }, null); } /// <summary> /// Null logger in array should give ArgumentNullException /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void BuildNullLoggerInArray() { ProjectInstance instance = new ProjectInstance(ProjectRootElement.Create()); instance.Build("t", new ILogger[] { null }); } /// <summary> /// Null remote logger in array should give ArgumentNullException /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void BuildNullRemoteLoggerInArray() { ProjectInstance instance = new ProjectInstance(ProjectRootElement.Create()); instance.Build("t", null, new ForwardingLoggerRecord[] { null }); } /// <summary> /// Null target name should imply the default target /// </summary> [TestMethod] [TestCategory("serialize")] public void BuildNullTargetNameIsDefaultTarget() { ProjectRootElement xml = ProjectRootElement.Create(); xml.AddTarget("t").AddTask("Message").SetParameter("Text", "[OK]"); ProjectInstance instance = new ProjectInstance(xml); MockLogger logger = new MockLogger(); string target = null; instance.Build(target, new ILogger[] { logger }); logger.AssertLogContains("[OK]"); } /// <summary> /// Build system should correctly reset itself between builds of /// project instances. /// </summary> [TestMethod] [TestCategory("serialize")] public void BuildProjectInstancesConsecutively() { ProjectInstance instance1 = new Project().CreateProjectInstance(); BuildRequestData buildRequestData1 = new BuildRequestData(instance1, new string[] { }); BuildManager.DefaultBuildManager.Build(new BuildParameters(), buildRequestData1); ProjectInstance instance2 = new Project().CreateProjectInstance(); BuildRequestData buildRequestData2 = new BuildRequestData(instance1, new string[] { }); BuildManager.DefaultBuildManager.Build(new BuildParameters(), buildRequestData2); } /// <summary> /// Verifies that the built-in metadata for specialized ProjectInstances is present when items are the simplest (no macros or wildcards). /// </summary> [TestMethod] public void CreateProjectInstanceWithItemsContainingProjects() { const string CapturedMetadataName = "DefiningProjectFullPath"; var pc = new ProjectCollection(); var projA = ProjectRootElement.Create(pc); var projB = ProjectRootElement.Create(pc); projA.FullPath = Path.Combine(Path.GetTempPath(), "a.proj"); projB.FullPath = Path.Combine(Path.GetTempPath(), "b.proj"); projB.AddImport("a.proj"); projA.AddItem("Compile", "aItem.cs"); projB.AddItem("Compile", "bItem.cs"); var projBEval = new Project(projB, null, null, pc); var projBInstance = projBEval.CreateProjectInstance(); var projBInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("Compile", "bItem.cs").Single(); var projAInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("Compile", "aItem.cs").Single(); Assert.AreEqual(ProjectCollection.Escape(projB.FullPath), projBInstanceItem.GetMetadataValue(CapturedMetadataName)); Assert.AreEqual(ProjectCollection.Escape(projA.FullPath), projAInstanceItem.GetMetadataValue(CapturedMetadataName)); // Although GetMetadataValue returns non-null, GetMetadata returns null... Assert.IsNull(projAInstanceItem.GetMetadata(CapturedMetadataName)); // .. Just like built-in metadata does: (this segment just demonstrates similar functionality -- it's not meant to test built-in metadata) Assert.IsNotNull(projAInstanceItem.GetMetadataValue("Identity")); Assert.IsNull(projAInstanceItem.GetMetadata("Identity")); Assert.IsTrue(projAInstanceItem.HasMetadata(CapturedMetadataName)); Assert.IsFalse(projAInstanceItem.Metadata.Any()); Assert.IsTrue(projAInstanceItem.MetadataNames.Contains(CapturedMetadataName, StringComparer.OrdinalIgnoreCase)); Assert.AreEqual(projAInstanceItem.MetadataCount, projAInstanceItem.MetadataNames.Count); } /// <summary> /// Verifies that the built-in metadata for specialized ProjectInstances is present when items are based on wildcards in the construction model. /// </summary> [TestMethod] public void DefiningProjectItemBuiltInMetadataFromWildcards() { const string CapturedMetadataName = "DefiningProjectFullPath"; var pc = new ProjectCollection(); var projA = ProjectRootElement.Create(pc); var projB = ProjectRootElement.Create(pc); string tempDir = Path.GetTempFileName(); File.Delete(tempDir); Directory.CreateDirectory(tempDir); File.Create(Path.Combine(tempDir, "aItem.cs")).Dispose(); projA.FullPath = Path.Combine(tempDir, "a.proj"); projB.FullPath = Path.Combine(tempDir, "b.proj"); projB.AddImport("a.proj"); projA.AddItem("Compile", "*.cs"); projB.AddItem("CompileB", "@(Compile)"); var projBEval = new Project(projB, null, null, pc); var projBInstance = projBEval.CreateProjectInstance(); var projAInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("Compile", "aItem.cs").Single(); var projBInstanceItem = projBInstance.GetItemsByItemTypeAndEvaluatedInclude("CompileB", "aItem.cs").Single(); Assert.AreEqual(ProjectCollection.Escape(projA.FullPath), projAInstanceItem.GetMetadataValue(CapturedMetadataName)); Assert.AreEqual(ProjectCollection.Escape(projB.FullPath), projBInstanceItem.GetMetadataValue(CapturedMetadataName)); Assert.IsTrue(projAInstanceItem.HasMetadata(CapturedMetadataName)); Assert.IsFalse(projAInstanceItem.Metadata.Any()); Assert.IsTrue(projAInstanceItem.MetadataNames.Contains(CapturedMetadataName, StringComparer.OrdinalIgnoreCase)); Assert.AreEqual(projAInstanceItem.MetadataCount, projAInstanceItem.MetadataNames.Count); } /// <summary> /// Validate that the DefiningProject* metadata is set to the correct project based on a variety /// of means of item creation. /// </summary> [TestMethod] public void TestDefiningProjectMetadata() { string projectA = Path.Combine(ObjectModelHelpers.TempProjectDir, "a.proj"); string projectB = Path.Combine(ObjectModelHelpers.TempProjectDir, "b.proj"); string includeFileA = Path.Combine(ObjectModelHelpers.TempProjectDir, "aaa4.cs"); string includeFileB = Path.Combine(ObjectModelHelpers.TempProjectDir, "bbb4.cs"); string contentsA = @"<?xml version=`1.0` encoding=`utf-8`?> <Project ToolsVersion=`msbuilddefaulttoolsversion` DefaultTargets=`Validate` xmlns=`msbuildnamespace`> <ItemGroup> <A Include=`aaaa.cs` /> <A2 Include=`aaa2.cs` /> <A2 Include=`aaa3.cs`> <Foo>Bar</Foo> </A2> </ItemGroup> <Import Project=`b.proj` /> <ItemGroup> <E Include=`@(C)` /> <F Include=`@(C);@(C2)` /> <G Include=`@(C->'%(Filename)')` /> <H Include=`@(C2->WithMetadataValue('Foo', 'Bar'))` /> <U Include=`*4.cs` /> </ItemGroup> <Target Name=`AddFromMainProject`> <ItemGroup> <B Include=`bbbb.cs` /> <I Include=`@(C)` /> <J Include=`@(C);@(C2)` /> <K Include=`@(C->'%(Filename)')` /> <L Include=`@(C2->WithMetadataValue('Foo', 'Bar'))` /> <V Include=`*4.cs` /> </ItemGroup> </Target> <Target Name=`Validate` DependsOnTargets=`AddFromMainProject;AddFromImport`> <Warning Text=`A is wrong: EXPECTED: [a] ACTUAL: [%(A.DefiningProjectName)]` Condition=`'%(A.DefiningProjectName)' != 'a'` /> <Warning Text=`B is wrong: EXPECTED: [a] ACTUAL: [%(B.DefiningProjectName)]` Condition=`'%(B.DefiningProjectName)' != 'a'` /> <Warning Text=`C is wrong: EXPECTED: [b] ACTUAL: [%(C.DefiningProjectName)]` Condition=`'%(C.DefiningProjectName)' != 'b'` /> <Warning Text=`D is wrong: EXPECTED: [b] ACTUAL: [%(D.DefiningProjectName)]` Condition=`'%(D.DefiningProjectName)' != 'b'` /> <Warning Text=`E is wrong: EXPECTED: [a] ACTUAL: [%(E.DefiningProjectName)]` Condition=`'%(E.DefiningProjectName)' != 'a'` /> <Warning Text=`F is wrong: EXPECTED: [a] ACTUAL: [%(F.DefiningProjectName)]` Condition=`'%(F.DefiningProjectName)' != 'a'` /> <Warning Text=`G is wrong: EXPECTED: [a] ACTUAL: [%(G.DefiningProjectName)]` Condition=`'%(G.DefiningProjectName)' != 'a'` /> <Warning Text=`H is wrong: EXPECTED: [a] ACTUAL: [%(H.DefiningProjectName)]` Condition=`'%(H.DefiningProjectName)' != 'a'` /> <Warning Text=`I is wrong: EXPECTED: [a] ACTUAL: [%(I.DefiningProjectName)]` Condition=`'%(I.DefiningProjectName)' != 'a'` /> <Warning Text=`J is wrong: EXPECTED: [a] ACTUAL: [%(J.DefiningProjectName)]` Condition=`'%(J.DefiningProjectName)' != 'a'` /> <Warning Text=`K is wrong: EXPECTED: [a] ACTUAL: [%(K.DefiningProjectName)]` Condition=`'%(K.DefiningProjectName)' != 'a'` /> <Warning Text=`L is wrong: EXPECTED: [a] ACTUAL: [%(L.DefiningProjectName)]` Condition=`'%(L.DefiningProjectName)' != 'a'` /> <Warning Text=`M is wrong: EXPECTED: [b] ACTUAL: [%(M.DefiningProjectName)]` Condition=`'%(M.DefiningProjectName)' != 'b'` /> <Warning Text=`N is wrong: EXPECTED: [b] ACTUAL: [%(N.DefiningProjectName)]` Condition=`'%(N.DefiningProjectName)' != 'b'` /> <Warning Text=`O is wrong: EXPECTED: [b] ACTUAL: [%(O.DefiningProjectName)]` Condition=`'%(O.DefiningProjectName)' != 'b'` /> <Warning Text=`P is wrong: EXPECTED: [b] ACTUAL: [%(P.DefiningProjectName)]` Condition=`'%(P.DefiningProjectName)' != 'b'` /> <Warning Text=`Q is wrong: EXPECTED: [b] ACTUAL: [%(Q.DefiningProjectName)]` Condition=`'%(Q.DefiningProjectName)' != 'b'` /> <Warning Text=`R is wrong: EXPECTED: [b] ACTUAL: [%(R.DefiningProjectName)]` Condition=`'%(R.DefiningProjectName)' != 'b'` /> <Warning Text=`S is wrong: EXPECTED: [b] ACTUAL: [%(S.DefiningProjectName)]` Condition=`'%(S.DefiningProjectName)' != 'b'` /> <Warning Text=`T is wrong: EXPECTED: [b] ACTUAL: [%(T.DefiningProjectName)]` Condition=`'%(T.DefiningProjectName)' != 'b'` /> <Warning Text=`U is wrong: EXPECTED: [a] ACTUAL: [%(U.DefiningProjectName)]` Condition=`'%(U.DefiningProjectName)' != 'a'` /> <Warning Text=`V is wrong: EXPECTED: [a] ACTUAL: [%(V.DefiningProjectName)]` Condition=`'%(V.DefiningProjectName)' != 'a'` /> <Warning Text=`W is wrong: EXPECTED: [b] ACTUAL: [%(W.DefiningProjectName)]` Condition=`'%(W.DefiningProjectName)' != 'b'` /> <Warning Text=`X is wrong: EXPECTED: [b] ACTUAL: [%(X.DefiningProjectName)]` Condition=`'%(X.DefiningProjectName)' != 'b'` /> </Target> </Project>"; string contentsB = @"<?xml version=`1.0` encoding=`utf-8`?> <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <ItemGroup> <C Include=`cccc.cs` /> <C2 Include=`ccc2.cs` /> <C2 Include=`ccc3.cs`> <Foo>Bar</Foo> </C2> <M Include=`@(A)` /> <N Include=`@(A);@(A2)` /> <O Include=`@(A->'%(Filename)')` /> <P Include=`@(A2->WithMetadataValue('Foo', 'Bar'))` /> <W Include=`*4.cs` /> </ItemGroup> <Target Name=`AddFromImport`> <ItemGroup> <D Include=`dddd.cs` /> <Q Include=`@(A)` /> <R Include=`@(A);@(A2)` /> <S Include=`@(A->'%(Filename)')` /> <T Include=`@(A2->WithMetadataValue('Foo', 'Bar'))` /> <X Include=`*4.cs` /> </ItemGroup> </Target> </Project>"; try { File.WriteAllText(projectA, ObjectModelHelpers.CleanupFileContents(contentsA)); File.WriteAllText(projectB, ObjectModelHelpers.CleanupFileContents(contentsB)); File.WriteAllText(includeFileA, "aaaaaaa"); File.WriteAllText(includeFileB, "bbbbbbb"); MockLogger logger = ObjectModelHelpers.BuildTempProjectFileExpectSuccess("a.proj"); logger.AssertNoWarnings(); } finally { if (File.Exists(projectA)) { File.Delete(projectA); } if (File.Exists(projectB)) { File.Delete(projectB); } if (File.Exists(includeFileA)) { File.Delete(includeFileA); } if (File.Exists(includeFileB)) { File.Delete(includeFileB); } } } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetProperty() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.SetProperty("a", "b"); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_RemoveProperty() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.RemoveProperty("p1"); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_RemoveItem() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.RemoveItem(Helpers.GetFirst(instance.Items)); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_AddItem() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.AddItem("a", "b"); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_AddItemWithMetadata() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.AddItem("a", "b", new List<KeyValuePair<string, string>>()); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_Build() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.Build(); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetEvaluatedInclude() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).EvaluatedInclude = "x"; }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetEvaluatedIncludeEscaped() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { ((ITaskItem2)Helpers.GetFirst(instance.Items)).EvaluatedIncludeEscaped = "x"; }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetItemSpec() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { ((ITaskItem2)Helpers.GetFirst(instance.Items)).ItemSpec = "x"; }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetMetadataOnItem1() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { ((ITaskItem2)Helpers.GetFirst(instance.Items)).SetMetadataValueLiteral("a", "b"); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetMetadataOnItem2() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).SetMetadata(new List<KeyValuePair<string, string>>()); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetMetadataOnItem3() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).SetMetadata("a", "b"); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_RemoveMetadataFromItem() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).RemoveMetadata("n"); }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetEvaluatedValueOnProperty() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Properties).EvaluatedValue = "v2"; }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetEvaluatedValueOnPropertyFromProject() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("p1").EvaluatedValue = "v2"; }); } /// <summary> /// Test operation fails on immutable project instance /// </summary> [TestMethod] public void ImmutableProjectInstance_SetNewProperty() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.SetProperty("newproperty", "v2"); }); } /// <summary> /// Setting global properties should fail if the project is immutable, even though the property /// was originally created as mutable /// </summary> [TestMethod] public void ImmutableProjectInstance_SetGlobalProperty() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.SetProperty("g", "gv2"); }); } /// <summary> /// Setting environment originating properties should fail if the project is immutable, even though the property /// was originally created as mutable /// </summary> [TestMethod] public void ImmutableProjectInstance_SetEnvironmentProperty() { var instance = GetSampleProjectInstance(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.SetProperty("username", "someone_else_here"); }); } /// <summary> /// Cloning inherits unless otherwise specified /// </summary> [TestMethod] public void ImmutableProjectInstance_CloneMutableFromImmutable() { var protoInstance = GetSampleProjectInstance(true /* immutable */); var instance = protoInstance.DeepCopy(false /* mutable */); // These should not throw instance.SetProperty("p", "pnew"); instance.AddItem("i", "ii"); Helpers.GetFirst(instance.Items).EvaluatedInclude = "new"; instance.SetProperty("g", "gnew"); instance.SetProperty("username", "someone_else_here"); } /// <summary> /// Cloning inherits unless otherwise specified /// </summary> [TestMethod] public void ImmutableProjectInstance_CloneImmutableFromMutable() { var protoInstance = GetSampleProjectInstance(false /* mutable */); var instance = protoInstance.DeepCopy(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("g").EvaluatedValue = "v2"; }); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("username").EvaluatedValue = "someone_else_here"; }); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Properties).EvaluatedValue = "v2"; }); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).EvaluatedInclude = "new"; }); } /// <summary> /// Cloning inherits unless otherwise specified /// </summary> [TestMethod] public void ImmutableProjectInstance_CloneImmutableFromImmutable() { var protoInstance = GetSampleProjectInstance(true /* immutable */); var instance = protoInstance.DeepCopy(/* inherit */); // Should not have bothered cloning Assert.IsTrue(Object.ReferenceEquals(protoInstance, instance)); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("g").EvaluatedValue = "v2"; }); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("username").EvaluatedValue = "someone_else_here"; }); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Properties).EvaluatedValue = "v2"; }); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).EvaluatedInclude = "new"; }); } /// <summary> /// Cloning inherits unless otherwise specified /// </summary> [TestMethod] public void ImmutableProjectInstance_CloneImmutableFromImmutable2() { var protoInstance = GetSampleProjectInstance(true /* immutable */); var instance = protoInstance.DeepCopy(true /* immutable */); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("g").EvaluatedValue = "v2"; }); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { instance.GetProperty("username").EvaluatedValue = "someone_else_here"; }); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Properties).EvaluatedValue = "v2"; }); Helpers.VerifyAssertThrowsInvalidOperation(delegate () { Helpers.GetFirst(instance.Items).EvaluatedInclude = "new"; }); } /// <summary> /// Cloning inherits unless otherwise specified /// </summary> [TestMethod] public void ImmutableProjectInstance_CloneMutableFromMutable() { var protoInstance = GetSampleProjectInstance(false /* mutable */); var instance = protoInstance.DeepCopy(/* inherit */); // These should not throw instance.SetProperty("p", "pnew"); instance.AddItem("i", "ii"); Helpers.GetFirst(instance.Items).EvaluatedInclude = "new"; instance.SetProperty("g", "gnew"); instance.SetProperty("username", "someone_else_here"); } /// <summary> /// Cloning inherits unless otherwise specified /// </summary> [TestMethod] public void ImmutableProjectInstance_CloneMutableFromMutable2() { var protoInstance = GetSampleProjectInstance(false /* mutable */); var instance = protoInstance.DeepCopy(false /* mutable */); // These should not throw instance.SetProperty("p", "pnew"); instance.AddItem("i", "ii"); Helpers.GetFirst(instance.Items).EvaluatedInclude = "new"; instance.SetProperty("g", "gnew"); instance.SetProperty("username", "someone_else_here"); } /// <summary> /// Create a ProjectInstance with some items and properties and targets /// </summary> private static ProjectInstance GetSampleProjectInstance(bool isImmutable = false) { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <n>n1</n> </i> </ItemDefinitionGroup> <PropertyGroup> <p1>v1</p1> <p2>v2</p2> <p2>$(p2)X$(p)</p2> </PropertyGroup> <ItemGroup> <i Include='i0'/> <i Include='i1'> <m>m1</m> </i> <i Include='$(p1)'/> </ItemGroup> <Target Name='t'> <t1 a='a1' b='b1' ContinueOnError='coe' Condition='c'/> <t2/> </Target> <Target Name='tt'/> </Project> "; ProjectInstance p = GetProjectInstance(content, isImmutable); return p; } /// <summary> /// Create a ProjectInstance from provided project content /// </summary> private static ProjectInstance GetProjectInstance(string content, bool immutable = false) { var globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties["g"] = "gv"; Project project = new Project(XmlReader.Create(new StringReader(content)), globalProperties, "4.0"); ProjectInstance instance = immutable ? project.CreateProjectInstance(ProjectInstanceSettings.Immutable) : project.CreateProjectInstance(); return instance; } /// <summary> /// Create a ProjectInstance that's empty /// </summary> private static ProjectInstance GetEmptyProjectInstance() { ProjectRootElement xml = ProjectRootElement.Create(); Project project = new Project(xml); ProjectInstance instance = project.CreateProjectInstance(); return instance; } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.DistributedEmission.Iff { /// <summary> /// Enumeration values for Type1Parameter3Mode3CodeStatus (der.iff.type.1.fop.param3, Parameter 3 - Mode 3 Code/Status, /// section 8.3.1.2.4) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public struct Type1Parameter3Mode3CodeStatus { /// <summary> /// Status /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Status")] public enum StatusValue : uint { /// <summary> /// Off /// </summary> Off = 0, /// <summary> /// On /// </summary> On = 1 } /// <summary> /// Damage /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Damage")] public enum DamageValue : uint { /// <summary> /// No damage /// </summary> NoDamage = 0, /// <summary> /// Damage /// </summary> Damage = 1 } /// <summary> /// Malfunction /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Malfunction")] public enum MalfunctionValue : uint { /// <summary> /// No malfunction /// </summary> NoMalfunction = 0, /// <summary> /// Malfunction /// </summary> Malfunction = 1 } private byte codeElement1; private byte codeElement2; private byte codeElement3; private byte codeElement4; private Type1Parameter3Mode3CodeStatus.StatusValue status; private Type1Parameter3Mode3CodeStatus.DamageValue damage; private Type1Parameter3Mode3CodeStatus.MalfunctionValue malfunction; /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(Type1Parameter3Mode3CodeStatus left, Type1Parameter3Mode3CodeStatus right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(Type1Parameter3Mode3CodeStatus left, Type1Parameter3Mode3CodeStatus right) { if (object.ReferenceEquals(left, right)) { return true; } // If parameters are null return false (cast to object to prevent recursive loop!) if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } /// <summary> /// Performs an explicit conversion from <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> to <see cref="System.UInt16"/>. /// </summary> /// <param name="obj">The <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> scheme instance.</param> /// <returns>The result of the conversion.</returns> public static explicit operator ushort(Type1Parameter3Mode3CodeStatus obj) { return obj.ToUInt16(); } /// <summary> /// Performs an explicit conversion from <see cref="System.UInt16"/> to <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/>. /// </summary> /// <param name="value">The ushort value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator Type1Parameter3Mode3CodeStatus(ushort value) { return Type1Parameter3Mode3CodeStatus.FromUInt16(value); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> instance from the byte array. /// </summary> /// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/>.</param> /// <param name="index">The starting position within value.</param> /// <returns>The <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> instance, represented by a byte array.</returns> /// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception> /// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception> public static Type1Parameter3Mode3CodeStatus FromByteArray(byte[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length - 1 || index + 2 > array.Length - 1) { throw new IndexOutOfRangeException(); } return FromUInt16(BitConverter.ToUInt16(array, index)); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> instance from the ushort value. /// </summary> /// <param name="value">The ushort value which represents the <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> instance.</param> /// <returns>The <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> instance, represented by the ushort value.</returns> public static Type1Parameter3Mode3CodeStatus FromUInt16(ushort value) { Type1Parameter3Mode3CodeStatus ps = new Type1Parameter3Mode3CodeStatus(); uint mask0 = 0x0007; byte shift0 = 0; uint newValue0 = value & mask0 >> shift0; ps.CodeElement1 = (byte)newValue0; uint mask1 = 0x0038; byte shift1 = 3; uint newValue1 = value & mask1 >> shift1; ps.CodeElement2 = (byte)newValue1; uint mask2 = 0x01c0; byte shift2 = 6; uint newValue2 = value & mask2 >> shift2; ps.CodeElement3 = (byte)newValue2; uint mask3 = 0x0e00; byte shift3 = 9; uint newValue3 = value & mask3 >> shift3; ps.CodeElement4 = (byte)newValue3; uint mask5 = 0x2000; byte shift5 = 13; uint newValue5 = value & mask5 >> shift5; ps.Status = (Type1Parameter3Mode3CodeStatus.StatusValue)newValue5; uint mask6 = 0x4000; byte shift6 = 14; uint newValue6 = value & mask6 >> shift6; ps.Damage = (Type1Parameter3Mode3CodeStatus.DamageValue)newValue6; uint mask7 = 0x8000; byte shift7 = 15; uint newValue7 = value & mask7 >> shift7; ps.Malfunction = (Type1Parameter3Mode3CodeStatus.MalfunctionValue)newValue7; return ps; } /// <summary> /// Gets or sets the codeelement1. /// </summary> /// <value>The codeelement1.</value> public byte CodeElement1 { get { return this.codeElement1; } set { this.codeElement1 = value; } } /// <summary> /// Gets or sets the codeelement2. /// </summary> /// <value>The codeelement2.</value> public byte CodeElement2 { get { return this.codeElement2; } set { this.codeElement2 = value; } } /// <summary> /// Gets or sets the codeelement3. /// </summary> /// <value>The codeelement3.</value> public byte CodeElement3 { get { return this.codeElement3; } set { this.codeElement3 = value; } } /// <summary> /// Gets or sets the codeelement4. /// </summary> /// <value>The codeelement4.</value> public byte CodeElement4 { get { return this.codeElement4; } set { this.codeElement4 = value; } } /// <summary> /// Gets or sets the status. /// </summary> /// <value>The status.</value> public Type1Parameter3Mode3CodeStatus.StatusValue Status { get { return this.status; } set { this.status = value; } } /// <summary> /// Gets or sets the damage. /// </summary> /// <value>The damage.</value> public Type1Parameter3Mode3CodeStatus.DamageValue Damage { get { return this.damage; } set { this.damage = value; } } /// <summary> /// Gets or sets the malfunction. /// </summary> /// <value>The malfunction.</value> public Type1Parameter3Mode3CodeStatus.MalfunctionValue Malfunction { get { return this.malfunction; } set { this.malfunction = value; } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is Type1Parameter3Mode3CodeStatus)) { return false; } return this.Equals((Type1Parameter3Mode3CodeStatus)obj); } /// <summary> /// Determines whether the specified <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> instance is equal to this instance. /// </summary> /// <param name="other">The <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> instance to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(Type1Parameter3Mode3CodeStatus other) { // If parameter is null return false (cast to object to prevent recursive loop!) if ((object)other == null) { return false; } return this.CodeElement1 == other.CodeElement1 && this.CodeElement2 == other.CodeElement2 && this.CodeElement3 == other.CodeElement3 && this.CodeElement4 == other.CodeElement4 && this.Status == other.Status && this.Damage == other.Damage && this.Malfunction == other.Malfunction; } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> to the byte array. /// </summary> /// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> instance.</returns> public byte[] ToByteArray() { return BitConverter.GetBytes(this.ToUInt16()); } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> to the ushort value. /// </summary> /// <returns>The ushort value representing the current <see cref="OpenDis.Enumerations.DistributedEmission.Iff.Type1Parameter3Mode3CodeStatus"/> instance.</returns> public ushort ToUInt16() { ushort val = 0; val |= (ushort)((uint)this.CodeElement1 << 0); val |= (ushort)((uint)this.CodeElement2 << 3); val |= (ushort)((uint)this.CodeElement3 << 6); val |= (ushort)((uint)this.CodeElement4 << 9); val |= (ushort)((uint)this.Status << 13); val |= (ushort)((uint)this.Damage << 14); val |= (ushort)((uint)this.Malfunction << 15); return val; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { int hash = 17; // Overflow is fine, just wrap unchecked { hash = (hash * 29) + this.CodeElement1.GetHashCode(); hash = (hash * 29) + this.CodeElement2.GetHashCode(); hash = (hash * 29) + this.CodeElement3.GetHashCode(); hash = (hash * 29) + this.CodeElement4.GetHashCode(); hash = (hash * 29) + this.Status.GetHashCode(); hash = (hash * 29) + this.Damage.GetHashCode(); hash = (hash * 29) + this.Malfunction.GetHashCode(); } return hash; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using log4net; using OpenSim.Framework; namespace OpenSim.Region.Physics.Manager { /// <summary> /// Description of MyClass. /// </summary> public class PhysicsPluginManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<string, IPhysicsPlugin> _PhysPlugins = new Dictionary<string, IPhysicsPlugin>(); private Dictionary<string, IMeshingPlugin> _MeshPlugins = new Dictionary<string, IMeshingPlugin>(); /// <summary> /// Constructor. /// </summary> public PhysicsPluginManager() { // Load "plugins", that are hard coded and not existing in form of an external lib, and hence always // available IMeshingPlugin plugHard; plugHard = new ZeroMesherPlugin(); _MeshPlugins.Add(plugHard.GetName(), plugHard); m_log.Info("[PHYSICS]: Added meshing engine: " + plugHard.GetName()); } /// <summary> /// Get a physics scene for the given physics engine and mesher. /// </summary> /// <param name="physEngineName"></param> /// <param name="meshEngineName"></param> /// <param name="config"></param> /// <returns></returns> public PhysicsScene GetPhysicsScene(string physEngineName, string meshEngineName, IConfigSource config, string regionName) { if (String.IsNullOrEmpty(physEngineName)) { return PhysicsScene.Null; } if (String.IsNullOrEmpty(meshEngineName)) { return PhysicsScene.Null; } IMesher meshEngine = null; if (_MeshPlugins.ContainsKey(meshEngineName)) { m_log.Info("[PHYSICS]: creating meshing engine " + meshEngineName); meshEngine = _MeshPlugins[meshEngineName].GetMesher(config); } else { m_log.WarnFormat("[PHYSICS]: couldn't find meshingEngine: {0}", meshEngineName); throw new ArgumentException(String.Format("couldn't find meshingEngine: {0}", meshEngineName)); } if (_PhysPlugins.ContainsKey(physEngineName)) { m_log.Info("[PHYSICS]: creating " + physEngineName); PhysicsScene result = _PhysPlugins[physEngineName].GetScene(regionName); result.Initialise(meshEngine, config); return result; } else { m_log.WarnFormat("[PHYSICS]: couldn't find physicsEngine: {0}", physEngineName); throw new ArgumentException(String.Format("couldn't find physicsEngine: {0}", physEngineName)); } } /// <summary> /// Load all plugins in assemblies at the given path /// </summary> /// <param name="pluginsPath"></param> public void LoadPluginsFromAssemblies(string assembliesPath) { // Walk all assemblies (DLLs effectively) and see if they are home // of a plugin that is of interest for us string[] pluginFiles = Directory.GetFiles(assembliesPath, "*.dll"); for (int i = 0; i < pluginFiles.Length; i++) { LoadPluginsFromAssembly(pluginFiles[i]); } } /// <summary> /// Load plugins from an assembly at the given path /// </summary> /// <param name="assemblyPath"></param> public void LoadPluginsFromAssembly(string assemblyPath) { // TODO / NOTE // The assembly named 'OpenSim.Region.Physics.BasicPhysicsPlugin' was loaded from // 'file:///C:/OpenSim/trunk2/bin/Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll' // using the LoadFrom context. The use of this context can result in unexpected behavior // for serialization, casting and dependency resolution. In almost all cases, it is recommended // that the LoadFrom context be avoided. This can be done by installing assemblies in the // Global Assembly Cache or in the ApplicationBase directory and using Assembly. // Load when explicitly loading assemblies. Assembly pluginAssembly = null; Type[] types = null; try { pluginAssembly = Assembly.LoadFrom(assemblyPath); } catch (Exception ex) { m_log.Error("[PHYSICS]: Failed to load plugin from " + assemblyPath, ex); } if (pluginAssembly != null) { try { types = pluginAssembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath + ": " + ex.LoaderExceptions[0].Message, ex); } catch (Exception ex) { m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath, ex); } if (types != null) { foreach (Type pluginType in types) { if (pluginType.IsPublic) { if (!pluginType.IsAbstract) { Type physTypeInterface = pluginType.GetInterface("IPhysicsPlugin", true); if (physTypeInterface != null) { IPhysicsPlugin plug = (IPhysicsPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); plug.Init(); if (!_PhysPlugins.ContainsKey(plug.GetName())) { _PhysPlugins.Add(plug.GetName(), plug); m_log.Info("[PHYSICS]: Added physics engine: " + plug.GetName()); } } Type meshTypeInterface = pluginType.GetInterface("IMeshingPlugin", true); if (meshTypeInterface != null) { IMeshingPlugin plug = (IMeshingPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); if (!_MeshPlugins.ContainsKey(plug.GetName())) { _MeshPlugins.Add(plug.GetName(), plug); m_log.Info("[PHYSICS]: Added meshing engine: " + plug.GetName()); } } physTypeInterface = null; meshTypeInterface = null; } } } } } pluginAssembly = null; } //--- public static void PhysicsPluginMessage(string message, bool isWarning) { if (isWarning) { m_log.Warn("[PHYSICS]: " + message); } else { m_log.Info("[PHYSICS]: " + message); } } //--- } public interface IPhysicsPlugin { bool Init(); PhysicsScene GetScene(String sceneIdentifier); string GetName(); void Dispose(); } public interface IMeshingPlugin { string GetName(); IMesher GetMesher(IConfigSource config); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using Microsoft.Win32.SafeHandles; namespace System.Net.Security { // // Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob. // #if DEBUG internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle { #else internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid { #endif public SafeSspiAuthDataHandle() : base(true) { } protected override bool ReleaseHandle() { return Interop.SspiCli.SspiFreeAuthIdentity(handle) == Interop.SECURITY_STATUS.OK; } } // // A set of Safe Handles that depend on native FreeContextBuffer finalizer. // #if DEBUG internal abstract class SafeFreeContextBuffer : DebugSafeHandle { #else internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid { #endif protected SafeFreeContextBuffer() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { int res = -1; SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null; res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY); pkgArray = pkgArray_SECURITY; if (res != 0) { pkgArray?.SetHandleAsInvalid(); } return res; } internal static SafeFreeContextBuffer CreateEmptyHandle() { return new SafeFreeContextBuffer_SECURITY(); } // // After PInvoke call the method will fix the refHandle.handle with the returned value. // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned. // // This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.) // public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { if (refHandle is SafeFreeContextBuffer) { ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer); } else { ((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer); } } if (status != 0) { refHandle?.SetHandleAsInvalid(); } return status; } public static int SetContextAttributes( SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, byte[] buffer) { try { bool ignore = false; phContext.DangerousAddRef(ref ignore); return Interop.SspiCli.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length); } finally { phContext.DangerousRelease(); } } } internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer { internal SafeFreeContextBuffer_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } // // Implementation of handles required CertFreeCertificateContext // #if DEBUG internal sealed class SafeFreeCertContext : DebugSafeHandle { #else internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid { #endif internal SafeFreeCertContext() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } private const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040; protected override bool ReleaseHandle() { Interop.Crypt32.CertFreeCertificateContext(handle); return true; } } // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal abstract class SafeFreeCredentials : DebugSafeHandle { #else internal abstract class SafeFreeCredentials : SafeHandle { #endif internal Interop.SspiCli.CredHandle _handle; //should be always used as by ref in PInvokes parameters protected SafeFreeCredentials() : base(IntPtr.Zero, true) { _handle = new Interop.SspiCli.CredHandle(); } #if TRACE_VERBOSE public override string ToString() { return "0x" + _handle.ToString(); } #endif public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } #if DEBUG public new IntPtr DangerousGetHandle() { Debug.Fail("This method should never be called for this type"); throw NotImplemented.ByDesign; } #endif public static unsafe int AcquireDefaultCredential( string package, Interop.SspiCli.CredentialUse intent, out SafeFreeCredentials outCredential) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent); int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, IntPtr.Zero, null, null, ref outCredential._handle, out timeStamp); #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out timeStamp); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, Interop.SspiCli.CredentialUse intent, ref Interop.SspiCli.SCHANNEL_CRED authdata, out SafeFreeCredentials outCredential) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, package, intent, authdata); int errorCode = -1; long timeStamp; // If there is a certificate, wrap it into an array. // Not threadsafe. IntPtr copiedPtr = authdata.paCred; try { IntPtr certArrayPtr = new IntPtr(&copiedPtr); if (copiedPtr != IntPtr.Zero) { authdata.paCred = certArrayPtr; } outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp); } finally { authdata.paCred = copiedPtr; } #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } } // // This is a class holding a Credential handle reference, used for static handles cache // #if DEBUG internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid { #else internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid { #endif // // Static cache will return the target handle if found the reference in the table. // internal SafeFreeCredentials Target; internal static SafeCredentialReference CreateReference(SafeFreeCredentials target) { SafeCredentialReference result = new SafeCredentialReference(target); if (result.IsInvalid) { return null; } return result; } private SafeCredentialReference(SafeFreeCredentials target) : base() { // Bumps up the refcount on Target to signify that target handle is statically cached so // its dispose should be postponed bool ignore = false; target.DangerousAddRef(ref ignore); Target = target; SetHandle(new IntPtr(0)); // make this handle valid } protected override bool ReleaseHandle() { SafeFreeCredentials target = Target; target?.DangerousRelease(); Target = null; return true; } } internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials { public SafeFreeCredential_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.SspiCli.FreeCredentialsHandle(ref _handle) == 0; } } // // Implementation of handles that are dependent on DeleteSecurityContext // #if DEBUG internal abstract partial class SafeDeleteContext : DebugSafeHandle { #else internal abstract partial class SafeDeleteContext : SafeHandle { #endif private const string dummyStr = " "; private static readonly IdnMapping s_idnMapping = new IdnMapping(); protected SafeFreeCredentials _EffectiveCredential; //------------------------------------------------------------------- internal static unsafe int InitializeSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, ReadOnlySpan<SecurityBuffer> inSecBuffers, ref SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { #if TRACE_VERBOSE if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, $"credential:{inCredentials}, crefContext:{refContext}, targetName:{targetName}, inFlags:{inFlags}, endianness:{endianness}"); NetEventSource.Info(null, $"inSecBuffers.Length = {inSecBuffers.Length}"); } #endif if (inCredentials == null) { throw new ArgumentNullException(nameof(inCredentials)); } Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; bool isContextAbsent = true; if (refContext != null) { isContextAbsent = refContext._handle.IsZero; } // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { Span<Interop.SspiCli.SecBuffer> inUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[inSecurityBufferDescriptor.cBuffers]; inUnmanagedBuffer.Clear(); fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) fixed (void* pinnedToken0 = inSecBuffers.Length > 0 ? inSecBuffers[0].token : null) fixed (void* pinnedToken1 = inSecBuffers.Length > 1 ? inSecBuffers[1].token : null) fixed (void* pinnedToken2 = inSecBuffers.Length > 2 ? inSecBuffers[2].token : null) // pin all buffers, even if null or not used, to avoid needing to allocate GCHandles { Debug.Assert(inSecBuffers.Length <= 3); // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { ref readonly SecurityBuffer securityBuffer = ref inSecBuffers[index]; // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken != null ? securityBuffer.unmanagedToken.DangerousGetHandle() : securityBuffer.token == null || securityBuffer.token.Length == 0 ? IntPtr.Zero : Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}"); #endif } fixed (byte* pinnedOutBytes = outSecBuffer.token) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. Interop.SspiCli.SecBuffer outUnmanagedBuffer = default; outSecurityBufferDescriptor.pBuffers = &outUnmanagedBuffer; outUnmanagedBuffer.cbBuffer = outSecBuffer.size; outUnmanagedBuffer.BufferType = outSecBuffer.type; outUnmanagedBuffer.pvBuffer = outSecBuffer.token == null || outSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedOutBytes + outSecBuffer.offset); if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to InitializeSecurityContextW in cases where an "contextHandle" was // already present and non-zero. if (isContextAbsent) refContext = new SafeDeleteContext_SECURITY(); } if (targetName == null || targetName.Length == 0) { targetName = dummyStr; } string punyCode = s_idnMapping.GetAscii(targetName); fixed (char* namePtr = punyCode) { errorCode = MustRunInitializeSecurityContext( ref inCredentials, isContextAbsent, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, &inSecurityBufferDescriptor, refContext, ref outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); } if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshalling OUT buffer"); // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer.cbBuffer; outSecBuffer.type = outUnmanagedBuffer.BufferType; outSecBuffer.token = outSecBuffer.size > 0 ? new Span<byte>((byte*)outUnmanagedBuffer.pvBuffer, outUnmanagedBuffer.cbBuffer).ToArray() : null; } } } finally { outFreeContextBuffer?.Dispose(); } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}"); return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunInitializeSecurityContext( ref SafeFreeCredentials inCredentials, bool isContextAbsent, byte* targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, Interop.SspiCli.SecBufferDesc* inputBuffer, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags attributes, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; // Now that "outContext" (or "refContext" by the caller) references an actual handle (and cannot // be closed until it is released below), point "inContextPtr" to its embedded handle (or // null if the embedded handle has not yet been initialized). Interop.SspiCli.CredHandle contextHandle = outContext._handle; void* inContextPtr = contextHandle.IsZero ? null : &contextHandle; // The "isContextAbsent" supplied by the caller is generally correct but was computed without proper // synchronization. Rewrite the indicator now that the final "inContext" is known, update if necessary. isContextAbsent = (inContextPtr == null); errorCode = Interop.SspiCli.InitializeSecurityContextW( ref credentialHandle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, ref outputBuffer, ref attributes, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle outContext._EffectiveCredential?.DangerousRelease(); outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (isContextAbsent && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } return errorCode; } //------------------------------------------------------------------- internal static unsafe int AcceptSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, ReadOnlySpan<SecurityBuffer> inSecBuffers, ref SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { #if TRACE_VERBOSE if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, $"credential={inCredentials}, refContext={refContext}, inFlags={inFlags}"); NetEventSource.Info(null, $"inSecBuffers.Length = {inSecBuffers.Length}"); } #endif if (inCredentials == null) { throw new ArgumentNullException(nameof(inCredentials)); } Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Length); Interop.SspiCli.SecBufferDesc outSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.SspiCli.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; bool isContextAbsent = true; if (refContext != null) { isContextAbsent = refContext._handle.IsZero; } // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { Span<Interop.SspiCli.SecBuffer> inUnmanagedBuffer = stackalloc Interop.SspiCli.SecBuffer[inSecurityBufferDescriptor.cBuffers]; inUnmanagedBuffer.Clear(); fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) fixed (void* pinnedToken0 = inSecBuffers.Length > 0 ? inSecBuffers[0].token : null) fixed (void* pinnedToken1 = inSecBuffers.Length > 1 ? inSecBuffers[1].token : null) fixed (void* pinnedToken2 = inSecBuffers.Length > 2 ? inSecBuffers[2].token : null) // pin all buffers, even if null or not used, to avoid needing to allocate GCHandles { Debug.Assert(inSecBuffers.Length <= 3); // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.pBuffers = inUnmanagedBufferPtr; for (int index = 0; index < inSecurityBufferDescriptor.cBuffers; ++index) { ref readonly SecurityBuffer securityBuffer = ref inSecBuffers[index]; // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].cbBuffer = securityBuffer.size; inUnmanagedBuffer[index].BufferType = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. inUnmanagedBuffer[index].pvBuffer = securityBuffer.unmanagedToken != null ? securityBuffer.unmanagedToken.DangerousGetHandle() : securityBuffer.token == null || securityBuffer.token.Length == 0 ? IntPtr.Zero : Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{securityBuffer.size} BufferType:{securityBuffer.type}"); #endif } fixed (byte* pinnedOutBytes = outSecBuffer.token) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. Interop.SspiCli.SecBuffer outUnmanagedBuffer = default; outSecurityBufferDescriptor.pBuffers = &outUnmanagedBuffer; // Copy the SecurityBuffer content into unmanaged place holder. outUnmanagedBuffer.cbBuffer = outSecBuffer.size; outUnmanagedBuffer.BufferType = outSecBuffer.type; outUnmanagedBuffer.pvBuffer = outSecBuffer.token == null || outSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedOutBytes + outSecBuffer.offset); if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to AcceptSecurityContext in cases where an "contextHandle" was // already present and non-zero. if (isContextAbsent) refContext = new SafeDeleteContext_SECURITY(); } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, isContextAbsent, &inSecurityBufferDescriptor, inFlags, endianness, refContext, ref outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Marshaling OUT buffer"); // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer.cbBuffer; outSecBuffer.type = outUnmanagedBuffer.BufferType; outSecBuffer.token = outUnmanagedBuffer.cbBuffer > 0 ? new Span<byte>((byte*)outUnmanagedBuffer.pvBuffer, outUnmanagedBuffer.cbBuffer).ToArray() : null; } } } finally { outFreeContextBuffer?.Dispose(); } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"errorCode:0x{errorCode:x8}, refContext:{refContext}"); return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavor or null can be passed if no handle is returned. // private static unsafe int MustRunAcceptSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, bool isContextAbsent, Interop.SspiCli.SecBufferDesc* inputBuffer, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness endianness, SafeDeleteContext outContext, ref Interop.SspiCli.SecBufferDesc outputBuffer, ref Interop.SspiCli.ContextFlags outFlags, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // Run the body of this method as a non-interruptible block. try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.SspiCli.CredHandle credentialHandle = inCredentials._handle; long timeStamp; // Now that "outContext" (or "refContext" by the caller) references an actual handle (and cannot // be closed until it is released below), point "inContextPtr" to its embedded handle (or // null if the embedded handle has not yet been initialized). Interop.SspiCli.CredHandle contextHandle = outContext._handle; void* inContextPtr = contextHandle.IsZero ? null : &contextHandle; // The "isContextAbsent" supplied by the caller is generally correct but was computed without proper // synchronization. Rewrite the indicator now that the final "inContext" is known, update if necessary. isContextAbsent = (inContextPtr == null); errorCode = Interop.SspiCli.AcceptSecurityContext( ref credentialHandle, inContextPtr, inputBuffer, inFlags, endianness, ref outContext._handle, ref outputBuffer, ref outFlags, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle. outContext._EffectiveCredential?.DangerousRelease(); outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes. handleTemplate.Set(((Interop.SspiCli.SecBuffer*)outputBuffer.pBuffers)->pvBuffer); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (isContextAbsent && (errorCode & 0x80000000) != 0) { // An error on the first call, need to set the out handle to invalid value. outContext._handle.SetToInvalid(); } return errorCode; } internal static unsafe int CompleteAuthToken( ref SafeDeleteContext refContext, in SecurityBuffer inSecBuffer) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(null, "SafeDeleteContext::CompleteAuthToken"); NetEventSource.Info(null, $" refContext = {refContext}"); NetEventSource.Info(null, $" inSecBuffer = {inSecBuffer}"); } var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; Interop.SspiCli.SecBuffer inUnmanagedBuffer = default; inSecurityBufferDescriptor.pBuffers = &inUnmanagedBuffer; fixed (byte* pinnedToken = inSecBuffer.token) { inUnmanagedBuffer.cbBuffer = inSecBuffer.size; inUnmanagedBuffer.BufferType = inSecBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. inUnmanagedBuffer.pvBuffer = inSecBuffer.unmanagedToken != null ? inSecBuffer.unmanagedToken.DangerousGetHandle() : inSecBuffer.token == null || inSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedToken + inSecBuffer.offset); #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{inSecBuffer.size} BufferType: {inSecBuffer.type}"); #endif Interop.SspiCli.CredHandle contextHandle = refContext != null ? refContext._handle : default; if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to CompleteAuthToken in cases where a nonzero "contextHandle" was // already present. In these cases, allow the "refContext" to flow through unmodified // (which will generate an ObjectDisposedException below). In all other cases, continue to // build a new "refContext" in an attempt to maximize compat. if (contextHandle.IsZero) { refContext = new SafeDeleteContext_SECURITY(); } } bool gotRef = false; try { refContext.DangerousAddRef(ref gotRef); errorCode = Interop.SspiCli.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { if (gotRef) { refContext.DangerousRelease(); } } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged CompleteAuthToken() errorCode:0x{errorCode:x8} refContext:{refContext}"); return errorCode; } internal static unsafe int ApplyControlToken( ref SafeDeleteContext refContext, in SecurityBuffer inSecBuffer) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(null); NetEventSource.Info(null, $" refContext = {refContext}"); NetEventSource.Info(null, $" inSecBuffer = {inSecBuffer}"); } int errorCode = (int)Interop.SECURITY_STATUS.InvalidHandle; // Fix Descriptor pointer that points to unmanaged SecurityBuffers. fixed (byte* pinnedInSecBufferToken = inSecBuffer.token) { var inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(1); Interop.SspiCli.SecBuffer inUnmanagedBuffer = default; inSecurityBufferDescriptor.pBuffers = &inUnmanagedBuffer; inUnmanagedBuffer.cbBuffer = inSecBuffer.size; inUnmanagedBuffer.BufferType = inSecBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. inUnmanagedBuffer.pvBuffer = inSecBuffer.unmanagedToken != null ? inSecBuffer.unmanagedToken.DangerousGetHandle() : inSecBuffer.token == null || inSecBuffer.token.Length == 0 ? IntPtr.Zero : (IntPtr)(pinnedInSecBufferToken + inSecBuffer.offset); #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"SecBuffer: cbBuffer:{inSecBuffer.size} BufferType:{inSecBuffer.type}"); #endif Interop.SspiCli.CredHandle contextHandle = refContext != null ? refContext._handle : default; if (refContext == null || refContext.IsInvalid) { // Previous versions unconditionally built a new "refContext" here, but would pass // incorrect arguments to ApplyControlToken in cases where a nonzero "contextHandle" was // already present. In these cases, allow the "refContext" to flow through unmodified // (which will generate an ObjectDisposedException below). In all other cases, continue to // build a new "refContext" in an attempt to maximize compat. if (contextHandle.IsZero) { refContext = new SafeDeleteContext_SECURITY(); } } bool gotRef = false; try { refContext.DangerousAddRef(ref gotRef); errorCode = Interop.SspiCli.ApplyControlToken(contextHandle.IsZero ? null : &contextHandle, ref inSecurityBufferDescriptor); } finally { if (gotRef) { refContext.DangerousRelease(); } } } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"unmanaged ApplyControlToken() errorCode:0x{errorCode:x8} refContext: {refContext}"); return errorCode; } } internal sealed class SafeDeleteContext_SECURITY : SafeDeleteContext { internal SafeDeleteContext_SECURITY() : base() { } protected override bool ReleaseHandle() { this._EffectiveCredential?.DangerousRelease(); return Interop.SspiCli.DeleteSecurityContext(ref _handle) == 0; } } // Based on SafeFreeContextBuffer. internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding { private int _size; public override int Size { get { return _size; } } public override bool IsInvalid { get { return handle == new IntPtr(0) || handle == new IntPtr(-1); } } internal unsafe void Set(IntPtr value) { this.handle = value; } internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle() { return new SafeFreeContextBufferChannelBinding_SECURITY(); } public static unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute contextAttribute, SecPkgContext_Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { int status = (int)Interop.SECURITY_STATUS.InvalidHandle; // SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which // map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique. if (contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_ENDPOINT_BINDINGS && contextAttribute != Interop.SspiCli.ContextAttribute.SECPKG_ATTR_UNIQUE_BINDINGS) { return status; } try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.SspiCli.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { refHandle.Set((*buffer).Bindings); refHandle._size = (*buffer).BindingsLength; } if (status != 0) { refHandle?.SetHandleAsInvalid(); } return status; } public override string ToString() { if (IsInvalid) { return null; } var bytes = new byte[_size]; Marshal.Copy(handle, bytes, 0, bytes.Length); return BitConverter.ToString(bytes).Replace('-', ' '); } } internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding { protected override bool ReleaseHandle() { return Interop.SspiCli.FreeContextBuffer(handle) == 0; } } }
// 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.IO; using System.Linq; using System.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class PublicKeyTests { private static PublicKey GetTestRsaKey() { using (var cert = new X509Certificate2(TestData.MsCertificate)) { return cert.PublicKey; } } private static PublicKey GetTestDsaKey() { using (var cert = new X509Certificate2(TestData.DssCer)) { return cert.PublicKey; } } private static PublicKey GetTestECDsaKey() { using (var cert = new X509Certificate2(TestData.ECDsa256Certificate)) { return cert.PublicKey; } } /// <summary> /// First parameter is the cert, the second is a hash of "Hello" /// </summary> public static IEnumerable<object[]> BrainpoolCurves { get { yield return new object[] { TestData.ECDsabrainpoolP160r1_CertificatePemBytes, "9145C79DD4DF758EB377D13B0DB81F83CE1A63A4099DDC32FE228B06EB1F306423ED61B6B4AF4691".HexToByteArray() }; yield return new object[] { TestData.ECDsabrainpoolP160r1_ExplicitCertificatePemBytes, "6D74F1C9BCBBA5A25F67E670B3DABDB36C24E8FAC3266847EB2EE7E3239208ADC696BB421AB380B4".HexToByteArray() }; } } [Fact] public static void TestOid_RSA() { PublicKey pk = GetTestRsaKey(); Assert.Equal("1.2.840.113549.1.1.1", pk.Oid.Value); } [Fact] public static void TestOid_DSA() { PublicKey pk = GetTestDsaKey(); Assert.Equal("1.2.840.10040.4.1", pk.Oid.Value); } [Fact] public static void TestOid_ECDSA() { PublicKey pk = GetTestECDsaKey(); Assert.Equal("1.2.840.10045.2.1", pk.Oid.Value); } [Fact] public static void TestPublicKey_Key_RSA() { PublicKey pk = GetTestRsaKey(); using (AsymmetricAlgorithm alg = pk.Key) { Assert.NotNull(alg); Assert.Same(alg, pk.Key); Assert.Equal(2048, alg.KeySize); Assert.IsAssignableFrom<RSA>(alg); VerifyKey_RSA( /* cert */ null, (RSA)alg); } } [Fact] public static void TestPublicKey_Key_DSA() { PublicKey pk = GetTestDsaKey(); using (AsymmetricAlgorithm alg = pk.Key) { Assert.NotNull(alg); Assert.Same(alg, pk.Key); Assert.Equal(1024, alg.KeySize); Assert.IsAssignableFrom<DSA>(alg); VerifyKey_DSA((DSA)alg); } } [Fact] public static void TestPublicKey_Key_ECDSA() { PublicKey pk = GetTestECDsaKey(); Assert.Throws<NotSupportedException>(() => pk.Key); } private static void VerifyKey_DSA(DSA dsa) { DSAParameters dsaParameters = dsa.ExportParameters(false); byte[] expected_g = ( "859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481584413" + "E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310FEFD518" + "AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0DAFDA0" + "79BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D05431D").HexToByteArray(); byte[] expected_p = ( "871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180511D0DCEB8B97928" + "5708C800FC10CB15337A4AC1A48ED31394072015A7A6B525986B49E5E1139737" + "A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA41E8F0763AA613E29" + "C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DFB33C44D2F2DBE819").HexToByteArray(); byte[] expected_q = "E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D".HexToByteArray(); byte[] expected_y = ( "089A43F439B924BEF3529D8D6206D1FCA56A55CAF52B41D6CE371EBF07BDA132" + "C8EADC040007FCF4DA06C1F30504EBD8A77D301F5A4702F01F0D2A0707AC1DA3" + "8DD3251883286E12456234DA62EDA0DF5FE2FA07CD5B16F3638BECCA7786312D" + "A7D3594A4BB14E353884DA0E9AECB86E3C9BDB66FCA78EA85E1CC3F2F8BF0963").HexToByteArray(); Assert.Equal(expected_g, dsaParameters.G); Assert.Equal(expected_p, dsaParameters.P); Assert.Equal(expected_q, dsaParameters.Q); Assert.Equal(expected_y, dsaParameters.Y); } [Fact] public static void TestEncodedKeyValue_RSA() { byte[] expectedPublicKey = ( "3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" + "407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" + "137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" + "b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" + "109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" + "2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" + "2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" + "84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" + "0b950005b14f6571c50203010001").HexToByteArray(); PublicKey pk = GetTestRsaKey(); Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData); } [Fact] public static void TestEncodedKeyValue_DSA() { byte[] expectedPublicKey = ( "028180089a43f439b924bef3529d8d6206d1fca56a55caf52b41d6ce371ebf07" + "bda132c8eadc040007fcf4da06c1f30504ebd8a77d301f5a4702f01f0d2a0707" + "ac1da38dd3251883286e12456234da62eda0df5fe2fa07cd5b16f3638becca77" + "86312da7d3594a4bb14e353884da0e9aecb86e3c9bdb66fca78ea85e1cc3f2f8" + "bf0963").HexToByteArray(); PublicKey pk = GetTestDsaKey(); Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData); } [Fact] public static void TestEncodedKeyValue_ECDSA() { // Uncompressed key (04), then the X coord, then the Y coord. string expectedPublicKeyHex = "04" + "448D98EE08AEBA0D8B40F3C6DBD500E8B69F07C70C661771655228EA5A178A91" + "0EF5CB1759F6F2E062021D4F973F5BB62031BE87AE915CFF121586809E3219AF"; PublicKey pk = GetTestECDsaKey(); Assert.Equal(expectedPublicKeyHex, pk.EncodedKeyValue.RawData.ByteArrayToHex()); } [Fact] public static void TestEncodedParameters_RSA() { PublicKey pk = GetTestRsaKey(); // RSA has no key parameters, so the answer is always // DER:NULL (type 0x05, length 0x00) Assert.Equal(new byte[] { 0x05, 0x00 }, pk.EncodedParameters.RawData); } [Fact] public static void TestEncodedParameters_DSA() { byte[] expectedParameters = ( "3082011F02818100871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180" + "511D0DCEB8B979285708C800FC10CB15337A4AC1A48ED31394072015A7A6B525" + "986B49E5E1139737A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA4" + "1E8F0763AA613E29C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DF" + "B33C44D2F2DBE819021500E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D02" + "818100859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481" + "584413E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310F" + "EFD518AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0" + "DAFDA079BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D" + "05431D").HexToByteArray(); PublicKey pk = GetTestDsaKey(); Assert.Equal(expectedParameters, pk.EncodedParameters.RawData); } [Fact] public static void TestEncodedParameters_ECDSA() { // OID: 1.2.840.10045.3.1.7 string expectedParametersHex = "06082A8648CE3D030107"; PublicKey pk = GetTestECDsaKey(); Assert.Equal(expectedParametersHex, pk.EncodedParameters.RawData.ByteArrayToHex()); } [Fact] public static void TestKey_RSA() { using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { RSA rsa = cert.GetRSAPublicKey(); VerifyKey_RSA(cert, rsa); } } private static void VerifyKey_RSA(X509Certificate2 cert, RSA rsa) { RSAParameters rsaParameters = rsa.ExportParameters(false); byte[] expectedModulus = ( "E8AF5CA2200DF8287CBC057B7FADEEEB76AC28533F3ADB407DB38E33E6573FA5" + "51153454A5CFB48BA93FA837E12D50ED35164EEF4D7ADB137688B02CF0595CA9" + "EBE1D72975E41B85279BF3F82D9E41362B0B40FBBE3BBAB95C759316524BCA33" + "C537B0F3EB7EA8F541155C08651D2137F02CBA220B10B1109D772285847C4FB9" + "1B90B0F5A3FE8BF40C9A4EA0F5C90A21E2AAE3013647FD2F826A8103F5A935DC" + "94579DFB4BD40E82DB388F12FEE3D67A748864E162C4252E2AAE9D181F0E1EB6" + "C2AF24B40E50BCDE1C935C49A679B5B6DBCEF9707B280184B82A29CFBFA90505" + "E1E00F714DFDAD5C238329EBC7C54AC8E82784D37EC6430B950005B14F6571C5").HexToByteArray(); byte[] expectedExponent = new byte[] { 0x01, 0x00, 0x01 }; byte[] originalModulus = rsaParameters.Modulus; byte[] originalExponent = rsaParameters.Exponent; if (!expectedModulus.SequenceEqual(rsaParameters.Modulus) || !expectedExponent.SequenceEqual(rsaParameters.Exponent)) { Console.WriteLine("Modulus or Exponent not equal"); rsaParameters = rsa.ExportParameters(false); if (!expectedModulus.SequenceEqual(rsaParameters.Modulus) || !expectedExponent.SequenceEqual(rsaParameters.Exponent)) { Console.WriteLine("Second call to ExportParameters did not produce valid data either"); } if (cert != null) { rsa = cert.GetRSAPublicKey(); rsaParameters = rsa.ExportParameters(false); if (!expectedModulus.SequenceEqual(rsaParameters.Modulus) || !expectedExponent.SequenceEqual(rsaParameters.Exponent)) { Console.WriteLine("New key handle ExportParameters was not successful either"); } } } Assert.Equal(expectedModulus, originalModulus); Assert.Equal(expectedExponent, originalExponent); } [Fact] public static void TestKey_RSA384_ValidatesSignature() { byte[] signature = { 0x79, 0xD9, 0x3C, 0xBF, 0x54, 0xFA, 0x55, 0x8C, 0x44, 0xC3, 0xC3, 0x83, 0x85, 0xBB, 0x78, 0x44, 0xCD, 0x0F, 0x5A, 0x8E, 0x71, 0xC9, 0xC2, 0x68, 0x68, 0x0A, 0x33, 0x93, 0x19, 0x37, 0x02, 0x06, 0xE2, 0xF7, 0x67, 0x97, 0x3C, 0x67, 0xB3, 0xF4, 0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C, }; byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes)) using (RSA rsa = cert.GetRSAPublicKey()) { Assert.True(rsa.VerifyData(helloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)); } } [Theory, MemberData(nameof(BrainpoolCurves))] public static void TestKey_ECDsabrainpool_PublicKey(byte[] curveData, byte[] notUsed) { _ = notUsed; byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); try { using (var cert = new X509Certificate2(curveData)) { using (ECDsa ec = cert.GetECDsaPublicKey()) { Assert.Equal(160, ec.KeySize); // The public key should be unable to sign. Assert.ThrowsAny<CryptographicException>(() => ec.SignData(helloBytes, HashAlgorithmName.SHA256)); } } } catch (CryptographicException) { // Windows 7, Windows 8, Ubuntu 14, CentOS can fail. Verify known good platforms don't fail. Assert.False(PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10); Assert.False(PlatformDetection.IsUbuntu && !PlatformDetection.IsUbuntu1404); } } [Fact] public static void TestECDsaPublicKey() { byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(384, publicKey.KeySize); // The public key should be unable to sign. Assert.ThrowsAny<CryptographicException>(() => publicKey.SignData(helloBytes, HashAlgorithmName.SHA256)); } } [Fact] public static void TestECDsaPublicKey_ValidatesSignature() { // This signature was produced as the output of ECDsaCng.SignData with the same key // on .NET 4.6. Ensure it is verified here as a data compatibility test. // // Note that since ECDSA signatures contain randomness as an input, this value is unlikely // to be reproduced by another equivalent program. byte[] existingSignature = { // r: 0x7E, 0xD7, 0xEF, 0x46, 0x04, 0x92, 0x61, 0x27, 0x9F, 0xC9, 0x1B, 0x7B, 0x8A, 0x41, 0x6A, 0xC6, 0xCF, 0xD4, 0xD4, 0xD1, 0x73, 0x05, 0x1F, 0xF3, 0x75, 0xB2, 0x13, 0xFA, 0x82, 0x2B, 0x55, 0x11, 0xBE, 0x57, 0x4F, 0x20, 0x07, 0x24, 0xB7, 0xE5, 0x24, 0x44, 0x33, 0xC3, 0xB6, 0x8F, 0xBC, 0x1F, // s: 0x48, 0x57, 0x25, 0x39, 0xC0, 0x84, 0xB9, 0x0E, 0xDA, 0x32, 0x35, 0x16, 0xEF, 0xA0, 0xE2, 0x34, 0x35, 0x7E, 0x10, 0x38, 0xA5, 0xE4, 0x8B, 0xD3, 0xFC, 0xE7, 0x60, 0x25, 0x4E, 0x63, 0xF7, 0xDB, 0x7C, 0xBF, 0x18, 0xD6, 0xD3, 0x49, 0xD0, 0x93, 0x08, 0xC5, 0xAA, 0xA6, 0xE5, 0xFD, 0xD0, 0x96, }; byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(384, publicKey.KeySize); bool isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256); Assert.True(isSignatureValid, "isSignatureValid"); } } [Theory, MemberData(nameof(BrainpoolCurves))] public static void TestECDsaPublicKey_BrainpoolP160r1_ValidatesSignature(byte[] curveData, byte[] existingSignature) { byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); try { using (var cert = new X509Certificate2(curveData)) { using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(160, publicKey.KeySize); // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); bool isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256); Assert.True(isSignatureValid, "isSignatureValid"); unchecked { --existingSignature[existingSignature.Length - 1]; } isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256); Assert.False(isSignatureValid, "isSignatureValidNeg"); } } } catch (CryptographicException) { // Windows 7, Windows 8, Ubuntu 14, CentOS can fail. Verify known good platforms don't fail. Assert.False(PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10); Assert.False(PlatformDetection.IsUbuntu && !PlatformDetection.IsUbuntu1404); } } [Fact] public static void TestECDsaPublicKey_NonSignatureCert() { using (var cert = new X509Certificate2(TestData.EccCert_KeyAgreement)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); // But, due to KeyUsage, it shouldn't be used for ECDSA. Assert.Null(publicKey); } } [Fact] public static void TestECDsa224PublicKey() { using (var cert = new X509Certificate2(TestData.ECDsa224Certificate)) { // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); ECDsa ecdsa; try { ecdsa = cert.GetECDsaPublicKey(); } catch (CryptographicException) { // Windows 7, Windows 8, CentOS. return; } // Other Unix using (ecdsa) { byte[] data = ByteUtils.AsciiBytes("Hello"); byte[] signature = ( // r "8ede5053d546d35c1aba829bca3ecf493eb7a73f751548bd4cf2ad10" + // s "5e3da9d359001a6be18e2b4e49205e5219f30a9daeb026159f41b9de").HexToByteArray(); Assert.True(ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA1)); } } } #if !NO_DSA_AVAILABLE [Fact] public static void TestDSAPublicKey() { using (var cert = new X509Certificate2(TestData.DssCer)) using (DSA pubKey = cert.GetDSAPublicKey()) { Assert.NotNull(pubKey); VerifyKey_DSA(pubKey); } } [Fact] public static void TestDSAPublicKey_VerifiesSignature() { byte[] data = { 1, 2, 3, 4, 5 }; byte[] wrongData = { 0xFE, 2, 3, 4, 5 }; byte[] signature = "B06E26CFC939F25B864F52ABD3288222363A164259B0027FFC95DBC88F9204F7A51A901F3005C9F7".HexToByteArray(); using (var cert = new X509Certificate2(TestData.Dsa1024Cert)) using (DSA pubKey = cert.GetDSAPublicKey()) { Assert.True(pubKey.VerifyData(data, signature, HashAlgorithmName.SHA1), "pubKey verifies signature"); Assert.False(pubKey.VerifyData(wrongData, signature, HashAlgorithmName.SHA1), "pubKey verifies tampered data"); signature[0] ^= 0xFF; Assert.False(pubKey.VerifyData(data, signature, HashAlgorithmName.SHA1), "pubKey verifies tampered signature"); } } [Fact] public static void TestDSAPublicKey_RSACert() { using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes)) using (DSA pubKey = cert.GetDSAPublicKey()) { Assert.Null(pubKey); } } [Fact] public static void TestDSAPublicKey_ECDSACert() { using (var cert = new X509Certificate2(TestData.ECDsa256Certificate)) using (DSA pubKey = cert.GetDSAPublicKey()) { Assert.Null(pubKey); } } #endif [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public static void TestKey_ECDsaCng256() { TestKey_ECDsaCng(TestData.ECDsa256Certificate, TestData.ECDsaCng256PublicKey); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public static void TestKey_ECDsaCng384() { TestKey_ECDsaCng(TestData.ECDsa384Certificate, TestData.ECDsaCng384PublicKey); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public static void TestKey_ECDsaCng521() { TestKey_ECDsaCng(TestData.ECDsa521Certificate, TestData.ECDsaCng521PublicKey); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public static void TestKey_BrainpoolP160r1() { if (PlatformDetection.WindowsVersion >= 10) { TestKey_ECDsaCng(TestData.ECDsabrainpoolP160r1_CertificatePemBytes, TestData.ECDsabrainpoolP160r1_PublicKey); } } private static void TestKey_ECDsaCng(byte[] certBytes, TestData.ECDsaCngKeyValues expected) { using (X509Certificate2 cert = new X509Certificate2(certBytes)) { ECDsaCng e = (ECDsaCng)(cert.GetECDsaPublicKey()); CngKey k = e.Key; byte[] blob = k.Export(CngKeyBlobFormat.EccPublicBlob); using (BinaryReader br = new BinaryReader(new MemoryStream(blob))) { int magic = br.ReadInt32(); int cbKey = br.ReadInt32(); Assert.Equal(expected.QX.Length, cbKey); byte[] qx = br.ReadBytes(cbKey); byte[] qy = br.ReadBytes(cbKey); Assert.Equal<byte>(expected.QX, qx); Assert.Equal<byte>(expected.QY, qy); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SecurityTests.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.ServiceModel.Security; namespace System.ServiceModel.Description { internal class DispatcherBuilder { internal static ClientRuntime BuildProxyBehavior(ServiceEndpoint serviceEndpoint, out BindingParameterCollection parameters) { parameters = new BindingParameterCollection(); SecurityContractInformationEndpointBehavior.ClientInstance.AddBindingParameters(serviceEndpoint, parameters); AddBindingParameters(serviceEndpoint, parameters); ContractDescription contractDescription = serviceEndpoint.Contract; ClientRuntime clientRuntime = new ClientRuntime(contractDescription.Name, contractDescription.Namespace); clientRuntime.ContractClientType = contractDescription.ContractType; IdentityVerifier identityVerifier = serviceEndpoint.Binding.GetProperty<IdentityVerifier>(parameters); if (identityVerifier != null) { clientRuntime.IdentityVerifier = identityVerifier; } for (int i = 0; i < contractDescription.Operations.Count; i++) { OperationDescription operation = contractDescription.Operations[i]; if (!operation.IsServerInitiated()) { DispatcherBuilder.BuildProxyOperation(operation, clientRuntime); } else { DispatcherBuilder.BuildDispatchOperation(operation, clientRuntime.CallbackDispatchRuntime); } } DispatcherBuilder.ApplyClientBehavior(serviceEndpoint, clientRuntime); return clientRuntime; } internal class ListenUriInfo { private Uri _listenUri; private ListenUriMode _listenUriMode; public ListenUriInfo(Uri listenUri, ListenUriMode listenUriMode) { _listenUri = listenUri; _listenUriMode = listenUriMode; } public Uri ListenUri { get { return _listenUri; } } public ListenUriMode ListenUriMode { get { return _listenUriMode; } } // implement Equals and GetHashCode so that we can use this as a key in a dictionary public override bool Equals(Object other) { return this.Equals(other as ListenUriInfo); } public bool Equals(ListenUriInfo other) { if (other == null) { return false; } if (object.ReferenceEquals(this, other)) { return true; } return (_listenUriMode == other._listenUriMode) && EndpointAddress.UriEquals(_listenUri, other._listenUri, true /* ignoreCase */, true /* includeHost */); } public override int GetHashCode() { return EndpointAddress.UriGetHashCode(_listenUri, true /* includeHost */); } } private static void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection parameters) { foreach (IContractBehavior icb in endpoint.Contract.Behaviors) { icb.AddBindingParameters(endpoint.Contract, endpoint, parameters); } foreach (IEndpointBehavior ieb in endpoint.Behaviors) { ieb.AddBindingParameters(endpoint, parameters); } foreach (OperationDescription op in endpoint.Contract.Operations) { foreach (IOperationBehavior iob in op.Behaviors) { iob.AddBindingParameters(op, parameters); } } } private static void BuildProxyOperation(OperationDescription operation, ClientRuntime parent) { ClientOperation child; if (operation.Messages.Count == 1) { child = new ClientOperation(parent, operation.Name, operation.Messages[0].Action); } else { child = new ClientOperation(parent, operation.Name, operation.Messages[0].Action, operation.Messages[1].Action); } child.TaskMethod = operation.TaskMethod; child.TaskTResult = operation.TaskTResult; child.SyncMethod = operation.SyncMethod; child.BeginMethod = operation.BeginMethod; child.EndMethod = operation.EndMethod; child.IsOneWay = operation.IsOneWay; child.IsInitiating = operation.IsInitiating; child.IsTerminating = operation.IsTerminating; child.IsSessionOpenNotificationEnabled = operation.IsSessionOpenNotificationEnabled; for (int i = 0; i < operation.Faults.Count; i++) { FaultDescription fault = operation.Faults[i]; child.FaultContractInfos.Add(new FaultContractInfo(fault.Action, fault.DetailType, fault.ElementName, fault.Namespace, operation.KnownTypes)); } parent.Operations.Add(child); } private static void BuildDispatchOperation(OperationDescription operation, DispatchRuntime parent) { string requestAction = operation.Messages[0].Action; DispatchOperation child = null; if (operation.IsOneWay) { child = new DispatchOperation(parent, operation.Name, requestAction); } else { string replyAction = operation.Messages[1].Action; child = new DispatchOperation(parent, operation.Name, requestAction, replyAction); } child.HasNoDisposableParameters = operation.HasNoDisposableParameters; child.IsTerminating = operation.IsTerminating; child.IsSessionOpenNotificationEnabled = operation.IsSessionOpenNotificationEnabled; for (int i = 0; i < operation.Faults.Count; i++) { FaultDescription fault = operation.Faults[i]; child.FaultContractInfos.Add(new FaultContractInfo(fault.Action, fault.DetailType, fault.ElementName, fault.Namespace, operation.KnownTypes)); } if (requestAction != MessageHeaders.WildcardAction) { parent.Operations.Add(child); } else { if (parent.HasMatchAllOperation) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxMultipleContractStarOperations0)); } parent.UnhandledDispatchOperation = child; } } private static void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime clientRuntime) { // contract behaviors ContractDescription contractDescription = serviceEndpoint.Contract; for (int i = 0; i < contractDescription.Behaviors.Count; i++) { IContractBehavior behavior = contractDescription.Behaviors[i]; behavior.ApplyClientBehavior(contractDescription, serviceEndpoint, clientRuntime); } // endpoint behaviors BindingInformationEndpointBehavior.Instance.ApplyClientBehavior(serviceEndpoint, clientRuntime); for (int i = 0; i < serviceEndpoint.Behaviors.Count; i++) { IEndpointBehavior behavior = serviceEndpoint.Behaviors[i]; behavior.ApplyClientBehavior(serviceEndpoint, clientRuntime); } // operation behaviors DispatcherBuilder.BindOperations(contractDescription, clientRuntime, null); } private static void BindOperations(ContractDescription contract, ClientRuntime proxy, DispatchRuntime dispatch) { if (!(((proxy == null) != (dispatch == null)))) { throw Fx.AssertAndThrowFatal("DispatcherBuilder.BindOperations: ((proxy == null) != (dispatch == null))"); } MessageDirection local = (proxy == null) ? MessageDirection.Input : MessageDirection.Output; for (int i = 0; i < contract.Operations.Count; i++) { OperationDescription operation = contract.Operations[i]; MessageDescription first = operation.Messages[0]; if (first.Direction != local) { if (proxy == null) { proxy = dispatch.CallbackClientRuntime; } ClientOperation proxyOperation = proxy.Operations[operation.Name]; Fx.Assert(proxyOperation != null, ""); for (int j = 0; j < operation.Behaviors.Count; j++) { IOperationBehavior behavior = operation.Behaviors[j]; behavior.ApplyClientBehavior(operation, proxyOperation); } } else { if (dispatch == null) { dispatch = proxy.CallbackDispatchRuntime; } DispatchOperation dispatchOperation = null; if (dispatch.Operations.Contains(operation.Name)) { dispatchOperation = dispatch.Operations[operation.Name]; } if (dispatchOperation == null && dispatch.UnhandledDispatchOperation != null && dispatch.UnhandledDispatchOperation.Name == operation.Name) { dispatchOperation = dispatch.UnhandledDispatchOperation; } if (dispatchOperation != null) { for (int j = 0; j < operation.Behaviors.Count; j++) { IOperationBehavior behavior = operation.Behaviors[j]; behavior.ApplyDispatchBehavior(operation, dispatchOperation); } } } } } internal class BindingInformationEndpointBehavior : IEndpointBehavior { private static BindingInformationEndpointBehavior s_instance; public static BindingInformationEndpointBehavior Instance { get { if (s_instance == null) { s_instance = new BindingInformationEndpointBehavior(); } return s_instance; } } public void Validate(ServiceEndpoint serviceEndpoint) { } public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection parameters) { } public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime behavior) { behavior.ManualAddressing = this.IsManualAddressing(serviceEndpoint.Binding); behavior.EnableFaults = !this.IsMulticast(serviceEndpoint.Binding); if (serviceEndpoint.Contract.IsDuplex()) { behavior.CallbackDispatchRuntime.ChannelDispatcher.MessageVersion = serviceEndpoint.Binding.MessageVersion; } } public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher) { IBindingRuntimePreferences runtimePreferences = serviceEndpoint.Binding as IBindingRuntimePreferences; if (runtimePreferences != null) { // it is ok to go up to the ChannelDispatcher here, since // all endpoints that share a ChannelDispatcher also share the same binding endpointDispatcher.ChannelDispatcher.ReceiveSynchronously = runtimePreferences.ReceiveSynchronously; } endpointDispatcher.ChannelDispatcher.ManualAddressing = this.IsManualAddressing(serviceEndpoint.Binding); endpointDispatcher.ChannelDispatcher.EnableFaults = !this.IsMulticast(serviceEndpoint.Binding); endpointDispatcher.ChannelDispatcher.MessageVersion = serviceEndpoint.Binding.MessageVersion; } private bool IsManualAddressing(Binding binding) { TransportBindingElement transport = binding.CreateBindingElements().Find<TransportBindingElement>(); if (transport == null) { string text = SR.Format(SR.SFxBindingMustContainTransport2, binding.Name, binding.Namespace); Exception error = new InvalidOperationException(text); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error); } return transport.ManualAddressing; } private bool IsMulticast(Binding binding) { IBindingMulticastCapabilities multicast = binding.GetProperty<IBindingMulticastCapabilities>(new BindingParameterCollection()); return (multicast != null) && multicast.IsMulticast; } } internal class SecurityContractInformationEndpointBehavior : IEndpointBehavior { private bool _isForClient; private SecurityContractInformationEndpointBehavior(bool isForClient) { _isForClient = isForClient; } private static SecurityContractInformationEndpointBehavior s_serverInstance; public static SecurityContractInformationEndpointBehavior ServerInstance { get { if (s_serverInstance == null) { s_serverInstance = new SecurityContractInformationEndpointBehavior(false); } return s_serverInstance; } } private static SecurityContractInformationEndpointBehavior s_clientInstance; public static SecurityContractInformationEndpointBehavior ClientInstance { get { if (s_clientInstance == null) { s_clientInstance = new SecurityContractInformationEndpointBehavior(true); } return s_clientInstance; } } public void Validate(ServiceEndpoint serviceEndpoint) { } public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher) { } public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime behavior) { } public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection parameters) { // get Contract info security needs, and put in BindingParameterCollection ISecurityCapabilities isc = null; BindingElementCollection elements = endpoint.Binding.CreateBindingElements(); if (isc != null) { // ensure existence of binding parameter ChannelProtectionRequirements requirements = parameters.Find<ChannelProtectionRequirements>(); if (requirements == null) { requirements = new ChannelProtectionRequirements(); parameters.Add(requirements); } MessageEncodingBindingElement encoding = elements.Find<MessageEncodingBindingElement>(); // use endpoint.Binding.Version if (encoding != null && encoding.MessageVersion.Addressing == AddressingVersion.None) { // This binding does not support response actions, so... requirements.Add(ChannelProtectionRequirements.CreateFromContractAndUnionResponseProtectionRequirements(endpoint.Contract, isc, _isForClient)); } else { requirements.Add(ChannelProtectionRequirements.CreateFromContract(endpoint.Contract, isc, _isForClient)); } } } } } }
/* * Copyright 2011-2012 Paul Heasley * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; namespace phdesign.NppToolBucket.Infrastructure { internal enum SettingsSection { Global, FindAndReplace, Guids } internal class Settings { [DllImport("kernel32")] private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnedString, uint nSize, string lpFileName); [DllImport("kernel32")] private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName); private readonly string _iniFilePath; private Dictionary<string, Dictionary<string, Setting>> _allSettings; public Settings(string filePath) { _iniFilePath = filePath; if (!File.Exists(filePath)) { var iniFileDirectory = Path.GetDirectoryName(filePath); if (iniFileDirectory != null && !Directory.Exists(iniFileDirectory)) Directory.CreateDirectory(iniFileDirectory); using (var writer = File.CreateText(filePath)) writer.Write( @"; {0} plugin configuration file. ; Please restart Notepad++ after modifying this file for changes to take effect. ; ShowTabBarIcons: If true, displays icons in the tab bar for some of the main plugin operations [Global] ShowTabBarIcons=True", Main.PluginName); } Load(); } public string Get(SettingsSection section, string keyName, string defaultValue) { var setting = GetSetting(section.ToString(), keyName); return setting == null ? defaultValue : setting.Value ?? defaultValue; } public int GetInt(SettingsSection section, string keyName, int defaultValue) { var setting = GetSetting(section.ToString(), keyName); if (setting == null) return defaultValue; int value; return int.TryParse(setting.Value, out value) ? value : defaultValue; } public bool GetBool(SettingsSection section, string keyName, bool defaultValue) { var setting = GetSetting(section.ToString(), keyName); if (setting == null || string.IsNullOrEmpty(setting.Value)) return defaultValue; if (setting.Value.Equals("true", StringComparison.CurrentCultureIgnoreCase) || setting.Value == "1") return true; if (setting.Value.Equals("false", StringComparison.CurrentCultureIgnoreCase) || setting.Value == "0") return false; return defaultValue; } public void Set(SettingsSection section, string keyName, string value) { Dictionary<string, Setting> sectionSettings; if (!_allSettings.TryGetValue(section.ToString(), out sectionSettings)) { sectionSettings = new Dictionary<string, Setting>(); _allSettings.Add(section.ToString(), sectionSettings); } Setting setting; if (!sectionSettings.TryGetValue(keyName, out setting)) { sectionSettings.Add( keyName, new Setting(value) {IsDirty = true}); } else if (setting.Value != value) { setting.Value = value; setting.IsDirty = true; } } public void Set(SettingsSection section, string keyName, int value) { Set(section, keyName, value.ToString()); } public void Set(SettingsSection section, string keyName, bool value) { Set(section, keyName, value ? "True" : "False"); } public void Save() { foreach (var section in _allSettings) { foreach (var setting in section.Value) { if (setting.Value.IsDirty) WritePrivateProfileString(section.Key, setting.Key, setting.Value.Value, _iniFilePath); } } } private void Load() { _allSettings = new Dictionary<string, Dictionary<string, Setting>>(); foreach (var sectionName in GetSections()) { var section = new Dictionary<string, Setting>(); foreach (var keyName in GetKeys(sectionName)) { section.Add(keyName, new Setting(GetValue(sectionName, keyName))); } _allSettings.Add(sectionName, section); } } private List<string> GetSections() { return new List<string>(GetValue(null, null).Split('\0')); } private List<string> GetKeys(string sectionName) { return new List<string>(GetValue(sectionName, null).Split('\0')); } private string GetValue(string sectionName, string keyName) { const uint bufSize = 32767; var truncateLastByte = (sectionName == null || keyName == null) ? 1 : 0; var buffer = new char[bufSize]; uint bytesReturned = GetPrivateProfileString(sectionName, keyName, null, buffer, bufSize, _iniFilePath); if (bytesReturned == 0) return string.Empty; return new string(buffer, 0, (int)bytesReturned - truncateLastByte); } //private string GetValue(string sectionName, string keyName) //{ // const int minBufSize = 255; // int bufSize, retVal; // var attempts = 0; // var bufSizeTooSmall = (sectionName == null || keyName == null) ? 2 : 1; // var value = new StringBuilder(minBufSize); // do // { // bufSize = minBufSize * ++attempts; // value.Capacity = bufSize; // // http://msdn.microsoft.com/en-us/library/ms724353(v=vs.85).aspx // // If return value is buffer size - 1 then buffer is too small. // retVal = Win32.GetPrivateProfileString(sectionName, keyName, null, value, bufSize, _iniFilePath); // } while (retVal == bufSize - bufSizeTooSmall && bufSize + minBufSize < value.MaxCapacity); // return value.ToString(); //} private Setting GetSetting(string sectionName, string keyName) { Dictionary<string, Setting> sectionSettings; if (!_allSettings.TryGetValue(sectionName, out sectionSettings)) return null; Setting setting; return !sectionSettings.TryGetValue(keyName, out setting) ? null : setting; } private class Setting { public string Value; public bool IsDirty; public Setting(string value) { Value = value; } } } }
namespace OpenQA.Selenium.DevTools.Target { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Represents an adapter for the Target domain to simplify the command interface. /// </summary> public class TargetAdapter { private readonly DevToolsSession m_session; private readonly string m_domainName = "Target"; private Dictionary<string, DevToolsEventData> m_eventMap = new Dictionary<string, DevToolsEventData>(); public TargetAdapter(DevToolsSession session) { m_session = session ?? throw new ArgumentNullException(nameof(session)); m_session.DevToolsEventReceived += OnDevToolsEventReceived; m_eventMap["attachedToTarget"] = new DevToolsEventData(typeof(AttachedToTargetEventArgs), OnAttachedToTarget); m_eventMap["detachedFromTarget"] = new DevToolsEventData(typeof(DetachedFromTargetEventArgs), OnDetachedFromTarget); m_eventMap["receivedMessageFromTarget"] = new DevToolsEventData(typeof(ReceivedMessageFromTargetEventArgs), OnReceivedMessageFromTarget); m_eventMap["targetCreated"] = new DevToolsEventData(typeof(TargetCreatedEventArgs), OnTargetCreated); m_eventMap["targetDestroyed"] = new DevToolsEventData(typeof(TargetDestroyedEventArgs), OnTargetDestroyed); m_eventMap["targetCrashed"] = new DevToolsEventData(typeof(TargetCrashedEventArgs), OnTargetCrashed); m_eventMap["targetInfoChanged"] = new DevToolsEventData(typeof(TargetInfoChangedEventArgs), OnTargetInfoChanged); } /// <summary> /// Gets the DevToolsSession associated with the adapter. /// </summary> public DevToolsSession Session { get { return m_session; } } /// <summary> /// Issued when attached to target because of auto-attach or `attachToTarget` command. /// </summary> public event EventHandler<AttachedToTargetEventArgs> AttachedToTarget; /// <summary> /// Issued when detached from target for any reason (including `detachFromTarget` command). Can be /// issued multiple times per target if multiple sessions have been attached to it. /// </summary> public event EventHandler<DetachedFromTargetEventArgs> DetachedFromTarget; /// <summary> /// Notifies about a new protocol message received from the session (as reported in /// `attachedToTarget` event). /// </summary> public event EventHandler<ReceivedMessageFromTargetEventArgs> ReceivedMessageFromTarget; /// <summary> /// Issued when a possible inspection target is created. /// </summary> public event EventHandler<TargetCreatedEventArgs> TargetCreated; /// <summary> /// Issued when a target is destroyed. /// </summary> public event EventHandler<TargetDestroyedEventArgs> TargetDestroyed; /// <summary> /// Issued when a target has crashed. /// </summary> public event EventHandler<TargetCrashedEventArgs> TargetCrashed; /// <summary> /// Issued when some information about a target has changed. This only happens between /// `targetCreated` and `targetDestroyed`. /// </summary> public event EventHandler<TargetInfoChangedEventArgs> TargetInfoChanged; /// <summary> /// Activates (focuses) the target. /// </summary> public async Task<ActivateTargetCommandResponse> ActivateTarget(ActivateTargetCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ActivateTargetCommandSettings, ActivateTargetCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Attaches to the target with given id. /// </summary> public async Task<AttachToTargetCommandResponse> AttachToTarget(AttachToTargetCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<AttachToTargetCommandSettings, AttachToTargetCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Attaches to the browser target, only uses flat sessionId mode. /// </summary> public async Task<AttachToBrowserTargetCommandResponse> AttachToBrowserTarget(AttachToBrowserTargetCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<AttachToBrowserTargetCommandSettings, AttachToBrowserTargetCommandResponse>(command ?? new AttachToBrowserTargetCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Closes the target. If the target is a page that gets closed too. /// </summary> public async Task<CloseTargetCommandResponse> CloseTarget(CloseTargetCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<CloseTargetCommandSettings, CloseTargetCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Inject object to the target's main frame that provides a communication /// channel with browser target. /// /// Injected object will be available as `window[bindingName]`. /// /// The object has the follwing API: /// - `binding.send(json)` - a method to send messages over the remote debugging protocol /// - `binding.onmessage = json => handleMessage(json)` - a callback that will be called for the protocol notifications and command responses. /// </summary> public async Task<ExposeDevToolsProtocolCommandResponse> ExposeDevToolsProtocol(ExposeDevToolsProtocolCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<ExposeDevToolsProtocolCommandSettings, ExposeDevToolsProtocolCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Creates a new empty BrowserContext. Similar to an incognito profile but you can have more than /// one. /// </summary> public async Task<CreateBrowserContextCommandResponse> CreateBrowserContext(CreateBrowserContextCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<CreateBrowserContextCommandSettings, CreateBrowserContextCommandResponse>(command ?? new CreateBrowserContextCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns all browser contexts created with `Target.createBrowserContext` method. /// </summary> public async Task<GetBrowserContextsCommandResponse> GetBrowserContexts(GetBrowserContextsCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetBrowserContextsCommandSettings, GetBrowserContextsCommandResponse>(command ?? new GetBrowserContextsCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Creates a new page. /// </summary> public async Task<CreateTargetCommandResponse> CreateTarget(CreateTargetCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<CreateTargetCommandSettings, CreateTargetCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Detaches session with given id. /// </summary> public async Task<DetachFromTargetCommandResponse> DetachFromTarget(DetachFromTargetCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<DetachFromTargetCommandSettings, DetachFromTargetCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Deletes a BrowserContext. All the belonging pages will be closed without calling their /// beforeunload hooks. /// </summary> public async Task<DisposeBrowserContextCommandResponse> DisposeBrowserContext(DisposeBrowserContextCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<DisposeBrowserContextCommandSettings, DisposeBrowserContextCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Returns information about a target. /// </summary> public async Task<GetTargetInfoCommandResponse> GetTargetInfo(GetTargetInfoCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetTargetInfoCommandSettings, GetTargetInfoCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Retrieves a list of available targets. /// </summary> public async Task<GetTargetsCommandResponse> GetTargets(GetTargetsCommandSettings command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<GetTargetsCommandSettings, GetTargetsCommandResponse>(command ?? new GetTargetsCommandSettings(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Sends protocol message over session with given id. /// </summary> public async Task<SendMessageToTargetCommandResponse> SendMessageToTarget(SendMessageToTargetCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SendMessageToTargetCommandSettings, SendMessageToTargetCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Controls whether to automatically attach to new targets which are considered to be related to /// this one. When turned on, attaches to all existing related targets as well. When turned off, /// automatically detaches from all currently attached targets. /// </summary> public async Task<SetAutoAttachCommandResponse> SetAutoAttach(SetAutoAttachCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetAutoAttachCommandSettings, SetAutoAttachCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Controls whether to discover available targets and notify via /// `targetCreated/targetInfoChanged/targetDestroyed` events. /// </summary> public async Task<SetDiscoverTargetsCommandResponse> SetDiscoverTargets(SetDiscoverTargetsCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetDiscoverTargetsCommandSettings, SetDiscoverTargetsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } /// <summary> /// Enables target discovery for the specified locations, when `setDiscoverTargets` was set to /// `true`. /// </summary> public async Task<SetRemoteLocationsCommandResponse> SetRemoteLocations(SetRemoteLocationsCommandSettings command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true) { return await m_session.SendCommand<SetRemoteLocationsCommandSettings, SetRemoteLocationsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived); } private void OnDevToolsEventReceived(object sender, DevToolsEventReceivedEventArgs e) { if (e.DomainName == m_domainName) { if (m_eventMap.ContainsKey(e.EventName)) { var eventData = m_eventMap[e.EventName]; var eventArgs = e.EventData.ToObject(eventData.EventArgsType); eventData.EventInvoker(eventArgs); } } } private void OnAttachedToTarget(object rawEventArgs) { AttachedToTargetEventArgs e = rawEventArgs as AttachedToTargetEventArgs; if (e != null && AttachedToTarget != null) { AttachedToTarget(this, e); } } private void OnDetachedFromTarget(object rawEventArgs) { DetachedFromTargetEventArgs e = rawEventArgs as DetachedFromTargetEventArgs; if (e != null && DetachedFromTarget != null) { DetachedFromTarget(this, e); } } private void OnReceivedMessageFromTarget(object rawEventArgs) { ReceivedMessageFromTargetEventArgs e = rawEventArgs as ReceivedMessageFromTargetEventArgs; if (e != null && ReceivedMessageFromTarget != null) { ReceivedMessageFromTarget(this, e); } } private void OnTargetCreated(object rawEventArgs) { TargetCreatedEventArgs e = rawEventArgs as TargetCreatedEventArgs; if (e != null && TargetCreated != null) { TargetCreated(this, e); } } private void OnTargetDestroyed(object rawEventArgs) { TargetDestroyedEventArgs e = rawEventArgs as TargetDestroyedEventArgs; if (e != null && TargetDestroyed != null) { TargetDestroyed(this, e); } } private void OnTargetCrashed(object rawEventArgs) { TargetCrashedEventArgs e = rawEventArgs as TargetCrashedEventArgs; if (e != null && TargetCrashed != null) { TargetCrashed(this, e); } } private void OnTargetInfoChanged(object rawEventArgs) { TargetInfoChangedEventArgs e = rawEventArgs as TargetInfoChangedEventArgs; if (e != null && TargetInfoChanged != null) { TargetInfoChanged(this, e); } } } }
// ----------------------------------------------------------------------- // <copyright file="PickerBase.Generated.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // <auto-generated> // This code was generated by a tool. DO NOT EDIT // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ----------------------------------------------------------------------- #region StyleCop Suppression - generated code using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; namespace Microsoft.Management.UI.Internal { /// <summary> /// This control provides basic functionality for Picker-like controls. /// </summary> /// <remarks> /// /// /// If a custom template is provided for this control, then the template MUST provide the following template parts: /// /// PART_DropDown - A required template part which must be of type DismissiblePopup. The dropdown which hosts the picker. /// PART_DropDownButton - A required template part which must be of type ToggleButton. The ToggleButton which controls whether the dropdown is open. /// /// </remarks> [TemplatePart(Name="PART_DropDown", Type=typeof(DismissiblePopup))] [TemplatePart(Name="PART_DropDownButton", Type=typeof(ToggleButton))] [Localizability(LocalizationCategory.None)] partial class PickerBase { // // Fields // private DismissiblePopup dropDown; private ToggleButton dropDownButton; // // CloseDropDown routed command // /// <summary> /// Informs the PickerBase that it should close the dropdown. /// </summary> public static readonly RoutedCommand CloseDropDownCommand = new RoutedCommand("CloseDropDown",typeof(PickerBase)); static private void CloseDropDownCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e) { PickerBase obj = (PickerBase) sender; obj.OnCloseDropDownExecuted( e ); } /// <summary> /// Called when CloseDropDown executes. /// </summary> /// <remarks> /// Informs the PickerBase that it should close the dropdown. /// </remarks> protected virtual void OnCloseDropDownExecuted(ExecutedRoutedEventArgs e) { OnCloseDropDownExecutedImplementation(e); } partial void OnCloseDropDownExecutedImplementation(ExecutedRoutedEventArgs e); // // DropDownButtonTemplate dependency property // /// <summary> /// Identifies the DropDownButtonTemplate dependency property. /// </summary> public static readonly DependencyProperty DropDownButtonTemplateProperty = DependencyProperty.Register( "DropDownButtonTemplate", typeof(ControlTemplate), typeof(PickerBase), new PropertyMetadata( null, DropDownButtonTemplateProperty_PropertyChanged) ); /// <summary> /// Gets or sets a value that controls the visual tree of the DropDown button. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets a value that controls the visual tree of the DropDown button.")] [Localizability(LocalizationCategory.None)] public ControlTemplate DropDownButtonTemplate { get { return (ControlTemplate) GetValue(DropDownButtonTemplateProperty); } set { SetValue(DropDownButtonTemplateProperty,value); } } static private void DropDownButtonTemplateProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { PickerBase obj = (PickerBase) o; obj.OnDropDownButtonTemplateChanged( new PropertyChangedEventArgs<ControlTemplate>((ControlTemplate)e.OldValue, (ControlTemplate)e.NewValue) ); } /// <summary> /// Occurs when DropDownButtonTemplate property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<ControlTemplate>> DropDownButtonTemplateChanged; /// <summary> /// Called when DropDownButtonTemplate property changes. /// </summary> protected virtual void OnDropDownButtonTemplateChanged(PropertyChangedEventArgs<ControlTemplate> e) { OnDropDownButtonTemplateChangedImplementation(e); RaisePropertyChangedEvent(DropDownButtonTemplateChanged, e); } partial void OnDropDownButtonTemplateChangedImplementation(PropertyChangedEventArgs<ControlTemplate> e); // // DropDownStyle dependency property // /// <summary> /// Identifies the DropDownStyle dependency property. /// </summary> public static readonly DependencyProperty DropDownStyleProperty = DependencyProperty.Register( "DropDownStyle", typeof(Style), typeof(PickerBase), new PropertyMetadata( null, DropDownStyleProperty_PropertyChanged) ); /// <summary> /// Gets or sets the style of the drop-down. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets the style of the drop-down.")] [Localizability(LocalizationCategory.None)] public Style DropDownStyle { get { return (Style) GetValue(DropDownStyleProperty); } set { SetValue(DropDownStyleProperty,value); } } static private void DropDownStyleProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { PickerBase obj = (PickerBase) o; obj.OnDropDownStyleChanged( new PropertyChangedEventArgs<Style>((Style)e.OldValue, (Style)e.NewValue) ); } /// <summary> /// Occurs when DropDownStyle property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<Style>> DropDownStyleChanged; /// <summary> /// Called when DropDownStyle property changes. /// </summary> protected virtual void OnDropDownStyleChanged(PropertyChangedEventArgs<Style> e) { OnDropDownStyleChangedImplementation(e); RaisePropertyChangedEvent(DropDownStyleChanged, e); } partial void OnDropDownStyleChangedImplementation(PropertyChangedEventArgs<Style> e); // // IsOpen dependency property // /// <summary> /// Identifies the IsOpen dependency property. /// </summary> public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register( "IsOpen", typeof(bool), typeof(PickerBase), new PropertyMetadata( BooleanBoxes.FalseBox, IsOpenProperty_PropertyChanged) ); /// <summary> /// Gets or sets a value indicating whether the Popup is visible. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets a value indicating whether the Popup is visible.")] [Localizability(LocalizationCategory.None)] public bool IsOpen { get { return (bool) GetValue(IsOpenProperty); } set { SetValue(IsOpenProperty,BooleanBoxes.Box(value)); } } static private void IsOpenProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { PickerBase obj = (PickerBase) o; obj.OnIsOpenChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) ); } /// <summary> /// Occurs when IsOpen property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<bool>> IsOpenChanged; /// <summary> /// Called when IsOpen property changes. /// </summary> protected virtual void OnIsOpenChanged(PropertyChangedEventArgs<bool> e) { OnIsOpenChangedImplementation(e); RaisePropertyChangedEvent(IsOpenChanged, e); } partial void OnIsOpenChangedImplementation(PropertyChangedEventArgs<bool> e); /// <summary> /// Called when a property changes. /// </summary> private void RaisePropertyChangedEvent<T>(EventHandler<PropertyChangedEventArgs<T>> eh, PropertyChangedEventArgs<T> e) { if(eh != null) { eh(this,e); } } // // OnApplyTemplate // /// <summary> /// Called when ApplyTemplate is called. /// </summary> public override void OnApplyTemplate() { PreOnApplyTemplate(); base.OnApplyTemplate(); this.dropDown = WpfHelp.GetTemplateChild<DismissiblePopup>(this,"PART_DropDown"); this.dropDownButton = WpfHelp.GetTemplateChild<ToggleButton>(this,"PART_DropDownButton"); PostOnApplyTemplate(); } partial void PreOnApplyTemplate(); partial void PostOnApplyTemplate(); // // Static constructor // /// <summary> /// Called when the type is initialized. /// </summary> static PickerBase() { DefaultStyleKeyProperty.OverrideMetadata(typeof(PickerBase), new FrameworkPropertyMetadata(typeof(PickerBase))); CommandManager.RegisterClassCommandBinding( typeof(PickerBase), new CommandBinding( PickerBase.CloseDropDownCommand, CloseDropDownCommand_CommandExecuted )); StaticConstructorImplementation(); } static partial void StaticConstructorImplementation(); } } #endregion
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Build.Construction; using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectJsonMigration.Transforms; using Microsoft.DotNet.Internal.ProjectModel; using Microsoft.DotNet.Tools.Common; using NuGet.Frameworks; using NuGet.LibraryModel; using NuGet.Versioning; namespace Microsoft.DotNet.ProjectJsonMigration.Rules { internal class MigratePackageDependenciesAndToolsRule : IMigrationRule { private readonly ITransformApplicator _transformApplicator; private readonly ProjectDependencyFinder _projectDependencyFinder; private string _projectDirectory; private SupportedPackageVersions _supportedPackageVersions; public MigratePackageDependenciesAndToolsRule(ITransformApplicator transformApplicator = null) { _transformApplicator = transformApplicator ?? new TransformApplicator(); _projectDependencyFinder = new ProjectDependencyFinder(); _supportedPackageVersions = new SupportedPackageVersions(); } public void Apply(MigrationSettings migrationSettings, MigrationRuleInputs migrationRuleInputs) { CleanExistingPackageReferences(migrationRuleInputs.OutputMSBuildProject); _projectDirectory = migrationSettings.ProjectDirectory; var project = migrationRuleInputs.DefaultProjectContext.ProjectFile; var tfmDependencyMap = new Dictionary<string, IEnumerable<ProjectLibraryDependency>>(); var targetFrameworks = project.GetTargetFrameworks(); var noFrameworkPackageReferenceItemGroup = migrationRuleInputs.OutputMSBuildProject.AddItemGroup(); AddProjectTypeSpecificDependencies( migrationRuleInputs, migrationSettings, noFrameworkPackageReferenceItemGroup); // Migrate Direct Deps first MigrateDependencies( project, migrationRuleInputs, null, project.Dependencies, migrationSettings.SolutionFile, itemGroup: noFrameworkPackageReferenceItemGroup); MigrationTrace.Instance.WriteLine(String.Format(LocalizableStrings.MigratingCountTargetFrameworks, targetFrameworks.Count())); foreach (var targetFramework in targetFrameworks) { MigrationTrace.Instance.WriteLine(String.Format(LocalizableStrings.MigratingFramework, targetFramework.FrameworkName.GetShortFolderName())); MigrateImports( migrationRuleInputs.CommonPropertyGroup, targetFramework, migrationRuleInputs.IsMultiTFM); MigrateDependencies( project, migrationRuleInputs, targetFramework.FrameworkName, targetFramework.Dependencies, migrationSettings.SolutionFile); } MigrateTools(project, migrationRuleInputs.OutputMSBuildProject); } private void AddProjectTypeSpecificDependencies( MigrationRuleInputs migrationRuleInputs, MigrationSettings migrationSettings, ProjectItemGroupElement noFrameworkPackageReferenceItemGroup) { var project = migrationRuleInputs.DefaultProjectContext.ProjectFile; var type = project.GetProjectType(); switch (type) { case ProjectType.Test: _transformApplicator.Execute( PackageDependencyInfoTransform().Transform( new PackageDependencyInfo { Name = SupportedPackageVersions.TestSdkPackageName, Version = ConstantPackageVersions.TestSdkPackageVersion }), noFrameworkPackageReferenceItemGroup, mergeExisting: false); if (project.TestRunner.Equals("xunit", StringComparison.OrdinalIgnoreCase)) { _transformApplicator.Execute( PackageDependencyInfoTransform().Transform( new PackageDependencyInfo { Name = SupportedPackageVersions.XUnitPackageName, Version = ConstantPackageVersions.XUnitPackageVersion }), noFrameworkPackageReferenceItemGroup, mergeExisting: false); _transformApplicator.Execute( PackageDependencyInfoTransform().Transform( new PackageDependencyInfo { Name = SupportedPackageVersions.XUnitRunnerPackageName, Version = ConstantPackageVersions.XUnitRunnerPackageVersion }), noFrameworkPackageReferenceItemGroup, mergeExisting: false); } else if (project.TestRunner.Equals("mstest", StringComparison.OrdinalIgnoreCase)) { _transformApplicator.Execute( PackageDependencyInfoTransform().Transform( new PackageDependencyInfo { Name = SupportedPackageVersions.MstestTestAdapterName, Version = ConstantPackageVersions.MstestTestAdapterVersion }), noFrameworkPackageReferenceItemGroup, mergeExisting: false); _transformApplicator.Execute( PackageDependencyInfoTransform().Transform( new PackageDependencyInfo { Name = SupportedPackageVersions.MstestTestFrameworkName, Version = ConstantPackageVersions.MstestTestFrameworkVersion }), noFrameworkPackageReferenceItemGroup, mergeExisting: false); } break; default: break; } } private void MigrateImports( ProjectPropertyGroupElement commonPropertyGroup, TargetFrameworkInformation targetFramework, bool isMultiTFM) { var transform = ImportsTransformation.Transform(targetFramework); if (transform != null) { transform.Condition = isMultiTFM ? targetFramework.FrameworkName.GetMSBuildCondition() : null; _transformApplicator.Execute(transform, commonPropertyGroup, mergeExisting: true); } else { MigrationTrace.Instance.WriteLine(String.Format(LocalizableStrings.ImportsTransformNullFor, nameof(MigratePackageDependenciesAndToolsRule), targetFramework.FrameworkName.GetShortFolderName())); } } private void CleanExistingPackageReferences(ProjectRootElement outputMSBuildProject) { var packageRefs = outputMSBuildProject.Items.Where(i => i.ItemType == "PackageReference").ToList(); foreach (var packageRef in packageRefs) { var parent = packageRef.Parent; packageRef.Parent.RemoveChild(packageRef); parent.RemoveIfEmpty(); } } private void MigrateTools( Project project, ProjectRootElement output) { if (project.Tools == null || !project.Tools.Any()) { return; } var itemGroup = output.AddItemGroup(); foreach (var tool in project.Tools) { _transformApplicator.Execute( ToolTransform().Transform(ToPackageDependencyInfo( tool, SupportedPackageVersions.ProjectToolPackages)), itemGroup, mergeExisting: true); } } private void MigrateDependencies( Project project, MigrationRuleInputs migrationRuleInputs, NuGetFramework framework, IEnumerable<ProjectLibraryDependency> dependencies, SlnFile solutionFile, ProjectItemGroupElement itemGroup=null) { var projectDependencies = new HashSet<string>(GetAllProjectReferenceNames( project, framework, migrationRuleInputs.ProjectXproj, solutionFile)); var packageDependencies = dependencies.Where(d => !projectDependencies.Contains(d.Name)).ToList(); string condition = framework?.GetMSBuildCondition() ?? ""; itemGroup = itemGroup ?? migrationRuleInputs.OutputMSBuildProject.ItemGroups.FirstOrDefault(i => i.Condition == condition) ?? migrationRuleInputs.OutputMSBuildProject.AddItemGroup(); itemGroup.Condition = condition; AutoInjectImplicitProjectJsonAssemblyReferences(framework, packageDependencies); foreach (var packageDependency in packageDependencies) { MigrationTrace.Instance.WriteLine(packageDependency.Name); AddItemTransform<PackageDependencyInfo> transform; if (packageDependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.Reference) { transform = FrameworkDependencyTransform; } else { transform = PackageDependencyInfoTransform(); if (packageDependency.Type.Equals(LibraryDependencyType.Build)) { transform = transform.WithMetadata("PrivateAssets", "All"); } else if (packageDependency.SuppressParent != LibraryIncludeFlagUtils.DefaultSuppressParent) { var metadataValue = ReadLibraryIncludeFlags(packageDependency.SuppressParent); transform = transform.WithMetadata("PrivateAssets", metadataValue); } if (packageDependency.IncludeType != LibraryIncludeFlags.All) { var metadataValue = ReadLibraryIncludeFlags(packageDependency.IncludeType); transform = transform.WithMetadata("IncludeAssets", metadataValue); } } var packageDependencyInfo = ToPackageDependencyInfo( packageDependency, _supportedPackageVersions.ProjectDependencyPackages); if (packageDependencyInfo != null && packageDependencyInfo.IsMetaPackage) { var metaPackageTransform = RuntimeFrameworkVersionTransformation.Transform(packageDependencyInfo); if(metaPackageTransform == null) { metaPackageTransform = NetStandardImplicitPackageVersionTransformation.Transform(packageDependencyInfo); } if (migrationRuleInputs.IsMultiTFM) { metaPackageTransform.Condition = condition; } _transformApplicator.Execute( metaPackageTransform, migrationRuleInputs.CommonPropertyGroup, mergeExisting: true); } else { _transformApplicator.Execute( transform.Transform(packageDependencyInfo), itemGroup, mergeExisting: true); } } } private PackageDependencyInfo ToPackageDependencyInfo( ProjectLibraryDependency dependency, IDictionary<PackageDependencyInfo, PackageDependencyInfo> dependencyToVersionMap) { var name = dependency.Name; var version = dependency.LibraryRange?.VersionRange?.OriginalString; var minRange = dependency.LibraryRange?.VersionRange?.ToNonSnapshotRange().MinVersion; var possibleMappings = dependencyToVersionMap.Where(c => c.Key.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (possibleMappings.Any() && !string.IsNullOrEmpty(version)) { var possibleVersions = possibleMappings.Select(p => VersionRange.Parse(p.Key.Version)); var matchVersion = possibleVersions.FirstOrDefault(p => p.Satisfies(minRange)); if (matchVersion != null) { var dependencyInfo = possibleMappings.First(c => c.Key.Version.Equals(matchVersion.OriginalString, StringComparison.OrdinalIgnoreCase)).Value; if (dependencyInfo == null) { return null; } name = dependencyInfo.Name; version = dependencyInfo.Version; } } return new PackageDependencyInfo { Name = name, Version = version }; } private void AutoInjectImplicitProjectJsonAssemblyReferences(NuGetFramework framework, IList<ProjectLibraryDependency> packageDependencies) { if (framework?.IsDesktop() ?? false) { InjectAssemblyReferenceIfNotPresent("System", packageDependencies); if (framework.Version >= new Version(4, 0)) { InjectAssemblyReferenceIfNotPresent("Microsoft.CSharp", packageDependencies); } } } private void InjectAssemblyReferenceIfNotPresent(string dependencyName, IList<ProjectLibraryDependency> packageDependencies) { if (!packageDependencies.Any(dep => string.Equals(dep.Name, dependencyName, StringComparison.OrdinalIgnoreCase))) { packageDependencies.Add(new ProjectLibraryDependency { LibraryRange = new LibraryRange(dependencyName, LibraryDependencyTarget.Reference) }); } } private string ReadLibraryIncludeFlags(LibraryIncludeFlags includeFlags) { if ((includeFlags ^ LibraryIncludeFlags.All) == 0) { return "All"; } if ((includeFlags ^ LibraryIncludeFlags.None) == 0) { return "None"; } var flagString = ""; var allFlagsAndNames = new List<Tuple<string, LibraryIncludeFlags>> { Tuple.Create("Analyzers", LibraryIncludeFlags.Analyzers), Tuple.Create("Build", LibraryIncludeFlags.Build), Tuple.Create("Compile", LibraryIncludeFlags.Compile), Tuple.Create("ContentFiles", LibraryIncludeFlags.ContentFiles), Tuple.Create("Native", LibraryIncludeFlags.Native), Tuple.Create("Runtime", LibraryIncludeFlags.Runtime) }; foreach (var flagAndName in allFlagsAndNames) { var name = flagAndName.Item1; var flag = flagAndName.Item2; if ((includeFlags & flag) == flag) { if (!string.IsNullOrEmpty(flagString)) { flagString += ";"; } flagString += name; } } return flagString; } private IEnumerable<string> GetAllProjectReferenceNames( Project project, NuGetFramework framework, ProjectRootElement xproj, SlnFile solutionFile) { var csprojReferenceItems = _projectDependencyFinder.ResolveXProjProjectDependencies(xproj); var migratedXProjDependencyPaths = csprojReferenceItems.SelectMany(p => p.Includes()); var migratedXProjDependencyNames = new HashSet<string>(migratedXProjDependencyPaths.Select(p => Path.GetFileNameWithoutExtension(PathUtility.GetPathWithDirectorySeparator(p)))); var projectDependencies = _projectDependencyFinder.ResolveDirectProjectDependenciesForFramework( project, framework, preResolvedProjects: migratedXProjDependencyNames, solutionFile: solutionFile); return projectDependencies.Select(p => p.Name).Concat(migratedXProjDependencyNames); } private AddItemTransform<PackageDependencyInfo> FrameworkDependencyTransform => new AddItemTransform<PackageDependencyInfo>( "Reference", dep => dep.Name, dep => "", dep => true); private Func<AddItemTransform<PackageDependencyInfo>> PackageDependencyInfoTransform => () => new AddItemTransform<PackageDependencyInfo>( "PackageReference", dep => dep.Name, dep => "", dep => dep != null) .WithMetadata("Version", r => r.Version, expressedAsAttribute: true); private AddItemTransform<PackageDependencyInfo> SdkPackageDependencyTransform => PackageDependencyInfoTransform() .WithMetadata("PrivateAssets", r => r.PrivateAssets, r => !string.IsNullOrEmpty(r.PrivateAssets)); private Func<AddItemTransform<PackageDependencyInfo>> ToolTransform => () => new AddItemTransform<PackageDependencyInfo>( "DotNetCliToolReference", dep => dep.Name, dep => "", dep => dep != null) .WithMetadata("Version", r => r.Version, expressedAsAttribute: true); private AddPropertyTransform<TargetFrameworkInformation> ImportsTransformation => new AddPropertyTransform<TargetFrameworkInformation>( "PackageTargetFallback", t => $"$(PackageTargetFallback);{string.Join(";", t.Imports)}", t => t.Imports.OrEmptyIfNull().Any()); private AddPropertyTransform<PackageDependencyInfo> RuntimeFrameworkVersionTransformation => new AddPropertyTransform<PackageDependencyInfo>( "RuntimeFrameworkVersion", p => p.Version, p => p.Name.Equals("Microsoft.NETCore.App", StringComparison.OrdinalIgnoreCase)); private AddPropertyTransform<PackageDependencyInfo> NetStandardImplicitPackageVersionTransformation => new AddPropertyTransform<PackageDependencyInfo>( "NetStandardImplicitPackageVersion", p => p.Version, p => p.Name.Equals("NETStandard.Library", StringComparison.OrdinalIgnoreCase)); } }
using System.Diagnostics; using System; using System.Management; using System.Collections; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Web.UI.Design; using System.Data; using System.Collections.Generic; using System.Linq; using System.IO; using System.Data.OleDb; using System.Text; using System.Threading; namespace SoftLogik.IO { public sealed class ExcelServices { private static object _lock = new object(); public static DataTable GetExcelTable(string SourceFile, string WorkSheets) { //dim ex as System.Data.OleDb.OleDbConnection cn; System.Data.OleDb.OleDbDataAdapter cmd; DataTable ds = new DataTable(); cn = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + SourceFile + ";Extended Properties=Excel 8.0;"); try { // Select the data from Sheet1 of the workbook. cmd = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + WorkSheets, cn); cn.Open(); cmd.Fill(ds); } catch (System.Exception) { } finally { cn.Close(); } return ds; } private static OleDbConnection GetExcelConnection(string SourceFile, bool UseExcelMethod) { OleDbConnection ExcelConnection = null; if (! UseExcelMethod) { ExcelConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + SourceFile + ";Extended Properties=\"HTML Import;\""); } else { ExcelConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + SourceFile + ";Extended Properties=\"Excel 8.0;IMEX=1;HDR=Yes;\""); } try { //Test the connection ExcelConnection.Open(); } catch (System.Exception) { if (! UseExcelMethod) { ExcelConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + SourceFile + ";Extended Properties=\"Excel 8.0;IMEX=1;HDR=Yes;\""); } else { ExcelConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + SourceFile + ";Extended Properties=\"HTML Import;\""); } } finally { if (ExcelConnection.State != ConnectionState.Closed) { ExcelConnection.Close(); } } return ExcelConnection; } public static DataTable GetExcelWorkSheet(string SourceFile, int workSheetNumber) { return GetExcelWorkSheet(SourceFile, workSheetNumber, null); } public static DataTable GetExcelWorkSheet(string SourceFile, int workSheetNumber, ExcelDataColumnCollection AdditionalColumns) { bool IsFirstRetry = true; bool IsFirstColumnRetry = true; OleDbConnection ExcelConnection = GetExcelConnection(SourceFile, false); RetryConnection_Line: OleDbCommand ExcelCommand = new OleDbCommand(); ExcelCommand.Connection = ExcelConnection; OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand); DataTable ExcelDataTable = new DataTable(); try { lock(_lock) { ExcelConnection.Open(); DataTable ExcelSheets = ExcelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] {null, null, null, "TABLE"}); string SpreadSheetName; if ((ExcelSheets != null)&& ExcelSheets.Rows.Count > 0) { SpreadSheetName = "[" + ExcelSheets.Rows[workSheetNumber]["TABLE_NAME"].ToString() + "]"; } else { SpreadSheetName = "[Sheet1$]"; } if (AdditionalColumns != null) { if (AdditionalColumns.Count > 0) { ExcelCommand.CommandText = "SELECT *, " + AdditionalColumns.SqlText + " FROM " + SpreadSheetName; } } else { ExcelCommand.CommandText = "SELECT * FROM " + SpreadSheetName; } try { ExcelAdapter.Fill(ExcelDataTable); } catch (System.Exception) { } finally { if (ExcelDataTable.Columns.Count == 0 && IsFirstColumnRetry) { IsFirstColumnRetry = false; ExcelCommand.CommandText = "SELECT * FROM [" + Path.GetFileNameWithoutExtension(SourceFile) + "]"; ExcelAdapter.Fill(ExcelDataTable); } } } } catch (System.Exception) { if (IsFirstRetry) { IsFirstRetry = false; ExcelConnection = GetExcelConnection(SourceFile, true); goto RetryConnection_Line; } } finally { if (ExcelConnection.State != ConnectionState.Closed) { ExcelConnection.Close(); } } return ExcelDataTable; } public static IDataReader GetExcelReader(string SourceFile, int workSheetNumber) { bool IsFirstRetry = true; OleDbConnection ExcelConnection = GetExcelConnection(SourceFile, false); RetryConnection_Line: OleDbCommand ExcelCommand = new OleDbCommand(); ExcelCommand.Connection = ExcelConnection; OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand); DataTable ExcelDataTable = new DataTable(); try { ExcelConnection.Open(); DataTable ExcelSheets = ExcelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] {null, null, null, "TABLE"}); string SpreadSheetName; if ((ExcelSheets != null)&& ExcelSheets.Rows.Count > 0) { SpreadSheetName = "[" + ExcelSheets.Rows[workSheetNumber]["TABLE_NAME"].ToString() + "]"; } else { SpreadSheetName = "[Sheet1]"; } ExcelCommand.CommandText = "SELECT * FROM " + SpreadSheetName; return ((IDataReader) (ExcelCommand.ExecuteReader())); } catch (System.Exception) { if (IsFirstRetry) { IsFirstRetry = false; ExcelConnection = GetExcelConnection(SourceFile, true); goto RetryConnection_Line; } } finally { if (ExcelConnection.State != ConnectionState.Closed) { ExcelConnection.Close(); } } return null; } public static DataTable GetDBFileData(string SourceFile, string TableName) { OleDbConnection DBFileConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=" + Path.GetDirectoryName(SourceFile) + "\\;Mode=Share Deny Write;Extended Properties=\";Jet OLEDB:System database=\";Jet OLEDB:Registry Path=\";Jet OLEDB:Engine Type=82;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don\'t Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False"); OleDbCommand DBFileCommand = new OleDbCommand(); DBFileCommand.Connection = DBFileConnection; OleDbDataAdapter DBFileAdapter = new OleDbDataAdapter(DBFileCommand); DataTable DBFileDataTable = new DataTable(); try { DBFileConnection.Open(); DBFileCommand.CommandType = CommandType.TableDirect; DBFileCommand.CommandText = TableName; DBFileAdapter.Fill(DBFileDataTable); } catch (System.Exception) { } finally { if (DBFileConnection.State != ConnectionState.Closed) { DBFileConnection.Close(); } } return DBFileDataTable; } } public class ExcelDataColumn { private string _Name; public string @Name { get { return _Name; } set { _Name = value; } } private string _Value; public string Value { get { return _Value; } set { _Value = value; } } private DbType _DataType; public DbType DataType { get { return _DataType; } set { _DataType = value; } } public ExcelDataColumn(string Name, string Value, DbType DataType) { this._Name = Name; this._Value = Value; this._DataType = DataType; } public ExcelDataColumn(string Name, string Value) { this._Name = Name; this._Value = Value; this._DataType = DbType.String; } } public class ExcelDataColumnCollection : System.Collections.ObjectModel.KeyedCollection<string, ExcelDataColumn> { protected override string GetKeyForItem(ExcelDataColumn item) { return item.Name; } public string SqlText { get { StringBuilder sb = new StringBuilder(1024); foreach (ExcelDataColumn itm in this) { switch (itm.DataType) { case DbType.String: case DbType.StringFixedLength: case DbType.DateTime: case DbType.AnsiString: case DbType.AnsiStringFixedLength: case DbType.Date: case DbType.DateTime2: case DbType.DateTimeOffset: case DbType.Guid: case DbType.Time: case DbType.Xml: sb.AppendFormat(" \'{0}\' as {1}, ", itm.Value, itm.Name); break; default: sb.AppendFormat(" {0} as {1}, ", itm.Value, itm.Name); break; } } string retString = sb.ToString().Trim(); return retString.Substring(0, retString.Length - 1); } } public void Add(string Name, string Value, DbType DataType) { this.Add(new ExcelDataColumn(Name, Value, DataType)); } public void Add(string Name, string Value) { this.Add(new ExcelDataColumn(Name, 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.Net.Sockets; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public class CertificateValidationClientServer : IDisposable { private readonly ITestOutputHelper _output; private readonly X509Certificate2 _clientCertificate; private readonly X509Certificate2 _serverCertificate; private bool _clientCertificateRemovedByFilter; public CertificateValidationClientServer(ITestOutputHelper output) { _output = output; _serverCertificate = Configuration.Certificates.GetServerCertificate(); _clientCertificate = Configuration.Certificates.GetClientCertificate(); } public void Dispose() { _serverCertificate.Dispose(); _clientCertificate.Dispose(); } [Theory] [InlineData(false)] [InlineData(true)] public async Task CertificateValidationClientServer_EndToEnd_Ok(bool useClientSelectionCallback) { IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 0); var server = new TcpListener(endPoint); server.Start(); _clientCertificateRemovedByFilter = false; if (PlatformDetection.IsWindows7 && !useClientSelectionCallback && !Capability.IsTrustedRootCertificateInstalled()) { // https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2 // Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed: // The behavior to send the Trusted Issuers List by default is off. // // In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built // by the server using certificates from the Trusted Root Authorities certificate store. // The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates. _clientCertificateRemovedByFilter = true; } using (var clientConnection = new TcpClient()) { IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint; Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port); Task<TcpClient> serverAccept = server.AcceptTcpClientAsync(); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(clientConnect, serverAccept); LocalCertificateSelectionCallback clientCertCallback = null; if (useClientSelectionCallback) { clientCertCallback = ClientCertSelectionCallback; } using (TcpClient serverConnection = await serverAccept) using (SslStream sslClientStream = new SslStream( clientConnection.GetStream(), false, ClientSideRemoteServerCertificateValidation, clientCertCallback)) using (SslStream sslServerStream = new SslStream( serverConnection.GetStream(), false, ServerSideRemoteClientCertificateValidation)) { string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false); var clientCerts = new X509CertificateCollection(); if (!useClientSelectionCallback) { clientCerts.Add(_clientCertificate); } Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync( serverName, clientCerts, SslProtocolSupport.DefaultSslProtocols, false); Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync( _serverCertificate, true, SslProtocolSupport.DefaultSslProtocols, false); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(clientAuthentication, serverAuthentication); if (!_clientCertificateRemovedByFilter) { Assert.True(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated"); Assert.True(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated"); Assert.Equal(sslServerStream.RemoteCertificate.Subject, _clientCertificate.Subject); } else { Assert.False(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated"); Assert.False(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated"); Assert.Null(sslServerStream.RemoteCertificate); } Assert.Equal(sslClientStream.RemoteCertificate.Subject, _serverCertificate.Subject); } } } private X509Certificate ClientCertSelectionCallback( object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { return _clientCertificate; } private bool ServerSideRemoteClientCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None; if (!Capability.IsTrustedRootCertificateInstalled()) { if (!_clientCertificateRemovedByFilter) { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors; } else { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateNotAvailable; } } else { // Validate only if we're able to build a trusted chain. ValidateCertificateAndChain(_clientCertificate, chain); } Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors); if (!_clientCertificateRemovedByFilter) { Assert.Equal(_clientCertificate, certificate); } return true; } private bool ClientSideRemoteServerCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None; if (!Capability.IsTrustedRootCertificateInstalled()) { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors; } else { // Validate only if we're able to build a trusted chain. ValidateCertificateAndChain(_serverCertificate, chain); } Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors); Assert.Equal(_serverCertificate, certificate); return true; } private void ValidateCertificateAndChain(X509Certificate2 cert, X509Chain trustedChain) { _output.WriteLine("ValidateCertificateAndChain()"); // Verify that the certificate is in the trustedChain. _output.WriteLine($"cert: subject={cert.Subject}, issuer={cert.Issuer}, thumbprint={cert.Thumbprint}"); Assert.Equal(cert.Thumbprint, trustedChain.ChainElements[0].Certificate.Thumbprint); // Verify that the root certificate in the chain is the one that issued the received certificate. foreach (X509ChainElement element in trustedChain.ChainElements) { _output.WriteLine( $"chain cert: subject={element.Certificate.Subject}, issuer={element.Certificate.Issuer}, thumbprint={element.Certificate.Thumbprint}"); } Assert.Equal(cert.Issuer, trustedChain.ChainElements[1].Certificate.Subject); } } }
using System; using System.Text; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Security; using SFML.System; namespace SFML { namespace Window { //////////////////////////////////////////////////////////// /// <summary> /// Enumeration of window creation styles /// </summary> //////////////////////////////////////////////////////////// [Flags] public enum Styles { /// <summary>No border / title bar (this flag and all others are mutually exclusive)</summary> None = 0, /// <summary>Title bar + fixed border</summary> Titlebar = 1 << 0, /// <summary>Titlebar + resizable border + maximize button</summary> Resize = 1 << 1, /// <summary>Titlebar + close button</summary> Close = 1 << 2, /// <summary>Fullscreen mode (this flag and all others are mutually exclusive))</summary> Fullscreen = 1 << 3, /// <summary>Default window style (titlebar + resize + close)</summary> Default = Titlebar | Resize | Close } //////////////////////////////////////////////////////////// /// <summary> /// Window is a rendering window ; it can create a new window /// or connect to an existing one /// </summary> //////////////////////////////////////////////////////////// public class Window : ObjectBase { //////////////////////////////////////////////////////////// /// <summary> /// Create the window with default style and creation settings /// </summary> /// <param name="mode">Video mode to use</param> /// <param name="title">Title of the window</param> //////////////////////////////////////////////////////////// public Window(VideoMode mode, string title) : this(mode, title, Styles.Default, new ContextSettings(0, 0)) { } //////////////////////////////////////////////////////////// /// <summary> /// Create the window with default creation settings /// </summary> /// <param name="mode">Video mode to use</param> /// <param name="title">Title of the window</param> /// <param name="style">Window style (Resize | Close by default)</param> //////////////////////////////////////////////////////////// public Window(VideoMode mode, string title, Styles style) : this(mode, title, style, new ContextSettings(0, 0)) { } //////////////////////////////////////////////////////////// /// <summary> /// Create the window /// </summary> /// <param name="mode">Video mode to use</param> /// <param name="title">Title of the window</param> /// <param name="style">Window style (Resize | Close by default)</param> /// <param name="settings">Creation parameters</param> //////////////////////////////////////////////////////////// public Window(VideoMode mode, string title, Styles style, ContextSettings settings) : base(IntPtr.Zero) { // Copy the title to a null-terminated UTF-32 byte array byte[] titleAsUtf32 = Encoding.UTF32.GetBytes(title + '\0'); unsafe { fixed (byte* titlePtr = titleAsUtf32) { CPointer = sfWindow_createUnicode(mode, (IntPtr)titlePtr, style, ref settings); } } } //////////////////////////////////////////////////////////// /// <summary> /// Create the window from an existing control with default creation settings /// </summary> /// <param name="handle">Platform-specific handle of the control</param> //////////////////////////////////////////////////////////// public Window(IntPtr handle) : this(handle, new ContextSettings(0, 0)) { } //////////////////////////////////////////////////////////// /// <summary> /// Create the window from an existing control /// </summary> /// <param name="Handle">Platform-specific handle of the control</param> /// <param name="settings">Creation parameters</param> //////////////////////////////////////////////////////////// public Window(IntPtr Handle, ContextSettings settings) : base(sfWindow_createFromHandle(Handle, ref settings)) { } //////////////////////////////////////////////////////////// /// <summary> /// Tell whether or not the window is opened (ie. has been created). /// Note that a hidden window (Show(false)) /// will still return true /// </summary> /// <returns>True if the window is opened</returns> //////////////////////////////////////////////////////////// public virtual bool IsOpen { get { return sfWindow_isOpen(CPointer); } } //////////////////////////////////////////////////////////// /// <summary> /// Close (destroy) the window. /// The Window instance remains valid and you can call /// Create to recreate the window /// </summary> //////////////////////////////////////////////////////////// public virtual void Close() { sfWindow_close(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Display the window on screen /// </summary> //////////////////////////////////////////////////////////// public virtual void Display() { sfWindow_display(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Creation settings of the window /// </summary> //////////////////////////////////////////////////////////// public virtual ContextSettings Settings { get {return sfWindow_getSettings(CPointer);} } //////////////////////////////////////////////////////////// /// <summary> /// Position of the window /// </summary> //////////////////////////////////////////////////////////// public virtual Vector2i Position { get { return sfWindow_getPosition(CPointer); } set { sfWindow_setPosition(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Size of the rendering region of the window /// </summary> //////////////////////////////////////////////////////////// public virtual Vector2u Size { get { return sfWindow_getSize(CPointer); } set { sfWindow_setSize(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Change the title of the window /// </summary> /// <param name="title">New title</param> //////////////////////////////////////////////////////////// public virtual void SetTitle(string title) { // Copy the title to a null-terminated UTF-32 byte array byte[] titleAsUtf32 = Encoding.UTF32.GetBytes(title + '\0'); unsafe { fixed (byte* titlePtr = titleAsUtf32) { sfWindow_setUnicodeTitle(CPointer, (IntPtr)titlePtr); } } } //////////////////////////////////////////////////////////// /// <summary> /// Change the window's icon /// </summary> /// <param name="width">Icon's width, in pixels</param> /// <param name="height">Icon's height, in pixels</param> /// <param name="pixels">Array of pixels, format must be RGBA 32 bits</param> //////////////////////////////////////////////////////////// public virtual void SetIcon(uint width, uint height, byte[] pixels) { unsafe { fixed (byte* PixelsPtr = pixels) { sfWindow_setIcon(CPointer, width, height, PixelsPtr); } } } //////////////////////////////////////////////////////////// /// <summary> /// Show or hide the window /// </summary> /// <param name="visible">True to show the window, false to hide it</param> //////////////////////////////////////////////////////////// public virtual void SetVisible(bool visible) { sfWindow_setVisible(CPointer, visible); } //////////////////////////////////////////////////////////// /// <summary> /// Show or hide the mouse cursor /// </summary> /// <param name="show">True to show, false to hide</param> //////////////////////////////////////////////////////////// public virtual void SetMouseCursorVisible(bool show) { sfWindow_setMouseCursorVisible(CPointer, show); } //////////////////////////////////////////////////////////// /// <summary> /// Enable / disable vertical synchronization /// </summary> /// <param name="enable">True to enable v-sync, false to deactivate</param> //////////////////////////////////////////////////////////// public virtual void SetVerticalSyncEnabled(bool enable) { sfWindow_setVerticalSyncEnabled(CPointer, enable); } //////////////////////////////////////////////////////////// /// <summary> /// Enable or disable automatic key-repeat. /// Automatic key-repeat is enabled by default /// </summary> /// <param name="enable">True to enable, false to disable</param> //////////////////////////////////////////////////////////// public virtual void SetKeyRepeatEnabled(bool enable) { sfWindow_setKeyRepeatEnabled(CPointer, enable); } //////////////////////////////////////////////////////////// /// <summary> /// Activate the window as the current target /// for rendering /// </summary> /// <returns>True if operation was successful, false otherwise</returns> //////////////////////////////////////////////////////////// public virtual bool SetActive() { return SetActive(true); } //////////////////////////////////////////////////////////// /// <summary> /// Activate of deactivate the window as the current target /// for rendering /// </summary> /// <param name="active">True to activate, false to deactivate (true by default)</param> /// <returns>True if operation was successful, false otherwise</returns> //////////////////////////////////////////////////////////// public virtual bool SetActive(bool active) { return sfWindow_setActive(CPointer, active); } //////////////////////////////////////////////////////////// /// <summary> /// Limit the framerate to a maximum fixed frequency /// </summary> /// <param name="limit">Framerate limit, in frames per seconds (use 0 to disable limit)</param> //////////////////////////////////////////////////////////// public virtual void SetFramerateLimit(uint limit) { sfWindow_setFramerateLimit(CPointer, limit); } //////////////////////////////////////////////////////////// /// <summary> /// Change the joystick threshold, ie. the value below which /// no move event will be generated /// </summary> /// <param name="threshold">New threshold, in range [0, 100]</param> //////////////////////////////////////////////////////////// public virtual void SetJoystickThreshold(float threshold) { sfWindow_setJoystickThreshold(CPointer, threshold); } //////////////////////////////////////////////////////////// /// <summary> /// OS-specific handle of the window /// </summary> //////////////////////////////////////////////////////////// public virtual IntPtr SystemHandle { get {return sfWindow_getSystemHandle(CPointer);} } //////////////////////////////////////////////////////////// /// <summary> /// Wait for a new event and dispatch it to the corresponding /// event handler /// </summary> //////////////////////////////////////////////////////////// public void WaitAndDispatchEvents() { Event e; if (WaitEvent(out e)) CallEventHandler(e); } //////////////////////////////////////////////////////////// /// <summary> /// Call the event handlers for each pending event /// </summary> //////////////////////////////////////////////////////////// public void DispatchEvents() { Event e; while (PollEvent(out e)) CallEventHandler(e); } //////////////////////////////////////////////////////////// /// <summary> /// Request the current window to be made the active /// foreground window /// </summary> //////////////////////////////////////////////////////////// public virtual void RequestFocus() { sfWindow_requestFocus(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Check whether the window has the input focus /// </summary> /// <returns>True if the window has focus, false otherwise</returns> //////////////////////////////////////////////////////////// public virtual bool HasFocus() { return sfWindow_hasFocus(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[Window]" + " Size(" + Size + ")" + " Position(" + Position + ")" + " Settings(" + Settings + ")"; } //////////////////////////////////////////////////////////// /// <summary> /// Constructor for derived classes /// </summary> /// <param name="cPointer">Pointer to the internal object in the C API</param> /// <param name="dummy">Internal hack :)</param> //////////////////////////////////////////////////////////// protected Window(IntPtr cPointer, int dummy) : base(cPointer) { // TODO : find a cleaner way of separating this constructor from Window(IntPtr handle) } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to get the next event (non-blocking) /// </summary> /// <param name="eventToFill">Variable to fill with the raw pointer to the event structure</param> /// <returns>True if there was an event, false otherwise</returns> //////////////////////////////////////////////////////////// protected virtual bool PollEvent(out Event eventToFill) { return sfWindow_pollEvent(CPointer, out eventToFill); } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to get the next event (blocking) /// </summary> /// <param name="eventToFill">Variable to fill with the raw pointer to the event structure</param> /// <returns>False if any error occured</returns> //////////////////////////////////////////////////////////// protected virtual bool WaitEvent(out Event eventToFill) { return sfWindow_waitEvent(CPointer, out eventToFill); } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to get the mouse position relative to the window. /// This function is protected because it is called by another class of /// another module, it is not meant to be called by users. /// </summary> /// <returns>Relative mouse position</returns> //////////////////////////////////////////////////////////// protected internal virtual Vector2i InternalGetMousePosition() { return sfMouse_getPosition(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to set the mouse position relative to the window. /// This function is protected because it is called by another class of /// another module, it is not meant to be called by users. /// </summary> /// <param name="position">Relative mouse position</param> //////////////////////////////////////////////////////////// protected internal virtual void InternalSetMousePosition(Vector2i position) { sfMouse_setPosition(position, CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Internal function to get the touch position relative to the window. /// This function is protected because it is called by another class of /// another module, it is not meant to be called by users. /// </summary> /// <param name="Finger">Finger index</param> /// <returns>Relative touch position</returns> //////////////////////////////////////////////////////////// protected internal virtual Vector2i InternalGetTouchPosition(uint Finger) { return sfTouch_getPosition(Finger, CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { sfWindow_destroy(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Call the event handler for the given event /// </summary> /// <param name="e">Event to dispatch</param> //////////////////////////////////////////////////////////// private void CallEventHandler(Event e) { switch (e.Type) { case EventType.Closed : if (Closed != null) Closed(this, EventArgs.Empty); break; case EventType.GainedFocus : if (GainedFocus != null) GainedFocus(this, EventArgs.Empty); break; case EventType.JoystickButtonPressed: if (JoystickButtonPressed != null) JoystickButtonPressed(this, new JoystickButtonEventArgs(e.JoystickButton)); break; case EventType.JoystickButtonReleased : if (JoystickButtonReleased != null) JoystickButtonReleased(this, new JoystickButtonEventArgs(e.JoystickButton)); break; case EventType.JoystickMoved : if (JoystickMoved != null) JoystickMoved(this, new JoystickMoveEventArgs(e.JoystickMove)); break; case EventType.JoystickConnected: if (JoystickConnected != null) JoystickConnected(this, new JoystickConnectEventArgs(e.JoystickConnect)); break; case EventType.JoystickDisconnected: if (JoystickDisconnected != null) JoystickDisconnected(this, new JoystickConnectEventArgs(e.JoystickConnect)); break; case EventType.KeyPressed : if (KeyPressed != null) KeyPressed(this, new KeyEventArgs(e.Key)); break; case EventType.KeyReleased : if (KeyReleased != null) KeyReleased(this, new KeyEventArgs(e.Key)); break; case EventType.LostFocus : if (LostFocus != null) LostFocus(this, EventArgs.Empty); break; case EventType.MouseButtonPressed : if (MouseButtonPressed != null) MouseButtonPressed(this, new MouseButtonEventArgs(e.MouseButton)); break; case EventType.MouseButtonReleased : if (MouseButtonReleased != null) MouseButtonReleased(this, new MouseButtonEventArgs(e.MouseButton)); break; case EventType.MouseEntered : if (MouseEntered != null) MouseEntered(this, EventArgs.Empty); break; case EventType.MouseLeft : if (MouseLeft != null) MouseLeft(this, EventArgs.Empty); break; case EventType.MouseMoved : if (MouseMoved != null) MouseMoved(this, new MouseMoveEventArgs(e.MouseMove)); break; case EventType.MouseWheelMoved : if (MouseWheelMoved != null) MouseWheelMoved(this, new MouseWheelEventArgs(e.MouseWheel)); break; case EventType.Resized : if (Resized != null) Resized(this, new SizeEventArgs(e.Size)); break; case EventType.TextEntered : if (TextEntered != null) TextEntered(this, new TextEventArgs(e.Text)); break; case EventType.TouchBegan : if (TouchBegan != null) TouchBegan(this, new TouchEventArgs(e.Touch)); break; case EventType.TouchMoved: if (TouchMoved != null) TouchMoved(this, new TouchEventArgs(e.Touch)); break; case EventType.TouchEnded: if (TouchEnded != null) TouchEnded(this, new TouchEventArgs(e.Touch)); break; case EventType.SensorChanged: if (SensorChanged != null) SensorChanged(this, new SensorEventArgs(e.Sensor)); break; default: break; } } /// <summary>Event handler for the Closed event</summary> public event EventHandler Closed = null; /// <summary>Event handler for the Resized event</summary> public event EventHandler<SizeEventArgs> Resized = null; /// <summary>Event handler for the LostFocus event</summary> public event EventHandler LostFocus = null; /// <summary>Event handler for the GainedFocus event</summary> public event EventHandler GainedFocus = null; /// <summary>Event handler for the TextEntered event</summary> public event EventHandler<TextEventArgs> TextEntered = null; /// <summary>Event handler for the KeyPressed event</summary> public event EventHandler<KeyEventArgs> KeyPressed = null; /// <summary>Event handler for the KeyReleased event</summary> public event EventHandler<KeyEventArgs> KeyReleased = null; /// <summary>Event handler for the MouseWheelMoved event</summary> public event EventHandler<MouseWheelEventArgs> MouseWheelMoved = null; /// <summary>Event handler for the MouseButtonPressed event</summary> public event EventHandler<MouseButtonEventArgs> MouseButtonPressed = null; /// <summary>Event handler for the MouseButtonReleased event</summary> public event EventHandler<MouseButtonEventArgs> MouseButtonReleased = null; /// <summary>Event handler for the MouseMoved event</summary> public event EventHandler<MouseMoveEventArgs> MouseMoved = null; /// <summary>Event handler for the MouseEntered event</summary> public event EventHandler MouseEntered = null; /// <summary>Event handler for the MouseLeft event</summary> public event EventHandler MouseLeft = null; /// <summary>Event handler for the JoystickButtonPressed event</summary> public event EventHandler<JoystickButtonEventArgs> JoystickButtonPressed = null; /// <summary>Event handler for the JoystickButtonReleased event</summary> public event EventHandler<JoystickButtonEventArgs> JoystickButtonReleased = null; /// <summary>Event handler for the JoystickMoved event</summary> public event EventHandler<JoystickMoveEventArgs> JoystickMoved = null; /// <summary>Event handler for the JoystickConnected event</summary> public event EventHandler<JoystickConnectEventArgs> JoystickConnected = null; /// <summary>Event handler for the JoystickDisconnected event</summary> public event EventHandler<JoystickConnectEventArgs> JoystickDisconnected = null; /// <summary>Event handler for the TouchBegan event</summary> public event EventHandler<TouchEventArgs> TouchBegan = null; /// <summary>Event handler for the TouchMoved event</summary> public event EventHandler<TouchEventArgs> TouchMoved = null; /// <summary>Event handler for the TouchEnded event</summary> public event EventHandler<TouchEventArgs> TouchEnded = null; /// <summary>Event handler for the SensorChanged event</summary> public event EventHandler<SensorEventArgs> SensorChanged = null; #region Imports [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfWindow_create(VideoMode Mode, string Title, Styles Style, ref ContextSettings Params); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfWindow_createUnicode(VideoMode Mode, IntPtr Title, Styles Style, ref ContextSettings Params); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfWindow_createFromHandle(IntPtr Handle, ref ContextSettings Params); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_destroy(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfWindow_isOpen(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_close(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfWindow_pollEvent(IntPtr CPointer, out Event Evt); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfWindow_waitEvent(IntPtr CPointer, out Event Evt); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_display(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern ContextSettings sfWindow_getSettings(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2i sfWindow_getPosition(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setPosition(IntPtr CPointer, Vector2i position); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2u sfWindow_getSize(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setSize(IntPtr CPointer, Vector2u size); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setTitle(IntPtr CPointer, string title); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setUnicodeTitle(IntPtr CPointer, IntPtr title); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] unsafe static extern void sfWindow_setIcon(IntPtr CPointer, uint Width, uint Height, byte* Pixels); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setVisible(IntPtr CPointer, bool visible); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setMouseCursorVisible(IntPtr CPointer, bool Show); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setVerticalSyncEnabled(IntPtr CPointer, bool Enable); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setKeyRepeatEnabled(IntPtr CPointer, bool Enable); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfWindow_setActive(IntPtr CPointer, bool Active); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setFramerateLimit(IntPtr CPointer, uint Limit); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern uint sfWindow_getFrameTime(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_setJoystickThreshold(IntPtr CPointer, float Threshold); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfWindow_getSystemHandle(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfWindow_requestFocus(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfWindow_hasFocus(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2i sfMouse_getPosition(IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMouse_setPosition(Vector2i position, IntPtr CPointer); [DllImport("csfml-window-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2i sfTouch_getPosition(uint Finger, IntPtr RelativeTo); #endregion } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Utils; using osu.Game.Graphics; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Rulesets.Osu.UI; using osu.Game.Screens.Play; using osu.Game.Skinning; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Osu.Skinning.Legacy { public class LegacyCursorParticles : CompositeDrawable, IKeyBindingHandler<OsuAction> { public bool Active => breakSpewer?.Active.Value == true || kiaiSpewer?.Active.Value == true; private LegacyCursorParticleSpewer breakSpewer; private LegacyCursorParticleSpewer kiaiSpewer; [Resolved(canBeNull: true)] private Player player { get; set; } [Resolved(canBeNull: true)] private OsuPlayfield playfield { get; set; } [Resolved(canBeNull: true)] private GameplayState gameplayState { get; set; } [BackgroundDependencyLoader] private void load(ISkinSource skin) { var texture = skin.GetTexture("star2"); var starBreakAdditive = skin.GetConfig<OsuSkinColour, Color4>(OsuSkinColour.StarBreakAdditive)?.Value ?? new Color4(255, 182, 193, 255); if (texture != null) { // stable "magic ratio". see OsuPlayfieldAdjustmentContainer for full explanation. texture.ScaleAdjust *= 1.6f; } InternalChildren = new[] { breakSpewer = new LegacyCursorParticleSpewer(texture, 20) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Colour = starBreakAdditive, Direction = SpewDirection.None, }, kiaiSpewer = new LegacyCursorParticleSpewer(texture, 60) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Colour = starBreakAdditive, Direction = SpewDirection.None, }, }; if (player != null) ((IBindable<bool>)breakSpewer.Active).BindTo(player.IsBreakTime); } protected override void Update() { if (playfield == null || gameplayState == null) return; DrawableHitObject kiaiHitObject = null; // Check whether currently in a kiai section first. This is only done as an optimisation to avoid enumerating AliveObjects when not necessary. if (gameplayState.Beatmap.ControlPointInfo.EffectPointAt(Time.Current).KiaiMode) kiaiHitObject = playfield.HitObjectContainer.AliveObjects.FirstOrDefault(isTracking); kiaiSpewer.Active.Value = kiaiHitObject != null; } private bool isTracking(DrawableHitObject h) { if (!h.HitObject.Kiai) return false; switch (h) { case DrawableSlider slider: return slider.Tracking.Value; case DrawableSpinner spinner: return spinner.RotationTracker.Tracking; } return false; } public bool OnPressed(KeyBindingPressEvent<OsuAction> e) { handleInput(e.Action, true); return false; } public void OnReleased(KeyBindingReleaseEvent<OsuAction> e) { handleInput(e.Action, false); } private bool leftPressed; private bool rightPressed; private void handleInput(OsuAction action, bool pressed) { switch (action) { case OsuAction.LeftButton: leftPressed = pressed; break; case OsuAction.RightButton: rightPressed = pressed; break; } if (leftPressed && rightPressed) breakSpewer.Direction = SpewDirection.Omni; else if (leftPressed) breakSpewer.Direction = SpewDirection.Left; else if (rightPressed) breakSpewer.Direction = SpewDirection.Right; else breakSpewer.Direction = SpewDirection.None; } private class LegacyCursorParticleSpewer : ParticleSpewer, IRequireHighFrequencyMousePosition { private const int particle_duration_min = 300; private const int particle_duration_max = 1000; public SpewDirection Direction { get; set; } protected override bool CanSpawnParticles => base.CanSpawnParticles && cursorScreenPosition.HasValue; protected override float ParticleGravity => 240; public LegacyCursorParticleSpewer(Texture texture, int perSecond) : base(texture, perSecond, particle_duration_max) { Active.BindValueChanged(_ => resetVelocityCalculation()); } private Vector2? cursorScreenPosition; private Vector2 cursorVelocity; private const double max_velocity_frame_length = 15; private double velocityFrameLength; private Vector2 totalPosDifference; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true; protected override bool OnMouseMove(MouseMoveEvent e) { if (cursorScreenPosition == null) { cursorScreenPosition = e.ScreenSpaceMousePosition; return base.OnMouseMove(e); } // calculate cursor velocity. totalPosDifference += e.ScreenSpaceMousePosition - cursorScreenPosition.Value; cursorScreenPosition = e.ScreenSpaceMousePosition; velocityFrameLength += Math.Abs(Clock.ElapsedFrameTime); if (velocityFrameLength > max_velocity_frame_length) { cursorVelocity = totalPosDifference / (float)velocityFrameLength; totalPosDifference = Vector2.Zero; velocityFrameLength = 0; } return base.OnMouseMove(e); } private void resetVelocityCalculation() { cursorScreenPosition = null; totalPosDifference = Vector2.Zero; velocityFrameLength = 0; } protected override FallingParticle CreateParticle() => new FallingParticle { StartPosition = ToLocalSpace(cursorScreenPosition ?? Vector2.Zero), Duration = RNG.NextSingle(particle_duration_min, particle_duration_max), StartAngle = (float)(RNG.NextDouble() * 4 - 2), EndAngle = RNG.NextSingle(-2f, 2f), EndScale = RNG.NextSingle(2f), Velocity = getVelocity(), }; private Vector2 getVelocity() { Vector2 velocity = Vector2.Zero; switch (Direction) { case SpewDirection.Left: velocity = new Vector2( RNG.NextSingle(-460f, 0), RNG.NextSingle(-40f, 40f) ); break; case SpewDirection.Right: velocity = new Vector2( RNG.NextSingle(0, 460f), RNG.NextSingle(-40f, 40f) ); break; case SpewDirection.Omni: velocity = new Vector2( RNG.NextSingle(-460f, 460f), RNG.NextSingle(-160f, 160f) ); break; } velocity += cursorVelocity * 40; return velocity; } } private enum SpewDirection { None, Left, Right, Omni, } } }
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System; using System.Data.Common; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.Internal; using Microsoft.EntityFrameworkCore.Utilities; using MySqlConnector; // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore { /// <summary> /// Provides extension methods on <see cref="DbContextOptionsBuilder"/> and <see cref="DbContextOptionsBuilder{T}"/> /// to configure a <see cref="DbContext"/> to use with MySQL/MariaDB and Pomelo.EntityFrameworkCore.MySql. /// </summary> public static class MySqlDbContextOptionsBuilderExtensions { /// <summary> /// <para> /// Configures the context to connect to a MySQL compatible database, but without initially setting any /// <see cref="DbConnection" /> or connection string. /// </para> /// <para> /// The connection or connection string must be set before the <see cref="DbContext" /> is used to connect /// to a database. Set a connection using <see cref="RelationalDatabaseFacadeExtensions.SetDbConnection" />. /// Set a connection string using <see cref="RelationalDatabaseFacadeExtensions.SetConnectionString" />. /// </para> /// </summary> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="serverVersion"> /// <para> /// The version of the database server. /// </para> /// <para> /// Create an object for this parameter by calling the static method /// <see cref="ServerVersion.Create(System.Version,ServerType)"/>, /// by calling the static method <see cref="ServerVersion.AutoDetect(string)"/> (which retrieves the server version directly /// from the database server), /// by parsing a version string using the static methods /// <see cref="ServerVersion.Parse(string)"/> or <see cref="ServerVersion.TryParse(string,out ServerVersion)"/>, /// or by directly instantiating an object from the <see cref="MySqlServerVersion"/> (for MySQL) or /// <see cref="MariaDbServerVersion"/> (for MariaDB) classes. /// </para> /// </param> /// <param name="mySqlOptionsAction"> An optional action to allow additional MySQL specific configuration. </param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder UseMySql( [NotNull] this DbContextOptionsBuilder optionsBuilder, [NotNull] ServerVersion serverVersion, [CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null) { Check.NotNull(optionsBuilder, nameof(optionsBuilder)); var extension = GetOrCreateExtension(optionsBuilder) .WithServerVersion(serverVersion); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); ConfigureWarnings(optionsBuilder); mySqlOptionsAction?.Invoke(new MySqlDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder; } /// <summary> /// Configures the context to connect to a MySQL compatible database. /// </summary> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="connectionString"> The connection string of the database to connect to. </param> /// <param name="serverVersion"> /// <para> /// The version of the database server. /// </para> /// <para> /// Create an object for this parameter by calling the static method /// <see cref="ServerVersion.Create(System.Version,ServerType)"/>, /// by calling the static method <see cref="ServerVersion.AutoDetect(string)"/> (which retrieves the server version directly /// from the database server), /// by parsing a version string using the static methods /// <see cref="ServerVersion.Parse(string)"/> or <see cref="ServerVersion.TryParse(string,out ServerVersion)"/>, /// or by directly instantiating an object from the <see cref="MySqlServerVersion"/> (for MySQL) or /// <see cref="MariaDbServerVersion"/> (for MariaDB) classes. /// </para> /// </param> /// <param name="mySqlOptionsAction"> An optional action to allow additional MySQL specific configuration. </param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder UseMySql( [NotNull] this DbContextOptionsBuilder optionsBuilder, [NotNull] string connectionString, [NotNull] ServerVersion serverVersion, [CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null) { Check.NotNull(optionsBuilder, nameof(optionsBuilder)); Check.NotEmpty(connectionString, nameof(connectionString)); var resolvedConnectionString = new NamedConnectionStringResolver(optionsBuilder.Options) .ResolveConnectionString(connectionString); var csb = new MySqlConnectionStringBuilder(resolvedConnectionString) { AllowUserVariables = true, UseAffectedRows = false }; resolvedConnectionString = csb.ConnectionString; var extension = (MySqlOptionsExtension)GetOrCreateExtension(optionsBuilder) .WithServerVersion(serverVersion) .WithConnectionString(resolvedConnectionString); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); ConfigureWarnings(optionsBuilder); mySqlOptionsAction?.Invoke(new MySqlDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder; } /// <summary> /// Configures the context to connect to a MySQL compatible database. /// </summary> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="connection"> /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is /// in the open state then EF will not open or close the connection. If the connection is in the closed /// state then EF will open and close the connection as needed. /// </param> /// <param name="serverVersion"> /// <para> /// The version of the database server. /// </para> /// <para> /// Create an object for this parameter by calling the static method /// <see cref="ServerVersion.Create(System.Version,ServerType)"/>, /// by calling the static method <see cref="ServerVersion.AutoDetect(string)"/> (which retrieves the server version directly /// from the database server), /// by parsing a version string using the static methods /// <see cref="ServerVersion.Parse(string)"/> or <see cref="ServerVersion.TryParse(string,out ServerVersion)"/>, /// or by directly instantiating an object from the <see cref="MySqlServerVersion"/> (for MySQL) or /// <see cref="MariaDbServerVersion"/> (for MariaDB) classes. /// </para> /// </param> /// <param name="mySqlOptionsAction"> An optional action to allow additional MySQL specific configuration. </param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder UseMySql( [NotNull] this DbContextOptionsBuilder optionsBuilder, [NotNull] DbConnection connection, [NotNull] ServerVersion serverVersion, [CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null) { Check.NotNull(optionsBuilder, nameof(optionsBuilder)); Check.NotNull(connection, nameof(connection)); var resolvedConnectionString = connection.ConnectionString is not null ? new NamedConnectionStringResolver(optionsBuilder.Options) .ResolveConnectionString(connection.ConnectionString) : null; var csb = new MySqlConnectionStringBuilder(resolvedConnectionString); if (!csb.AllowUserVariables || csb.UseAffectedRows) { try { csb.AllowUserVariables = true; csb.UseAffectedRows = false; connection.ConnectionString = csb.ConnectionString; } catch (MySqlException e) { throw new InvalidOperationException( @"The connection string used with Pomelo.EntityFrameworkCore.MySql must contain ""AllowUserVariables=true;UseAffectedRows=false"".", e); } } var extension = (MySqlOptionsExtension)GetOrCreateExtension(optionsBuilder) .WithServerVersion(serverVersion) .WithConnection(connection); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); ConfigureWarnings(optionsBuilder); mySqlOptionsAction?.Invoke(new MySqlDbContextOptionsBuilder(optionsBuilder)); return optionsBuilder; } /// <summary> /// <para> /// Configures the context to connect to a MySQL compatible database, but without initially setting any /// <see cref="DbConnection" /> or connection string. /// </para> /// <para> /// The connection or connection string must be set before the <see cref="DbContext" /> is used to connect /// to a database. Set a connection using <see cref="RelationalDatabaseFacadeExtensions.SetDbConnection" />. /// Set a connection string using <see cref="RelationalDatabaseFacadeExtensions.SetConnectionString" />. /// </para> /// </summary> /// <typeparam name="TContext"> The type of context to be configured. </typeparam> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="serverVersion"> /// <para> /// The version of the database server. /// </para> /// <para> /// Create an object for this parameter by calling the static method /// <see cref="ServerVersion.Create(System.Version,ServerType)"/>, /// by calling the static method <see cref="ServerVersion.AutoDetect(string)"/> (which retrieves the server version directly /// from the database server), /// by parsing a version string using the static methods /// <see cref="ServerVersion.Parse(string)"/> or <see cref="ServerVersion.TryParse(string,out ServerVersion)"/>, /// or by directly instantiating an object from the <see cref="MySqlServerVersion"/> (for MySQL) or /// <see cref="MariaDbServerVersion"/> (for MariaDB) classes. /// </para> /// </param> /// <param name="mySqlOptionsAction"> An optional action to allow additional MySQL specific configuration. </param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder<TContext> UseMySql<TContext>( [NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder, [NotNull] ServerVersion serverVersion, [CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null) where TContext : DbContext => (DbContextOptionsBuilder<TContext>)UseMySql( (DbContextOptionsBuilder)optionsBuilder, serverVersion, mySqlOptionsAction); /// <summary> /// Configures the context to connect to a MySQL compatible database. /// </summary> /// <typeparam name="TContext"> The type of context to be configured. </typeparam> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="connectionString"> The connection string of the database to connect to. </param> /// <param name="serverVersion"> /// <para> /// The version of the database server. /// </para> /// <para> /// Create an object for this parameter by calling the static method /// <see cref="ServerVersion.Create(System.Version,ServerType)"/>, /// by calling the static method <see cref="ServerVersion.AutoDetect(string)"/> (which retrieves the server version directly /// from the database server), /// by parsing a version string using the static methods /// <see cref="ServerVersion.Parse(string)"/> or <see cref="ServerVersion.TryParse(string,out ServerVersion)"/>, /// or by directly instantiating an object from the <see cref="MySqlServerVersion"/> (for MySQL) or /// <see cref="MariaDbServerVersion"/> (for MariaDB) classes. /// </para> /// </param> /// <param name="mySqlOptionsAction"> An optional action to allow additional MySQL specific configuration. </param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder<TContext> UseMySql<TContext>( [NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder, [NotNull] string connectionString, [NotNull] ServerVersion serverVersion, [CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null) where TContext : DbContext => (DbContextOptionsBuilder<TContext>)UseMySql( (DbContextOptionsBuilder)optionsBuilder, connectionString, serverVersion, mySqlOptionsAction); /// <summary> /// Configures the context to connect to a MySQL compatible database. /// </summary> /// <param name="optionsBuilder"> The builder being used to configure the context. </param> /// <param name="connection"> /// An existing <see cref="DbConnection" /> to be used to connect to the database. If the connection is /// in the open state then EF will not open or close the connection. If the connection is in the closed /// state then EF will open and close the connection as needed. /// </param> /// <typeparam name="TContext"> The type of context to be configured. </typeparam> /// <param name="serverVersion"> /// <para> /// The version of the database server. /// </para> /// <para> /// Create an object for this parameter by calling the static method /// <see cref="ServerVersion.Create(System.Version,ServerType)"/>, /// by calling the static method <see cref="ServerVersion.AutoDetect(string)"/> (which retrieves the server version directly /// from the database server), /// by parsing a version string using the static methods /// <see cref="ServerVersion.Parse(string)"/> or <see cref="ServerVersion.TryParse(string,out ServerVersion)"/>, /// or by directly instantiating an object from the <see cref="MySqlServerVersion"/> (for MySQL) or /// <see cref="MariaDbServerVersion"/> (for MariaDB) classes. /// </para> /// </param> /// <param name="mySqlOptionsAction"> An optional action to allow additional MySQL specific configuration. </param> /// <returns> The options builder so that further configuration can be chained. </returns> public static DbContextOptionsBuilder<TContext> UseMySql<TContext>( [NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder, [NotNull] DbConnection connection, [NotNull] ServerVersion serverVersion, [CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null) where TContext : DbContext => (DbContextOptionsBuilder<TContext>)UseMySql( (DbContextOptionsBuilder)optionsBuilder, connection, serverVersion, mySqlOptionsAction); private static MySqlOptionsExtension GetOrCreateExtension(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.Options.FindExtension<MySqlOptionsExtension>() ?? new MySqlOptionsExtension(); private static void ConfigureWarnings(DbContextOptionsBuilder optionsBuilder) { var coreOptionsExtension = optionsBuilder.Options.FindExtension<CoreOptionsExtension>() ?? new CoreOptionsExtension(); coreOptionsExtension = coreOptionsExtension.WithWarningsConfiguration( coreOptionsExtension.WarningsConfiguration.TryWithExplicit( RelationalEventId.AmbientTransactionWarning, WarningBehavior.Throw)); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(coreOptionsExtension); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ServiceModel.WSHttpBindingBase.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel { abstract public partial class WSHttpBindingBase : System.ServiceModel.Channels.Binding, System.ServiceModel.Channels.IBindingRuntimePreferences { #region Methods and constructors public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default(System.ServiceModel.Channels.BindingElementCollection); } protected abstract System.ServiceModel.Channels.SecurityBindingElement CreateMessageSecurity(); protected abstract System.ServiceModel.Channels.TransportBindingElement GetTransport(); public bool ShouldSerializeReaderQuotas() { return default(bool); } public bool ShouldSerializeReliableSession() { return default(bool); } public bool ShouldSerializeTextEncoding() { return default(bool); } protected WSHttpBindingBase() { } protected WSHttpBindingBase(bool reliableSessionEnabled) { Contract.Ensures(reliableSessionEnabled == this.ReliableSession.Enabled); } #endregion #region Properties and indexers public bool BypassProxyOnLocal { get { return default(bool); } set { } } public EnvelopeVersion EnvelopeVersion { get { Contract.Ensures(Contract.Result<System.ServiceModel.EnvelopeVersion>() != null); Contract.Ensures(Contract.Result<System.ServiceModel.EnvelopeVersion>() == System.ServiceModel.EnvelopeVersion.Soap12); return default(EnvelopeVersion); } } public HostNameComparisonMode HostNameComparisonMode { get { return default(HostNameComparisonMode); } set { } } public long MaxBufferPoolSize { get { return default(long); } set { } } public long MaxReceivedMessageSize { get { return default(long); } set { } } public WSMessageEncoding MessageEncoding { get { return default(WSMessageEncoding); } set { } } public Uri ProxyAddress { get { return default(Uri); } set { } } public System.Xml.XmlDictionaryReaderQuotas ReaderQuotas { get { Contract.Ensures(Contract.Result<System.Xml.XmlDictionaryReaderQuotas>() != null); return default(System.Xml.XmlDictionaryReaderQuotas); } set { Contract.Requires(value != null); } } public OptionalReliableSession ReliableSession { get { Contract.Ensures(Contract.Result<OptionalReliableSession>() != null); return default(OptionalReliableSession); } set { Contract.Requires(value != null); } } public override string Scheme { get { return default(string); } } bool System.ServiceModel.Channels.IBindingRuntimePreferences.ReceiveSynchronously { get { return default(bool); } } public Encoding TextEncoding { get { return default(Encoding); } set { } } public bool TransactionFlow { get { return default(bool); } set { } } public bool UseDefaultWebProxy { get { return default(bool); } set { } } #endregion } }
/* * 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 Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace OpenSim.Region.CoreModules { /// <summary> /// Enables Prim limits for parcel. /// </summary> /// <remarks> /// This module selectivly enables parcel prim limits. /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "PrimLimitsModule")] public class PrimLimitsModule : INonSharedRegionModule { protected IDialogModule m_dialogModule; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool m_enabled; public string Name { get { return "PrimLimitsModule"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { if (!m_enabled) { return; } scene.Permissions.OnRezObject += CanRezObject; scene.Permissions.OnObjectEntry += CanObjectEnter; scene.Permissions.OnDuplicateObject += CanDuplicateObject; m_log.DebugFormat("[PRIM LIMITS]: Region {0} added", scene.RegionInfo.RegionName); } public void Close() { } public void Initialise(IConfigSource config) { string permissionModules = Util.GetConfigVarFromSections<string>(config, "permissionmodules", new string[] { "Startup", "Permissions" }, "DefaultPermissionsModule"); List<string> modules = new List<string>(permissionModules.Split(',').Select(m => m.Trim())); if (!modules.Contains("PrimLimitsModule")) return; m_log.DebugFormat("[PRIM LIMITS]: Initialized module"); m_enabled = true; } public void RegionLoaded(Scene scene) { m_dialogModule = scene.RequestModuleInterface<IDialogModule>(); } public void RemoveRegion(Scene scene) { if (m_enabled) { return; } scene.Permissions.OnRezObject -= CanRezObject; scene.Permissions.OnObjectEntry -= CanObjectEnter; scene.Permissions.OnDuplicateObject -= CanDuplicateObject; } //OnDuplicateObject private bool CanDuplicateObject(int objectCount, UUID objectID, UUID ownerID, Scene scene, Vector3 objectPosition) { ILandObject lo = scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y); string response = DoCommonChecks(objectCount, ownerID, lo, scene); if (response != null) { m_dialogModule.SendAlertToUser(ownerID, response); return false; } return true; } private bool CanObjectEnter(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene) { SceneObjectPart obj = scene.GetSceneObjectPart(objectID); Vector3 oldPoint = obj.GroupPosition; int objectCount = obj.ParentGroup.PrimCount; ILandObject oldParcel = scene.LandChannel.GetLandObject(oldPoint.X, oldPoint.Y); ILandObject newParcel = scene.LandChannel.GetLandObject(newPoint.X, newPoint.Y); // newParcel will be null only if it outside of our current region. If this is the case, then the // receiving permissions will perform the check. if (newParcel == null) return true; // The prim hasn't crossed a region boundary so we don't need to worry // about prim counts here if (oldParcel.Equals(newParcel)) { return true; } // Prim counts are determined by the location of the root prim. if we're // moving a child prim, just let it pass if (!obj.IsRoot) { return true; } // TODO: Add Special Case here for temporary prims string response = DoCommonChecks(objectCount, obj.OwnerID, newParcel, scene); if (response != null) { m_dialogModule.SendAlertToUser(obj.OwnerID, response); return false; } return true; } private bool CanRezObject(int objectCount, UUID ownerID, Vector3 objectPosition, Scene scene) { ILandObject lo = scene.LandChannel.GetLandObject(objectPosition.X, objectPosition.Y); string response = DoCommonChecks(objectCount, ownerID, lo, scene); if (response != null) { m_dialogModule.SendAlertToUser(ownerID, response); return false; } return true; } private string DoCommonChecks(int objectCount, UUID ownerID, ILandObject lo, Scene scene) { string response = null; int simulatorCapacity = lo.GetSimulatorMaxPrimCount(); if ((objectCount + lo.PrimCounts.Total) > simulatorCapacity) { response = "Unable to rez object because the parcel is too full"; } else { int maxPrimsPerUser = scene.RegionInfo.MaxPrimsPerUser; if (maxPrimsPerUser >= 0) { // per-user prim limit is set if (ownerID != lo.LandData.OwnerID || lo.LandData.IsGroupOwned) { // caller is not the sole Parcel owner EstateSettings estateSettings = scene.RegionInfo.EstateSettings; if (ownerID != estateSettings.EstateOwner) { // caller is NOT the Estate owner List<UUID> mgrs = new List<UUID>(estateSettings.EstateManagers); if (!mgrs.Contains(ownerID)) { // caller is not an Estate Manager if ((lo.PrimCounts.Users[ownerID] + objectCount) > maxPrimsPerUser) { response = "Unable to rez object because you have reached your limit"; } } } } } } return response; } } }
// // System.Web.Services.Protocols.SoapMessage.cs // // Author: // Tim Coleman ([email protected]) // Lluis Sanchez Gual ([email protected]) // // Copyright (C) Tim Coleman, 2002 // // // 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.IO; using System.Web.Services; namespace System.Web.Services.Protocols { public abstract class SoapMessage { #region Fields string content_type = "text/xml"; string content_encoding; SoapException exception = null; SoapHeaderCollection headers; SoapMessageStage stage; Stream stream; object[] inParameters; object[] outParameters; #if NET_2_0 SoapProtocolVersion soapVersion; #endif #endregion // Fields #region Constructors internal SoapMessage () { headers = new SoapHeaderCollection (); } internal SoapMessage (Stream stream) { this.stream = stream; } internal SoapMessage (Stream stream, SoapException exception) { this.exception = exception; this.stream = stream; headers = new SoapHeaderCollection (); } #endregion #region Properties internal object[] InParameters { get { return inParameters; } set { inParameters = value; } } internal object[] OutParameters { get { return outParameters; } set { outParameters = value; } } public abstract string Action { get; } public string ContentType { get { return content_type; } set { content_type = value; } } public SoapException Exception { get { return exception; } #if NET_2_0 set { exception = value; } #endif } public SoapHeaderCollection Headers { get { return headers; } } public abstract LogicalMethodInfo MethodInfo { get; } public abstract bool OneWay { get; } public SoapMessageStage Stage { get { return stage; } } internal void SetStage (SoapMessageStage stage) { this.stage = stage; } public Stream Stream { get { return stream; } } public abstract string Url { get; } #if NET_1_1 public string ContentEncoding { get { return content_encoding; } set { content_encoding = value; } } #else internal string ContentEncoding { get { return content_encoding; } set { content_encoding = value; } } #endif #if NET_2_0 [System.Runtime.InteropServices.ComVisible(false)] public virtual SoapProtocolVersion SoapVersion { get { return soapVersion; } } #endif #endregion Properties #region Methods protected abstract void EnsureInStage (); protected abstract void EnsureOutStage (); protected void EnsureStage (SoapMessageStage stage) { if ((((int) stage) & ((int) Stage)) == 0) throw new InvalidOperationException ("The current SoapMessageStage is not the asserted stage or stages."); } public object GetInParameterValue (int index) { return inParameters [index]; } public object GetOutParameterValue (int index) { if (MethodInfo.IsVoid) return outParameters [index]; else return outParameters [index + 1]; } public object GetReturnValue () { if (!MethodInfo.IsVoid && exception == null) return outParameters [0]; else return null; } internal void SetHeaders (SoapHeaderCollection headers) { this.headers = headers; } internal void SetException (SoapException ex) { exception = ex; } internal void CollectHeaders (object target, HeaderInfo[] headers, SoapHeaderDirection direction) { Headers.Clear (); foreach (HeaderInfo hi in headers) { if ((hi.Direction & direction) != 0 && !hi.IsUnknownHeader) { SoapHeader headerVal = hi.GetHeaderValue (target) as SoapHeader; if (headerVal != null) Headers.Add (headerVal); } } } internal void UpdateHeaderValues (object target, HeaderInfo[] headersInfo) { foreach (SoapHeader header in Headers) { HeaderInfo hinfo = FindHeader (headersInfo, header.GetType ()); if (hinfo != null) { hinfo.SetHeaderValue (target, header); header.DidUnderstand = !hinfo.IsUnknownHeader; } } } HeaderInfo FindHeader (HeaderInfo[] headersInfo, Type headerType) { HeaderInfo unknownHeaderInfo = null; foreach (HeaderInfo headerInfo in headersInfo) { if (headerInfo.HeaderType == headerType) return headerInfo; else if (headerInfo.IsUnknownHeader) unknownHeaderInfo = headerInfo; } return unknownHeaderInfo; } #endregion // Methods } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Web; using System.Web.SessionState; //using AutoMapper; using ILPathways.Business; using ILPathways.Common; using ILPathways.DAL; using ILPathways.Utilities; using AcctSvce = Isle.BizServices.workNetAccountServices; using PatronMgr = LRWarehouse.DAL.PatronManager; //.use alias for easy change to Gateway //using ThisUser = ILPathways.Business.AppUser; //using ThisUserProfile = ILPathways.Business.AppUserProfile; //using PatronMgr = ILPathways.DAL.PatronManager; using LRWarehouse.Business; using Patron = LRWarehouse.Business.Patron; using ThisUserProfile = LRWarehouse.Business.PatronProfile; using EFDal = IOERBusinessEntities; using Isle.DTO; namespace Isle.BizServices { public class AccountServices : ServiceHelper { static string thisClassName = "AccountServices"; PatronMgr myManager = new PatronMgr(); static string SessionLoginProxy = "Session Login Proxy"; #region Authorization private static bool CanUserAuthor( Patron appUser ) { bool isValid = true; return isValid; } private static bool CanUserOrgAuthor( Patron appUser ) { bool isValid = true; return isValid; } /// <summary> /// return true if user is part of the site admin group /// 16-02-26 mp - added static version /// TODO - add a session variable to save repeated calls /// </summary> /// <param name="user"></param> /// <returns></returns> public static bool IsUserAnAdmin(Patron user) { string siteAdminObjectName = ServiceHelper.GetAppKeyValue("siteAdminObjectName"); //"Site.Admin" return SecurityManager.GetGroupObjectPrivileges(user, siteAdminObjectName).CreatePrivilege > (int)ILPathways.Business.EPrivilegeDepth.State; } public bool IsUserAdmin(Patron user) { string siteAdminObjectName = ServiceHelper.GetAppKeyValue("siteAdminObjectName"); //"Site.Admin" return SecurityManager.GetGroupObjectPrivileges(user, siteAdminObjectName).CreatePrivilege > (int)ILPathways.Business.EPrivilegeDepth.State; } public bool CanAdminUserAdminAnyLibrary() { bool adminUserCanAdminAnyLibrary = ServiceHelper.GetAppKeyValue( "adminUserCanAdminAnyLibrary", false ); return adminUserCanAdminAnyLibrary; } public void SetUserAdminRole(Patron appUser) { string siteAdminObjectName = ServiceHelper.GetAppKeyValue("siteAdminObjectName"); ApplicationRolePrivilege arp = SecurityManager.GetGroupObjectPrivileges(appUser, siteAdminObjectName); if (arp.CreatePrivilege > (int)EPrivilegeDepth.State ) { //NOTE: this needs to be put back in the session! //actually this is set at login //add kludge until improved if ("2 22 24 56".IndexOf(appUser.Id.ToString()) > -1) appUser.TopAuthorization = (int)EUserRole.ProgramAdministrator; else appUser.TopAuthorization = ( int ) EUserRole.ProgramStaff; } else if (arp.CreatePrivilege == (int)EPrivilegeDepth.State) { //NOTE: this needs to be put back in the session! //actually this is set at login appUser.TopAuthorization = (int)EUserRole.StateAdministrator; } } #endregion #region Patron methods #region ====== Core Methods =============================================== /// <summary> /// Delete an User record using rowId /// </summary> /// <param name="pRowId"></param> /// <param name="statusMessage"></param> /// <returns></returns> public bool Delete( string pRowId, ref string statusMessage ) { //TODO - chg to ws call?? PatronMgr mgr = new PatronMgr(); return mgr.Delete( pRowId, ref statusMessage ); }// /// <summary> /// Add an User record /// </summary> /// <param name="entity"></param> /// <param name="statusMessage"></param> /// <returns></returns> public int Create( Patron entity, ref string statusMessage ) { PatronMgr mgr = new PatronMgr(); return mgr.Create( entity, ref statusMessage ); } /// <summary> /// Update an User record /// </summary> /// <param name="entity"></param> /// <returns></returns> public string Update( Patron entity ) { PatronMgr mgr = new PatronMgr(); return mgr.Update( entity ); }// public int PatronProfile_Create( ThisUserProfile entity, ref string statusMessage ) { if ( entity.UserId > 0 ) { PatronMgr mgr = new PatronMgr(); return mgr.PatronProfile_Create( entity, ref statusMessage ); } else { statusMessage = "Error - no userId was found"; return 0; } }// public string PatronProfile_Update( ThisUserProfile entity ) { PatronMgr mgr = new PatronMgr(); return mgr.PatronProfile_Update( entity ); }// public string PatronProfile_UpdateImage( ThisUserProfile entity ) { PatronMgr mgr = new PatronMgr(); return mgr.PatronProfile_Update( entity ); }// #endregion #region ====== Retrieval Methods =============================================== /// <summary> /// Get User record and profile via integer id /// </summary> /// <param name="pId"></param> /// <returns></returns> public Patron Get( int pId ) { PatronMgr mgr = new PatronMgr(); return mgr.Get( pId ); }// /// <summary> /// Get user and profile /// </summary> /// <param name="pId"></param> /// <returns></returns> public static Patron GetUser( int pId ) { PatronMgr mgr = new PatronMgr(); return mgr.Get( pId ); } public static Patron Account_GetByExternalIdentifier( string identifier ) { return EFDal.AccountManager.Account_GetByExternalIdentifier( identifier ); }// /// <summary> /// Check if a username exists /// </summary> /// <param name="userName"></param> /// <returns></returns> public bool DoesUserNameExist( string userName ) { PatronMgr mgr = new PatronMgr(); return mgr.DoesUserNameExist( userName ); }// /// <summary> /// Check if an email already is associated with an account /// </summary> /// <param name="email"></param> /// <returns></returns> public bool DoesUserEmailExist( string email ) { if ( string.IsNullOrWhiteSpace( email ) ) return false; PatronMgr mgr = new PatronMgr(); return mgr.DoesUserEmailExist( email ); }// /// <summary> /// retrieve user by username /// </summary> /// <param name="userName"></param> /// <returns></returns> public Patron GetByUsername( string userName ) { PatronMgr mgr = new PatronMgr(); return mgr.GetByUsername( userName ); }// /// <summary> /// Get User record via rowId /// </summary> /// <param name="pRowId"></param> /// <returns></returns> public Patron GetByRowId( string pRowId ) { if ( pRowId == null || pRowId.Trim().Length != 36 ) return new Patron() { IsValid = false }; PatronMgr mgr = new PatronMgr(); return mgr.GetByRowId( pRowId ); }// /// <summary> /// Retrieve by User RowId - called from UserDataService /// </summary> /// <param name="rowId"></param> /// <param name="encryptedPassword"></param> /// <returns></returns> public Patron GetByRowId( string rowId, ref string statusMessage ) { Patron user = new Patron(); string message = "There was an error while processing the request."; try { user = myManager.GetByRowId( rowId ); if (user.Id == 0 || !user.IsValid) { user.IsValid = false; user.Id = 0; } } catch ( Exception ex ) { ServiceHelper.LogError( "AccountServices.GetByRowId(rowId, ref string statusMessage): " + ex.ToString() ); statusMessage = message; return null; } return user; } // /// <summary> /// Get user using the temp proxyId /// </summary> /// <param name="pRowId"></param> /// <returns></returns> public Patron GetByProxyRowId( string proxyId, ref string statusMessage ) { if ( proxyId == null || proxyId.Trim().Length != 36 ) { statusMessage = "Error: invalaid request"; return new Patron() { IsValid = false }; } Patron user = GetUserFromProxy( proxyId, ref statusMessage ); return user; }// /// <summary> /// Get User record via email /// </summary> /// <param name="email"></param> /// <returns></returns> public Patron GetByEmail( string email ) { PatronMgr mgr = new PatronMgr(); return mgr.GetByEmail( email.Trim() ); }// /// <summary> /// Login user /// </summary> /// <param name="loginName">Can be either email address or user name</param> /// <param name="password"></param> /// <param name="statusMessage"></param> /// <returns></returns> public Patron Login( string loginName, string password, ref string statusMessage ) { return Authorize( loginName, password, ref statusMessage ); }// /// <summary> /// Authorize user /// </summary> /// <param name="userName">Can be either email address or user name</param> /// <param name="password"></param> /// <param name="statusMessage"></param> /// <returns></returns> public Patron Authorize( string userName, string password, ref string statusMessage ) { Patron appUser = new Patron(); appUser.IsValid = false; if ( userName == null || userName.Length < 4 || password == null || password.Length < 7 ) { statusMessage = "Some required fields are empty."; return appUser; } string encryptedPassword = ""; if ( password.Length > 40 ) { //already encrypted encryptedPassword = password; } else { encryptedPassword = ServiceHelper.Encrypt( password ); } PatronMgr mgr = new PatronMgr(); //get user appUser = mgr.Authorize( userName, encryptedPassword ); if ( appUser == null || appUser.IsValid == false ) { statusMessage = "Error: Login failed - Invalid credentials"; } else { //add proxy appUser.ProxyId = Create_SessionProxyLoginId( appUser.Id, ref statusMessage ); //handle admin users SetUserAdminRole(appUser); } return appUser; } public Patron RecoverPassword( string lookup ) { PatronMgr mgr = new PatronMgr(); return mgr.RecoverPassword( lookup ); } /// <summary> /// Search for User related data using passed parameters /// - uses custom paging /// - only requested range of rows will be returned /// </summary> /// <param name="pFilter"></param> /// <param name="pOrderBy">Sort order of results. If blank, the proc should have a default sort order</param> /// <param name="pStartPageIndex"></param> /// <param name="pMaximumRows"></param> /// <param name="pTotalRows"></param> /// <returns></returns> public List<Patron> Search( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, bool pOutputRelTables, ref int pTotalRows ) { PatronMgr mgr = new PatronMgr(); return mgr.Search( pFilter, pOrderBy, pStartPageIndex, pMaximumRows, ref pTotalRows ); } public DataSet UserSearch( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, bool pOutputRelTables, ref int pTotalRows ) { PatronMgr mgr = new PatronMgr(); return mgr.UserSearch( pFilter, pOrderBy, pStartPageIndex, pMaximumRows, ref pTotalRows ); } public ThisUserProfile PatronProfile_Get( int pUserId ) { PatronMgr mgr = new PatronMgr(); return mgr.PatronProfile_Get( pUserId ); }// public static List<Patron> GetAllUsers() { EFDal.ResourceEntities ctx = new EFDal.ResourceEntities(); List<EFDal.Patron> eflist = ctx.Patrons .OrderBy( s => s.LastName ) .ToList(); List<Patron> list = new List<Patron>(); if ( eflist.Count > 0 ) { foreach ( EFDal.Patron item in eflist ) { Patron e = new Patron(); e.Id = item.Id; e.FirstName = item.FirstName; e.LastName = item.LastName; list.Add( e ); } } return list; } public static List<CodeItem> GetAllUsersAsCodes() { CodeItem ci = new CodeItem(); EFDal.ResourceEntities ctx = new EFDal.ResourceEntities(); List<EFDal.Patron> eflist = ctx.Patrons.OrderBy( s => s.LastName ).ToList(); List<CodeItem> list = new List<CodeItem>(); if ( eflist.Count > 0 ) { foreach ( EFDal.Patron item in eflist ) { ci = new CodeItem(); ci.Id = item.Id; ci.Title = item.LastName == null ? "" : item.LastName + ", " + item.FirstName; list.Add( ci ); } } return list; } /// <summary> /// Determine if current user is a logged in (registered) user /// </summary> /// <returns></returns> public static bool IsUserAuthenticated() { bool isUserAuthenticated = false; try { Patron appUser = GetUserFromSession(); isUserAuthenticated = IsUserAuthenticated( appUser ); } catch { } return isUserAuthenticated; } // public static bool IsUserAuthenticated( Patron appUser ) { bool isUserAuthenticated = false; try { if ( appUser == null || appUser.Id == 0 || appUser.IsValid == false ) { isUserAuthenticated = false; } else { isUserAuthenticated = true; } } catch { } return isUserAuthenticated; } // public static Patron GetUserFromSession() { if ( HttpContext.Current.Session != null ) { return GetUserFromSession( HttpContext.Current.Session ); } else return null; } // public static Patron GetUserFromSession( HttpSessionState session ) { Patron user = new Patron(); try { //Get the user user = ( Patron ) session[ Constants.USER_REGISTER ]; if ( user.Id == 0 || !user.IsValid ) { user.IsValid = false; user.Id = 0; } } catch { user = new Patron(); user.IsValid = false; } return user; } #endregion #endregion #region patron - proxy login methods public string Create_SessionProxyLoginId( int userId, ref string statusMessage ) { return Create_ProxyLoginId( userId, SessionLoginProxy, 1, ref statusMessage ); } public string Create_RegistrationConfirmProxyLoginId( int userId, ref string statusMessage ) { int expiryDays = ServiceHelper.GetAppKeyValue( "registrationConfExpiryDays", 5 ); return Create_ProxyLoginId( userId, "Registration Immediate Confirmation", expiryDays, ref statusMessage ); } public string Create_ForgotPasswordProxyLoginId( int userId, ref string statusMessage ) { int expiryDays = ServiceHelper.GetAppKeyValue( "forgotPasswordExiryDays", 1 ); return Create_ProxyLoginId( userId, "Forgot Password", expiryDays, ref statusMessage ); } public string Create_3rdPartyAddProxyLoginId( int userId, ref string statusMessage ) { int expiryDays = ServiceHelper.GetAppKeyValue( "user3rdPartyAddExpiryDays", 14 ); return Create_ProxyLoginId( userId, "User added from org.", expiryDays, ref statusMessage ); } public string Create_3rdPartyAddProxyLoginId( int userId, string proxyType, ref string statusMessage ) { int expiryDays = ServiceHelper.GetAppKeyValue( "user3rdPartyAddExpiryDays", 14 ); return Create_ProxyLoginId( userId, proxyType, expiryDays, ref statusMessage ); } /// <summary> /// General proxy type - usually a week to handle weekends /// </summary> /// <param name="userId"></param> /// <param name="proxyType"></param> /// <param name="statusMessage"></param> /// <returns></returns> public string Create_ProxyLoginId( int userId, string proxyType, ref string statusMessage ) { int expiryDays = ServiceHelper.GetAppKeyValue( "proxyLoginExiryDays", 5 ); return Create_ProxyLoginId( userId, proxyType, expiryDays, ref statusMessage ); } public string Create_SSOProxyLoginId(int userId, ref string statusMessage) { return Create_ProxyLoginId(userId, "SSO", 1, ref statusMessage); } /// <summary> /// Create a proxy guid for use in auto login /// </summary> /// <param name="userId"></param> /// <param name="proxyType"></param> /// <param name="statusMessage"></param> /// <returns></returns> public string Create_ProxyLoginId( int userId, string proxyType, int expiryDays, ref string statusMessage ) { EFDal.System_GenerateLoginId efEntity = new EFDal.System_GenerateLoginId(); string proxyId = ""; try { using ( var context = new EFDal.ResourceContext() ) { efEntity.UserId = userId; efEntity.ProxyId = Guid.NewGuid(); efEntity.Created = System.DateTime.Now; if ( proxyType == SessionLoginProxy ) { //expire at midnight - not really good for night owls //efEntity.ExpiryDate = new System.DateTime( DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59 ); efEntity.ExpiryDate = System.DateTime.Now.AddDays( expiryDays ); } else efEntity.ExpiryDate = System.DateTime.Now.AddDays( expiryDays ); efEntity.IsActive = true; efEntity.ProxyType = proxyType; context.System_GenerateLoginId.Add( efEntity ); // submit the change to database int count = context.SaveChanges(); if ( count > 0 ) { statusMessage = "Successful"; int id = efEntity.Id; return efEntity.ProxyId.ToString(); } else { //?no info on error return proxyId; } } } catch ( Exception ex ) { LoggingHelper.LogError( ex, thisClassName + ".Create_ProxyLoginId()" ); statusMessage = ex.Message; return proxyId; } } /// <summary> /// Retrieve userId for a proxy. /// Even if the proxy has been used, the userid is returned - do can check if multiple links were used for the same user/email /// </summary> /// <param name="rowId"></param> /// <param name="isProxyValid"></param> /// <param name="doingCheckOnly">If true, a valid proxy will not be inactivated</param> /// <param name="statusMessage"></param> /// <returns></returns> public int GetUserIdFromProxy( string rowId, bool doingCheckOnly, ref bool isProxyValid, ref string statusMessage ) { int userId = 0; isProxyValid = false; using ( var context = new EFDal.ResourceContext() ) { Guid id = new Guid( rowId ); EFDal.System_GenerateLoginId proxy = context.System_GenerateLoginId.FirstOrDefault( s => s.ProxyId == id ); if ( proxy != null && proxy.Id > 0 ) { if ( proxy.IsActive == false ) { statusMessage = "Error: invalid request, previously used."; userId = proxy.UserId; } else if ( proxy.ExpiryDate != null && proxy.ExpiryDate < System.DateTime.Now ) { statusMessage = "Error: the request has expired."; userId = proxy.UserId; } else { isProxyValid = true; userId = proxy.UserId; if ( doingCheckOnly == false ) { //now set inactive (or delete??) ==> assuming only reason for get is to do the login InactivateProxy( rowId, ref statusMessage ); } } } else { statusMessage = "Error: invalid request (temp id not found)."; } } return userId; } public Patron GetUserFromProxy( string rowId, ref string statusMessage ) { Patron user = new Patron(); if ( rowId == null || rowId.Trim().Length != 36 ) { statusMessage = "Error: invalid proxy id."; return user; } using ( var context = new EFDal.ResourceContext() ) { Guid id = new Guid( rowId ); EFDal.System_GenerateLoginId proxy = context.System_GenerateLoginId.FirstOrDefault( s => s.ProxyId == id ); if ( proxy != null && proxy.Id > 0 ) { if ( proxy.IsActive == false ) { statusMessage = "Error: invalid request, this temporary login key has been previously used."; } else if ( proxy.ExpiryDate != null && proxy.ExpiryDate < System.DateTime.Now ) { statusMessage = "Error: this temporary login key has expired."; } else { user = new AccountServices().Get( proxy.UserId ); //now set inactive (or delete??) InactivateProxy( rowId, ref statusMessage ); } } else { statusMessage = "Error: invalid request (temporary login key not found)."; } } return user; } public bool InactivateProxy( string rowId, ref string statusMessage ) { bool isValid = true; using ( var context = new EFDal.ResourceContext() ) { Guid id = new Guid( rowId ); EFDal.System_GenerateLoginId proxy = context.System_GenerateLoginId.FirstOrDefault( s => s.ProxyId == id ); if ( proxy != null && proxy.Id > 0 ) { proxy.IsActive = false; proxy.AccessDate = System.DateTime.Now; context.SaveChanges(); } } return isValid; } #endregion #region === Dashboard methods public static DashboardDTO GetMyDashboard( int forUserId ) { Patron user = GetUser( forUserId ); return GetDashboard( user, forUserId, 0 ); } public static DashboardDTO GetMyDashboard( Patron user ) { return GetDashboard( user, user.Id, 0 ); } public static DashboardDTO GetMyDashboard( Patron user, int maxResources ) { return GetDashboard( user, user.Id, maxResources ); } private static DashboardDTO GetDashboard( int forUserId, int requestedByUserId ) { Patron user = GetUser( forUserId ); return GetDashboard( user, requestedByUserId, 0 ); } public static DashboardDTO GetDashboard( Patron user, int requestedByUserId, int maxResources ) { DashboardDTO dto = new DashboardDTO(); if ( user.Id == requestedByUserId ) dto.isMyDashboard = true; if ( maxResources > 0 ) dto.maxResources = maxResources; else dto.maxResources = GetAppKeyValue( "maxDashboardResources", 8 ); dto.userId = user.Id; dto.name = user.FullName(); dto.avatarUrl = user.ImageUrl; dto.description = user.UserProfile.RoleProfile; dto.jobTitle = user.UserProfile.JobTitle; dto.role = user.UserProfile.PublishingRole; dto.organization = user.UserProfile.Organization; //future link to organization page //library LibraryBizService ls = new LibraryBizService(); ls.Library_FillDashboard( dto, user, requestedByUserId ); //my resources EFDal.EFResourceManager.Resource_FillDashboard( dto ); //my followed lib resources //my org/library membership lib resources return dto; } public static void FillDashboard( DashboardDTO dto ) { if ( dto.userId == 0 ) { dto.message = "Error - a userid is required"; return; } Patron user = GetUser( dto.userId ); FillDashboard( dto, user, dto.userId, 0 ); } public static void FillDashboard( DashboardDTO dto, Patron user ) { //Patron user = GetUser( forUserId ); FillDashboard( dto, user, user.Id, 0 ); } public static void FillDashboard( DashboardDTO dto, int forUserId, int requestedByUserId ) { Patron user = GetUser( forUserId ); FillDashboard( dto, user, requestedByUserId, 0 ); } public static void FillDashboard( DashboardDTO dto, Patron user, int requestedByUserId, int maxResources ) { //should be initialized, but just in case if (dto == null) dto = new DashboardDTO(); if ( user.Id == requestedByUserId ) dto.isMyDashboard = true; if ( maxResources > 0 && dto.maxResources == 0) dto.maxResources = maxResources; else if ( dto.maxResources == 0 ) dto.maxResources = GetAppKeyValue( "maxDashboardResources", 8 ); dto.userId = user.Id; dto.name = user.FullName(); dto.avatarUrl = user.ImageUrl; dto.description = user.UserProfile.RoleProfile; dto.jobTitle = user.UserProfile.JobTitle; dto.role = user.UserProfile.PublishingRole; dto.organization = user.UserProfile.Organization; //future link to organization page //library LibraryBizService ls = new LibraryBizService(); ls.Library_FillDashboard( dto, user, requestedByUserId ); //my resources EFDal.EFResourceManager.Resource_FillDashboard( dto ); //my followed lib resources //my org/library membership lib resources } #endregion #region === Person Following ===== public static int Person_FollowingAdd( int pFollowingUserId, int FollowedByUserId ) { return EFDal.AccountManager.PersonFollowing_Add( pFollowingUserId, FollowedByUserId ); }// public static bool Person_FollowingDelete( int pFollowingUserId, int FollowedByUserId ) { return EFDal.AccountManager.PersonFollowing_Delete( pFollowingUserId, FollowedByUserId ); }// public static bool Person_FollowingIsMember( int pFollowingUserId, int FollowedByUserId ) { return EFDal.AccountManager.PersonFollowing_IsMember( pFollowingUserId, FollowedByUserId ); }// #endregion #region ====== workNet/external Methods =============================================== string codedPassword = "Niemand hat die Absicht, eine mauer zu errichten!"; public Patron GetByWorkNetId( int pworkNetId ) { PatronMgr mgr = new PatronMgr(); return mgr.GetByWorkNetId( pworkNetId ); }// public Patron GetByWorkNetCredentials( string loginId, string token ) { return GetByExtSiteCredentials( 1, loginId, token ); }// public Patron GetByExtSiteCredentials( int externalSiteId, string loginId, string token ) { PatronMgr mgr = new PatronMgr(); return mgr.GetByExtSiteCredentials( externalSiteId, loginId, token ); }// /// <summary> /// Login with workNet credentials /// This using a web service on old workNet, and is obsolete /// </summary> /// <param name="loginName"></param> /// <param name="password"></param> /// <returns></returns> [Obsolete] public Patron LoginViaWorkNet( string loginName, string password ) { AcctSvce.AccountSoapClient wsClient = new AcctSvce.AccountSoapClient(); AcctSvce.AccountDetail acct = new AcctSvce.AccountDetail(); string encryptedPassword = ServiceHelper.Encrypt( codedPassword ); acct = wsClient.Login( "workNet902", codedPassword, loginName, password ); if ( acct != null && acct.worknetId > 0 ) { //now do we arbitrarily create a pathways account? //BO.Patron user = new BO.Patron(); Patron user = new Patron(); user.FirstName = acct.firstName; user.LastName = acct.lastName; user.Email = acct.email; user.UserName = acct.userName; user.Password = password; user.IsValid = true; //user.worknetId = acct.worknetId; user.RowId = new Guid( acct.rowId ); return user; } else { Patron user = new Patron(); user.Message = acct.statusMessage; //"Error: Invalid Username or Password"; user.IsValid = false; return user; } } /// <summary> /// get a external account /// </summary> /// <param name="id"></param> /// <param name="userId"></param> /// <param name="externalSiteId"></param> /// <param name="externalLoginProvider"></param> /// <param name="token"></param> /// <param name="statusMessage"></param> /// <returns></returns> public PatronExternalAccount ExternalAccount_Get( int id, int userId, int externalSiteId, string externalLoginProvider, string token, ref string statusMessage ) { PatronExternalAccount acct = myManager.ExternalAccount_Get( id, userId, externalSiteId, externalLoginProvider, token, ref statusMessage ); return acct; } /// <summary> /// Create an external account record /// </summary> /// <param name="userId"></param> /// <param name="externalSiteId"></param> /// <param name="loginName"></param> /// <param name="token"></param> /// <param name="statusMessage"></param> /// <returns></returns> public int ExternalAccount_Create( int userId, int externalSiteId, string loginName, string token, ref string statusMessage ) { return myManager.ExternalAccount_Create( userId, externalSiteId, loginName, token, ref statusMessage ); } public int ExternalAccount_Create( int userId, string externalLoginProvider, string loginName, string token, ref string statusMessage ) { return myManager.ExternalAccount_Create( userId, externalLoginProvider, loginName, token, ref statusMessage ); } #endregion } }
//--------------------------------------------------------------------- // <copyright file="RequestUriProcessor.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Provides a class capable of processing Astoria request Uris. // </summary> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Services { #region Namespaces. using System; using System.Collections; using System.Collections.Generic; using System.Data.Services.Client; using System.Data.Services.Parsing; using System.Data.Services.Providers; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; #endregion Namespaces. // Syntax for Astoria segments: // segment ::= identifier [ query ] // query ::= "(" key ")" // key ::= keyvalue *["," keyvalue] // keyvalue ::= *quotedvalue | *unquotedvalue // quotedvalue ::= "'" *qvchar "'" // qvchar ::= char-except-quote | "''" // unquotedvalue ::= char /// <summary> /// Use this class to process a web data service request Uri. /// </summary> internal static class RequestUriProcessor { /// <summary>MethodInfo for the RequestUriProcessor.InvokeWhere method.</summary> private static readonly MethodInfo InvokeWhereMethodInfo = typeof(RequestUriProcessor).GetMethod("InvokeWhere", BindingFlags.NonPublic | BindingFlags.Static); /// <summary>Recursion limit on segment length.</summary> private const int RecursionLimit = 100; /// <summary> /// Parses the request Uri that the host is exposing and returns /// information about the intended results. /// </summary> /// <param name="absoluteRequestUri">Request uri that needs to get processed.</param> /// <param name="service">Data service for which the request is being processed.</param> /// <returns> /// An initialized RequestDescription instance describing what the /// request is for. /// </returns> /// <exception cref="DataServiceException"> /// A <see cref="DataServiceException" /> with status code 404 (Not Found) is returned if an identifier /// in a segment cannot be resolved; 400 (Bad Request) is returned if a syntax /// error is found when processing a restriction (parenthesized text) or /// in the query portion. /// </exception> /// <remarks> /// Very important: no rights are checked on the last segment of the request. /// </remarks> internal static RequestDescription ProcessRequestUri(Uri absoluteRequestUri, IDataService service) { Debug.Assert(service != null, "service != null"); Debug.Assert(absoluteRequestUri != null, "absoluteRequestUri != null"); Debug.Assert(absoluteRequestUri.IsAbsoluteUri, "absoluteRequestUri.IsAbsoluteUri(" + absoluteRequestUri + ")"); string[] segments = EnumerateSegments(absoluteRequestUri, service.OperationContext.AbsoluteServiceUri); if (segments.Length > RecursionLimit) { throw DataServiceException.CreateBadRequestError(Strings.RequestUriProcessor_TooManySegments); } SegmentInfo[] segmentInfos = CreateSegments(segments, service); SegmentInfo lastSegment = (segmentInfos.Length == 0) ? null : segmentInfos[segmentInfos.Length - 1]; RequestTargetKind targetKind = (lastSegment == null) ? RequestTargetKind.ServiceDirectory : lastSegment.TargetKind; // Create a ResultDescription from the processed segments. RequestDescription resultDescription; Uri resultUri = GetResultUri(service.OperationContext); if (targetKind == RequestTargetKind.Metadata || targetKind == RequestTargetKind.Batch || targetKind == RequestTargetKind.ServiceDirectory) { resultDescription = new RequestDescription(targetKind, RequestTargetSource.None, resultUri); } else if (targetKind == RequestTargetKind.VoidServiceOperation) { Debug.Assert(lastSegment != null, "lastSegment != null"); Debug.Assert(lastSegment.TargetSource == RequestTargetSource.ServiceOperation, "targetSource == RequestTargetSource.ServiceOperation"); service.Provider.InvokeServiceOperation(lastSegment.Operation, lastSegment.OperationParameters); resultDescription = new RequestDescription( RequestTargetKind.VoidServiceOperation, // targetKind RequestTargetSource.ServiceOperation, // targetSource resultUri); // resultUri } else { Debug.Assert(lastSegment != null, "lastSegment != null"); Debug.Assert( targetKind == RequestTargetKind.ComplexObject || targetKind == RequestTargetKind.OpenProperty || targetKind == RequestTargetKind.OpenPropertyValue || targetKind == RequestTargetKind.Primitive || targetKind == RequestTargetKind.PrimitiveValue || targetKind == RequestTargetKind.Resource || targetKind == RequestTargetKind.MediaResource, "Known targetKind " + targetKind); RequestTargetSource targetSource = lastSegment.TargetSource; ResourceProperty projectedProperty = lastSegment.ProjectedProperty; string containerName = (lastSegment.TargetKind != RequestTargetKind.PrimitiveValue && lastSegment.TargetKind != RequestTargetKind.OpenPropertyValue && lastSegment.TargetKind != RequestTargetKind.MediaResource) ? lastSegment.Identifier : segmentInfos[segmentInfos.Length - 2].Identifier; bool usesContainerName = (targetSource == RequestTargetSource.Property && projectedProperty != null && projectedProperty.Kind != ResourcePropertyKind.ResourceSetReference) || (targetSource == RequestTargetSource.ServiceOperation && lastSegment.Operation.ResultKind == ServiceOperationResultKind.QueryWithSingleResult); string mimeType = (targetSource == RequestTargetSource.Property && projectedProperty != null) ? projectedProperty.MimeType : (targetSource == RequestTargetSource.ServiceOperation) ? lastSegment.Operation.MimeType : null; RequestQueryCountOption countOption = lastSegment.Identifier == XmlConstants.UriCountSegment ? RequestQueryCountOption.ValueOnly : RequestQueryCountOption.None; // Throw if $count and $inlinecount requests have been disabled by the user if (countOption != RequestQueryCountOption.None && !service.Configuration.DataServiceBehavior.AcceptCountRequests) { throw DataServiceException.CreateBadRequestError(Strings.DataServiceConfiguration_CountNotSupportedInV1Server); } resultDescription = new RequestDescription( segmentInfos, containerName, usesContainerName, mimeType, resultUri) { CountOption = lastSegment.Identifier == XmlConstants.UriCountSegment ? RequestQueryCountOption.ValueOnly : RequestQueryCountOption.None }; // Update the feature version if the target set contains any type with FF KeepInContent=false. resultDescription.UpdateAndCheckEpmFeatureVersion(service); // Update the response DSV for GET if the target set contains any type with FF KeepInContent=false. // // Note the response DSV is payload specific and since for GET we won't know if the instances to be // serialized will contain any properties with FF KeepInContent=false until serialization time which // happens after the headers are written, the best we can do is to determin this at the set level. // // For CUD operations we'll raise the version based on the actual instances at deserialization time. if (service.OperationContext.Host.AstoriaHttpVerb == AstoriaVerbs.GET) { resultDescription.UpdateEpmResponseVersion(service.OperationContext.Host.RequestAccept, service.Provider); } } // Process query options ($filter, $orderby, $expand, etc.) resultDescription = RequestQueryProcessor.ProcessQuery(service, resultDescription); // $count, $inlinecount and $select are 2.0 features - raise the max version of used features accordingly if (resultDescription.CountOption != RequestQueryCountOption.None || (resultDescription.RootProjectionNode != null && resultDescription.RootProjectionNode.ProjectionsSpecified)) { resultDescription.RaiseFeatureVersion(2, 0, service.Configuration); } return resultDescription; } /// <summary>Appends a segment with the specified escaped <paramref name='text' />.</summary> /// <param name='uri'>URI to append to.</param> /// <param name='text'>Segment text, already escaped.</param> /// <returns>A new URI with a new segment escaped.</returns> internal static Uri AppendEscapedSegment(Uri uri, string text) { Debug.Assert(uri != null, "uri != null"); Debug.Assert(text != null, "text != null"); UriBuilder builder = new UriBuilder(uri); if (!builder.Path.EndsWith("/", StringComparison.Ordinal)) { builder.Path += "/"; } builder.Path += text; return builder.Uri; } /// <summary>Appends a segment with the specified unescaped <paramref name='text' />.</summary> /// <param name='uri'>URI to append to.</param> /// <param name='text'>Segment text, already escaped.</param> /// <returns>A new URI with a new segment escaped.</returns> internal static Uri AppendUnescapedSegment(Uri uri, string text) { Debug.Assert(uri != null, "uri != null"); Debug.Assert(text != null, "text != null"); return AppendEscapedSegment(uri, Uri.EscapeDataString(text)); } /// <summary>Gets the absolute URI that a reference (typically from a POST or PUT body) points to.</summary> /// <param name="reference">Textual, URI-encoded reference.</param> /// <param name="operationContext">Context for current operation.</param> /// <returns>The absolute URI that <paramref name="reference"/> resolves to.</returns> internal static Uri GetAbsoluteUriFromReference(string reference, DataServiceOperationContext operationContext) { return GetAbsoluteUriFromReference(reference, operationContext.AbsoluteServiceUri); } /// <summary>Gets the absolute URI that a reference (typically from a POST or PUT body) points to.</summary> /// <param name="reference">Textual, URI-encoded reference.</param> /// <param name="absoluteServiceUri">Absolure URI for service, used to validate that the URI points within.</param> /// <returns>The absolute URI that <paramref name="reference"/> resolves to.</returns> internal static Uri GetAbsoluteUriFromReference(string reference, Uri absoluteServiceUri) { Debug.Assert(!String.IsNullOrEmpty(reference), "!String.IsNullOrEmpty(reference) -- caller should check and throw appropriate message"); Debug.Assert(absoluteServiceUri != null, "absoluteServiceUri != null"); Debug.Assert(absoluteServiceUri.IsAbsoluteUri, "absoluteServiceUri.IsAbsoluteUri(" + absoluteServiceUri + ")"); Uri referenceAsUri = new Uri(reference, UriKind.RelativeOrAbsolute); if (!referenceAsUri.IsAbsoluteUri) { string slash = String.Empty; if (absoluteServiceUri.OriginalString.EndsWith("/", StringComparison.Ordinal)) { if (reference.StartsWith("/", StringComparison.Ordinal)) { reference = reference.Substring(1, reference.Length - 1); } } else if (!reference.StartsWith("/", StringComparison.Ordinal)) { slash = "/"; } referenceAsUri = new Uri(absoluteServiceUri.OriginalString + slash + reference); } if (!UriUtil.UriInvariantInsensitiveIsBaseOf(absoluteServiceUri, referenceAsUri)) { string message = Strings.BadRequest_RequestUriDoesNotHaveTheRightBaseUri(referenceAsUri, absoluteServiceUri); throw DataServiceException.CreateBadRequestError(message); } Debug.Assert( referenceAsUri.IsAbsoluteUri, "referenceAsUri.IsAbsoluteUri(" + referenceAsUri + ") - otherwise composition from absolute yielded relative"); return referenceAsUri; } /// <summary>Gets the specified <paramref name="uri"/> as a string suitable for an HTTP request.</summary> /// <param name="uri"><see cref="Uri"/> to get string for.</param> /// <returns>A string suitable for an HTTP request.</returns> internal static string GetHttpRequestUrl(Uri uri) { Debug.Assert(uri != null, "uri != null"); if (uri.IsAbsoluteUri) { return uri.GetComponents(UriComponents.HttpRequestUrl, UriFormat.UriEscaped); } else { return uri.OriginalString; } } /// <summary>Gets the URI to the results, without the query component.</summary> /// <param name="operationContext">OperationContext with request information.</param> /// <returns>The URI to the results, without the query component.</returns> internal static Uri GetResultUri(DataServiceOperationContext operationContext) { Debug.Assert(operationContext != null, "operationContext != null"); Uri requestUri = operationContext.AbsoluteRequestUri; UriBuilder resultBuilder = new UriBuilder(requestUri); resultBuilder.Query = null; // This is fix for bug 565322. // Since we don't allow uri to compose on collections, () must be present // as the last thing in the uri, if present. We need to remove the () from // the uri, since its a optional thing and we want to return a canonical // uri from the server. if (resultBuilder.Path.EndsWith("()", StringComparison.Ordinal)) { resultBuilder.Path = resultBuilder.Path.Substring(0, resultBuilder.Path.Length - 2); } return resultBuilder.Uri; } /// <summary> /// Returns an object that can enumerate the segments in the specified path (eg: /foo/bar -&gt; foo, bar). /// </summary> /// <param name="absoluteRequestUri">A valid path portion of an uri.</param> /// <param name="baseUri">baseUri for the request that is getting processed.</param> /// <returns>An enumerable object of unescaped segments.</returns> internal static string[] EnumerateSegments(Uri absoluteRequestUri, Uri baseUri) { Debug.Assert(absoluteRequestUri != null, "absoluteRequestUri != null"); Debug.Assert(absoluteRequestUri.IsAbsoluteUri, "absoluteRequestUri.IsAbsoluteUri(" + absoluteRequestUri.IsAbsoluteUri + ")"); Debug.Assert(baseUri != null, "baseUri != null"); Debug.Assert(baseUri.IsAbsoluteUri, "baseUri.IsAbsoluteUri(" + baseUri + ")"); if (!UriUtil.UriInvariantInsensitiveIsBaseOf(baseUri, absoluteRequestUri)) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_RequestUriDoesNotHaveTheRightBaseUri(absoluteRequestUri, baseUri)); } try { // Uri uri = absoluteRequestUri; int numberOfSegmentsToSkip = 0; // Since there is a svc part in the segment, we will need to skip 2 segments numberOfSegmentsToSkip = baseUri.Segments.Length; string[] uriSegments = uri.Segments; int populatedSegmentCount = 0; for (int i = numberOfSegmentsToSkip; i < uriSegments.Length; i++) { string segment = uriSegments[i]; if (segment.Length != 0 && segment != "/") { populatedSegmentCount++; } } string[] segments = new string[populatedSegmentCount]; int segmentIndex = 0; for (int i = numberOfSegmentsToSkip; i < uriSegments.Length; i++) { string segment = uriSegments[i]; if (segment.Length != 0 && segment != "/") { if (segment[segment.Length - 1] == '/') { segment = segment.Substring(0, segment.Length - 1); } segments[segmentIndex++] = Uri.UnescapeDataString(segment); } } Debug.Assert(segmentIndex == segments.Length, "segmentIndex == segments.Length -- otherwise we mis-counted populated/skipped segments."); return segments; } catch (UriFormatException) { throw DataServiceException.CreateSyntaxError(); } } /// <summary> /// Given the uri, extract the key values from the uri /// </summary> /// <param name="absoluteRequestUri">uri from which the key values needs to be extracted</param> /// <param name="service">Data context for which the request is being processed.</param> /// <param name="containerName">returns the name of the source resource set name</param> /// <returns>key values as specified in the uri</returns> internal static KeyInstance ExtractKeyValuesFromUri(Uri absoluteRequestUri, IDataService service, out string containerName) { Debug.Assert(absoluteRequestUri != null, "absoluteRequestUri != null"); Debug.Assert(absoluteRequestUri.IsAbsoluteUri, "absoluteRequestUri.IsAbsoluteUri(" + absoluteRequestUri + ")"); Debug.Assert(service != null, "service != null"); RequestDescription description = RequestUriProcessor.ProcessRequestUri(absoluteRequestUri, service); // if (description.TargetKind != RequestTargetKind.Resource || !description.IsSingleResult || description.TargetSource != RequestTargetSource.EntitySet) { throw DataServiceException.CreateBadRequestError(Strings.BadRequestStream_MustSpecifyCanonicalUriInPayload(absoluteRequestUri)); } // Dereferencing an object by specifying its key values implied the right to read it. Debug.Assert(description.LastSegmentInfo.SingleResult, "description.LastSegmentInfo.SingleResult"); DataServiceConfiguration.CheckResourceRightsForRead(description.LastSegmentInfo.TargetContainer, true /* singleResult */); containerName = description.ContainerName; Debug.Assert(description.LastSegmentInfo.Key != null && !description.LastSegmentInfo.Key.IsEmpty, "Key Must be specified"); return description.LastSegmentInfo.Key; } /// <summary>Invokes Queryable.Select for the specified query and selector.</summary> /// <param name="query">Query to invoke .Select method on.</param> /// <param name="projectedType">Type that will be projected out.</param> /// <param name="selector">Selector lambda expression.</param> /// <returns>The resulting query.</returns> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] internal static IQueryable InvokeSelectForTypes(IQueryable query, Type projectedType, LambdaExpression selector) { Debug.Assert(query != null, "query != null"); Debug.Assert(projectedType != null, "projectedType != null"); Debug.Assert(selector != null, "selector != null"); MethodInfo method = typeof(RequestUriProcessor).GetMethod("InvokeSelect", BindingFlags.Static | BindingFlags.NonPublic); method = method.MakeGenericMethod(query.ElementType, projectedType); return (IQueryable)method.Invoke(null, new object[] { query, selector }); } /// <summary>Invokes Queryable.Where for the specified query and predicate.</summary> /// <param name="query">Query to invoke .Where method on.</param> /// <param name="predicate">Predicate to pass as argument.</param> /// <returns>The resulting query.</returns> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] internal static IQueryable InvokeWhereForType(IQueryable query, LambdaExpression predicate) { Debug.Assert(query != null, "query != null"); Debug.Assert(predicate != null, "predicate != null"); MethodInfo whereMethod = InvokeWhereMethodInfo.MakeGenericMethod(query.ElementType); return (IQueryable)whereMethod.Invoke(null, new object[] { query, predicate }); } /// <summary>Composes the filter portion of a segment onto the specifies query.</summary> /// <param name="filter">Filter portion of segment, possibly null.</param> /// <param name="segment">Segment on which to compose.</param> private static void ComposeQuery(string filter, SegmentInfo segment) { Debug.Assert(filter != null, "filter != null"); Debug.Assert(segment != null, "segment!= null"); Debug.Assert(segment.SingleResult == false, "segment.SingleResult == false"); ResourceType resourceType = segment.TargetResourceType; segment.Key = ExtractKeyValues(resourceType, filter); segment.SingleResult = !segment.Key.IsEmpty; if (segment.SingleResult) { if (!segment.Key.AreValuesNamed && segment.Key.ValueCount > 1) { throw DataServiceException.CreateBadRequestError(Strings.RequestUriProcessor_KeysMustBeNamed); } segment.RequestQueryable = SelectResourceByKey(segment.RequestQueryable, resourceType, segment.Key); segment.SingleResult = true; } } /// <summary>Creates the first <see cref="SegmentInfo"/> for a request.</summary> /// <param name="service">Service for which the request is being processed.</param> /// <param name="identifier">Identifier portion of segment.</param> /// <param name="checkRights">Whether rights should be checked on this segment.</param> /// <param name="queryPortion">Query portion with key; possibly null.</param> /// <param name="isLastSegment">True if the first segment is also the last segment.</param> /// <param name="crossReferencingUrl">whether this segment references some other segment.</param> /// <returns>A description of the information on the segment.</returns> private static SegmentInfo CreateFirstSegment(IDataService service, string identifier, bool checkRights, string queryPortion, bool isLastSegment, out bool crossReferencingUrl) { Debug.Assert(service != null, "service != null"); Debug.Assert(identifier != null, "identifier != null"); crossReferencingUrl = false; SegmentInfo segment = new SegmentInfo(); segment.Identifier = identifier; // Look for well-known system entry points. if (segment.Identifier == XmlConstants.UriMetadataSegment) { WebUtil.CheckSyntaxValid(queryPortion == null); segment.TargetKind = RequestTargetKind.Metadata; return segment; } if (segment.Identifier == XmlConstants.UriBatchSegment) { WebUtil.CheckSyntaxValid(queryPortion == null); segment.TargetKind = RequestTargetKind.Batch; return segment; } if (segment.Identifier == XmlConstants.UriCountSegment) { // $count on root: throw throw DataServiceException.CreateResourceNotFound(Strings.RequestUriProcessor_CountOnRoot); } // Look for a service operation. segment.Operation = service.Provider.TryResolveServiceOperation(segment.Identifier); if (segment.Operation != null) { WebUtil.DebugEnumIsDefined(segment.Operation.ResultKind); segment.TargetSource = RequestTargetSource.ServiceOperation; if (service.OperationContext.RequestMethod != segment.Operation.Method) { throw DataServiceException.CreateMethodNotAllowed(Strings.RequestUriProcessor_MethodNotAllowed, segment.Operation.Method); } segment.TargetContainer = segment.Operation.ResourceSet; if (segment.Operation.ResultKind != ServiceOperationResultKind.Void) { segment.TargetResourceType = segment.Operation.ResultType; } else { segment.TargetResourceType = null; } segment.OperationParameters = ReadOperationParameters(service.OperationContext.Host, segment.Operation); switch (segment.Operation.ResultKind) { case ServiceOperationResultKind.QueryWithMultipleResults: case ServiceOperationResultKind.QueryWithSingleResult: try { segment.RequestQueryable = (IQueryable)service.Provider.InvokeServiceOperation(segment.Operation, segment.OperationParameters); } catch (TargetInvocationException exception) { ErrorHandler.HandleTargetInvocationException(exception); throw; } WebUtil.CheckResourceExists(segment.RequestQueryable != null, segment.Identifier); segment.SingleResult = (segment.Operation.ResultKind == ServiceOperationResultKind.QueryWithSingleResult); break; case ServiceOperationResultKind.DirectValue: case ServiceOperationResultKind.Enumeration: object methodResult; try { methodResult = service.Provider.InvokeServiceOperation(segment.Operation, segment.OperationParameters); } catch (TargetInvocationException exception) { ErrorHandler.HandleTargetInvocationException(exception); throw; } segment.SingleResult = (segment.Operation.ResultKind == ServiceOperationResultKind.DirectValue); WebUtil.CheckResourceExists(segment.SingleResult || methodResult != null, segment.Identifier); // Enumerations shouldn't be null. segment.RequestEnumerable = segment.SingleResult ? new object[1] { methodResult } : (IEnumerable)methodResult; segment.TargetResourceType = segment.Operation.ResultType; segment.TargetKind = TargetKindFromType(segment.TargetResourceType); WebUtil.CheckSyntaxValid(queryPortion == null); RequestQueryProcessor.CheckEmptyQueryArguments(service, false /*checkForOnlyV2QueryParameters*/); break; default: Debug.Assert(segment.Operation.ResultKind == ServiceOperationResultKind.Void, "segment.Operation.ResultKind == ServiceOperationResultKind.Nothing"); segment.TargetKind = RequestTargetKind.VoidServiceOperation; break; } if (segment.RequestQueryable != null) { segment.TargetKind = TargetKindFromType(segment.TargetResourceType); if (queryPortion != null) { WebUtil.CheckSyntaxValid(!segment.SingleResult); ComposeQuery(queryPortion, segment); } } if (checkRights) { DataServiceConfiguration.CheckServiceRights(segment.Operation, segment.SingleResult); } return segment; } SegmentInfo newSegmentInfo = service.GetSegmentForContentId(segment.Identifier); if (newSegmentInfo != null) { newSegmentInfo.Identifier = segment.Identifier; crossReferencingUrl = true; return newSegmentInfo; } // Look for an entity set. ResourceSetWrapper container = service.Provider.TryResolveResourceSet(segment.Identifier); WebUtil.CheckResourceExists(container != null, segment.Identifier); if (ShouldRequestQuery(service, isLastSegment, false, queryPortion)) { #if DEBUG segment.RequestQueryable = service.Provider.GetQueryRootForResourceSet(container, service); #else segment.RequestQueryable = service.Provider.GetQueryRootForResourceSet(container); #endif WebUtil.CheckResourceExists(segment.RequestQueryable != null, segment.Identifier); } segment.TargetContainer = container; segment.TargetResourceType = container.ResourceType; segment.TargetSource = RequestTargetSource.EntitySet; segment.TargetKind = RequestTargetKind.Resource; segment.SingleResult = false; if (queryPortion != null) { ComposeQuery(queryPortion, segment); } if (checkRights) { DataServiceConfiguration.CheckResourceRightsForRead(container, segment.SingleResult); } if (segment.RequestQueryable != null) { // We only need to invoke the query interceptor if we called get query root. segment.RequestQueryable = DataServiceConfiguration.ComposeResourceContainer(service, container, segment.RequestQueryable); } return segment; } /// <summary>Whether a query should be requested and composed with interceptors for a segment.</summary> /// <param name="service">Service under which request is being analyzed.</param> /// <param name="isLastSegment">Whether this is the last segment of the URI.</param> /// <param name="isAfterLink">Is the current segment being checked after a $links segment.</param> /// <param name="queryPortion">Query portion of the segment.</param> /// <returns>true if the segments should be read and composed with interceptors; false otherwise.</returns> /// <remarks> /// For V1 providers we always get the query root or else we introduce a breaking change. /// If this is an insert operation and the current segment is the first and last segment, /// we don't need to get the query root as we won't even invoke the query. /// Note that we need to make sure we only skip the query root if the query portion is null, this /// is because in the deep insert case, we can be doing a binding to a single entity and we would /// need the query root for that entity. /// We shall also skip requesting the query if the request is for an update on $links for non-V1 providers. /// </remarks> private static bool ShouldRequestQuery(IDataService service, bool isLastSegment, bool isAfterLink, string queryPortion) { Debug.Assert(service != null, "service != null"); if (service.Provider.IsV1Provider) { return true; } AstoriaVerbs verbUsed = service.OperationContext.Host.AstoriaHttpVerb; bool isPostQueryForSet = isLastSegment && verbUsed == AstoriaVerbs.POST && string.IsNullOrEmpty(queryPortion); bool isUpdateQueryForLinks = isAfterLink && (verbUsed == AstoriaVerbs.PUT || verbUsed == AstoriaVerbs.MERGE); return !(isPostQueryForSet || isUpdateQueryForLinks); } /// <summary>Creates a <see cref="SegmentInfo"/> array for the given <paramref name="segments"/>.</summary> /// <param name="segments">Segments to process.</param> /// <param name="service">Service for which segments are being processed.</param> /// <returns>Segment information describing the given <paramref name="segments"/>.</returns> private static SegmentInfo[] CreateSegments(string[] segments, IDataService service) { Debug.Assert(segments != null, "segments != null"); Debug.Assert(service != null, "service != null"); SegmentInfo previous = null; SegmentInfo[] segmentInfos = new SegmentInfo[segments.Length]; bool crossReferencingUri = false; bool postLinkSegment = false; for (int i = 0; i < segments.Length; i++) { string segmentText = segments[i]; bool checkRights = (i != segments.Length - 1); // Whether rights should be checked on this segment. string identifier; bool hasQuery = ExtractSegmentIdentifier(segmentText, out identifier); string queryPortion = hasQuery ? segmentText.Substring(identifier.Length) : null; SegmentInfo segment; // We allow a single trailing '/', which results in an empty segment. // However System.Uri removes it, so any empty segment we see is a 404 error. if (identifier.Length == 0) { throw DataServiceException.ResourceNotFoundError(Strings.RequestUriProcessor_EmptySegmentInRequestUrl); } if (previous == null) { segment = CreateFirstSegment(service, identifier, checkRights, queryPortion, segments.Length == 1, out crossReferencingUri); } else if (previous.TargetKind == RequestTargetKind.Batch || previous.TargetKind == RequestTargetKind.Metadata || previous.TargetKind == RequestTargetKind.PrimitiveValue || previous.TargetKind == RequestTargetKind.VoidServiceOperation || previous.TargetKind == RequestTargetKind.OpenPropertyValue || previous.TargetKind == RequestTargetKind.MediaResource) { // Nothing can come after a $metadata, $value or $batch segment. // Nothing can come after a service operation with void return type. throw DataServiceException.ResourceNotFoundError(Strings.RequestUriProcessor_MustBeLeafSegment(previous.Identifier)); } else if (postLinkSegment && identifier != XmlConstants.UriCountSegment) { // DEVNOTE([....]): [Resources]/$links/[Property]/$count is valid throw DataServiceException.ResourceNotFoundError(Strings.RequestUriProcessor_CannotSpecifyAfterPostLinkSegment(identifier, XmlConstants.UriLinkSegment)); } else if (previous.TargetKind == RequestTargetKind.Primitive) { // $value is the well-known identifier to return a primitive property // in its natural MIME format. if (identifier != XmlConstants.UriValueSegment) { throw DataServiceException.ResourceNotFoundError(Strings.RequestUriProcessor_ValueSegmentAfterScalarPropertySegment(previous.Identifier, identifier)); } WebUtil.CheckSyntaxValid(!hasQuery); segment = new SegmentInfo(previous); segment.Identifier = identifier; segment.SingleResult = true; segment.TargetKind = RequestTargetKind.PrimitiveValue; } else if (previous.TargetKind == RequestTargetKind.Resource && previous.SingleResult && identifier == XmlConstants.UriLinkSegment) { segment = new SegmentInfo(previous); segment.Identifier = identifier; segment.TargetKind = RequestTargetKind.Link; } else { Debug.Assert( previous.TargetKind == RequestTargetKind.ComplexObject || previous.TargetKind == RequestTargetKind.Resource || previous.TargetKind == RequestTargetKind.OpenProperty || previous.TargetKind == RequestTargetKind.Link, "previous.TargetKind(" + previous.TargetKind + ") can have properties"); postLinkSegment = (previous.TargetKind == RequestTargetKind.Link); // Enumerable and DirectValue results cannot be composed at all. if (previous.Operation != null && (previous.Operation.ResultKind == ServiceOperationResultKind.Enumeration || previous.Operation.ResultKind == ServiceOperationResultKind.DirectValue)) { throw DataServiceException.ResourceNotFoundError( Strings.RequestUriProcessor_IEnumerableServiceOperationsCannotBeFurtherComposed(previous.Identifier)); } if (!previous.SingleResult && identifier != XmlConstants.UriCountSegment) { // $count can be applied to a collection throw DataServiceException.CreateBadRequestError( Strings.RequestUriProcessor_CannotQueryCollections(previous.Identifier)); } segment = new SegmentInfo(); segment.Identifier = identifier; segment.TargetSource = RequestTargetSource.Property; // A segment will correspond to a property in the object model; // if we are processing an open type, anything further in the // URI also represents an open type property. if (previous.TargetResourceType == null) { Debug.Assert(previous.TargetKind == RequestTargetKind.OpenProperty, "For open properties, the target resource type must be null"); segment.ProjectedProperty = null; } else { Debug.Assert(previous.TargetKind != RequestTargetKind.OpenProperty, "Since the query element type is known, this can't be open property"); Debug.Assert(previous.TargetResourceType != null, "Previous wasn't open, so it should have a resource type"); segment.ProjectedProperty = previous.TargetResourceType.TryResolvePropertyName(identifier); } if (identifier == XmlConstants.UriCountSegment) { if (previous.TargetKind != RequestTargetKind.Resource) { throw DataServiceException.CreateResourceNotFound(Strings.RequestUriProcessor_CountNotSupported(previous.Identifier)); } if (previous.SingleResult) { throw DataServiceException.CreateResourceNotFound(Strings.RequestUriProcessor_CannotQuerySingletons(previous.Identifier, identifier)); } if (service.OperationContext.Host.AstoriaHttpVerb != AstoriaVerbs.GET) { throw DataServiceException.CreateBadRequestError(Strings.RequestQueryProcessor_RequestVerbCannotCountError); } segment.RequestEnumerable = previous.RequestEnumerable; segment.SingleResult = true; segment.TargetKind = RequestTargetKind.PrimitiveValue; segment.TargetResourceType = previous.TargetResourceType; segment.TargetContainer = previous.TargetContainer; } else if (identifier == XmlConstants.UriValueSegment && (previous.TargetKind == RequestTargetKind.OpenProperty || (previous.TargetKind == RequestTargetKind.Resource))) { segment.RequestEnumerable = previous.RequestEnumerable; segment.SingleResult = true; segment.TargetResourceType = previous.TargetResourceType; if (previous.TargetKind == RequestTargetKind.OpenProperty) { segment.TargetKind = RequestTargetKind.OpenPropertyValue; } else { // If the previous segment is an entity, we expect it to be an MLE. We cannot validate our assumption // until later when we get the actual instance of the entity because the type hierarchy can contain // a mix of MLE and non-MLE types. segment.TargetKind = RequestTargetKind.MediaResource; // There is no valid query option for Media Resource. RequestQueryProcessor.CheckEmptyQueryArguments(service, false /*checkForOnlyV2QueryParameters*/); } } else if (segment.ProjectedProperty == null) { // Handle an open type property. If the current leaf isn't an // object (which implies it's already an open type), then // it should be marked as an open type. if (previous.TargetResourceType != null) { WebUtil.CheckResourceExists(previous.TargetResourceType.IsOpenType, segment.Identifier); } // Open navigation properties are not supported on OpenTypes. We should throw on the following cases: // 1. the segment after $links is always a navigation property pointing to a resource // 2. if the segment hasQuery, it is pointing to a resource // 3. if this is a POST operation, the target has to be either a set of links or an entity set if (previous.TargetKind == RequestTargetKind.Link || hasQuery || service.OperationContext.Host.AstoriaHttpVerb == AstoriaVerbs.POST) { throw DataServiceException.CreateBadRequestError(Strings.OpenNavigationPropertiesNotSupportedOnOpenTypes(segment.Identifier)); } segment.TargetResourceType = null; segment.TargetKind = RequestTargetKind.OpenProperty; segment.SingleResult = true; if (!crossReferencingUri) { segment.RequestQueryable = SelectOpenProperty(previous.RequestQueryable, identifier); } } else { // Handle a strongly-typed property. segment.TargetResourceType = segment.ProjectedProperty.ResourceType; ResourcePropertyKind propertyKind = segment.ProjectedProperty.Kind; segment.SingleResult = (propertyKind != ResourcePropertyKind.ResourceSetReference); if (!crossReferencingUri) { if (segment.ProjectedProperty.CanReflectOnInstanceTypeProperty) { segment.RequestQueryable = segment.SingleResult ? SelectElement(previous.RequestQueryable, segment.ProjectedProperty) : SelectMultiple(previous.RequestQueryable, segment.ProjectedProperty); } else { segment.RequestQueryable = segment.SingleResult ? SelectLateBoundProperty( previous.RequestQueryable, segment.ProjectedProperty) : SelectLateBoundPropertyMultiple( previous.RequestQueryable, segment.ProjectedProperty); } } if (previous.TargetKind == RequestTargetKind.Link && segment.ProjectedProperty.TypeKind != ResourceTypeKind.EntityType) { throw DataServiceException.CreateBadRequestError(Strings.RequestUriProcessor_LinkSegmentMustBeFollowedByEntitySegment(identifier, XmlConstants.UriLinkSegment)); } switch (propertyKind) { case ResourcePropertyKind.ComplexType: segment.TargetKind = RequestTargetKind.ComplexObject; break; case ResourcePropertyKind.ResourceReference: case ResourcePropertyKind.ResourceSetReference: segment.TargetKind = RequestTargetKind.Resource; segment.TargetContainer = service.Provider.GetContainer(previous.TargetContainer, previous.TargetResourceType, segment.ProjectedProperty); if (segment.TargetContainer == null) { throw DataServiceException.CreateResourceNotFound(segment.ProjectedProperty.Name); } break; default: Debug.Assert(segment.ProjectedProperty.IsOfKind(ResourcePropertyKind.Primitive), "must be primitive type property"); segment.TargetKind = RequestTargetKind.Primitive; break; } if (hasQuery) { WebUtil.CheckSyntaxValid(!segment.SingleResult); if (!crossReferencingUri) { ComposeQuery(queryPortion, segment); } else { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_ResourceCanBeCrossReferencedOnlyForBindOperation); } } // Do security checks and authorization query composition. if (segment.TargetContainer != null) { if (checkRights) { DataServiceConfiguration.CheckResourceRightsForRead(segment.TargetContainer, segment.SingleResult); } if (!crossReferencingUri && ShouldRequestQuery(service, i == segments.Length - 1, postLinkSegment, queryPortion)) { segment.RequestQueryable = DataServiceConfiguration.ComposeResourceContainer(service, segment.TargetContainer, segment.RequestQueryable); } } } } #if DEBUG segment.AssertValid(); #endif segmentInfos[i] = segment; previous = segment; } if (segments.Length != 0 && previous.TargetKind == RequestTargetKind.Link) { throw DataServiceException.CreateBadRequestError(Strings.RequestUriProcessor_MissingSegmentAfterLink(XmlConstants.UriLinkSegment)); } return segmentInfos; } /// <summary>Returns an object that can enumerate key values.</summary> /// <param name="resourceType">resource type whose keys need to be extracted</param> /// <param name="filter">Key (query) part of an Astoria segment.</param> /// <returns>An object that can enumerate key values.</returns> private static KeyInstance ExtractKeyValues(ResourceType resourceType, string filter) { KeyInstance key; filter = RemoveFilterParens(filter); WebUtil.CheckSyntaxValid(KeyInstance.TryParseKeysFromUri(filter, out key)); if (!key.IsEmpty) { // Make sure the keys specified in the uri matches with the number of keys in the metadata if (resourceType.KeyProperties.Count != key.ValueCount) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_KeyCountMismatch(resourceType.FullName)); } WebUtil.CheckSyntaxValid(key.TryConvertValues(resourceType)); } return key; } /// <summary>Extracts the identifier part of the unescaped Astoria segment.</summary> /// <param name="segment">Unescaped Astoria segment.</param> /// <param name="identifier">On returning, the identifier in the segment.</param> /// <returns>true if keys follow the identifier.</returns> private static bool ExtractSegmentIdentifier(string segment, out string identifier) { Debug.Assert(segment != null, "segment != null"); int filterStart = 0; while (filterStart < segment.Length && segment[filterStart] != '(') { filterStart++; } identifier = segment.Substring(0, filterStart); return filterStart < segment.Length; } /// <summary>Generic method to invoke a Select method on an IQueryable source.</summary> /// <typeparam name="TSource">Element type of the source.</typeparam> /// <typeparam name="TResult">Result type of the projection.</typeparam> /// <param name="source">Source query.</param> /// <param name="selector">Lambda expression that turns TSource into TResult.</param> /// <returns>A new query that projects TSource into TResult.</returns> private static IQueryable InvokeSelect<TSource, TResult>(IQueryable source, LambdaExpression selector) { Debug.Assert(source != null, "source != null"); Debug.Assert(selector != null, "selector != null"); IQueryable<TSource> typedSource = (IQueryable<TSource>)source; Expression<Func<TSource, TResult>> typedSelector = (Expression<Func<TSource, TResult>>)selector; return Queryable.Select<TSource, TResult>(typedSource, typedSelector); } /// <summary>Generic method to invoke a SelectMany method on an IQueryable source.</summary> /// <typeparam name="TSource">Element type of the source.</typeparam> /// <typeparam name="TResult">Result type of the projection.</typeparam> /// <param name="source">Source query.</param> /// <param name="selector">Lambda expression that turns TSource into IEnumerable&lt;TResult&gt;.</param> /// <returns>A new query that projects TSource into IEnumerable&lt;TResult&gt;.</returns> private static IQueryable InvokeSelectMany<TSource, TResult>(IQueryable source, LambdaExpression selector) { Debug.Assert(source != null, "source != null"); Debug.Assert(selector != null, "selector != null"); IQueryable<TSource> typedSource = (IQueryable<TSource>)source; Expression<Func<TSource, IEnumerable<TResult>>> typedSelector = (Expression<Func<TSource, IEnumerable<TResult>>>)selector; return Queryable.SelectMany<TSource, TResult>(typedSource, typedSelector); } /// <summary>Generic method to invoke a Where method on an IQueryable source.</summary> /// <typeparam name="TSource">Element type of the source.</typeparam> /// <param name="query">Source query.</param> /// <param name="predicate">Lambda expression that filters the result of the query.</param> /// <returns>A new query that filters the query.</returns> private static IQueryable InvokeWhere<TSource>(IQueryable query, LambdaExpression predicate) { Debug.Assert(query != null, "query != null"); Debug.Assert(predicate != null, "predicate != null"); IQueryable<TSource> typedQueryable = (IQueryable<TSource>)query; // If the type of predicate is not TSource, we need to replace the parameter with // a downcasted parameter type if predicate's input is a base class of TSource. if (predicate.Parameters[0].Type != typeof(TSource) && predicate.Parameters[0].Type.IsAssignableFrom(typeof(TSource))) { predicate = RequestUriProcessor.ReplaceParameterTypeForLambda(predicate, typeof(TSource)); } Expression<Func<TSource, bool>> typedPredicate = (Expression<Func<TSource, bool>>)predicate; return Queryable.Where<TSource>(typedQueryable, typedPredicate); } /// <summary>Replaced the type of input parameter with the given <paramref name="targetType"/></summary> /// <param name="input">Input lambda expression.</param> /// <param name="targetType">Type of the new parameter that will be replaced.</param> /// <returns>New lambda expression with parameter of new type.</returns> private static LambdaExpression ReplaceParameterTypeForLambda(LambdaExpression input, Type targetType) { Debug.Assert(input.Parameters.Count == 1, "Assuming a single parameter for input lambda expression in this function."); ParameterExpression p = Expression.Parameter(targetType, input.Parameters[0].Name); return Expression.Lambda( ParameterReplacerVisitor.Replace(input.Body, input.Parameters[0], p), p); } /// <summary> /// Reads the parameters for the specified <paramref name="operation"/> from the /// <paramref name="host"/>. /// </summary> /// <param name="host">Host with request information.</param> /// <param name="operation">Operation with parameters to be read.</param> /// <returns>A new object[] with parameter values.</returns> private static object[] ReadOperationParameters(DataServiceHostWrapper host, ServiceOperationWrapper operation) { Debug.Assert(host != null, "host != null"); object[] operationParameters = new object[operation.Parameters.Count]; for (int i = 0; i < operation.Parameters.Count; i++) { Type parameterType = operation.Parameters[i].ParameterType.InstanceType; string queryStringValue = host.GetQueryStringItem(operation.Parameters[i].Name); Type underlyingType = Nullable.GetUnderlyingType(parameterType); if (String.IsNullOrEmpty(queryStringValue)) { WebUtil.CheckSyntaxValid(parameterType.IsClass || underlyingType != null); operationParameters[i] = null; } else { // We choose to be a little more flexible than with keys and // allow surrounding whitespace (which is never significant). // See SQLBUDT #555944. queryStringValue = queryStringValue.Trim(); Type targetType = underlyingType ?? parameterType; if (WebConvert.IsKeyTypeQuoted(targetType)) { WebUtil.CheckSyntaxValid(WebConvert.IsKeyValueQuoted(queryStringValue)); } WebUtil.CheckSyntaxValid(WebConvert.TryKeyStringToPrimitive(queryStringValue, targetType, out operationParameters[i])); } } return operationParameters; } /// <summary>Removes the parens around the filter part of a query.</summary> /// <param name='filter'>Filter with parens included.</param> /// <returns>Filter without parens.</returns> private static string RemoveFilterParens(string filter) { Debug.Assert(filter != null, "filter != null"); WebUtil.CheckSyntaxValid(filter.Length > 0 && filter[0] == '(' && filter[filter.Length - 1] == ')'); return filter.Substring(1, filter.Length - 2); } /// <summary>Project a property with a single element out of the specified query.</summary> /// <param name="query">Base query to project from.</param> /// <param name="property">Property to project.</param> /// <returns>A query with a composed primitive property projection.</returns> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] private static IQueryable SelectElement(IQueryable query, ResourceProperty property) { Debug.Assert(query != null, "query != null"); Debug.Assert(property.Kind != ResourcePropertyKind.ResourceSetReference, "property != ResourcePropertyKind.ResourceSetReference"); ParameterExpression parameter = Expression.Parameter(query.ElementType, "element"); MemberExpression body = Expression.Property(parameter, property.Name); LambdaExpression selector = Expression.Lambda(body, parameter); MethodInfo method = typeof(RequestUriProcessor).GetMethod("InvokeSelect", BindingFlags.Static | BindingFlags.NonPublic); method = method.MakeGenericMethod(query.ElementType, property.Type); return (IQueryable)method.Invoke(null, new object[] { query, selector }); } /// <summary>Project a property with multiple elements out of the specified query.</summary> /// <param name="query">Base query to project from.</param> /// <param name="property">Property to project.</param> /// <returns>A query with a composed primitive property projection.</returns> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] private static IQueryable SelectMultiple(IQueryable query, ResourceProperty property) { Debug.Assert(query != null, "query != null"); Debug.Assert(property.Kind == ResourcePropertyKind.ResourceSetReference, "property == ResourcePropertyKind.ResourceSetReference"); Type enumerableElement = BaseServiceProvider.GetIEnumerableElement(property.Type); Debug.Assert(enumerableElement != null, "Providers should never expose a property as a resource-set if it doesn't implement IEnumerable`1."); ParameterExpression parameter = Expression.Parameter(query.ElementType, "element"); UnaryExpression body = Expression.ConvertChecked( Expression.Property(parameter, property.Name), typeof(IEnumerable<>).MakeGenericType(enumerableElement)); LambdaExpression selector = Expression.Lambda(body, parameter); MethodInfo method = typeof(RequestUriProcessor).GetMethod("InvokeSelectMany", BindingFlags.Static | BindingFlags.NonPublic); method = method.MakeGenericMethod(query.ElementType, enumerableElement); return (IQueryable)method.Invoke(null, new object[] { query, selector }); } /// <summary>Project a property with a single element out of the specified query over an late bound (possibily open) property.</summary> /// <param name="query">Base query to project from.</param> /// <param name="propertyName">Name of property to project.</param> /// <returns>A query with a composed property projection.</returns> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] private static IQueryable SelectOpenProperty(IQueryable query, string propertyName) { Debug.Assert(query != null, "query != null"); Debug.Assert(propertyName != null, "propertyName != null"); ParameterExpression parameter = Expression.Parameter(query.ElementType, "element"); Expression body = Expression.Call(null /* instance */, OpenTypeMethods.GetValueOpenPropertyMethodInfo, parameter, Expression.Constant(propertyName)); LambdaExpression selector = Expression.Lambda(body, parameter); MethodInfo method = typeof(RequestUriProcessor).GetMethod("InvokeSelect", BindingFlags.Static | BindingFlags.NonPublic); method = method.MakeGenericMethod(query.ElementType, typeof(object)); return (IQueryable)method.Invoke(null, new object[] { query, selector }); } /// <summary>Project a property with a single element out of the specified query over an late bound (possibily open) property.</summary> /// <param name="query">Base query to project from.</param> /// <param name="property">Resource property containing the metadata for the late bound property.</param> /// <returns>A query with a composed property projection.</returns> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] private static IQueryable SelectLateBoundProperty(IQueryable query, ResourceProperty property) { Debug.Assert(query != null, "query != null"); Debug.Assert(property != null && !property.CanReflectOnInstanceTypeProperty, "property != null && !property.CanReflectOnInstanceTypeProperty"); ParameterExpression parameter = Expression.Parameter(query.ElementType, "element"); Expression body = Expression.Call(null /*instance*/, DataServiceProviderMethods.GetValueMethodInfo, parameter, Expression.Constant(property)); body = Expression.Convert(body, property.Type); LambdaExpression selector = Expression.Lambda(body, parameter); MethodInfo method = typeof(RequestUriProcessor).GetMethod("InvokeSelect", BindingFlags.Static | BindingFlags.NonPublic); method = method.MakeGenericMethod(query.ElementType, property.Type); return (IQueryable)method.Invoke(null, new object[] { query, selector }); } /// <summary>Project a property with a single element out of the specified query over an late bound (possibily open) property.</summary> /// <param name="query">Base query to project from.</param> /// <param name="property">Resource property containing the metadata for the late bound property.</param> /// <returns>A query with a composed property projection.</returns> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] private static IQueryable SelectLateBoundPropertyMultiple(IQueryable query, ResourceProperty property) { Debug.Assert(query != null, "query != null"); Debug.Assert(property != null && property.Kind == ResourcePropertyKind.ResourceSetReference && !property.CanReflectOnInstanceTypeProperty, "property != null && property.Kind == ResourcePropertyKind.ResourceSetReference && !property.CanReflectOnInstanceTypeProperty"); Type enumerableElement = BaseServiceProvider.GetIEnumerableElement(property.Type); ParameterExpression parameter = Expression.Parameter(query.ElementType, "element"); MethodInfo getter = DataServiceProviderMethods.GetSequenceValueMethodInfo.MakeGenericMethod(enumerableElement); Expression body = Expression.Call(null /*instance*/, getter, parameter, Expression.Constant(property)); LambdaExpression selector = Expression.Lambda(body, parameter); MethodInfo method = typeof(RequestUriProcessor).GetMethod("InvokeSelectMany", BindingFlags.Static | BindingFlags.NonPublic); method = method.MakeGenericMethod(query.ElementType, enumerableElement); return (IQueryable)method.Invoke(null, new object[] { query, selector }); } /// <summary>Selects a single resource by key values.</summary> /// <param name="query">Base query for resources</param> /// <param name="resourceType">resource type whose keys are specified</param> /// <param name="key">Key values for the given resource type.</param> /// <returns>A new query that selects the single resource that matches the specified key values.</returns> private static IQueryable SelectResourceByKey(IQueryable query, ResourceType resourceType, KeyInstance key) { Debug.Assert(query != null, "query != null"); Debug.Assert(key != null && key.ValueCount != 0, "key != null && key.ValueCount != 0"); Debug.Assert(resourceType.KeyProperties.Count == key.ValueCount, "resourceType.KeyProperties.Count == key.ValueCount"); for (int i = 0; i < resourceType.KeyProperties.Count; i++) { ResourceProperty keyProperty = resourceType.KeyProperties[i]; Debug.Assert(keyProperty.IsOfKind(ResourcePropertyKind.Key), "keyProperty.IsOfKind(ResourcePropertyKind.Key)"); object keyValue; if (key.AreValuesNamed) { keyValue = key.NamedValues[keyProperty.Name]; } else { keyValue = key.PositionalValues[i]; } ParameterExpression parameter = Expression.Parameter(query.ElementType, "element"); Expression e; if (keyProperty.CanReflectOnInstanceTypeProperty) { e = Expression.Property(parameter, keyProperty.Name); } else { e = Expression.Call(null /*instance*/, DataServiceProviderMethods.GetValueMethodInfo, parameter, Expression.Constant(keyProperty)); e = Expression.Convert(e, keyProperty.Type); } BinaryExpression body = Expression.Equal((Expression)e, Expression.Constant(keyValue)); LambdaExpression predicate = Expression.Lambda(body, parameter); query = InvokeWhereForType(query, predicate); } return query; } /// <summary>Determines a matching target kind from the specified type.</summary> /// <param name="type">ResourceType of element to get kind for.</param> /// <returns>An appropriate <see cref="RequestTargetKind"/> for the specified <paramref name="type"/>.</returns> private static RequestTargetKind TargetKindFromType(ResourceType type) { Debug.Assert(type != null, "type != null"); switch (type.ResourceTypeKind) { case ResourceTypeKind.ComplexType: return RequestTargetKind.ComplexObject; case ResourceTypeKind.EntityType: return RequestTargetKind.Resource; default: Debug.Assert(type.ResourceTypeKind == ResourceTypeKind.Primitive, "typeKind == ResourceTypeKind.Primitive"); return RequestTargetKind.Primitive; } } } }
// **************************************************************** // 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; using System.Collections.Generic; using System.Reflection; using System.Text; namespace PclUnit.Constraints.Pieces { #region CollectionConstraint /// <summary> /// CollectionConstraint is the abstract base class for /// constraints that operate on collections. /// </summary> public abstract class CollectionConstraint : Constraint { /// <summary> /// Construct an empty CollectionConstraint /// </summary> public CollectionConstraint() { } /// <summary> /// Construct a CollectionConstraint /// </summary> /// <param name="arg"></param> public CollectionConstraint(object arg) : base(arg) { } /// <summary> /// Determines whether the specified enumerable is empty. /// </summary> /// <param name="enumerable">The enumerable.</param> /// <returns> /// <c>true</c> if the specified enumerable is empty; otherwise, <c>false</c>. /// </returns> protected static bool IsEmpty( IEnumerable enumerable ) { ICollection collection = enumerable as ICollection; if ( collection != null ) return collection.Count == 0; foreach (object o in enumerable) return false; return true; } /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override bool Matches(object actual) { this.actual = actual; IEnumerable enumerable = actual as IEnumerable; if ( enumerable == null ) throw new ArgumentException( "The actual value must be an IEnumerable", "actual" ); return doMatch( enumerable ); } /// <summary> /// Protected method to be implemented by derived classes /// </summary> /// <param name="collection"></param> /// <returns></returns> protected abstract bool doMatch(IEnumerable collection); } #endregion #region CollectionItemsEqualConstraint /// <summary> /// CollectionItemsEqualConstraint is the abstract base class for all /// collection constraints that apply some notion of item equality /// as a part of their operation. /// </summary> public abstract class CollectionItemsEqualConstraint : CollectionConstraint { // This is internal so that ContainsConstraint can set it // TODO: Figure out a way to avoid this indirection internal NUnitEqualityComparer comparer = NUnitEqualityComparer.Default; /// <summary> /// Construct an empty CollectionConstraint /// </summary> public CollectionItemsEqualConstraint() { } /// <summary> /// Construct a CollectionConstraint /// </summary> /// <param name="arg"></param> public CollectionItemsEqualConstraint(object arg) : base(arg) { } #region Modifiers /// <summary> /// Flag the constraint to ignore case and return self. /// </summary> public CollectionItemsEqualConstraint IgnoreCase { get { comparer.IgnoreCase = true; return this; } } /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using(IComparer comparer) { this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } #if CLR_2_0 || CLR_4_0 /// <summary> /// Flag the constraint to use the supplied IComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using<T>(IComparer<T> comparer) { this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied Comparison object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using<T>(Comparison<T> comparer) { this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using(IEqualityComparer comparer) { this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } /// <summary> /// Flag the constraint to use the supplied IEqualityComparer object. /// </summary> /// <param name="comparer">The IComparer object to use.</param> /// <returns>Self.</returns> public CollectionItemsEqualConstraint Using<T>(IEqualityComparer<T> comparer) { this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer)); return this; } #endif #endregion /// <summary> /// Compares two collection members for equality /// </summary> protected bool ItemsEqual(object x, object y) { Tolerance tolerance = Tolerance.Zero; return comparer.AreEqual(x, y, ref tolerance); } /// <summary> /// Return a new CollectionTally for use in making tests /// </summary> /// <param name="c">The collection to be included in the tally</param> protected CollectionTally Tally(IEnumerable c) { return new CollectionTally(comparer, c); } } #endregion #region EmptyCollectionConstraint /// <summary> /// EmptyCollectionConstraint tests whether a collection is empty. /// </summary> public class EmptyCollectionConstraint : CollectionConstraint { /// <summary> /// Check that the collection is empty /// </summary> /// <param name="collection"></param> /// <returns></returns> protected override bool doMatch(IEnumerable collection) { return IsEmpty( collection ); } /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.Write( "<empty>" ); } } #endregion #region UniqueItemsConstraint /// <summary> /// UniqueItemsConstraint tests whether all the items in a /// collection are unique. /// </summary> public class UniqueItemsConstraint : CollectionItemsEqualConstraint { /// <summary> /// Check that all items are unique. /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { List<object> list = new List<object>(); foreach (object o1 in actual) { foreach( object o2 in list ) if ( ItemsEqual(o1, o2) ) return false; list.Add(o1); } return true; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.Write("all items unique"); } } #endregion #region CollectionContainsConstraint /// <summary> /// CollectionContainsConstraint is used to test whether a collection /// contains an expected object as a member. /// </summary> public class CollectionContainsConstraint : CollectionItemsEqualConstraint { private object expected; /// <summary> /// Construct a CollectionContainsConstraint /// </summary> /// <param name="expected"></param> public CollectionContainsConstraint(object expected) : base(expected) { this.expected = expected; this.DisplayName = "contains"; } /// <summary> /// Test whether the expected item is contained in the collection /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { foreach (object obj in actual) if (ItemsEqual(obj, expected)) return true; return false; } /// <summary> /// Write a descripton of the constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("collection containing"); writer.WriteExpectedValue(expected); } } #endregion #region CollectionEquivalentConstraint /// <summary> /// CollectionEquivalentCOnstraint is used to determine whether two /// collections are equivalent. /// </summary> public class CollectionEquivalentConstraint : CollectionItemsEqualConstraint { private IEnumerable expected; /// <summary> /// Construct a CollectionEquivalentConstraint /// </summary> /// <param name="expected"></param> public CollectionEquivalentConstraint(IEnumerable expected) : base(expected) { this.expected = expected; this.DisplayName = "equivalent"; } /// <summary> /// Test whether two collections are equivalent /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { // This is just an optimization if( expected is ICollection && actual is ICollection ) if( ((ICollection)actual).Count != ((ICollection)expected).Count ) return false; CollectionTally tally = Tally(expected); return tally.TryRemove(actual) && tally.Count == 0; } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate("equivalent to"); writer.WriteExpectedValue(expected); } } #endregion #region CollectionSubsetConstraint /// <summary> /// CollectionSubsetConstraint is used to determine whether /// one collection is a subset of another /// </summary> public class CollectionSubsetConstraint : CollectionItemsEqualConstraint { private IEnumerable expected; /// <summary> /// Construct a CollectionSubsetConstraint /// </summary> /// <param name="expected">The collection that the actual value is expected to be a subset of</param> public CollectionSubsetConstraint(IEnumerable expected) : base(expected) { this.expected = expected; this.DisplayName = "subsetof"; } /// <summary> /// Test whether the actual collection is a subset of /// the expected collection provided. /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { return Tally(expected).TryRemove( actual ); } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WritePredicate( "subset of" ); writer.WriteExpectedValue(expected); } } #endregion #region CollectionOrderedConstraint /// <summary> /// CollectionOrderedConstraint is used to test whether a collection is ordered. /// </summary> public class CollectionOrderedConstraint : CollectionConstraint { private ComparisonAdapter comparer = ComparisonAdapter.Default; private string comparerName; private string propertyName; private bool descending; /// <summary> /// Construct a CollectionOrderedConstraint /// </summary> public CollectionOrderedConstraint() { this.DisplayName = "ordered"; } ///<summary> /// If used performs a reverse comparison ///</summary> public CollectionOrderedConstraint Descending { get { descending = true; return this; } } /// <summary> /// Modifies the constraint to use an IComparer and returns self. /// </summary> public CollectionOrderedConstraint Using(IComparer comparer) { this.comparer = ComparisonAdapter.For( comparer ); this.comparerName = comparer.GetType().FullName; return this; } #if CLR_2_0 || CLR_4_0 /// <summary> /// Modifies the constraint to use an IComparer&lt;T&gt; and returns self. /// </summary> public CollectionOrderedConstraint Using<T>(IComparer<T> comparer) { this.comparer = ComparisonAdapter.For(comparer); this.comparerName = comparer.GetType().FullName; return this; } /// <summary> /// Modifies the constraint to use a Comparison&lt;T&gt; and returns self. /// </summary> public CollectionOrderedConstraint Using<T>(Comparison<T> comparer) { this.comparer = ComparisonAdapter.For(new CompPclFix<T>(comparer)); this.comparerName = comparer.GetType().FullName; return this; } private class CompPclFix<T>:IComparer<T> { private Comparison<T> _del; public CompPclFix(Comparison<T> del) { _del = del; } public int Compare(T x, T y) { return _del(x, y); } } #endif /// <summary> /// Modifies the constraint to test ordering by the value of /// a specified property and returns self. /// </summary> public CollectionOrderedConstraint By(string propertyName) { this.propertyName = propertyName; return this; } /// <summary> /// Test whether the collection is ordered /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { object previous = null; int index = 0; foreach(object obj in actual) { object objToCompare = obj; if (obj == null) throw new ArgumentNullException("actual", "Null value at index " + index.ToString()); if (this.propertyName != null) { PropertyInfo prop = obj.GetType().GetProperty(propertyName); objToCompare = prop.GetValue(obj, null); if (objToCompare == null) throw new ArgumentNullException("actual", "Null property value at index " + index.ToString()); } if (previous != null) { //int comparisonResult = comparer.Compare(al[i], al[i + 1]); int comparisonResult = comparer.Compare(previous, objToCompare); if (descending && comparisonResult < 0) return false; if (!descending && comparisonResult > 0) return false; } previous = objToCompare; index++; } return true; } /// <summary> /// Write a description of the constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { if (propertyName == null) writer.Write("collection ordered"); else { writer.WritePredicate("collection ordered by"); writer.WriteExpectedValue(propertyName); } if (descending) writer.WriteModifier("descending"); } /// <summary> /// Returns the string representation of the constraint. /// </summary> /// <returns></returns> protected override string GetStringRepresentation() { StringBuilder sb = new StringBuilder("<ordered"); if (propertyName != null) sb.Append("by " + propertyName); if (descending) sb.Append(" descending"); if (comparerName != null) sb.Append(" " + comparerName); sb.Append(">"); return sb.ToString(); } } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Batch { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for BatchAccountOperations. /// </summary> public static partial class BatchAccountOperationsExtensions { /// <summary> /// Creates a new Batch account with the specified parameters. Existing /// accounts cannot be updated with this API and should instead be updated with /// the Update Batch Account API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// A name for the Batch account which must be unique within the region. Batch /// account names must be between 3 and 24 characters in length and must use /// only numbers and lowercase letters. This name is used as part of the DNS /// name that is used to access the Batch service in the region in which the /// account is created. For example: /// http://accountname.region.batch.azure.com/. /// </param> /// <param name='parameters'> /// Additional parameters for account creation. /// </param> public static BatchAccount Create(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters) { return operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Batch account with the specified parameters. Existing /// accounts cannot be updated with this API and should instead be updated with /// the Update Batch Account API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// A name for the Batch account which must be unique within the region. Batch /// account names must be between 3 and 24 characters in length and must use /// only numbers and lowercase letters. This name is used as part of the DNS /// name that is used to access the Batch service in the region in which the /// account is created. For example: /// http://accountname.region.batch.azure.com/. /// </param> /// <param name='parameters'> /// Additional parameters for account creation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BatchAccount> CreateAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the properties of an existing Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='parameters'> /// Additional parameters for account update. /// </param> public static BatchAccount Update(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates the properties of an existing Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='parameters'> /// Additional parameters for account update. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BatchAccount> UpdateAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> public static BatchAccountDeleteHeaders Delete(this IBatchAccountOperations operations, string resourceGroupName, string accountName) { return operations.DeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BatchAccountDeleteHeaders> DeleteAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets information about the specified Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> public static BatchAccount Get(this IBatchAccountOperations operations, string resourceGroupName, string accountName) { return operations.GetAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Gets information about the specified Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BatchAccount> GetAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets information about the Batch accounts associated with the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<BatchAccount> List(this IBatchAccountOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets information about the Batch accounts associated with the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<BatchAccount>> ListAsync(this IBatchAccountOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets information about the Batch accounts associated with the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> public static IPage<BatchAccount> ListByResourceGroup(this IBatchAccountOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets information about the Batch accounts associated with the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<BatchAccount>> ListByResourceGroupAsync(this IBatchAccountOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Synchronizes access keys for the auto-storage account configured for the /// specified Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> public static void SynchronizeAutoStorageKeys(this IBatchAccountOperations operations, string resourceGroupName, string accountName) { operations.SynchronizeAutoStorageKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Synchronizes access keys for the auto-storage account configured for the /// specified Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task SynchronizeAutoStorageKeysAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.SynchronizeAutoStorageKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Regenerates the specified account key for the Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='keyName'> /// The type of account key to regenerate. Possible values include: 'Primary', /// 'Secondary' /// </param> public static BatchAccountKeys RegenerateKey(this IBatchAccountOperations operations, string resourceGroupName, string accountName, AccountKeyType keyName) { return operations.RegenerateKeyAsync(resourceGroupName, accountName, keyName).GetAwaiter().GetResult(); } /// <summary> /// Regenerates the specified account key for the Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='keyName'> /// The type of account key to regenerate. Possible values include: 'Primary', /// 'Secondary' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BatchAccountKeys> RegenerateKeyAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, AccountKeyType keyName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, keyName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the account keys for the specified Batch account. /// </summary> /// <remarks> /// This operation applies only to Batch accounts created with a /// poolAllocationMode of 'BatchService'. If the Batch account was created with /// a poolAllocationMode of 'UserSubscription', clients cannot use access to /// keys to authenticate, and must use Azure Active Directory instead. In this /// case, getting the keys will fail. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> public static BatchAccountKeys GetKeys(this IBatchAccountOperations operations, string resourceGroupName, string accountName) { return operations.GetKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Gets the account keys for the specified Batch account. /// </summary> /// <remarks> /// This operation applies only to Batch accounts created with a /// poolAllocationMode of 'BatchService'. If the Batch account was created with /// a poolAllocationMode of 'UserSubscription', clients cannot use access to /// keys to authenticate, and must use Azure Active Directory instead. In this /// case, getting the keys will fail. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BatchAccountKeys> GetKeysAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new Batch account with the specified parameters. Existing /// accounts cannot be updated with this API and should instead be updated with /// the Update Batch Account API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// A name for the Batch account which must be unique within the region. Batch /// account names must be between 3 and 24 characters in length and must use /// only numbers and lowercase letters. This name is used as part of the DNS /// name that is used to access the Batch service in the region in which the /// account is created. For example: /// http://accountname.region.batch.azure.com/. /// </param> /// <param name='parameters'> /// Additional parameters for account creation. /// </param> public static BatchAccount BeginCreate(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters) { return operations.BeginCreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Batch account with the specified parameters. Existing /// accounts cannot be updated with this API and should instead be updated with /// the Update Batch Account API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// A name for the Batch account which must be unique within the region. Batch /// account names must be between 3 and 24 characters in length and must use /// only numbers and lowercase letters. This name is used as part of the DNS /// name that is used to access the Batch service in the region in which the /// account is created. For example: /// http://accountname.region.batch.azure.com/. /// </param> /// <param name='parameters'> /// Additional parameters for account creation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BatchAccount> BeginCreateAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> public static BatchAccountDeleteHeaders BeginDelete(this IBatchAccountOperations operations, string resourceGroupName, string accountName) { return operations.BeginDeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified Batch account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BatchAccountDeleteHeaders> BeginDeleteAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets information about the Batch accounts associated with the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<BatchAccount> ListNext(this IBatchAccountOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets information about the Batch accounts associated with the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<BatchAccount>> ListNextAsync(this IBatchAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets information about the Batch accounts associated with the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<BatchAccount> ListByResourceGroupNext(this IBatchAccountOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets information about the Batch accounts associated with the specified /// resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<BatchAccount>> ListByResourceGroupNextAsync(this IBatchAccountOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// 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.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipelines; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Internal; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.WebUtilities { /// <summary> /// Used to read an 'application/x-www-form-urlencoded' form. /// Internally reads from a PipeReader. /// </summary> public class FormPipeReader { private const int StackAllocThreshold = 128; private const int DefaultValueCountLimit = 1024; private const int DefaultKeyLengthLimit = 1024 * 2; private const int DefaultValueLengthLimit = 1024 * 1024 * 4; // Used for UTF8/ASCII (precalculated for fast path) // This uses C# compiler's ability to refer to static data directly. For more information see https://vcsjones.dev/2019/02/01/csharp-readonly-span-bytes-static private static ReadOnlySpan<byte> UTF8EqualEncoded => new byte[] { (byte)'=' }; private static ReadOnlySpan<byte> UTF8AndEncoded => new byte[] { (byte)'&' }; // Used for other encodings private readonly byte[]? _otherEqualEncoding; private readonly byte[]? _otherAndEncoding; private readonly PipeReader _pipeReader; private readonly Encoding _encoding; /// <summary> /// Initializes a new instance of <see cref="FormPipeReader"/>. /// </summary> /// <param name="pipeReader">The <see cref="PipeReader"/> to read from.</param> public FormPipeReader(PipeReader pipeReader) : this(pipeReader, Encoding.UTF8) { } /// <summary> /// Initializes a new instance of <see cref="FormPipeReader"/>. /// </summary> /// <param name="pipeReader">The <see cref="PipeReader"/> to read from.</param> /// <param name="encoding">The <see cref="Encoding"/>.</param> public FormPipeReader(PipeReader pipeReader, Encoding encoding) { // https://docs.microsoft.com/en-us/dotnet/core/compatibility/syslib-warnings/syslib0001 if (encoding is Encoding { CodePage: 65000 }) { throw new ArgumentException("UTF7 is unsupported and insecure. Please select a different encoding."); } _pipeReader = pipeReader; _encoding = encoding; if (_encoding != Encoding.UTF8 && _encoding != Encoding.ASCII) { _otherEqualEncoding = _encoding.GetBytes("="); _otherAndEncoding = _encoding.GetBytes("&"); } } /// <summary> /// The limit on the number of form values to allow in ReadForm or ReadFormAsync. /// </summary> public int ValueCountLimit { get; set; } = DefaultValueCountLimit; /// <summary> /// The limit on the length of form keys. /// </summary> public int KeyLengthLimit { get; set; } = DefaultKeyLengthLimit; /// <summary> /// The limit on the length of form values. /// </summary> public int ValueLengthLimit { get; set; } = DefaultValueLengthLimit; /// <summary> /// Parses an HTTP form body. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param> /// <returns>The collection containing the parsed HTTP form body.</returns> public async Task<Dictionary<string, StringValues>> ReadFormAsync(CancellationToken cancellationToken = default) { KeyValueAccumulator accumulator = default; while (true) { var readResult = await _pipeReader.ReadAsync(cancellationToken); var buffer = readResult.Buffer; if (!buffer.IsEmpty) { try { ParseFormValues(ref buffer, ref accumulator, readResult.IsCompleted); } catch { _pipeReader.AdvanceTo(buffer.Start, buffer.End); throw; } } if (readResult.IsCompleted) { _pipeReader.AdvanceTo(buffer.End); if (!buffer.IsEmpty) { throw new InvalidOperationException("End of body before form was fully parsed."); } break; } _pipeReader.AdvanceTo(buffer.Start, buffer.End); } return accumulator.GetResults(); } [MethodImpl(MethodImplOptions.NoInlining)] internal void ParseFormValues( ref ReadOnlySequence<byte> buffer, ref KeyValueAccumulator accumulator, bool isFinalBlock) { if (buffer.IsSingleSegment) { ParseFormValuesFast(buffer.FirstSpan, ref accumulator, isFinalBlock, out var consumed); buffer = buffer.Slice(consumed); return; } ParseValuesSlow(ref buffer, ref accumulator, isFinalBlock); } // Fast parsing for single span in ReadOnlySequence private void ParseFormValuesFast(ReadOnlySpan<byte> span, ref KeyValueAccumulator accumulator, bool isFinalBlock, out int consumed) { ReadOnlySpan<byte> key; ReadOnlySpan<byte> value; consumed = 0; var equalsDelimiter = GetEqualsForEncoding(); var andDelimiter = GetAndForEncoding(); while (span.Length > 0) { // Find the end of the key=value pair. var ampersand = span.IndexOf(andDelimiter); ReadOnlySpan<byte> keyValuePair; int equals; var foundAmpersand = ampersand != -1; if (foundAmpersand) { keyValuePair = span.Slice(0, ampersand); span = span.Slice(keyValuePair.Length + andDelimiter.Length); consumed += keyValuePair.Length + andDelimiter.Length; } else { // We can't know that what is currently read is the end of the form value, that's only the case if this is the final block // If we're not in the final block, then consume nothing if (!isFinalBlock) { // Don't buffer indefinitely if ((uint)span.Length > (uint)KeyLengthLimit + (uint)ValueLengthLimit) { ThrowKeyOrValueTooLargeException(); } return; } keyValuePair = span; span = default; consumed += keyValuePair.Length; } equals = keyValuePair.IndexOf(equalsDelimiter); if (equals == -1) { // Too long for the whole segment to be a key. if (keyValuePair.Length > KeyLengthLimit) { ThrowKeyTooLargeException(); } // There is no more data, this segment must be "key" with no equals or value. key = keyValuePair; value = default; } else { key = keyValuePair.Slice(0, equals); if (key.Length > KeyLengthLimit) { ThrowKeyTooLargeException(); } value = keyValuePair.Slice(equals + equalsDelimiter.Length); if (value.Length > ValueLengthLimit) { ThrowValueTooLargeException(); } } var decodedKey = GetDecodedString(key); var decodedValue = GetDecodedString(value); AppendAndVerify(ref accumulator, decodedKey, decodedValue); } } // For multi-segment parsing of a read only sequence private void ParseValuesSlow( ref ReadOnlySequence<byte> buffer, ref KeyValueAccumulator accumulator, bool isFinalBlock) { var sequenceReader = new SequenceReader<byte>(buffer); ReadOnlySequence<byte> keyValuePair; var consumed = sequenceReader.Position; var consumedBytes = default(long); var equalsDelimiter = GetEqualsForEncoding(); var andDelimiter = GetAndForEncoding(); while (!sequenceReader.End) { if (!sequenceReader.TryReadTo(out keyValuePair, andDelimiter)) { if (!isFinalBlock) { // Don't buffer indefinitely if ((uint)(sequenceReader.Consumed - consumedBytes) > (uint)KeyLengthLimit + (uint)ValueLengthLimit) { ThrowKeyOrValueTooLargeException(); } break; } // This must be the final key=value pair keyValuePair = buffer.Slice(sequenceReader.Position); sequenceReader.Advance(keyValuePair.Length); } if (keyValuePair.IsSingleSegment) { ParseFormValuesFast(keyValuePair.FirstSpan, ref accumulator, isFinalBlock: true, out var segmentConsumed); Debug.Assert(segmentConsumed == keyValuePair.FirstSpan.Length); consumedBytes = sequenceReader.Consumed; consumed = sequenceReader.Position; continue; } var keyValueReader = new SequenceReader<byte>(keyValuePair); ReadOnlySequence<byte> value; if (keyValueReader.TryReadTo(out ReadOnlySequence<byte> key, equalsDelimiter)) { if (key.Length > KeyLengthLimit) { ThrowKeyTooLargeException(); } value = keyValuePair.Slice(keyValueReader.Position); if (value.Length > ValueLengthLimit) { ThrowValueTooLargeException(); } } else { // Too long for the whole segment to be a key. if (keyValuePair.Length > KeyLengthLimit) { ThrowKeyTooLargeException(); } // There is no more data, this segment must be "key" with no equals or value. key = keyValuePair; value = default; } var decodedKey = GetDecodedStringFromReadOnlySequence(key); var decodedValue = GetDecodedStringFromReadOnlySequence(value); AppendAndVerify(ref accumulator, decodedKey, decodedValue); consumedBytes = sequenceReader.Consumed; consumed = sequenceReader.Position; } buffer = buffer.Slice(consumed); } private void ThrowKeyOrValueTooLargeException() { throw new InvalidDataException($"Form key length limit {KeyLengthLimit} or value length limit {ValueLengthLimit} exceeded."); } private void ThrowKeyTooLargeException() { throw new InvalidDataException($"Form key length limit {KeyLengthLimit} exceeded."); } private void ThrowValueTooLargeException() { throw new InvalidDataException($"Form value length limit {ValueLengthLimit} exceeded."); } [SkipLocalsInit] private string GetDecodedStringFromReadOnlySequence(in ReadOnlySequence<byte> ros) { if (ros.IsSingleSegment) { return GetDecodedString(ros.FirstSpan); } if (ros.Length < StackAllocThreshold) { Span<byte> buffer = stackalloc byte[StackAllocThreshold].Slice(0, (int)ros.Length); ros.CopyTo(buffer); return GetDecodedString(buffer); } else { var byteArray = ArrayPool<byte>.Shared.Rent((int)ros.Length); try { Span<byte> buffer = byteArray.AsSpan(0, (int)ros.Length); ros.CopyTo(buffer); return GetDecodedString(buffer); } finally { ArrayPool<byte>.Shared.Return(byteArray); } } } // Check that key/value constraints are met and appends value to accumulator. private void AppendAndVerify(ref KeyValueAccumulator accumulator, string decodedKey, string decodedValue) { accumulator.Append(decodedKey, decodedValue); if (accumulator.ValueCount > ValueCountLimit) { throw new InvalidDataException($"Form value count limit {ValueCountLimit} exceeded."); } } private string GetDecodedString(ReadOnlySpan<byte> readOnlySpan) { if (readOnlySpan.Length == 0) { return string.Empty; } else if (_encoding == Encoding.UTF8 || _encoding == Encoding.ASCII) { // UrlDecoder only works on UTF8 (and implicitly ASCII) // We need to create a Span from a ReadOnlySpan. This cast is safe because the memory is still held by the pipe // We will also create a string from it by the end of the function. var span = MemoryMarshal.CreateSpan(ref Unsafe.AsRef(readOnlySpan[0]), readOnlySpan.Length); try { var bytes = UrlDecoder.DecodeInPlace(span, isFormEncoding: true); span = span.Slice(0, bytes); return _encoding.GetString(span); } catch (InvalidOperationException ex) { throw new InvalidDataException("The form value contains invalid characters.", ex); } } else { // Slow path for Unicode and other encodings. // Just do raw string replacement. var decodedString = _encoding.GetString(readOnlySpan); decodedString = decodedString.Replace('+', ' '); return Uri.UnescapeDataString(decodedString); } } private ReadOnlySpan<byte> GetEqualsForEncoding() { if (_encoding == Encoding.UTF8 || _encoding == Encoding.ASCII) { return UTF8EqualEncoded; } else { return _otherEqualEncoding; } } private ReadOnlySpan<byte> GetAndForEncoding() { if (_encoding == Encoding.UTF8 || _encoding == Encoding.ASCII) { return UTF8AndEncoded; } else { return _otherAndEncoding; } } } }
using NSubstitute; using SemanticReleaseNotesParser.Abstractions; using SemanticReleaseNotesParser.Core; using System; using System.Collections.Generic; using System.IO; using System.IO.Abstractions; using System.IO.Abstractions.TestingHelpers; using System.Reflection; using System.Text; using Xunit; namespace SemanticReleaseNotesParser.Tests { public class ProgramTest : IDisposable { [Fact] public void Run_Help() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "-?" }); // assert Assert.Equal(1, _exitCode); Assert.Contains("-r", _output.ToString()); Assert.Contains("--releasenotes", _output.ToString()); } [Fact] public void Run_Default() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new string[0]); // assert Assert.Equal(0, _exitCode); Assert.Equal(ExpectedHtml, Program.FileSystem.File.ReadAllText("ReleaseNotes.html").Trim()); Assert.DoesNotContain("File output", _output.ToString()); Assert.Contains("File 'ReleaseNotes.html' generated", _output.ToString()); } [Fact] public void Run_Default_Debug() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "--debug" }); // assert Assert.Equal(0, _exitCode); Assert.Equal(ExpectedHtml, Program.FileSystem.File.ReadAllText("ReleaseNotes.html").Trim()); Assert.Contains("File output", _output.ToString()); } [Fact] public void Run_Default_FileNotExists_Exception() { // arrange Program.FileSystem = GetFileSystem(false); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new string[0]); // assert Assert.Equal(1, _exitCode); Assert.Contains("Release notes file 'ReleaseNotes.md' does not exists", _output.ToString()); } [Fact] public void Run_Custom_ReleaseNotes_And_OutputFile() { // arrange Program.FileSystem = GetFileSystem(true, "myreleansenotes.md"); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "-r=myreleansenotes.md", "-o=MyReleaseNotes.html" }); // assert Assert.Equal(0, _exitCode); Assert.Equal(ExpectedHtml, Program.FileSystem.File.ReadAllText("MyReleaseNotes.html").Trim()); } [Fact] public void Run_Custom_Template() { // arrange Program.FileSystem = GetFileSystem(true, "ReleaseNotes.md", "template.liquid", CustomTemplate); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "--template=template.liquid" }); // assert Assert.Equal(0, _exitCode); Assert.Equal(ExpectedCustomHtml, Program.FileSystem.File.ReadAllText("ReleaseNotes.html").Trim()); } [Fact] public void Run_Custom_Template_Does_Not_Exists() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "--template=template.liquid" }); // assert Assert.Equal(1, _exitCode); Assert.Contains("Template file 'template.liquid' does not exists", _output.ToString()); } [Fact] public void Run_Custom_Template_DebugLog() { // arrange Program.FileSystem = GetFileSystem(true, "ReleaseNotes.md", "template.liquid", CustomTemplate); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "--template=template.liquid", "--debug" }); // assert Assert.Equal(0, _exitCode); Assert.Equal(ExpectedCustomHtml, Program.FileSystem.File.ReadAllText("ReleaseNotes.html").Trim()); Assert.Contains("Custom template used: 'template.liquid'", _output.ToString()); } [Fact] public void Run_Default_Output_Format_Markdown() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "-f=markdown" }); // assert Assert.Equal(0, _exitCode); Assert.Equal(ExpectedMarkdow, Program.FileSystem.File.ReadAllText("ReleaseNotes.md").Trim()); } [Fact] public void Run_Handle_Global_Exception() { // arrange var fileSystem = Substitute.For<IFileSystem>(); fileSystem.File.Returns(ci => { throw new InvalidOperationException("Boom when accessing File"); }); Program.FileSystem = fileSystem; Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new string[0]); // assert Assert.Equal(1, _exitCode); Assert.Contains("An unexpected error occurred:", _output.ToString()); Assert.Contains("InvalidOperationException", _output.ToString()); Assert.Contains("Boom when accessing File", _output.ToString()); } [Fact] public void Run_Environment() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "-t=environment" }); // assert Assert.Equal(0, _exitCode); Assert.False(Program.FileSystem.File.Exists("ReleaseNotes.html")); Assert.Equal(ExpectedHtml, _environmentVariables["SemanticReleaseNotes"].Trim()); } [Fact] public void Run_FileAndEnvironment() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "-t=fileandenvironment" }); // assert Assert.Equal(0, _exitCode); Assert.Equal(ExpectedHtml, Program.FileSystem.File.ReadAllText("ReleaseNotes.html").Trim()); Assert.Equal(ExpectedHtml, _environmentVariables["SemanticReleaseNotes"].Trim()); } [Fact] public void Run_Environment_AppVeyor() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironmentAppVeyor(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "-t=environment" }); // assert Assert.Equal(0, _exitCode); Assert.False(Program.FileSystem.File.Exists("ReleaseNotes.html")); Assert.False(_environmentVariables.ContainsKey("SemanticReleaseNotes")); Assert.Equal(ExpectedAppVeyorData, _uploadedData); } [Fact] public void Run_IncludeStyle_Default() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); // act Program.Main(new[] { "-includestyle" }); // assert Assert.Equal(0, _exitCode); Assert.Equal(GetExampleAHtmlWithStyle(), Program.FileSystem.File.ReadAllText("ReleaseNotes.html").Trim()); } [Fact] public void Run_IncludeStyle_Custom() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); // act Program.Main(new[] { "-includestyle=\"body { color: black; width: 500px; }\"" }); // assert Assert.Equal(0, _exitCode); Assert.Equal(GetExampleAHtmlWithStyle("body { color: black; width: 500px; }"), Program.FileSystem.File.ReadAllText("ReleaseNotes.html").Trim()); } [Fact] public void Run_PluralizeCategoriesTitle() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); // act Program.Main(new[] { "--pluralizecategoriestitle", "-g=categories" }); // assert Assert.Equal(0, _exitCode); Assert.True(Program.FileSystem.File.Exists("ReleaseNotes.html")); Assert.Equal(ExpectedHtmlCategories, Program.FileSystem.File.ReadAllText("ReleaseNotes.html")); } [Fact] public void Run_Custom_OutputFile_With_Nonexisting_Folder() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironment(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "-o=NonExistingFolder/MyReleaseNotes.html" }); // assert Assert.Equal(0, _exitCode); Assert.Equal(ExpectedHtml, Program.FileSystem.File.ReadAllText("NonExistingFolder/MyReleaseNotes.html").Trim()); Assert.DoesNotContain("File output", _output.ToString()); Assert.Contains("File 'NonExistingFolder/MyReleaseNotes.html' generated", _output.ToString()); } [Fact] public void Run_Environment_GitHubActions() { // arrange Program.FileSystem = GetFileSystem(); Program.Environment = GetEnvironmentGitHubActions(); Program.WebClientFactory = GetWebClientFactory(); // act Program.Main(new[] { "-t=environment" }); // assert Assert.Equal(0, _exitCode); Assert.False(Program.FileSystem.File.Exists("ReleaseNotes.html")); Assert.False(_environmentVariables.ContainsKey("SemanticReleaseNotes")); Assert.Contains($"::set-env name=SemanticReleaseNotes::{ExpectedHtml.Replace("\r", "%0D").Replace("\n", "%0A")}", _output.ToString()); } private readonly StringBuilder _output; public ProgramTest() { _output = new StringBuilder(); Console.SetOut(new StringWriter(_output)); } private Dictionary<string, string> _environmentVariables; private int _exitCode; private IEnvironment GetEnvironment() { _environmentVariables = new Dictionary<string, string>(); var environment = Substitute.For<IEnvironment>(); environment.When(e => e.SetEnvironmentVariable(Arg.Any<string>(), Arg.Any<string>())).Do(ci => _environmentVariables.Add((string)ci.Args()[0], (string)ci.Args()[1])); environment.When(e => e.Exit(Arg.Any<int>())).Do(ci => _exitCode = ci.Arg<int>()); return environment; } private IEnvironment GetEnvironmentAppVeyor() { var environment = GetEnvironment(); environment.GetEnvironmentVariable("APPVEYOR_API_URL").Returns("http://localhost:8080"); environment.GetEnvironmentVariable("APPVEYOR").Returns("TRUE"); return environment; } private IEnvironment GetEnvironmentGitHubActions() { var environment = GetEnvironment(); environment.GetEnvironmentVariable("GITHUB_ACTIONS").Returns("true"); return environment; } private string _uploadedData; private string _address; private string _method; private IWebClientFactory GetWebClientFactory() { var webClient = Substitute.For<IWebClient>(); webClient.When(wc => wc.UploadData(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<byte[]>())) .Do(ci => { _address = (string)ci.Args()[0]; _method = (string)ci.Args()[1]; _uploadedData = Encoding.UTF8.GetString((byte[])ci.Args()[2]); }); var factory = Substitute.For<IWebClientFactory>(); factory.Create(Arg.Any<string>()).Returns(webClient); return factory; } private IFileSystem GetFileSystem(bool addFile = true, string fileName = "ReleaseNotes.md", string secondFileName = null, string secondFileContent = null) { var fileSystem = new MockFileSystem(); if (addFile) { fileSystem.AddFile(fileName, new MockFileData(DefaultMarkdown)); } if (secondFileName != null) { fileSystem.AddFile(secondFileName, new MockFileData(secondFileContent)); } return fileSystem; } private string GetExampleAHtmlWithStyle(string style = null) { if (style == null) { using (var reader = new StreamReader(Assembly.GetAssembly(typeof(SemanticReleaseNotesConverter)).GetManifestResourceStream("SemanticReleaseNotesParser.Core.Resources.DefaultStyle.css"))) { style = reader.ReadToEnd(); } } return string.Format(ExpectedHtmlWithHead, style); } public void Dispose() { _output.Clear(); } private const string DefaultMarkdown = @"A little summary # System - This is the **second** __list__ item. +new - This is the `third` list item. +fix"; private const string ExpectedHtml = @"<html> <body> <p>A little summary</p> <h1>System</h1> <ul> <li>{New} This is the <strong>second</strong> <strong>list</strong> item.</li> <li>{Fix} This is the <code>third</code> list item.</li> </ul> </body> </html>"; private const string ExpectedMarkdow = @"A little summary # System - {New} This is the **second** __list__ item. - {Fix} This is the `third` list item."; private const string CustomTemplate = @"{%- for section in release_notes.sections -%} # {{ section.name }} {%- for item in section.items -%} - {% if item.categories -%}{{ lcb }}{{ item.categories[0] }}{{ rcb }} {% endif %}{{ item.summary }} {%- if item.task_id %} [{{ item.task_id }}]({{ item.task_link }}) {%- endif -%} {%- endfor -%} {%- endfor -%} {{ release_notes.summary }}"; private const string ExpectedCustomHtml = @"<html> <body> <h1>System</h1> <ul> <li>{New} This is the <strong>second</strong> <strong>list</strong> item.</li> <li>{Fix} This is the <code>third</code> list item.</li> </ul> <p>A little summary</p> </body> </html>"; private const string ExpectedAppVeyorData = "{ \"name\": \"SemanticReleaseNotes\", \"value\": \"<html>\n<body>\n<p>A little summary<\\/p>\n<h1>System<\\/h1>\n<ul>\n<li>{New} This is the <strong>second<\\/strong> <strong>list<\\/strong> item.<\\/li>\n<li>{Fix} This is the <code>third<\\/code> list item.<\\/li>\n<\\/ul>\n<\\/body>\n<\\/html>\" }"; private const string ExpectedHtmlCategories = @"<html> <body> <p>A little summary</p> <h1>News</h1> <ul> <li>This is the <strong>second</strong> <strong>list</strong> item.</li> </ul> <h1>Fixes</h1> <ul> <li>This is the <code>third</code> list item.</li> </ul> </body> </html>"; private const string ExpectedHtmlWithHead = @"<html> <head> <style> {0} </style> </head> <body> <p>A little summary</p> <h1>System</h1> <ul> <li>{{New}} This is the <strong>second</strong> <strong>list</strong> item.</li> <li>{{Fix}} This is the <code>third</code> list item.</li> </ul> </body> </html>"; } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// LoadBalancersOperations operations. /// </summary> public partial interface ILoadBalancersOperations { /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a load balancer. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update load balancer /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the load balancers in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the load balancers in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; namespace Skarp.Version.Cli.Versioning { public class SemVerBumper { /// <summary> /// Bump the currently parsed version information with the specified <paramref name="bump"/> /// </summary> /// <param name="currentVersion"></param> /// <param name="bump">The bump to apply to the version</param> /// <param name="specificVersionToApply">The specific version to apply if bump is Specific</param> /// <param name="buildMeta">Additional build metadata to add to the final version string</param> /// <param name="preReleasePrefix">Override of default `next` pre-release prefix/label</param> public SemVer Bump( SemVer currentVersion, VersionBump bump, string specificVersionToApply = "", string buildMeta = "", string preReleasePrefix = "" ) { var newVersion = SemVer.FromString(currentVersion.ToSemVerVersionString()); newVersion.BuildMeta = buildMeta; switch (bump) { case VersionBump.Major: { HandleMajorBump(newVersion); break; } case VersionBump.PreMajor: { HandlePreMajorBump(newVersion, preReleasePrefix); break; } case VersionBump.Minor: { HandleMinorBump(newVersion); break; } case VersionBump.PreMinor: { HandlePreMinorBump(newVersion, preReleasePrefix); break; } case VersionBump.Patch: { HandlePatchBump(newVersion); break; } case VersionBump.PrePatch: { HandlePrePatchBump(newVersion, preReleasePrefix); break; } case VersionBump.PreRelease: { HandlePreReleaseBump(newVersion); break; } case VersionBump.Specific: { HandleSpecificVersion(specificVersionToApply, newVersion); break; } default: { throw new ArgumentOutOfRangeException(nameof(bump), $"VersionBump : {bump} not supported"); } } return newVersion; } private static void HandleSpecificVersion(string specificVersionToApply, SemVer newVersion) { if (string.IsNullOrEmpty(specificVersionToApply)) { throw new ArgumentException($"When bump is specific, specificVersionToApply must be provided"); } var specific = SemVer.FromString(specificVersionToApply); newVersion.Major = specific.Major; newVersion.Minor = specific.Minor; newVersion.Patch = specific.Patch; newVersion.PreRelease = specific.PreRelease; newVersion.BuildMeta = specific.BuildMeta; } private static void HandlePreReleaseBump(SemVer newVersion) { if (!newVersion.IsPreRelease) { throw new InvalidOperationException( "Cannot Prerelease bump when not already a prerelease. Please use prepatch, preminor or premajor to prepare"); } string preReleaseLabel = "next"; if (!int.TryParse(newVersion.PreRelease, out var preReleaseNumber)) { // it was not just a number, let's try to split it (pre-release might look like `next.42`) var preReleaseSplit = newVersion.PreRelease.Split("."); if (preReleaseSplit.Length != 2) { throw new ArgumentException( $"Pre-release part invalid. Must be either numeric or `label.number`. Got {newVersion.PreRelease}"); } if (!int.TryParse(preReleaseSplit[1], out preReleaseNumber)) { throw new ArgumentException( "Second part of pre-release is not numeric, cannot apply automatic prerelease roll. Should follow pattern `label.number`"); } preReleaseLabel = preReleaseSplit[0]; } // increment the pre-release number preReleaseNumber += 1; newVersion.PreRelease = $"{preReleaseLabel}.{preReleaseNumber}"; } private static void HandlePrePatchBump(SemVer newVersion, string preReleasePrefix) { if (string.IsNullOrWhiteSpace(preReleasePrefix)) { preReleasePrefix = "next"; } newVersion.Patch += 1; newVersion.PreRelease = $"{preReleasePrefix}.0"; } private void HandlePatchBump(SemVer newVersion) { if (!newVersion.IsPreRelease) { newVersion.Patch += 1; } else { newVersion.PreRelease = string.Empty; newVersion.BuildMeta = string.Empty; } } private void HandlePreMinorBump(SemVer newVersion, string preReleasePrefix) { if (string.IsNullOrWhiteSpace(preReleasePrefix)) { preReleasePrefix = "next"; } newVersion.Minor += 1; newVersion.Patch = 0; newVersion.PreRelease = $"{preReleasePrefix}.0"; } private void HandleMinorBump(SemVer newVersion) { if (newVersion.IsPreRelease) { newVersion.PreRelease = string.Empty; newVersion.BuildMeta = string.Empty; } else { newVersion.Minor += 1; newVersion.Patch = 0; } } private void HandlePreMajorBump(SemVer newVersion, string preReleasePrefix) { if (string.IsNullOrWhiteSpace(preReleasePrefix)) { preReleasePrefix = "next"; } newVersion.Major += 1; newVersion.Minor = 0; newVersion.Patch = 0; newVersion.PreRelease = $"{preReleasePrefix}.0"; } private void HandleMajorBump(SemVer newVersion) { if (newVersion.IsPreRelease) { newVersion.PreRelease = string.Empty; newVersion.BuildMeta = string.Empty; } else { newVersion.Major += 1; newVersion.Minor = 0; newVersion.Patch = 0; } } } }
using System; using System.CodeDom; using System.Xml; using System.Collections; namespace Stetic { public class ProjectIconFactory { ProjectIconSetCollection icons = new ProjectIconSetCollection (); public ProjectIconFactory() { } public ProjectIconSetCollection Icons { get { return icons; } } public ProjectIconSet GetIcon (string name) { foreach (ProjectIconSet icon in icons) if (icon.Name == name) return icon; return null; } public XmlElement Write (XmlDocument doc) { XmlElement elem = doc.CreateElement ("icon-factory"); foreach (ProjectIconSet icon in icons) elem.AppendChild (icon.Write (doc)); return elem; } public void Read (IProject project, XmlElement elem) { icons.Clear (); foreach (XmlElement child in elem.SelectNodes ("icon-set")) { ProjectIconSet icon = new ProjectIconSet (); icon.Read (project, child); icons.Add (icon); } } public void GenerateBuildCode (GeneratorContext ctx) { string varName = ctx.NewId (); CodeVariableDeclarationStatement varDec = new CodeVariableDeclarationStatement (typeof(Gtk.IconFactory), varName); varDec.InitExpression = new CodeObjectCreateExpression (typeof(Gtk.IconFactory)); ctx.Statements.Add (varDec); CodeVariableReferenceExpression var = new CodeVariableReferenceExpression (varName); foreach (ProjectIconSet icon in icons) { CodeExpression exp = new CodeMethodInvokeExpression ( var, "Add", new CodePrimitiveExpression (icon.Name), icon.GenerateObjectBuild (ctx) ); ctx.Statements.Add (exp); } CodeExpression addd = new CodeMethodInvokeExpression ( var, "AddDefault" ); ctx.Statements.Add (addd); } public Gdk.Pixbuf RenderIcon (IProject project, string name, Gtk.IconSize size) { ProjectIconSet icon = GetIcon (name); if (icon == null) return null; foreach (ProjectIconSource src in icon.Sources) { if (src.SizeWildcarded || src.Size == size) return src.Image.GetScaledImage (project, size); } return icon.Sources [0].Image.GetScaledImage (project, size); } public Gdk.Pixbuf RenderIcon (IProject project, string name, int size) { ProjectIconSet icon = GetIcon (name); if (icon == null) return null; return icon.Sources [0].Image.GetScaledImage (project, size, size); } } public class ProjectIconSet { ProjectIconSourceCollection sources = new ProjectIconSourceCollection (); string name; public string Name { get { return name; } set { name = value; } } public ProjectIconSourceCollection Sources { get { return sources; } } public XmlElement Write (XmlDocument doc) { XmlElement elem = doc.CreateElement ("icon-set"); elem.SetAttribute ("id", name); foreach (ProjectIconSource src in sources) elem.AppendChild (src.Write (doc)); return elem; } public void Read (IProject project, XmlElement elem) { sources.Clear (); name = elem.GetAttribute ("id"); if (name.Length == 0) throw new InvalidOperationException ("Name attribute not found"); foreach (XmlElement child in elem.SelectNodes ("source")) { ProjectIconSource src = new ProjectIconSource (); src.Read (project, child); sources.Add (src); } } internal CodeExpression GenerateObjectBuild (GeneratorContext ctx) { string varName = ctx.NewId (); CodeVariableDeclarationStatement varDec = new CodeVariableDeclarationStatement (typeof(Gtk.IconSet), varName); ctx.Statements.Add (varDec); CodeVariableReferenceExpression var = new CodeVariableReferenceExpression (varName); if (sources.Count == 1 && sources[0].AllWildcarded) { varDec.InitExpression = new CodeObjectCreateExpression ( typeof(Gtk.IconSet), sources[0].Image.ToCodeExpression (ctx) ); } else { varDec.InitExpression = new CodeObjectCreateExpression (typeof(Gtk.IconSet)); foreach (ProjectIconSource src in sources) { CodeExpression exp = new CodeMethodInvokeExpression ( var, "AddSource", src.GenerateObjectBuild (ctx) ); ctx.Statements.Add (exp); } } return var; } } public class ProjectIconSource: Gtk.IconSource { ImageInfo imageInfo; public ImageInfo Image { get { return imageInfo; } set { imageInfo = value; } } public bool AllWildcarded { get { return DirectionWildcarded && SizeWildcarded && StateWildcarded; } set { DirectionWildcarded = SizeWildcarded = StateWildcarded = true; } } public XmlElement Write (XmlDocument doc) { XmlElement elem = doc.CreateElement ("source"); XmlElement prop = doc.CreateElement ("property"); prop.SetAttribute ("name", "Image"); prop.InnerText = imageInfo.ToString (); elem.AppendChild (prop); if (!SizeWildcarded) { prop = doc.CreateElement ("property"); prop.SetAttribute ("name", "Size"); prop.InnerText = Size.ToString (); elem.AppendChild (prop); } if (!StateWildcarded) { prop = doc.CreateElement ("property"); prop.SetAttribute ("name", "State"); prop.InnerText = State.ToString (); elem.AppendChild (prop); } if (!DirectionWildcarded) { prop = doc.CreateElement ("property"); prop.SetAttribute ("name", "Direction"); prop.InnerText = Direction.ToString (); elem.AppendChild (prop); } return elem; } public void Read (IProject project, XmlElement elem) { XmlElement prop = elem.SelectSingleNode ("property[@name='Image']") as XmlElement; if (prop != null) imageInfo = ImageInfo.FromString (prop.InnerText); prop = elem.SelectSingleNode ("property[@name='Size']") as XmlElement; if (prop != null && prop.InnerText != "*") { SizeWildcarded = false; Size = (Gtk.IconSize) Enum.Parse (typeof(Gtk.IconSize), prop.InnerText); } else SizeWildcarded = true; prop = elem.SelectSingleNode ("property[@name='State']") as XmlElement; if (prop != null && prop.InnerText != "*") { StateWildcarded = false; State = (Gtk.StateType) Enum.Parse (typeof(Gtk.StateType), prop.InnerText); } else StateWildcarded = true; prop = elem.SelectSingleNode ("property[@name='Direction']") as XmlElement; if (prop != null && prop.InnerText != "*") { DirectionWildcarded = false; Direction = (Gtk.TextDirection) Enum.Parse (typeof(Gtk.TextDirection), prop.InnerText); } else DirectionWildcarded = true; } internal CodeExpression GenerateObjectBuild (GeneratorContext ctx) { string varName = ctx.NewId (); CodeVariableDeclarationStatement varDec = new CodeVariableDeclarationStatement (typeof(Gtk.IconSource), varName); varDec.InitExpression = new CodeObjectCreateExpression (typeof(Gtk.IconSource)); ctx.Statements.Add (varDec); CodeVariableReferenceExpression var = new CodeVariableReferenceExpression (varName); ctx.Statements.Add (new CodeAssignStatement ( new CodePropertyReferenceExpression (var, "Pixbuf"), imageInfo.ToCodeExpression (ctx) )); if (!SizeWildcarded) { ctx.Statements.Add (new CodeAssignStatement ( new CodePropertyReferenceExpression (var, "SizeWildcarded"), new CodePrimitiveExpression (false) )); ctx.Statements.Add (new CodeAssignStatement ( new CodePropertyReferenceExpression (var, "Size"), new CodeFieldReferenceExpression ( new CodeTypeReferenceExpression ("Gtk.IconSize"), Size.ToString () ) )); } if (!StateWildcarded) { ctx.Statements.Add (new CodeAssignStatement ( new CodePropertyReferenceExpression (var, "StateWildcarded"), new CodePrimitiveExpression (false) )); ctx.Statements.Add (new CodeAssignStatement ( new CodePropertyReferenceExpression (var, "State"), new CodeFieldReferenceExpression ( new CodeTypeReferenceExpression ("Gtk.StateType"), State.ToString () ) )); } if (!DirectionWildcarded) { ctx.Statements.Add (new CodeAssignStatement ( new CodePropertyReferenceExpression (var, "DirectionWildcarded"), new CodePrimitiveExpression (false) )); ctx.Statements.Add (new CodeAssignStatement ( new CodePropertyReferenceExpression (var, "Direction"), new CodeFieldReferenceExpression ( new CodeTypeReferenceExpression ("Gtk.TextDirection"), Direction.ToString () ) )); } return var; } } public class ProjectIconSetCollection: CollectionBase { public ProjectIconSet this [int n] { get { return (ProjectIconSet) List [n]; } } public void Add (ProjectIconSet icon) { List.Add (icon); } public void Remove (ProjectIconSet icon) { List.Remove (icon); } } public class ProjectIconSourceCollection: CollectionBase { public void AddRange (ICollection c) { foreach (ProjectIconSource s in c) List.Add (s); } public ProjectIconSource this [int n] { get { return (ProjectIconSource) List [n]; } } public void Add (ProjectIconSource source) { List.Add (source); } } }
/*============================================================================ * Copyright (C) Microsoft Corporation, All rights reserved. *============================================================================ */ #region Using directives using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// <para> /// This Cmdlet creates an instance of a CIM class based on the class /// definition, which is an instance factory /// </para> /// <para> /// If -ClientOnly is not specified, New-CimInstance will create a new instance /// on the server, otherwise just create client in-memory instance /// </para> /// </summary> [Cmdlet(VerbsCommon.New, "CimInstance", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=227963")] [OutputType(typeof(CimInstance))] public class NewCimInstanceCommand : CimBaseCommand { #region constructor /// <summary> /// constructor /// </summary> public NewCimInstanceCommand() : base(parameters, parameterSets) { DebugHelper.WriteLogEx(); } #endregion #region parameters /// <summary> /// The following is the definition of the input parameter "ClassName". /// Name of the Class to use to create Instance. /// </summary> [Parameter( Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter( Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] public String ClassName { get { return className; } set { className = value; base.SetParameter(value, nameClassName); } } private String className; /// <summary> /// <para> /// The following is the definition of the input parameter "ResourceUri". /// Define the Resource Uri for which the instances are retrieved. /// </para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] public Uri ResourceUri { get { return resourceUri; } set { this.resourceUri = value; base.SetParameter(value, nameResourceUri); } } private Uri resourceUri; /// <summary> /// <para> /// The following is the definition of the input parameter "Key". /// Enables the user to specify list of key property name. /// </para> /// <para> /// Example: -Key {"K1", "K2"} /// </para> /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] Key { get { return key; } set { key = value; base.SetParameter(value, nameKey); } } private String[] key; /// <summary> /// The following is the definition of the input parameter "CimClass". /// The CimClass is used to create Instance. /// </summary> [Parameter( Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = CimClassSessionSet)] [Parameter( Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = CimClassComputerSet)] public CimClass CimClass { get { return cimClass; } set { cimClass = value; base.SetParameter(value, nameCimClass); } } private CimClass cimClass; /// <summary> /// <para> /// The following is the definition of the input parameter "Property". /// Enables the user to specify instances with specific property values. /// </para> /// <para> /// Example: -Property @{P1="Value1";P2="Value2"} /// </para> /// </summary> [Parameter( Position = 1, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("Arguments")] public IDictionary Property { get { return property; } set { property = value; } } private IDictionary property; /// <summary> /// The following is the definition of the input parameter "Namespace". /// Namespace used to look for the classes under to store the instances. /// Default namespace is 'root\cimv2' /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] public String Namespace { get { return nameSpace; } set { nameSpace = value; base.SetParameter(value, nameNamespace); } } private String nameSpace; /// <summary> /// The following is the definition of the input parameter "OperationTimeoutSec". /// Operation Timeout of the cmdlet in seconds. Overrides the value in the Cim /// Session. /// </summary> [Alias(AliasOT)] [Parameter] public UInt32 OperationTimeoutSec { get { return operationTimeout; } set { operationTimeout = value; } } private UInt32 operationTimeout; /// <summary> /// <para> /// The following is the definition of the input parameter "CimSession". /// Identifies the CimSession which is to be used to create the instances. /// </para> /// </summary> [Parameter( Mandatory = true, ValueFromPipeline = true, ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter( Mandatory = true, ValueFromPipeline = true, ParameterSetName = CimBaseCommand.ResourceUriSessionSet)] [Parameter( Mandatory = true, ValueFromPipeline = true, ParameterSetName = CimClassSessionSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public CimSession[] CimSession { get { return cimSession; } set { cimSession = value; base.SetParameter(value, nameCimSession); } } private CimSession[] cimSession; /// <summary> /// <para>The following is the definition of the input parameter "ComputerName". /// Provides the name of the computer from which to create the instances. /// </para> /// <para> /// If no ComputerName is specified the default value is "localhost" /// </para> /// </summary> [Alias(AliasCN, AliasServerName)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ClassNameComputerSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimBaseCommand.ResourceUriComputerSet)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = CimClassComputerSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] ComputerName { get { return computerName; } set { computerName = value; base.SetParameter(value, nameComputerName); } } private String[] computerName; /// <summary> /// <para> /// The following is the definition of the input parameter "ClientOnly". /// Indicates to create a client only ciminstance object, NOT on the server. /// </para> /// </summary> [Alias("Local")] [Parameter( ParameterSetName = CimBaseCommand.ClassNameSessionSet)] [Parameter( ParameterSetName = CimBaseCommand.ClassNameComputerSet)] [Parameter( ParameterSetName = CimBaseCommand.CimClassComputerSet)] [Parameter( ParameterSetName = CimBaseCommand.CimClassSessionSet)] public SwitchParameter ClientOnly { get { return clientOnly; } set { clientOnly = value; base.SetParameter(value, nameClientOnly); } } private SwitchParameter clientOnly; #endregion #region cmdlet methods /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { this.CmdletOperation = new CmdletOperationBase(this); this.AtBeginProcess = false; }//End BeginProcessing() /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { base.CheckParameterSet(); this.CheckArgument(); if (this.ClientOnly) { string conflictParameterName = null; if (null != this.ComputerName) { conflictParameterName = @"ComputerName"; } else if (null != this.CimSession) { conflictParameterName = @"CimSession"; } if (null != conflictParameterName) { ThrowConflictParameterWasSet(@"New-CimInstance", conflictParameterName, @"ClientOnly"); return; } } CimNewCimInstance cimNewCimInstance = this.GetOperationAgent(); if (cimNewCimInstance == null) { cimNewCimInstance = CreateOperationAgent(); } cimNewCimInstance.NewCimInstance(this); cimNewCimInstance.ProcessActions(this.CmdletOperation); }//End ProcessRecord() /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { CimNewCimInstance cimNewCimInstance = this.GetOperationAgent(); if (cimNewCimInstance != null) { cimNewCimInstance.ProcessRemainActions(this.CmdletOperation); } }//End EndProcessing() #endregion #region helper methods /// <summary> /// <para> /// Get <see cref="CimNewCimInstance"/> object, which is /// used to delegate all New-CimInstance operations. /// </para> /// </summary> CimNewCimInstance GetOperationAgent() { return (this.AsyncOperation as CimNewCimInstance); } /// <summary> /// <para> /// Create <see cref="CimNewCimInstance"/> object, which is /// used to delegate all New-CimInstance operations. /// </para> /// </summary> /// <returns></returns> CimNewCimInstance CreateOperationAgent() { CimNewCimInstance cimNewCimInstance = new CimNewCimInstance(); this.AsyncOperation = cimNewCimInstance; return cimNewCimInstance; } /// <summary> /// check argument value /// </summary> private void CheckArgument() { switch (this.ParameterSetName) { case CimBaseCommand.ClassNameComputerSet: case CimBaseCommand.ClassNameSessionSet: // validate the classname this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); break; default: break; } } #endregion #region private members #region const string of parameter names internal const string nameClassName = "ClassName"; internal const string nameResourceUri = "ResourceUri"; internal const string nameKey = "Key"; internal const string nameCimClass = "CimClass"; internal const string nameProperty = "Property"; internal const string nameNamespace = "Namespace"; internal const string nameCimSession = "CimSession"; internal const string nameComputerName = "ComputerName"; internal const string nameClientOnly = "ClientOnly"; #endregion /// <summary> /// static parameter definition entries /// </summary> static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>> { { nameClassName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), } }, { nameResourceUri, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, true), } }, { nameKey, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), } }, { nameCimClass, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true), } }, { nameNamespace, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, false), } }, { nameCimSession, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), } }, { nameComputerName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ResourceUriComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, false), } }, { nameClientOnly, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimClassSessionSet, true), new ParameterDefinitionEntry(CimBaseCommand.CimClassComputerSet, true), } }, }; /// <summary> /// static parameter set entries /// </summary> static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry> { { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) }, { CimBaseCommand.CimClassSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.CimClassComputerSet, new ParameterSetEntry(1) }, { CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.ResourceUriComputerSet, new ParameterSetEntry(1) }, }; #endregion }//End Class }//End namespace
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace UnitTest.Epoxy { using System; using System.Net; using System.Threading; using System.Threading.Tasks; using Bond.Comm; using Bond.Comm.Epoxy; using Bond.Comm.Layers; using NUnit.Framework; using UnitTest.Comm; using UnitTest.Interfaces; using UnitTest.Layers; [TestFixture] public class EpoxyTransportTests : EpoxyTestBase { private const string AnyIpAddressString = "10.1.2.3"; private const int AnyPort = 12345; private static readonly IPAddress AnyIpAddress = new IPAddress(new byte[] { 10, 1, 2, 3 }); private static readonly Message<Bond.Void> EmptyMessage = new Message<Bond.Void>(new Bond.Void()); [Test] public void DefaultPorts_AreExpected() { Assert.AreEqual(25188, EpoxyTransport.DefaultPort); } [Test] public void Endpoint_Ctors() { var ipEndPoint = new IPEndPoint(IPAddress.Parse(AnyIpAddressString), AnyPort); var endpointFromPieces = new EpoxyTransport.Endpoint(AnyIpAddressString, AnyPort); Assert.AreEqual(AnyIpAddressString, endpointFromPieces.Host); Assert.AreEqual(AnyPort, endpointFromPieces.Port); var endpointFromIpEndPoint = new EpoxyTransport.Endpoint(ipEndPoint); Assert.AreEqual(AnyIpAddressString, endpointFromIpEndPoint.Host); Assert.AreEqual(AnyPort, endpointFromIpEndPoint.Port); Assert.AreEqual(endpointFromPieces, endpointFromIpEndPoint); } [Test] public void ParseStringAddress_NullOrEmpty_Throws() { Assert.Throws<ArgumentException>(() => EpoxyTransport.ParseStringAddress(null)); Assert.Throws<ArgumentException>(() => EpoxyTransport.ParseStringAddress(string.Empty)); } [Test] public void ParseStringAddress_ValidIpNoPort_ReturnsIpEndpoint() { var result = EpoxyTransport.ParseStringAddress(AnyIpAddressString); Assert.AreEqual(new IPEndPoint(AnyIpAddress, EpoxyTransport.DefaultPort), result); } [Test] public void ParseStringAddress_ValidIpWithPort_ReturnsIpEndpoint() { var result = EpoxyTransport.ParseStringAddress(AnyIpAddressString + ":" + AnyPort); Assert.AreEqual(new IPEndPoint(AnyIpAddress, AnyPort), result); } [Test] public void ParseStringAddress_InvalidIpAddress_Throws() { Assert.Throws<ArgumentException>(() => EpoxyTransport.ParseStringAddress("not an ip")); Assert.Throws<ArgumentException>(() => EpoxyTransport.ParseStringAddress("not an ip:12345")); Assert.Throws<ArgumentException>(() => EpoxyTransport.ParseStringAddress("not an ip:no a port")); } [Test] public void ParseStringAddress_InvalidPortAddress_Throws() { Assert.Throws<ArgumentException>(() => EpoxyTransport.ParseStringAddress("10.1.2.3:")); Assert.Throws<ArgumentException>(() => EpoxyTransport.ParseStringAddress("10.1.2.3::")); Assert.Throws<ArgumentException>(() => EpoxyTransport.ParseStringAddress("10.1.2.3:not a port")); } [Test] public void Parse_InvalidUris() { Assert.Null(EpoxyTransport.Parse(null, LoggerTests.BlackHole)); Assert.Null(EpoxyTransport.Parse("", LoggerTests.BlackHole)); Assert.Null(EpoxyTransport.Parse("127.0.0.1", LoggerTests.BlackHole)); Assert.Null(EpoxyTransport.Parse("cows", LoggerTests.BlackHole)); Assert.Null(EpoxyTransport.Parse(":12", LoggerTests.BlackHole)); Assert.Null(EpoxyTransport.Parse("epoxy://127.0.0.1:1000:1000", LoggerTests.BlackHole)); } [Test] public void Parse_SchemeMustBeEpoxy() { Assert.Null(EpoxyTransport.Parse("http://127.0.0.1", LoggerTests.BlackHole)); } [Test] public void Parse_NoResourceBesidesRootOrParamsAllowed() { Assert.Null(EpoxyTransport.Parse("epoxy://127.0.0.1/cows", LoggerTests.BlackHole)); Assert.Null(EpoxyTransport.Parse("epoxy://127.0.0.1?cows=cows", LoggerTests.BlackHole)); } [Test] public void Parse_AcceptableUris() { var endpoint = EpoxyTransport.Parse("epoxy://127.0.0.1", LoggerTests.BlackHole); Assert.NotNull(endpoint); Assert.AreEqual("127.0.0.1", endpoint.Value.Host); Assert.AreEqual(EpoxyTransport.DefaultPort, endpoint.Value.Port); endpoint = EpoxyTransport.Parse("epoxy://127.0.0.1/", LoggerTests.BlackHole); Assert.NotNull(endpoint); Assert.AreEqual("127.0.0.1", endpoint.Value.Host); Assert.AreEqual(EpoxyTransport.DefaultPort, endpoint.Value.Port); endpoint = EpoxyTransport.Parse("epoxy://127.0.0.1:10000", LoggerTests.BlackHole); Assert.NotNull(endpoint); Assert.AreEqual("127.0.0.1", endpoint.Value.Host); Assert.AreEqual(10000, endpoint.Value.Port); endpoint = EpoxyTransport.Parse("epoxy://127.0.0.1:10000/", LoggerTests.BlackHole); Assert.NotNull(endpoint); Assert.AreEqual("127.0.0.1", endpoint.Value.Host); Assert.AreEqual(10000, endpoint.Value.Port); endpoint = EpoxyTransport.Parse("epoxy://localhost", LoggerTests.BlackHole); Assert.NotNull(endpoint); Assert.AreEqual("localhost", endpoint.Value.Host); Assert.AreEqual(EpoxyTransport.DefaultPort, endpoint.Value.Port); endpoint = EpoxyTransport.Parse("epoxy://localhost/", LoggerTests.BlackHole); Assert.NotNull(endpoint); Assert.AreEqual("localhost", endpoint.Value.Host); Assert.AreEqual(EpoxyTransport.DefaultPort, endpoint.Value.Port); endpoint = EpoxyTransport.Parse("epoxy://localhost:10000", LoggerTests.BlackHole); Assert.NotNull(endpoint); Assert.AreEqual("localhost", endpoint.Value.Host); Assert.AreEqual(10000, endpoint.Value.Port); endpoint = EpoxyTransport.Parse("epoxy://localhost:10000/", LoggerTests.BlackHole); Assert.NotNull(endpoint); Assert.AreEqual("localhost", endpoint.Value.Host); Assert.AreEqual(10000, endpoint.Value.Port); } [Test] public void Builder_Construct_NoArgs_Succeeds() { var builder = new EpoxyTransportBuilder(); Assert.NotNull(builder.Construct()); } [Test] public async Task SetupListener_RequestReply_PayloadResponse() { TestClientServer<TestService> testClientServer = await SetupTestClientServer<TestService>(); var response = await testClientServer.ClientConnection.RequestResponseAsync<Bond.Void, Bond.Void>("TestService.RespondWithEmpty", EmptyMessage, CancellationToken.None); Assert.IsFalse(response.IsError); Assert.IsNotNull(response.Payload); Assert.IsNull(response.Error); Assert.AreEqual(1, testClientServer.Service.RespondWithEmpty_CallCount); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task SetupListener_RequestError_ErrorResponse() { TestClientServer<TestService> testClientServer = await SetupTestClientServer<TestService>(); var response = await testClientServer.ClientConnection.RequestResponseAsync<Bond.Void, Bond.Void>("TestService.RespondWithError", EmptyMessage, CancellationToken.None); Assert.IsTrue(response.IsError); Assert.IsNotNull(response.Error); var error = response.Error.Deserialize<Error>(); Assert.AreEqual((int)ErrorCode.InternalServerError, error.error_code); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task SetupListenerWithErrorHandler_RequestThatThrows_ErrorResponse() { TestClientServer<TestService> testClientServer = await SetupTestClientServer<TestService>(); var response = await testClientServer.ClientConnection.RequestResponseAsync<Bond.Void, Bond.Void>("TestService.ThrowInsteadOfResponding", EmptyMessage, CancellationToken.None); Assert.IsTrue(response.IsError); Assert.IsNotNull(response.Error); var error = response.Error.Deserialize<Error>(); Assert.AreEqual((int)ErrorCode.InternalServerError, error.error_code); Assert.That(error.message, Is.StringContaining(Errors.InternalErrorMessage)); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task TransportWithCustomResolver_UsesResolver() { await SetupTestClientServer<DummyTestService>(); Func<string, Task<IPAddress>> customResolver = host => Task.FromResult(IPAddress.Loopback); var clientTransport = new EpoxyTransportBuilder().SetResolver(customResolver).Construct(); EpoxyConnection clientConnection = await clientTransport.ConnectToAsync("epoxy://resolve-this-to-localhost/"); var proxy = new DummyTestProxy<EpoxyConnection>(clientConnection); var request = new Dummy {int_value = 100}; IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsFalse(response.IsError); var result = response.Payload.Deserialize(); Assert.AreEqual(101, result.int_value); await clientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_PayloadResponse() { TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var request = new Dummy { int_value = 100 }; IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsFalse(response.IsError); Assert.AreEqual(101, response.Payload.Deserialize().int_value); Assert.AreEqual(1, testClientServer.Service.RequestCount); Assert.AreEqual(0, testClientServer.Service.EventCount); Assert.AreEqual(request.int_value, testClientServer.Service.LastRequestReceived.int_value); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_Event() { TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var theEvent = new Dummy { int_value = 100 }; ManualResetEventSlim waitForEvent = testClientServer.Service.CreateResetEvent(); proxy.EventMethodAsync(theEvent); bool wasSignaled = waitForEvent.Wait(TimeSpan.FromSeconds(5)); Assert.IsTrue(wasSignaled, "Timed out waiting for event to fire"); Assert.AreEqual(0, testClientServer.Service.RequestCount); Assert.AreEqual(1, testClientServer.Service.EventCount); Assert.AreEqual(theEvent.int_value, testClientServer.Service.LastEventReceived.int_value); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_PayloadResponse_LayerData() { var layerStackProvider = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, new TestLayer_CheckPassedValue(1234)); TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(layerStackProvider, layerStackProvider); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var request = new Dummy { int_value = 100 }; IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsFalse(response.IsError); Assert.AreEqual(101, response.Payload.Deserialize().int_value); Assert.AreEqual(1, testClientServer.Service.RequestCount); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_PayloadResponse_ClientLayerErrors() { var errorLayer = new TestLayer_ReturnErrors(); var clientLayerStack = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, errorLayer); TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(null, clientLayerStack); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var request = new Dummy { int_value = 100 }; errorLayer.SetState(MessageType.Request, errorOnSend: true, errorOnReceive: false); IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsTrue(response.IsError); Assert.AreEqual(TestLayer_ReturnErrors.SendError, response.Error.Deserialize().error_code); Assert.AreEqual(0, testClientServer.Service.RequestCount); Assert.AreEqual(Dummy.Empty.int_value, testClientServer.Service.LastRequestReceived.int_value); errorLayer.SetState(MessageType.Response, errorOnSend: false, errorOnReceive: true); response = await proxy.ReqRspMethodAsync(request); Assert.IsTrue(response.IsError); Assert.AreEqual(TestLayer_ReturnErrors.ReceiveError, response.Error.Deserialize().error_code); Assert.AreEqual(1, testClientServer.Service.RequestCount); Assert.AreEqual(request.int_value, testClientServer.Service.LastRequestReceived.int_value); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_PayloadResponse_StatefulLayers() { var clientLayerProvider = new TestLayerProvider_StatefulAppend("Client"); var clientLayerStackProvider = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, clientLayerProvider); var serverLayerProvider = new TestLayerProvider_StatefulAppend("Server"); var serverLayerStackProvider = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, serverLayerProvider); TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(serverLayerStackProvider, clientLayerStackProvider); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var request = new Dummy { int_value = 100 }; clientLayerProvider.Layers.Clear(); serverLayerProvider.Layers.Clear(); IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsFalse(response.IsError); Assert.AreEqual(101, response.Payload.Deserialize().int_value); Assert.AreEqual(1, clientLayerProvider.Layers.Count); Assert.AreEqual(1, serverLayerProvider.Layers.Count); Assert.AreEqual("Client0SendClient0Receive", clientLayerProvider.Layers[0].State); Assert.AreEqual("Server0ReceiveServer0Send", serverLayerProvider.Layers[0].State); request.int_value = 101; response = await proxy.ReqRspMethodAsync(request); Assert.IsFalse(response.IsError); Assert.AreEqual(102, response.Payload.Deserialize().int_value); Assert.AreEqual(2, clientLayerProvider.Layers.Count); Assert.AreEqual(2, serverLayerProvider.Layers.Count); Assert.AreEqual("Client1SendClient1Receive", clientLayerProvider.Layers[1].State); Assert.AreEqual("Server1ReceiveServer1Send", serverLayerProvider.Layers[1].State); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_PayloadResponse_ServerLayerErrors() { var errorLayer = new TestLayer_ReturnErrors(); var serverLayerStackProvider = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, errorLayer); TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(serverLayerStackProvider, null); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var request = new Dummy { int_value = 100 }; errorLayer.SetState(MessageType.Request, errorOnSend: false, errorOnReceive: true); IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsTrue(response.IsError); Error error = response.Error.Deserialize(); Assert.AreEqual(TestLayer_ReturnErrors.ReceiveError, error.error_code); Assert.AreEqual(0, testClientServer.Service.RequestCount); Assert.AreEqual(Dummy.Empty.int_value, testClientServer.Service.LastRequestReceived.int_value); errorLayer.SetState(MessageType.Response, errorOnSend: true, errorOnReceive: false); response = await proxy.ReqRspMethodAsync(request); Assert.IsTrue(response.IsError); error = response.Error.Deserialize(); Assert.AreEqual(TestLayer_ReturnErrors.SendError, error.error_code); Assert.AreEqual(1, testClientServer.Service.RequestCount); Assert.AreEqual(request.int_value, testClientServer.Service.LastRequestReceived.int_value); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_Event_ClientLayerErrors() { var errorLayer = new TestLayer_ReturnErrors(); var clientLayerStackProvider = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, errorLayer); TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(null, clientLayerStackProvider); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var theEvent = new Dummy { int_value = 100 }; errorLayer.SetState(MessageType.Event, errorOnSend: true, errorOnReceive: false); ManualResetEventSlim waitForEvent = testClientServer.Service.CreateResetEvent(); proxy.EventMethodAsync(theEvent); bool wasSignaled = waitForEvent.Wait(TimeSpan.FromSeconds(1)); Assert.IsFalse(wasSignaled, "Event should not fire"); testClientServer.Service.ClearResetEvent(); Assert.AreEqual(0, testClientServer.Service.EventCount); Assert.AreEqual(Dummy.Empty.int_value, testClientServer.Service.LastEventReceived.int_value); errorLayer.SetState(MessageType.Event, errorOnSend: false, errorOnReceive: true); theEvent.int_value = 101; waitForEvent = testClientServer.Service.CreateResetEvent(); proxy.EventMethodAsync(theEvent); wasSignaled = waitForEvent.Wait(TimeSpan.FromSeconds(1)); Assert.IsTrue(wasSignaled, "Timed out waiting for event to fire"); Assert.AreEqual(1, testClientServer.Service.EventCount); Assert.AreEqual(theEvent.int_value, testClientServer.Service.LastEventReceived.int_value); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_Event_ServerLayerErrors() { var errorLayer = new TestLayer_ReturnErrors(); var serverLayerStackProvider = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, errorLayer); TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(serverLayerStackProvider, null); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var theEvent = new Dummy { int_value = 100 }; errorLayer.SetState(MessageType.Event, errorOnSend: false, errorOnReceive: true); ManualResetEventSlim waitForEvent = testClientServer.Service.CreateResetEvent(); proxy.EventMethodAsync(theEvent); bool wasSignaled = waitForEvent.Wait(TimeSpan.FromSeconds(1)); Assert.IsFalse(wasSignaled, "Event should not fire"); testClientServer.Service.ClearResetEvent(); Assert.AreEqual(0, testClientServer.Service.EventCount); Assert.AreEqual(Dummy.Empty.int_value, testClientServer.Service.LastEventReceived.int_value); errorLayer.SetState(MessageType.Event, errorOnSend: true, errorOnReceive: false); theEvent.int_value = 101; waitForEvent = testClientServer.Service.CreateResetEvent(); proxy.EventMethodAsync(theEvent); wasSignaled = waitForEvent.Wait(TimeSpan.FromSeconds(1)); Assert.IsTrue(wasSignaled, "Timed out waiting for event to fire"); Assert.AreEqual(1, testClientServer.Service.EventCount); Assert.AreEqual(theEvent.int_value, testClientServer.Service.LastEventReceived.int_value); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_Event_StatefulLayers() { var clientLayerProvider = new TestLayerProvider_StatefulAppend("Client"); var clientLayerStackProvider = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, clientLayerProvider); var serverLayerProvider = new TestLayerProvider_StatefulAppend("Server"); var serverLayerStackProvider = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, serverLayerProvider); TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(serverLayerStackProvider, clientLayerStackProvider); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var theEvent = new Dummy { int_value = 100 }; clientLayerProvider.Layers.Clear(); serverLayerProvider.Layers.Clear(); ManualResetEventSlim waitForEvent = testClientServer.Service.CreateResetEvent(); proxy.EventMethodAsync(theEvent); bool wasSignaled = waitForEvent.Wait(TimeSpan.FromSeconds(1)); Assert.IsTrue(wasSignaled, "Timed out waiting for event to fire"); Assert.AreEqual(1, testClientServer.Service.EventCount); Assert.AreEqual(theEvent.int_value, testClientServer.Service.LastEventReceived.int_value); Assert.AreEqual(1, clientLayerProvider.Layers.Count); Assert.AreEqual(1, serverLayerProvider.Layers.Count); Assert.AreEqual("Client0Send", clientLayerProvider.Layers[0].State); Assert.AreEqual("Server0Receive", serverLayerProvider.Layers[0].State); theEvent.int_value = 101; waitForEvent = testClientServer.Service.CreateResetEvent(); proxy.EventMethodAsync(theEvent); wasSignaled = waitForEvent.Wait(TimeSpan.FromSeconds(1)); Assert.IsTrue(wasSignaled, "Timed out waiting for event to fire"); Assert.AreEqual(2, testClientServer.Service.EventCount); Assert.AreEqual(theEvent.int_value, testClientServer.Service.LastEventReceived.int_value); Assert.AreEqual(2, clientLayerProvider.Layers.Count); Assert.AreEqual(2, serverLayerProvider.Layers.Count); Assert.AreEqual("Client1Send", clientLayerProvider.Layers[1].State); Assert.AreEqual("Server1Receive", serverLayerProvider.Layers[1].State); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_FailingLayerProvider_ClientSendReq() { // Fail after 1 successful GetLayerStack calls on client side var clientLayerStackProvider = new TestLayerStackProvider_Fails(1); TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(null, clientLayerStackProvider); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var request = new Dummy { int_value = 100 }; IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsFalse(response.IsError); Assert.AreEqual(101, response.Payload.Deserialize().int_value); request.int_value = 101; response = await proxy.ReqRspMethodAsync(request); Assert.IsTrue(response.IsError); Error error = response.Error.Deserialize(); Assert.AreEqual((int)ErrorCode.InternalServerError, error.error_code); Assert.AreEqual(TestLayerStackProvider_Fails.InternalDetails, error.message); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedService_GeneratedProxy_FailingLayerProvider_ServerReceiveReq() { // Fail after 1 successful GetLayerStack calls on server side var serverLayerStackProvider = new TestLayerStackProvider_Fails(1); TestClientServer<DummyTestService> testClientServer = await SetupTestClientServer<DummyTestService>(serverLayerStackProvider, null); var proxy = new DummyTestProxy<EpoxyConnection>(testClientServer.ClientConnection); var request = new Dummy { int_value = 100 }; IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsFalse(response.IsError); Assert.AreEqual(101, response.Payload.Deserialize().int_value); request.int_value = 101; response = await proxy.ReqRspMethodAsync(request); Assert.IsTrue(response.IsError); Error error = response.Error.Deserialize(); Assert.AreEqual((int)ErrorCode.InternalServerError, error.error_code); Assert.AreEqual(Errors.InternalErrorMessage, error.message); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public async Task GeneratedGenericService_GeneratedGenericProxy_PayloadResponse() { TestClientServer<GenericDummyTestService> testClientServer = await SetupTestClientServer<GenericDummyTestService>(); var proxy = new GenericTestProxy<Dummy, EpoxyConnection>(testClientServer.ClientConnection); var request = new Dummy { int_value = 100 }; IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsFalse(response.IsError); Assert.AreEqual(101, response.Payload.Deserialize().int_value); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); Assert.AreEqual(1, testClientServer.Service.RequestCount); Assert.AreEqual(0, testClientServer.Service.EventCount); Assert.AreEqual(request.int_value, testClientServer.Service.LastRequestReceived.int_value); } [Test] public async Task GeneratedGenericService_GeneratedGenericProxy_Event() { TestClientServer<GenericDummyTestService> testClientServer = await SetupTestClientServer<GenericDummyTestService>(); var proxy = new GenericTestProxy<Dummy, EpoxyConnection>(testClientServer.ClientConnection); var theEvent = new Dummy { int_value = 100 }; ManualResetEventSlim waitForEvent = testClientServer.Service.CreateResetEvent(); proxy.EventMethodAsync(theEvent); bool wasSignaled = waitForEvent.Wait(TimeSpan.FromSeconds(1)); Assert.IsTrue(wasSignaled, "Timed out waiting for event to fire"); Assert.AreEqual(0, testClientServer.Service.RequestCount); Assert.AreEqual(1, testClientServer.Service.EventCount); Assert.AreEqual(theEvent.int_value, testClientServer.Service.LastEventReceived.int_value); await testClientServer.ServiceTransport.StopAsync(); await testClientServer.ClientTransport.StopAsync(); } [Test] public void TestServiceMethodTypeValidation_Throws() { var exception = Assert.Throws<ArgumentException>(async () => await SetupTestClientServer<TestServiceEventMismatch>()); Assert.That(exception.Message, Is.StringContaining("registered as Event but callback not implemented as such")); exception = Assert.Throws<ArgumentException>(async () => await SetupTestClientServer<TestServiceReqResMismatch>()); Assert.That(exception.Message, Is.StringContaining("registered as RequestResponse but callback not implemented as such")); exception = Assert.Throws<ArgumentException>(async () => await SetupTestClientServer<TestServiceUnsupported>()); Assert.That(exception.Message, Is.StringContaining("registered as invalid type")); } [Test] public async Task IPv6Listener_RequestReply_PayloadResponse() { var transport = new EpoxyTransportBuilder().Construct(); listener = transport.MakeListener(new IPEndPoint(IPAddress.IPv6Loopback, EpoxyTransport.DefaultPort)); listener.AddService(new DummyTestService()); await listener.StartAsync(); EpoxyConnection conn = await transport.ConnectToAsync("epoxy://[::1]"); var proxy = new DummyTestProxy<EpoxyConnection>(conn); var request = new Dummy { int_value = 100 }; IMessage<Dummy> response = await proxy.ReqRspMethodAsync(request); Assert.IsFalse(response.IsError); Assert.AreEqual(101, response.Payload.Deserialize().int_value); await transport.StopAsync(); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 7/1/2009 4:01:55 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Linq; using GeoAPI.Geometries; namespace DotSpatial.Data { public class Raster<T> : Raster where T : IEquatable<T>, IComparable<T> { #region Private Variables /// <summary> /// The actual data values, stored as a jagged array of values of type T /// </summary> public T[][] Data; /// <summary> /// This is the same as the "Value" member except that it is type specific. /// This also supports the "ToDouble" method. /// </summary> protected ValueGrid<T> ValuesT { get; set; } #endregion #region Constructors /// <summary> /// Creates a new instance of Raster /// </summary> public Raster() { DataType = typeof(T); } /// <summary> /// Creates an raster of data type T /// </summary> /// <param name="numRows">The number of rows in the raster</param> /// <param name="numColumns">The number of columns in the raster</param> /// <param name="valueGrid">The default ValueGrid only supports standard numeric types, but if a different kind of value grid is needed, this allows it.</param> public Raster(int numRows, int numColumns, ValueGrid<T> valueGrid) { base.NumRows = numRows; base.NumColumns = numColumns; base.IsInRam = true; DataType = typeof(T); if (numRows * numColumns > 64000000) { base.NumRowsInFile = numRows; base.NumColumnsInFile = numColumns; base.IsInRam = false; base.Bounds = new RasterBounds(numRows, numColumns, new[] { 0.5, 1.0, 0.0, numRows - .5, 0.0, -1.0 }); base.NoDataValue = 0; // sets the no-data value to the minimum value for the specified type. ValuesT = valueGrid; base.Value = ValuesT; return; } Initialize(); } /// <summary> /// Creates a raster of data type T. /// </summary> /// <param name="numRows">The number of rows in the raster</param> /// <param name="numColumns">The number of columns in the raster</param> public Raster(int numRows, int numColumns) { base.NumRows = numRows; base.NumColumns = numColumns; DataType = typeof(T); if (numRows * numColumns > 64000000) { base.IsInRam = false; base.NumRowsInFile = numRows; base.NumColumnsInFile = numColumns; base.IsInRam = false; base.Bounds = new RasterBounds(numRows, numColumns, new[] { 0.5, 1.0, 0.0, numRows - .5, 0.0, -1.0 }); base.NoDataValue = 0; // sets the no-data value to the minimum value for the specified type. ValuesT = new ValueGrid<T>(this); base.Value = ValuesT; return; } base.IsInRam = true; Initialize(); } /// <summary> /// Used especially by the "save as" situation, this simply creates a new reference pointer for the actual data values. /// </summary> /// <param name="original"></param> public override void SetData(IRaster original) { Raster<T> temp = original as Raster<T>; if (temp == null) return; Data = temp.Data; Value = temp.Value; } /// <summary> /// Calls the basic setup for the raster /// </summary> protected void Initialize() { StartRow = 0; EndRow = NumRows - 1; StartColumn = 0; EndColumn = NumColumns - 1; NumColumnsInFile = NumColumns; NumRowsInFile = NumRows; // Just set the cell size to one NumValueCells = 0; if (IsInRam) { Bounds = new RasterBounds(NumRows, NumColumns, new[] { 0.5, 1.0, 0.0, NumRows - .5, 0.0, -1.0 }); Data = new T[NumRows][]; for (int row = 0; row < NumRows; row++) { Data[row] = new T[NumColumns]; } } Value = new ValueGrid<T>(this); NoDataValue = Global.ToDouble(Global.MinimumValue<T>()); DataType = typeof(T); } #endregion #region Methods /// <inheritdoc/> protected override void Dispose(bool disposeManagedResources) { if (disposeManagedResources) { Data = null; ValuesT = null; } base.Dispose(disposeManagedResources); } /// <summary> /// Creates a deep copy of this raster object so that the data values can be manipulated without /// interfering with the original raster. /// </summary> /// <returns></returns> public new Raster<T> Copy() { Raster<T> copy = MemberwiseClone() as Raster<T>; if (copy == null) return null; copy.Bounds = Bounds.Copy(); copy.Data = new T[NumRows][]; for (int row = 0; row < NumRows; row++) { copy.Data[row] = new T[NumColumns]; for (int col = 0; col < NumColumns; col++) { copy.Data[row][col] = Data[row][col]; } } copy.Value = new ValueGrid<T>(copy); copy.Bands = new List<IRaster>(); foreach (IRaster band in base.Bands) { if (band != this) copy.Bands.Add(band.Copy()); else copy.Bands.Add(copy); } return copy; } // ------------------------------------------FROM AND TO IN RAM ONLY ----------------- /// <summary> /// This creates a completely new raster from the windowed domain on the original raster. This new raster /// will not have a source file, and values like NumRowsInFile will correspond to the in memory version. /// All the values will be copied to the new source file. InRam must be true at this level. /// </summary> /// <param name="fileName"></param> /// <param name="startRow">The 0 based integer index of the top row to copy from this raster. If this raster is itself a window, 0 represents the startRow from the file.</param> /// <param name="endRow">The integer index of the bottom row to copy from this raster. The largest allowed value is NumRows - 1.</param> /// <param name="startColumn">The 0 based integer index of the leftmost column to copy from this raster. If this raster is a window, 0 represents the startColumn from the file.</param> /// <param name="endColumn">The 0 based integer index of the rightmost column to copy from this raster. The largest allowed value is NumColumns - 1</param> /// <param name="copyValues">If this is true, the values are saved to the file. If this is false and the data can be loaded into Ram, no file handling is done. Otherwise, a file of NoData values is created.</param> /// <param name="inRam">Boolean. If this is true and the window is small enough, a copy of the values will be loaded into memory.</param> /// <returns>An implementation of IRaster</returns> public IRaster CopyWindow(string fileName, int startRow, int endRow, int startColumn, int endColumn, bool copyValues, bool inRam) { if (inRam == false || (endColumn - startColumn + 1) * (endRow - startRow + 1) > 64000000) throw new ArgumentException(DataStrings.RasterRequiresCast); if (IsInRam == false) throw new ArgumentException(DataStrings.RasterRequiresCast); int numCols = endColumn - startColumn + 1; int numRows = endRow - startRow + 1; var result = new Raster<T>(numRows, numCols); result.Projection = Projection; // The affine coefficients defining the world file are the same except that they are translated over. Only the position of the // upper left corner changes. Everything else is the same as the previous raster. result.Bounds.AffineCoefficients = new AffineTransform(Bounds.AffineCoefficients).TransfromToCorner(startColumn, startRow); ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.CopyingValues, numRows); // copy values directly using both data structures for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { result.Data[row][col] = Data[startRow + row][startColumn + col]; } pm.CurrentValue = row; } pm.Reset(); result.Value = new ValueGrid<T>(result); return result; } /// <summary> /// Gets the statistics all the values. If the entire content is not currently in-ram, /// ReadRow will be used to read individual lines and performing the calculations. /// </summary> public override void GetStatistics() { ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.CalculatingStatistics, NumRows); T min = Global.MaximumValue<T>(); T max = Global.MinimumValue<T>(); double total = 0; double sqrTotal = 0; int count = 0; if (IsInRam == false || this.IsFullyWindowed() == false) { for (int row = 0; row < NumRowsInFile; row++) { T[] values = ReadRow(row); for (int col = 0; col < NumColumnsInFile; col++) { T val = values[col]; double dblVal = Global.ToDouble(val); if (dblVal == NoDataValue) continue; if (val.CompareTo(max) > 0) max = val; if (val.CompareTo(min) < 0) min = val; total += dblVal; sqrTotal += dblVal * dblVal; count++; } pm.CurrentValue = row; } } else { for (int row = 0; row < NumRows; row++) { for (int col = 0; col < NumColumns; col++) { T val = Data[row][col]; double dblVal = Global.ToDouble(val); if (dblVal == NoDataValue) { continue; } if (val.CompareTo(max) > 0) max = val; if (val.CompareTo(min) < 0) min = val; total += dblVal; sqrTotal += dblVal * dblVal; count++; } pm.CurrentValue = row; } } Value.Updated = false; Minimum = Global.ToDouble(min); Maximum = Global.ToDouble(max); Mean = total / count; NumValueCells = count; StdDeviation = (float)Math.Sqrt((sqrTotal / NumValueCells) - (total / NumValueCells) * (total / NumValueCells)); pm.Reset(); } // ----------------------------------- FROM AND TO IN RAM ONLY --------------------------------- /// <summary> /// This creates an IN MEMORY ONLY window from the in-memory window of this raster. If, however, the requested range /// is outside of what is contained in the in-memory portions of this raster, an appropriate cast /// is required to ensure that you have the correct File handling, like a BinaryRaster etc. /// </summary> /// <param name="startRow">The 0 based integer index of the top row to get from this raster. If this raster is itself a window, 0 represents the startRow from the file.</param> /// <param name="endRow">The integer index of the bottom row to get from this raster. The largest allowed value is NumRows - 1.</param> /// <param name="startColumn">The 0 based integer index of the leftmost column to get from this raster. If this raster is a window, 0 represents the startColumn from the file.</param> /// <param name="endColumn">The 0 based integer index of the rightmost column to get from this raster. The largest allowed value is NumColumns - 1</param> /// <param name="inRam">Boolean. If this is true and the window is small enough, a copy of the values will be loaded into memory.</param> /// <returns>An implementation of IRaster</returns> public IRaster GetWindow(int startRow, int endRow, int startColumn, int endColumn, bool inRam) { if (IsInRam == false) throw new ArgumentException(DataStrings.RasterRequiresCast); if (startRow < StartRow || endRow > EndRow || StartColumn < startColumn || EndColumn > endColumn) { // the requested extents are outside of the extents that have been windowed into ram. File Handling is required. throw new ArgumentException(DataStrings.RasterRequiresCast); } int numCols = endColumn - startColumn + 1; int numRows = endRow - startRow + 1; Raster<T> result = new Raster<T>(numRows, numCols); result.Filename = Filename; result.Projection = Projection; result.DataType = typeof(int); result.NumRows = numRows; result.NumColumns = numCols; result.NumRowsInFile = NumRowsInFile; result.NumColumnsInFile = NumColumnsInFile; result.NoDataValue = NoDataValue; result.StartColumn = startColumn; result.StartRow = startRow; result.EndColumn = endColumn; result.EndRow = EndRow; result.FileType = FileType; // Reposition the new "raster" so that it matches the specified window, not the whole raster result.Bounds.AffineCoefficients = new AffineTransform(Bounds.AffineCoefficients).TransfromToCorner(startColumn, startRow); // Now we can copy any values currently in memory. ProgressMeter pm = new ProgressMeter(ProgressHandler, DataStrings.CopyingValues, endRow); pm.StartValue = startRow; // copy values directly using both data structures for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { result.Data[row][col] = Data[startRow + row][startColumn + col]; } pm.CurrentValue = row; } pm.Reset(); result.Value = new ValueGrid<T>(result); return result; } /// <summary> /// Obtains only the statistics for the small window specified by startRow, endRow etc. /// this only works if the window is also InRam. /// </summary> public void GetWindowStatistics() { if (IsInRam == false) throw new ArgumentException(DataStrings.RasterRequiresCast); ProgressMeter pm = new ProgressMeter(ProgressHandler, "Calculating Statistics.", NumRows); double total = 0; double sqrTotal = 0; int count = 0; T min = Global.MaximumValue<T>(); T max = Global.MinimumValue<T>(); for (int row = 0; row < NumRows; row++) { for (int col = 0; col < NumColumns; col++) { T val = Data[row][col]; double dblVal = Global.ToDouble(val); if (dblVal != NoDataValue) { if (val.CompareTo(max) > 0) max = val; if (val.CompareTo(min) < 0) min = val; total += dblVal; sqrTotal += dblVal * dblVal; count++; } } pm.CurrentValue = row; } Value.Updated = false; Minimum = Global.ToDouble(min); Maximum = Global.ToDouble(max); NumValueCells = count; StdDeviation = (float)Math.Sqrt((sqrTotal / NumValueCells) - (total / NumValueCells) * (total / NumValueCells)); } /// <summary> /// Prevent the base raster "factory" style open function from working in subclasses. /// </summary> public override void Open() { if (IsInRam) { Data = ReadRaster(); GetStatistics(); } } /// <summary> /// This saves content from memory stored in the Data field to the file using whatever /// file format the file already exists as. /// </summary> public override void Save() { UpdateHeader(); WriteRaster(Data); } /// <summary> /// Reads a specific /// </summary> /// <param name="row"></param> /// <returns></returns> public T[] ReadRow(int row) { return ReadRaster(0, row, NumColumns, 1)[0]; } /// <summary> /// This method reads the values from the entire band into an array and returns the array as a single array. /// This assumes 0 offsets, the size of the entire image, and 0 for the pixel or line space. /// </summary> /// <returns>An array of values of type T, in row major order</returns> public T[][] ReadRaster() { return ReadRaster(0, 0, NumColumns, NumRows); } /// <summary> /// Most reading is optimized to read in a block at a time and process it. This method is designed /// for seeking through the file. It should work faster than the buffered methods in cases where /// an unusually arranged collection of values are required. Sorting the list before calling /// this should significantly improve performance. /// </summary> /// <param name="indices">A list or array of long values that are (Row * NumRowsInFile + Column)</param> public virtual List<T> GetValuesT(IEnumerable<long> indices) { if (IsInRam) { List<T> values = (from index in indices let row = (int)Math.Floor(index / (double)NumColumnsInFile) let col = (int)(index % NumColumnsInFile) select Data[row][col]).ToList(); return values; } // This code should never be called because it should get replaced // by file access code that is optimized, but if not, then this will be slow. return (from index in indices let row = (int)Math.Floor(index / (double)NumColumnsInFile) let col = (int)(index % NumColumnsInFile) select (T)Convert.ChangeType(Value[row, col], typeof(T))).ToList(); } // There is no need to override this any further, but GetValuesT should be implemented more intelligently in subclasses. /// <inheritdoc/> public override List<double> GetValues(IEnumerable<long> indices) { List<T> vals = GetValuesT(indices); return vals.Select(Global.ToDouble).ToList(); } /// <inheritdoc/> public override IRaster ReadBlock(int xOff, int yOff, int sizeX, int sizeY) { Raster<T> result = new Raster<T>(sizeY, sizeX); result.Data = ReadRaster(xOff, yOff, sizeX, sizeY); Coordinate topLeft = Bounds.CellCenter_ToProj(yOff, xOff); double[] aff = new double[6]; Array.Copy(Bounds.AffineCoefficients, 0, aff, 0, 6); aff[0] = topLeft.X; aff[3] = topLeft.Y; result.Bounds = new RasterBounds(sizeY, sizeX, aff); result.NoDataValue = NoDataValue; result.Projection = Projection; result.IsInRam = true; return result; } /// <summary> /// This Method should be overrridden by classes, and provides the primary ability. /// </summary> /// <param name="xOff">The horizontal offset of the area to read values from.</param> /// <param name="yOff">The vertical offset of the window to read values from.</param> /// <param name="sizeX">The number of values to read into the buffer.</param> /// <param name="sizeY">The vertical size of the window to read into the buffer.</param> /// <returns>The jagged array of raster values of type T.</returns> public virtual T[][] ReadRaster(int xOff, int yOff, int sizeX, int sizeY) { throw new NotImplementedException("This should be overridden by classes that specify a file format."); } /// <summary> /// Reads a specific /// </summary> /// <param name="buffer">The one dimensional array of values containing all the data for this particular content.</param> /// <param name="row">The integer row to write to the raster</param> public void WriteRow(T[] buffer, int row) { T[][] bufferJagged = new T[1][]; bufferJagged[0] = buffer; WriteRaster(bufferJagged, 0, row, NumColumns, 1); } /// <summary> /// This method reads the values from the entire band into an array and returns the array as a single array. /// This assumes 0 offsets, the size of the entire image, and 0 for the pixel or line space. /// </summary> /// <param name="buffer">The one dimensional array of values containing all the data for this particular content.</param> public void WriteRaster(T[][] buffer) { WriteRaster(buffer, 0, 0, NumColumns, NumRows); } /// <summary> /// This method reads the values from the entire band into an array and returns the array as a single array. /// This specifies a window where the xSize and ySize specified and 0 is used for the pixel and line space. /// </summary> /// <param name="buffer">The one dimensional array of values containing all the data for this particular content.</param> /// <param name="xOff">The horizontal offset of the area to read values from.</param> /// <param name="yOff">The vertical offset of the window to read values from.</param> /// <param name="xSize">The number of values to read into the buffer.</param> /// <param name="ySize">The vertical size of the window to read into the buffer.</param> public virtual void WriteRaster(T[][] buffer, int xOff, int yOff, int xSize, int ySize) { throw new NotImplementedException("This should be overridden by classes that specify a file format."); } /// <inheritdoc/> public override void WriteBlock(IRaster blockValues, int xOff, int yOff, int xSize, int ySize) { Raster<T> source = blockValues as Raster<T>; if (source != null) { if (ySize == source.NumColumns && xSize == source.NumColumns) { WriteRaster(source.Data, xOff, yOff, xSize, ySize); } else { T[][] values = new T[ySize][]; // data is of the same type so just set the values. for (int row = 0; row < ySize; row++) { if (xSize == NumColumns) { values[row] = source.Data[row]; } else { values[row] = new T[xSize]; Array.Copy(source.Data[row], 0, values[row], 0, xSize); } } WriteRaster(values, xOff, yOff, xSize, ySize); } } else { T[][] values = new T[ySize][]; // data is of the same type so just set the values. for (int row = 0; row < ySize; row++) { for (int col = 0; col < xSize; col++) { values[row][col] = (T)Convert.ChangeType(blockValues.Value[row, col], typeof(T)); } } WriteRaster(values, xOff, yOff, xSize, ySize); } } /// <summary> /// During a save opperation, this instructs the program to perform any writing that is not handled by /// the write raster content. /// </summary> protected virtual void UpdateHeader() { throw new NotImplementedException("This should be overridden by classes that specify a file format."); } #endregion #region Properties /// <summary> /// Gets the size of each raster element in bytes. /// </summary> /// <remarks> /// This only works for a few numeric types, and will return 0 if it is not identifiable as one /// of these basic types: byte, short, int, long, float, double, decimal, sbyte, ushort, uint, ulong, bool. /// </remarks> public override int ByteSize { get { return GetByteSize(default(T)); } } private static int GetByteSize(object value) { if (value is byte) return 1; if (value is short) return 2; if (value is int) return 4; if (value is long) return 8; if (value is float) return 4; if (value is double) return 8; if (value is sbyte) return 1; if (value is ushort) return 2; if (value is uint) return 4; if (value is ulong) return 8; if (value is bool) return 1; return 0; } #endregion } }
#if XMLCHARTYPE_GEN_RESOURCE #undef XMLCHARTYPE_USE_RESOURCE #endif //------------------------------------------------------------------------------ // <copyright file="XmlCharType.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ //#define XMLCHARTYPE_USE_RESOURCE // load the character properties from resources (XmlCharType.bin must be linked to System.Xml.dll) //#define XMLCHARTYPE_GEN_RESOURCE // generate the character properties into XmlCharType.bin #if XMLCHARTYPE_GEN_RESOURCE || XMLCHARTYPE_USE_RESOURCE using System.IO; using System.Reflection; #endif using System.Threading; using System.Diagnostics; namespace System.Xml { /// <include file='doc\XmlCharType.uex' path='docs/doc[@for="XmlCharType"]/*' /> /// <internalonly/> /// <devdoc> /// The XmlCharType class is used for quick character type recognition /// which is optimized for the first 127 ascii characters. /// </devdoc> #if SILVERLIGHT #if !SILVERLIGHT_XPATH [System.Runtime.CompilerServices.FriendAccessAllowed] // Used by System.ServiceModel.dll and System.Runtime.Serialization.dll #endif #endif #if XMLCHARTYPE_USE_RESOURCE unsafe internal struct XmlCharType { #else internal struct XmlCharType { #endif // Surrogate constants internal const int SurHighStart = 0xd800; // 1101 10xx internal const int SurHighEnd = 0xdbff; internal const int SurLowStart = 0xdc00; // 1101 11xx internal const int SurLowEnd = 0xdfff; internal const int SurMask = 0xfc00; // 1111 11xx #if XML10_FIFTH_EDITION // Characters defined in the XML 1.0 Fifth Edition // Whitespace chars -- Section 2.3 [3] // Star NCName characters -- Section 2.3 [4] (NameStartChar characters without ':') // NCName characters -- Section 2.3 [4a] (NameChar characters without ':') // Character data characters -- Section 2.2 [2] // Public ID characters -- Section 2.3 [13] // Characters defined in the XML 1.0 Fourth Edition // NCNameCharacters -- Appending B: Characters Classes in XML 1.0 4th edition and earlier - minus the ':' char per the Namespaces in XML spec // Letter characters -- Appending B: Characters Classes in XML 1.0 4th edition and earlier // This appendix has been deprecated in XML 1.0 5th edition, but we still need to use // the Letter and NCName definitions from the 4th edition in some places because of backwards compatibility internal const int fWhitespace = 1; internal const int fLetter = 2; internal const int fNCStartNameSC = 4; // SC = Single Char internal const int fNCNameSC = 8; // SC = Single Char internal const int fCharData = 16; internal const int fNCNameXml4e = 32; // NCName char according to the XML 1.0 4th edition internal const int fText = 64; internal const int fAttrValue = 128; // name surrogate constants private const int s_NCNameSurCombinedStart = 0x10000; private const int s_NCNameSurCombinedEnd = 0xEFFFF; private const int s_NCNameSurHighStart = SurHighStart + ((s_NCNameSurCombinedStart - 0x10000) / 1024); private const int s_NCNameSurHighEnd = SurHighStart + ((s_NCNameSurCombinedEnd - 0x10000) / 1024); private const int s_NCNameSurLowStart = SurLowStart + ((s_NCNameSurCombinedStart - 0x10000) % 1024); private const int s_NCNameSurLowEnd = SurLowStart + ((s_NCNameSurCombinedEnd - 0x10000) % 1024); #else // Characters defined in the XML 1.0 Fourth Edition // Whitespace chars -- Section 2.3 [3] // Letters -- Appendix B [84] // Starting NCName characters -- Section 2.3 [5] (Starting Name characters without ':') // NCName characters -- Section 2.3 [4] (Name characters without ':') // Character data characters -- Section 2.2 [2] // PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec internal const int fWhitespace = 1; internal const int fLetter = 2; internal const int fNCStartNameSC = 4; internal const int fNCNameSC = 8; internal const int fCharData = 16; internal const int fNCNameXml4e = 32; internal const int fText = 64; internal const int fAttrValue = 128; #endif // bitmap for public ID characters - 1 bit per character 0x0 - 0x80; no character > 0x80 is a PUBLIC ID char private const string s_PublicIdBitmap = "\u2400\u0000\uffbb\uafff\uffff\u87ff\ufffe\u07ff"; // size of XmlCharType table private const uint CharPropertiesSize = (uint)char.MaxValue + 1; #if !XMLCHARTYPE_USE_RESOURCE || XMLCHARTYPE_GEN_RESOURCE internal const string s_Whitespace = "\u0009\u000a\u000d\u000d\u0020\u0020"; #if XML10_FIFTH_EDITION // StartNameChar without ':' -- see Section 2.3 production [4] const string s_NCStartName = "\u0041\u005a\u005f\u005f\u0061\u007a\u00c0\u00d6" + "\u00d8\u00f6\u00f8\u02ff\u0370\u037d\u037f\u1fff" + "\u200c\u200d\u2070\u218f\u2c00\u2fef\u3001\ud7ff" + "\uf900\ufdcf\ufdf0\ufffd"; // NameChar without ':' -- see Section 2.3 production [4a] const string s_NCName = "\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" + "\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" + "\u00f8\u037d\u037f\u1fff\u200c\u200d\u203f\u2040" + "\u2070\u218f\u2c00\u2fef\u3001\ud7ff\uf900\ufdcf" + "\ufdf0\ufffd"; #else const string s_NCStartName = "\u0041\u005a\u005f\u005f\u0061\u007a" + "\u00c0\u00d6\u00d8\u00f6\u00f8\u0131\u0134\u013e" + "\u0141\u0148\u014a\u017e\u0180\u01c3\u01cd\u01f0" + "\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1" + "\u0386\u0386\u0388\u038a\u038c\u038c\u038e\u03a1" + "\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" + "\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" + "\u040e\u044f\u0451\u045c\u045e\u0481\u0490\u04c4" + "\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5" + "\u04f8\u04f9\u0531\u0556\u0559\u0559\u0561\u0586" + "\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0641\u064a" + "\u0671\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" + "\u06d5\u06d5\u06e5\u06e6\u0905\u0939\u093d\u093d" + "\u0958\u0961\u0985\u098c\u098f\u0990\u0993\u09a8" + "\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09dc\u09dd" + "\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10" + "\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36" + "\u0a38\u0a39\u0a59\u0a5c\u0a5e\u0a5e\u0a72\u0a74" + "\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" + "\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abd\u0abd" + "\u0ae0\u0ae0\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" + "\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3d\u0b3d" + "\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e\u0b90" + "\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f" + "\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9" + "\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33" + "\u0c35\u0c39\u0c60\u0c61\u0c85\u0c8c\u0c8e\u0c90" + "\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cde\u0cde" + "\u0ce0\u0ce1\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28" + "\u0d2a\u0d39\u0d60\u0d61\u0e01\u0e2e\u0e30\u0e30" + "\u0e32\u0e33\u0e40\u0e45\u0e81\u0e82\u0e84\u0e84" + "\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" + "\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" + "\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb0\u0eb2\u0eb3" + "\u0ebd\u0ebd\u0ec0\u0ec4\u0f40\u0f47\u0f49\u0f69" + "\u10a0\u10c5\u10d0\u10f6\u1100\u1100\u1102\u1103" + "\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112" + "\u113c\u113c\u113e\u113e\u1140\u1140\u114c\u114c" + "\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159" + "\u115f\u1161\u1163\u1163\u1165\u1165\u1167\u1167" + "\u1169\u1169\u116d\u116e\u1172\u1173\u1175\u1175" + "\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af" + "\u11b7\u11b8\u11ba\u11ba\u11bc\u11c2\u11eb\u11eb" + "\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9" + "\u1f00\u1f15\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d" + "\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d" + "\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe" + "\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb" + "\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u2126\u2126" + "\u212a\u212b\u212e\u212e\u2180\u2182\u3007\u3007" + "\u3021\u3029\u3041\u3094\u30a1\u30fa\u3105\u312c" + "\u4e00\u9fa5\uac00\ud7a3"; const string s_NCName = "\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" + "\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" + "\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" + "\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" + "\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345" + "\u0360\u0361\u0386\u038a\u038c\u038c\u038e\u03a1" + "\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" + "\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" + "\u040e\u044f\u0451\u045c\u045e\u0481\u0483\u0486" + "\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb" + "\u04ee\u04f5\u04f8\u04f9\u0531\u0556\u0559\u0559" + "\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd" + "\u05bf\u05bf\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea" + "\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" + "\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" + "\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9\u0901\u0903" + "\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963" + "\u0966\u096f\u0981\u0983\u0985\u098c\u098f\u0990" + "\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9" + "\u09bc\u09bc\u09be\u09c4\u09c7\u09c8\u09cb\u09cd" + "\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" + "\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" + "\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39" + "\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d" + "\u0a59\u0a5c\u0a5e\u0a5e\u0a66\u0a74\u0a81\u0a83" + "\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" + "\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5" + "\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" + "\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" + "\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3c\u0b43" + "\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d" + "\u0b5f\u0b61\u0b66\u0b6f\u0b82\u0b83\u0b85\u0b8a" + "\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c" + "\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5" + "\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" + "\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c" + "\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" + "\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56" + "\u0c60\u0c61\u0c66\u0c6f\u0c82\u0c83\u0c85\u0c8c" + "\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9" + "\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6" + "\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" + "\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39" + "\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d\u0d57\u0d57" + "\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a" + "\u0e40\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84" + "\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" + "\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" + "\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" + "\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9" + "\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35\u0f37\u0f37" + "\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84" + "\u0f86\u0f8b\u0f90\u0f95\u0f97\u0f97\u0f99\u0fad" + "\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6" + "\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" + "\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" + "\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" + "\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" + "\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" + "\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" + "\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" + "\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" + "\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" + "\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" + "\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" + "\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" + "\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" + "\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126" + "\u212a\u212b\u212e\u212e\u2180\u2182\u3005\u3005" + "\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" + "\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe" + "\u3105\u312c\u4e00\u9fa5\uac00\ud7a3"; #endif const string s_CharData = "\u0009\u000a\u000d\u000d\u0020\ud7ff\ue000\ufffd"; const string s_PublicID = "\u000a\u000a\u000d\u000d\u0020\u0021\u0023\u0025" + "\u0027\u003b\u003d\u003d\u003f\u005a\u005f\u005f" + "\u0061\u007a"; const string s_Text = // TextChar = CharData - { 0xA | 0xD | '<' | '&' | 0x9 | ']' | 0xDC00 - 0xDFFF } "\u0020\u0025\u0027\u003b\u003d\u005c\u005e\ud7ff\ue000\ufffd"; const string s_AttrValue = // AttrValueChar = CharData - { 0xA | 0xD | 0x9 | '<' | '>' | '&' | '\'' | '"' | 0xDC00 - 0xDFFF } "\u0020\u0021\u0023\u0025\u0028\u003b\u003d\u003d\u003f\ud7ff\ue000\ufffd"; // // XML 1.0 Fourth Edition definitions for name characters // const string s_LetterXml4e = "\u0041\u005a\u0061\u007a\u00c0\u00d6\u00d8\u00f6" + "\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" + "\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" + "\u0250\u02a8\u02bb\u02c1\u0386\u0386\u0388\u038a" + "\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6" + "\u03da\u03da\u03dc\u03dc\u03de\u03de\u03e0\u03e0" + "\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c" + "\u045e\u0481\u0490\u04c4\u04c7\u04c8\u04cb\u04cc" + "\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9\u0531\u0556" + "\u0559\u0559\u0561\u0586\u05d0\u05ea\u05f0\u05f2" + "\u0621\u063a\u0641\u064a\u0671\u06b7\u06ba\u06be" + "\u06c0\u06ce\u06d0\u06d3\u06d5\u06d5\u06e5\u06e6" + "\u0905\u0939\u093d\u093d\u0958\u0961\u0985\u098c" + "\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2" + "\u09b6\u09b9\u09dc\u09dd\u09df\u09e1\u09f0\u09f1" + "\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a\u0a30" + "\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59\u0a5c" + "\u0a5e\u0a5e\u0a72\u0a74\u0a85\u0a8b\u0a8d\u0a8d" + "\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0\u0ab2\u0ab3" + "\u0ab5\u0ab9\u0abd\u0abd\u0ae0\u0ae0\u0b05\u0b0c" + "\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33" + "\u0b36\u0b39\u0b3d\u0b3d\u0b5c\u0b5d\u0b5f\u0b61" + "\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a" + "\u0b9c\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa" + "\u0bae\u0bb5\u0bb7\u0bb9\u0c05\u0c0c\u0c0e\u0c10" + "\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39\u0c60\u0c61" + "\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3" + "\u0cb5\u0cb9\u0cde\u0cde\u0ce0\u0ce1\u0d05\u0d0c" + "\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d60\u0d61" + "\u0e01\u0e2e\u0e30\u0e30\u0e32\u0e33\u0e40\u0e45" + "\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a" + "\u0e8d\u0e8d\u0e94\u0e97\u0e99\u0e9f\u0ea1\u0ea3" + "\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae" + "\u0eb0\u0eb0\u0eb2\u0eb3\u0ebd\u0ebd\u0ec0\u0ec4" + "\u0f40\u0f47\u0f49\u0f69\u10a0\u10c5\u10d0\u10f6" + "\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" + "\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" + "\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" + "\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" + "\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" + "\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" + "\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" + "\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" + "\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" + "\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" + "\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" + "\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" + "\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" + "\u1ff6\u1ffc\u2126\u2126\u212a\u212b\u212e\u212e" + "\u2180\u2182\u3007\u3007\u3021\u3029\u3041\u3094" + "\u30a1\u30fa\u3105\u312c\u4e00\u9fa5\uac00\ud7a3"; const string s_NCNameXml4e = "\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" + "\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" + "\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" + "\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" + "\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345" + "\u0360\u0361\u0386\u038a\u038c\u038c\u038e\u03a1" + "\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" + "\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" + "\u040e\u044f\u0451\u045c\u045e\u0481\u0483\u0486" + "\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb" + "\u04ee\u04f5\u04f8\u04f9\u0531\u0556\u0559\u0559" + "\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd" + "\u05bf\u05bf\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea" + "\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" + "\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" + "\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9\u0901\u0903" + "\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963" + "\u0966\u096f\u0981\u0983\u0985\u098c\u098f\u0990" + "\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9" + "\u09bc\u09bc\u09be\u09c4\u09c7\u09c8\u09cb\u09cd" + "\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" + "\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" + "\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39" + "\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d" + "\u0a59\u0a5c\u0a5e\u0a5e\u0a66\u0a74\u0a81\u0a83" + "\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" + "\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5" + "\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" + "\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" + "\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3c\u0b43" + "\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d" + "\u0b5f\u0b61\u0b66\u0b6f\u0b82\u0b83\u0b85\u0b8a" + "\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c" + "\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5" + "\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" + "\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c" + "\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" + "\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56" + "\u0c60\u0c61\u0c66\u0c6f\u0c82\u0c83\u0c85\u0c8c" + "\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9" + "\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6" + "\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" + "\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39" + "\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d\u0d57\u0d57" + "\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a" + "\u0e40\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84" + "\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" + "\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" + "\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" + "\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9" + "\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35\u0f37\u0f37" + "\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84" + "\u0f86\u0f8b\u0f90\u0f95\u0f97\u0f97\u0f99\u0fad" + "\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6" + "\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" + "\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" + "\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" + "\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" + "\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" + "\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" + "\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" + "\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" + "\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" + "\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" + "\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" + "\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" + "\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" + "\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126" + "\u212a\u212b\u212e\u212e\u2180\u2182\u3005\u3005" + "\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" + "\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe" + "\u3105\u312c\u4e00\u9fa5\uac00\ud7a3"; #endif // static lock for XmlCharType class private static object s_Lock; private static object StaticLock { get { if ( s_Lock == null ) { object o = new object(); Interlocked.CompareExchange<object>( ref s_Lock, o, null ); } return s_Lock; } } #if XMLCHARTYPE_USE_RESOURCE #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY [System.Security.SecurityCritical] #endif private static volatile byte* s_CharProperties; #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY [System.Security.SecurityCritical] #endif internal byte* charProperties; #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY [System.Security.SecurityCritical] #endif static void InitInstance() { lock ( StaticLock ) { if ( s_CharProperties != null ) { return; } UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)Assembly.GetExecutingAssembly().GetManifestResourceStream( "XmlCharType.bin" ); Debug.Assert( memStream.Length == CharPropertiesSize ); byte* chProps = memStream.PositionPointer; Thread.MemoryBarrier(); // For weak memory models (IA64) s_CharProperties = chProps; } } #else // !XMLCHARTYPE_USE_RESOURCE private static volatile byte [] s_CharProperties; internal byte [] charProperties; static void InitInstance() { lock ( StaticLock ) { if ( s_CharProperties != null ) { return; } byte[] chProps = new byte[CharPropertiesSize]; s_CharProperties = chProps; SetProperties( s_Whitespace, fWhitespace ); SetProperties( s_LetterXml4e, fLetter ); SetProperties( s_NCStartName, fNCStartNameSC ); SetProperties( s_NCName, fNCNameSC ); SetProperties( s_CharData, fCharData ); SetProperties( s_NCNameXml4e, fNCNameXml4e ); SetProperties( s_Text, fText ); SetProperties( s_AttrValue, fAttrValue ); } } private static void SetProperties( string ranges, byte value ) { for ( int p = 0; p < ranges.Length; p += 2 ) { for ( int i = ranges[p], last = ranges[p + 1]; i <= last; i++ ) { s_CharProperties[i] |= value; } } } #endif #if XMLCHARTYPE_USE_RESOURCE #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY [System.Security.SecurityCritical] #endif private XmlCharType( byte* charProperties ) { #else private XmlCharType( byte[] charProperties ) { #endif Debug.Assert( s_CharProperties != null ); this.charProperties = charProperties; } public static XmlCharType Instance { #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif get { if ( s_CharProperties == null ) { InitInstance(); } return new XmlCharType( s_CharProperties ); } } // NOTE: This method will not be inlined (because it uses byte* charProperties) #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif public bool IsWhiteSpace( char ch ) { return ( charProperties[ch] & fWhitespace ) != 0; } #if !SILVERLIGHT public bool IsExtender( char ch ) { return ( ch == 0xb7 ); } #endif // NOTE: This method will not be inlined (because it uses byte* charProperties) #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif public bool IsNCNameSingleChar(char ch) { return ( charProperties[ch] & fNCNameSC ) != 0; } #if XML10_FIFTH_EDITION public bool IsNCNameSurrogateChar( string str, int index ) { if ( index + 1 >= str.Length ) { return false; } return InRange( str[index], s_NCNameSurHighStart, s_NCNameSurHighEnd ) && InRange( str[index + 1], s_NCNameSurLowStart, s_NCNameSurLowEnd ); } // Surrogate characters for names are the same for NameChar and StartNameChar, // so this method can be used for both public bool IsNCNameSurrogateChar(char lowChar, char highChar) { return InRange( highChar, s_NCNameSurHighStart, s_NCNameSurHighEnd ) && InRange( lowChar, s_NCNameSurLowStart, s_NCNameSurLowEnd ); } public bool IsNCNameHighSurrogateChar( char highChar ) { return InRange( highChar, s_NCNameSurHighStart, s_NCNameSurHighEnd ); } public bool IsNCNameLowSurrogateChar( char lowChar ) { return InRange( lowChar, s_NCNameSurLowStart, s_NCNameSurLowEnd ); } #endif // NOTE: This method will not be inlined (because it uses byte* charProperties) #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif public bool IsStartNCNameSingleChar(char ch) { return ( charProperties[ch] & fNCStartNameSC ) != 0; } #if XML10_FIFTH_EDITION // !!! NOTE: These is no IsStartNCNameSurrogateChar, use IsNCNameSurrogateChar instead. // Surrogate ranges for start name charaters are the same as for name characters. #endif public bool IsNameSingleChar(char ch) { return IsNCNameSingleChar(ch) || ch == ':'; } #if XML10_FIFTH_EDITION public bool IsNameSurrogateChar(char lowChar, char highChar) { return IsNCNameSurrogateChar(lowChar, highChar); } #endif public bool IsStartNameSingleChar(char ch) { return IsStartNCNameSingleChar(ch) || ch == ':'; } // NOTE: This method will not be inlined (because it uses byte* charProperties) #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif public bool IsCharData( char ch ) { return ( charProperties[ch] & fCharData ) != 0; } // [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif public bool IsPubidChar( char ch ) { if ( ch < (char)0x80 ) { return ( s_PublicIdBitmap[ch >> 4] & ( 1 << ( ch & 0xF ) ) ) != 0; } return false; } // TextChar = CharData - { 0xA, 0xD, '<', '&', ']' } // NOTE: This method will not be inlined (because it uses byte* charProperties) #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif internal bool IsTextChar( char ch ) { return ( charProperties[ch] & fText ) != 0; } // AttrValueChar = CharData - { 0xA, 0xD, 0x9, '<', '>', '&', '\'', '"' } // NOTE: This method will not be inlined (because it uses byte* charProperties) #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif internal bool IsAttributeValueChar( char ch ) { return ( charProperties[ch] & fAttrValue ) != 0; } // XML 1.0 Fourth Edition definitions // // NOTE: This method will not be inlined (because it uses byte* charProperties) #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif public bool IsLetter( char ch ) { return ( charProperties[ch] & fLetter ) != 0; } // NOTE: This method will not be inlined (because it uses byte* charProperties) // This method uses the XML 4th edition name character ranges #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif public bool IsNCNameCharXml4e( char ch ) { return ( charProperties[ch] & fNCNameXml4e ) != 0; } // This method uses the XML 4th edition name character ranges public bool IsStartNCNameCharXml4e( char ch ) { return IsLetter( ch ) || ch == '_'; } // This method uses the XML 4th edition name character ranges public bool IsNameCharXml4e( char ch ) { return IsNCNameCharXml4e( ch ) || ch == ':'; } // This method uses the XML 4th edition name character ranges public bool IsStartNameCharXml4e( char ch ) { return IsStartNCNameCharXml4e( ch ) || ch == ':'; } // Digit methods public static bool IsDigit( char ch ) { return InRange( ch, 0x30, 0x39 ); } #if !SILVERLIGHT public static bool IsHexDigit(char ch) { return InRange( ch, 0x30, 0x39 ) || InRange( ch, 'a', 'f' ) || InRange( ch, 'A', 'F' ); } #endif // Surrogate methods internal static bool IsHighSurrogate( int ch ) { return InRange( ch, SurHighStart, SurHighEnd ); } internal static bool IsLowSurrogate( int ch ) { return InRange( ch, SurLowStart, SurLowEnd ); } internal static bool IsSurrogate( int ch ) { return InRange( ch, SurHighStart, SurLowEnd ); } internal static int CombineSurrogateChar( int lowChar, int highChar ) { return ( lowChar - SurLowStart ) | ( ( highChar - SurHighStart ) << 10 ) + 0x10000; } internal static void SplitSurrogateChar( int combinedChar, out char lowChar, out char highChar ) { int v = combinedChar - 0x10000; lowChar = (char)( SurLowStart + v % 1024 ); highChar = (char)( SurHighStart + v / 1024 ); } internal bool IsOnlyWhitespace( string str ) { return IsOnlyWhitespaceWithPos( str ) == -1; } // Character checking on strings #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif internal int IsOnlyWhitespaceWithPos( string str ) { if ( str != null ) { for ( int i = 0; i < str.Length; i++ ) { if ( ( charProperties[str[i]] & fWhitespace ) == 0 ) { return i; } } } return -1; } #if SILVERLIGHT && !SILVERLIGHT_DISABLE_SECURITY && XMLCHARTYPE_USE_RESOURCE [System.Security.SecuritySafeCritical] #endif internal int IsOnlyCharData( string str ) { if ( str != null ) { for ( int i = 0; i < str.Length; i++ ) { if ( ( charProperties[str[i]] & fCharData ) == 0 ) { if ( i + 1 >= str.Length || !(XmlCharType.IsHighSurrogate(str[i]) && XmlCharType.IsLowSurrogate(str[i+1]))) { return i; } else { i++; } } } } return -1; } static internal bool IsOnlyDigits(string str, int startPos, int len) { Debug.Assert(str != null); Debug.Assert(startPos + len <= str.Length); Debug.Assert(startPos <= str.Length); for (int i = startPos; i < startPos + len; i++) { if (!IsDigit(str[i])) { return false; } } return true; } static internal bool IsOnlyDigits( char[] chars, int startPos, int len ) { Debug.Assert( chars != null ); Debug.Assert( startPos + len <= chars.Length ); Debug.Assert( startPos <= chars.Length ); for ( int i = startPos; i < startPos + len; i++ ) { if ( !IsDigit( chars[i] ) ) { return false; } } return true; } internal int IsPublicId( string str ) { if ( str != null ) { for ( int i = 0; i < str.Length; i++ ) { if ( !IsPubidChar(str[i]) ) { return i; } } } return -1; } // This method tests whether a value is in a given range with just one test; start and end should be constants private static bool InRange(int value, int start, int end) { Debug.Assert(start <= end); return (uint)(value - start) <= (uint)(end - start); } #if XMLCHARTYPE_GEN_RESOURCE // // Code for generating XmlCharType.bin table and s_PublicIdBitmap // // build command line: csc XmlCharType.cs /d:XMLCHARTYPE_GEN_RESOURCE // public static void Main( string[] args ) { try { InitInstance(); // generate PublicId bitmap ushort[] bitmap = new ushort[0x80 >> 4]; for (int i = 0; i < s_PublicID.Length; i += 2) { for (int j = s_PublicID[i], last = s_PublicID[i + 1]; j <= last; j++) { bitmap[j >> 4] |= (ushort)(1 << (j & 0xF)); } } Console.Write("private const string s_PublicIdBitmap = \""); for (int i = 0; i < bitmap.Length; i++) { Console.Write("\\u{0:x4}", bitmap[i]); } Console.WriteLine("\";"); Console.WriteLine(); string fileName = ( args.Length == 0 ) ? "XmlCharType.bin" : args[0]; Console.Write( "Writing XmlCharType character properties to {0}...", fileName ); FileStream fs = new FileStream( fileName, FileMode.Create ); for ( int i = 0; i < CharPropertiesSize; i += 4096 ) { fs.Write( s_CharProperties, i, 4096 ); } fs.Close(); Console.WriteLine( "done." ); } catch ( Exception e ) { Console.WriteLine(); Console.WriteLine( "Exception: {0}", e.Message ); } } #endif } }
#region File Description //----------------------------------------------------------------------------- // PlayerPosition.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using RolePlayingGameData; using Microsoft.Xna.Framework.Input.Touch; #endregion namespace RolePlaying { /// <summary> /// Static class for a tileable map /// </summary> static class TileEngine { #region Map /// <summary> /// The map being used by the tile engine. /// </summary> private static Map map = null; /// <summary> /// The map being used by the tile engine. /// </summary> public static Map Map { get { return map; } } /// <summary> /// The position of the outside 0,0 corner of the map, in pixels. /// </summary> private static Vector2 mapOriginPosition; /// <summary> /// Calculate the screen position of a given map location (in tiles). /// </summary> /// <param name="mapPosition">A map location, in tiles.</param> /// <returns>The current screen position of that location.</returns> public static Vector2 GetScreenPosition(Point mapPosition) { return new Vector2( mapOriginPosition.X + mapPosition.X * map.TileSize.X * ScaledVector2.DrawFactor, mapOriginPosition.Y + mapPosition.Y * map.TileSize.Y * ScaledVector2.DrawFactor); } /// <summary> /// Set the map in use by the tile engine. /// </summary> /// <param name="map">The new map for the tile engine.</param> /// <param name="portal">The portal the party is entering on, if any.</param> public static void SetMap(Map newMap, MapEntry<Portal> portalEntry) { // check the parameter if (newMap == null) { throw new ArgumentNullException("newMap"); } // assign the new map map = newMap; // reset the map origin, which will be recalculate on the first update mapOriginPosition = Vector2.Zero; // move the party to its initial position if (portalEntry == null) { // no portal - use the spawn position partyLeaderPosition.TilePosition = map.SpawnMapPosition; partyLeaderPosition.TileOffset = Vector2.Zero; partyLeaderPosition.Direction = Direction.South; } else { // use the portal provided, which may include automatic movement partyLeaderPosition.TilePosition = portalEntry.MapPosition; partyLeaderPosition.TileOffset = Vector2.Zero; partyLeaderPosition.Direction = portalEntry.Direction; autoPartyLeaderMovement = Vector2.Multiply( new Vector2(map.TileSize.X, map.TileSize.Y), new Vector2( portalEntry.Content.LandingMapPosition.X - partyLeaderPosition.TilePosition.X, portalEntry.Content.LandingMapPosition.Y - partyLeaderPosition.TilePosition.Y)); } } #endregion #region Graphics Data /// <summary> /// The viewport that the tile engine is rendering within. /// </summary> private static Viewport viewport; /// <summary> /// The viewport that the tile engine is rendering within. /// </summary> public static Viewport Viewport { get { return viewport; } set { viewport = value; viewportCenter = new Vector2( viewport.X + viewport.Width / 2f, viewport.Y + viewport.Height / 2f); } } /// <summary> /// The center of the current viewport. /// </summary> private static Vector2 viewportCenter; #endregion #region Party /// <summary> /// The speed of the party leader, in units per second. /// </summary> /// <remarks> /// The movementCollisionTolerance constant should be a multiple of this number. /// </remarks> private const float partyLeaderMovementSpeed = 3f; /// <summary> /// The current position of the party leader. /// </summary> private static PlayerPosition partyLeaderPosition = new PlayerPosition(); public static PlayerPosition PartyLeaderPosition { get { return partyLeaderPosition; } set { partyLeaderPosition = value; } } /// <summary> /// The automatic movement remaining for the party leader. /// </summary> /// <remarks> /// This is typically used for automatic movement when spawning on a map. /// </remarks> private static Vector2 autoPartyLeaderMovement = Vector2.Zero; /// <summary> /// Updates the automatic movement of the party. /// </summary> /// <returns>The automatic movement for this update.</returns> private static Vector2 UpdatePartyLeaderAutoMovement(GameTime gameTime) { // check for any remaining auto-movement if (autoPartyLeaderMovement == Vector2.Zero) { return Vector2.Zero; } // get the remaining-movement direction Vector2 autoMovementDirection = Vector2.Normalize(autoPartyLeaderMovement); // calculate the potential movement vector Vector2 movement = Vector2.Multiply(autoMovementDirection, partyLeaderMovementSpeed); // limit the potential movement vector by the remaining auto-movement movement.X = Math.Sign(movement.X) * MathHelper.Min(Math.Abs(movement.X), Math.Abs(autoPartyLeaderMovement.X)); movement.Y = Math.Sign(movement.Y) * MathHelper.Min(Math.Abs(movement.Y), Math.Abs(autoPartyLeaderMovement.Y)); // remove the movement from the total remaining auto-movement autoPartyLeaderMovement -= movement; return movement; } private static float CalculateMovement(float direction, float speed) { if (direction <= 25 && direction > 0) { direction = 0; } else if (direction >= -25 && direction < 0) { direction = 0; } float movement = direction / speed; return movement; } private static Vector2 TargetPoint; public static void StopMovement() { distanceToFollow = 0f; TargetPoint = Vector2.Zero; } /// <summary> /// Update the user-controlled movement of the party. /// </summary> /// <returns>The controlled movement for this update.</returns> private static Vector2 UpdateUserMovement(GameTime gameTime) { Vector2 desiredMovement = Vector2.Zero; if (InputManager.Gestures.Count > 0) { foreach (var item in InputManager.Gestures) { if (item.GestureType == GestureType.Tap) { if (item.Position != TargetPoint) { TargetPoint = item.Position; distanceToFollow = Vector2.Distance(TargetPoint, partyLeaderPosition.ScreenPosition); } desiredMovement = FollowMovement(TargetPoint); } else if (item.GestureType == GestureType.VerticalDrag || item.GestureType == GestureType.HorizontalDrag) { if (TargetPoint != Vector2.Zero) { StopMovement(); } desiredMovement = FreeMovement(desiredMovement); } } } else { if (TargetPoint == Vector2.Zero) { desiredMovement = FreeMovement(desiredMovement); } else { desiredMovement = FollowMovement(TargetPoint); } } if (desiredMovement != Vector2.Zero) { desiredMovement.Normalize(); desiredMovement *= 3f; } return desiredMovement; } private static Vector2 FreeMovement(Vector2 desiredMovement) { if (InputManager.CurrentTouchState.Count > 0) { TouchLocation gesture = InputManager.CurrentTouchState[InputManager.CurrentTouchState.Count - 1]; Vector2 dir = gesture.Position - partyLeaderPosition.ScreenPosition; desiredMovement.X += CalculateMovement(dir.X, partyLeaderMovementSpeed); desiredMovement.Y += CalculateMovement(dir.Y, partyLeaderMovementSpeed); } Vector2 vec = new Vector2(desiredMovement.X, desiredMovement.Y); return vec; } private static float distanceToFollow; public static Vector2 FollowMovement(Vector2 targetPoint) { if (distanceToFollow < 3) { StopMovement(); return Vector2.Zero; } Vector2 dir = targetPoint - partyLeaderPosition.ScreenPosition; Vector2 vecToMove =new Vector2(CalculateMovement(dir.X, partyLeaderMovementSpeed), CalculateMovement(dir.Y, partyLeaderMovementSpeed)); distanceToFollow -= 3; return vecToMove; } #endregion #region Collision /// <summary> /// The number of pixels that characters should be allowed to move into /// blocking tiles. /// </summary> /// <remarks> /// The partyMovementSpeed constant should cleanly divide this number. /// </remarks> const int movementCollisionTolerance = 12; /// <summary> /// Returns true if the player can move up from their current position. /// </summary> private static bool CanPartyLeaderMoveUp() { // if they're not within the tolerance of the next tile, then this is moot if (partyLeaderPosition.TileOffset.Y > -movementCollisionTolerance) { return true; } // if the player is at the outside left and right edges, // then check the diagonal tiles if (partyLeaderPosition.TileOffset.X < -movementCollisionTolerance) { if (map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X - 1, partyLeaderPosition.TilePosition.Y - 1))) { return false; } } else if (partyLeaderPosition.TileOffset.X > movementCollisionTolerance) { if (map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X + 1, partyLeaderPosition.TilePosition.Y - 1))) { return false; } } // check the tile above the current one return !map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X, partyLeaderPosition.TilePosition.Y - 1)); } /// <summary> /// Returns true if the player can move down from their current position. /// </summary> private static bool CanPartyLeaderMoveDown() { // if they're not within the tolerance of the next tile, then this is moot if (partyLeaderPosition.TileOffset.Y < movementCollisionTolerance) { return true; } // if the player is at the outside left and right edges, // then check the diagonal tiles if (partyLeaderPosition.TileOffset.X < -movementCollisionTolerance) { if (map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X - 1, partyLeaderPosition.TilePosition.Y + 1))) { return false; } } else if (partyLeaderPosition.TileOffset.X > movementCollisionTolerance) { if (map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X + 1, partyLeaderPosition.TilePosition.Y + 1))) { return false; } } // check the tile below the current one return !map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X, partyLeaderPosition.TilePosition.Y + 1)); } /// <summary> /// Returns true if the player can move left from their current position. /// </summary> private static bool CanPartyLeaderMoveLeft() { // if they're not within the tolerance of the next tile, then this is moot if (partyLeaderPosition.TileOffset.X > -movementCollisionTolerance) { return true; } // if the player is at the outside left and right edges, // then check the diagonal tiles if (partyLeaderPosition.TileOffset.Y < -movementCollisionTolerance) { if (map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X - 1, partyLeaderPosition.TilePosition.Y - 1))) { return false; } } else if (partyLeaderPosition.TileOffset.Y > movementCollisionTolerance) { if (map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X - 1, partyLeaderPosition.TilePosition.Y + 1))) { return false; } } // check the tile to the left of the current one return !map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X - 1, partyLeaderPosition.TilePosition.Y)); } /// <summary> /// Returns true if the player can move right from their current position. /// </summary> private static bool CanPartyLeaderMoveRight() { // if they're not within the tolerance of the next tile, then this is moot if (partyLeaderPosition.TileOffset.X < movementCollisionTolerance) { return true; } // if the player is at the outside left and right edges, // then check the diagonal tiles if (partyLeaderPosition.TileOffset.Y < -movementCollisionTolerance) { if (map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X + 1, partyLeaderPosition.TilePosition.Y - 1))) { return false; } } else if (partyLeaderPosition.TileOffset.Y > movementCollisionTolerance) { if (map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X + 1, partyLeaderPosition.TilePosition.Y + 1))) { return false; } } // check the tile to the right of the current one return !map.IsBlocked(new Point( partyLeaderPosition.TilePosition.X + 1, partyLeaderPosition.TilePosition.Y)); } #endregion #region Updating /// <summary> /// Update the tile engine. /// </summary> public static void Update(GameTime gameTime) { // check for auto-movement Vector2 autoMovement = UpdatePartyLeaderAutoMovement(gameTime); // if there is no auto-movement, handle user controls Vector2 userMovement = Vector2.Zero; if (autoMovement == Vector2.Zero) { userMovement = UpdateUserMovement(gameTime); // calculate the desired position if (userMovement != Vector2.Zero) { Point desiredTilePosition = partyLeaderPosition.TilePosition; Vector2 desiredTileOffset = partyLeaderPosition.TileOffset; PlayerPosition.CalculateMovement( Vector2.Multiply(userMovement, 15f ), ref desiredTilePosition, ref desiredTileOffset); // check for collisions or encounters in the new tile if ((partyLeaderPosition.TilePosition != desiredTilePosition) && !MoveIntoTile(desiredTilePosition)) { StopMovement(); userMovement = Vector2.Zero; } } } // move the party Point oldPartyLeaderTilePosition = partyLeaderPosition.TilePosition; partyLeaderPosition.Move(autoMovement + userMovement); // if the tile position has changed, check for random combat if ((autoMovement == Vector2.Zero) && (partyLeaderPosition.TilePosition != oldPartyLeaderTilePosition)) { Session.CheckForRandomCombat(Map.RandomCombat); } // adjust the map origin so that the party is at the center of the viewport mapOriginPosition += viewportCenter - (partyLeaderPosition.ScreenPosition + Session.Party.Players[0].MapSprite.SourceOffset); // make sure the boundaries of the map are never inside the viewport mapOriginPosition.X = MathHelper.Min(mapOriginPosition.X, viewport.X); mapOriginPosition.Y = MathHelper.Min(mapOriginPosition.Y, viewport.Y); mapOriginPosition.X += MathHelper.Max( (viewport.X + viewport.Width) - (mapOriginPosition.X + map.MapDimensions.X * (map.TileSize.X * ScaledVector2.DrawFactor )), 0f); mapOriginPosition.Y += MathHelper.Max( (viewport.Y + viewport.Height - Hud.HudHeight) - (mapOriginPosition.Y + map.MapDimensions.Y * (map.TileSize.Y * ScaledVector2.DrawFactor)), 0f); } /// <summary> /// Performs any actions associated with moving into a new tile. /// </summary> /// <returns>True if the character can move into the tile.</returns> private static bool MoveIntoTile(Point mapPosition) { // if the tile is blocked, then this is simple if (map.IsBlocked(mapPosition)) { System.Diagnostics.Debug.WriteLine("cannot move"); return false; } // check for anything that might be in the tile if (Session.EncounterTile(mapPosition)) { return false; } // nothing stops the party from moving into the tile return true; } #endregion #region Drawing /// <summary> /// Draw the visible tiles in the given map layers. /// </summary> public static void DrawLayers(SpriteBatch spriteBatch, bool drawBase, bool drawFringe, bool drawObject) { // check the parameters if (spriteBatch == null) { throw new ArgumentNullException("spriteBatch"); } if (!drawBase && !drawFringe && !drawObject) { return; } bool lastRowDraw = false; Rectangle destinationRectangle = new Rectangle(0, 0, (int)(map.TileSize.X * ScaledVector2.DrawFactor), (int)(map.TileSize.Y * ScaledVector2.DrawFactor)); for (int y = 0; y < map.MapDimensions.Y ; y++) { for (int x = 0; x < map.MapDimensions.X ; x++) { destinationRectangle.X = (int)mapOriginPosition.X + x * (int)(map.TileSize.X * ScaledVector2.DrawFactor); destinationRectangle.Y = (int)mapOriginPosition.Y + y * (int)(map.TileSize.Y * ScaledVector2.DrawFactor); // If the tile is inside the screen if (CheckVisibility(destinationRectangle)) { Point mapPosition = new Point(x, y); if (drawBase) { Rectangle sourceRectangle = map.GetBaseLayerSourceRectangle(mapPosition); if (sourceRectangle != Rectangle.Empty) { if (y == map.MapDimensions.Y -1) { spriteBatch.Draw(map.Texture, new Vector2( destinationRectangle.X, destinationRectangle.Y), sourceRectangle, Color.White, 0f, Vector2.Zero, new Vector2(1.333f, 2.2f), SpriteEffects.None, 0f); } else { spriteBatch.Draw(map.Texture, new Vector2( destinationRectangle.X, destinationRectangle.Y), sourceRectangle, Color.White, 0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } } } if (drawFringe) { Rectangle sourceRectangle = map.GetFringeLayerSourceRectangle(mapPosition); if (sourceRectangle != Rectangle.Empty) { if (y == map.MapDimensions.Y - 1) { spriteBatch.Draw(map.Texture, new Vector2( destinationRectangle.X, destinationRectangle.Y), sourceRectangle, Color.White, 0f, Vector2.Zero, new Vector2(1.333f, 2.2f), SpriteEffects.None, 0f); } else { spriteBatch.Draw(map.Texture, new Vector2( destinationRectangle.X, destinationRectangle.Y), sourceRectangle, Color.White, 0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } } } if (drawObject) { Rectangle sourceRectangle = map.GetObjectLayerSourceRectangle(mapPosition); if (sourceRectangle != Rectangle.Empty) { if (y == map.MapDimensions.Y -1) { spriteBatch.Draw(map.Texture, new Vector2( destinationRectangle.X, destinationRectangle.Y), sourceRectangle, Color.White, 0f, Vector2.Zero, new Vector2(1.333f, 2.2f), SpriteEffects.None, 0f); } else { spriteBatch.Draw(map.Texture, new Vector2( destinationRectangle.X, destinationRectangle.Y), sourceRectangle, Color.White, 0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } } } } else { if (!lastRowDraw) { y = y -2; lastRowDraw = true; break; } } } } } /// <summary> /// Returns true if the given rectangle is within the viewport. /// </summary> public static bool CheckVisibility(Rectangle screenRectangle) { return ((screenRectangle.X > viewport.X - screenRectangle.Width) && (screenRectangle.Y > viewport.Y - screenRectangle.Height) && (screenRectangle.X < viewport.X + viewport.Width) && (screenRectangle.Y < viewport.Y + viewport.Height)); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdigEngine { using System; using System.Collections.Immutable; using System.IO; using System.Linq; using MarkdigEngine.Extensions; using Markdig; using Markdig.Renderers; using Markdig.Syntax; using Microsoft.DocAsCode.Plugins; using Microsoft.DocAsCode.Common; public class MarkdigMarkdownService : IMarkdownService { public string Name => "markdig"; private readonly MarkdownServiceParameters _parameters; private readonly MarkdownValidatorBuilder _mvb; private readonly MarkdownContext _context; public MarkdigMarkdownService( MarkdownServiceParameters parameters, ICompositionContainer container = null) { _parameters = parameters; _mvb = MarkdownValidatorBuilder.Create(parameters, container); _context = new MarkdownContext( key => _parameters.Tokens.TryGetValue(key, out var value) ? value : null, (code, message, origin, line) => Logger.LogInfo(message, null, InclusionContext.File.ToString(), line?.ToString(), code), (code, message, origin, line) => Logger.LogSuggestion(message, null, InclusionContext.File.ToString(), line?.ToString(), code), (code, message, origin, line) => Logger.LogWarning(message, null, InclusionContext.File.ToString(), line?.ToString(), code), (code, message, origin, line) => Logger.LogError(message, null, InclusionContext.File.ToString(), line?.ToString(), code), ReadFile, GetLink, GetImageLink); } public MarkupResult Markup(string content, string filePath) { return Markup(content, filePath, false); } public MarkupResult Markup(string content, string filePath, bool enableValidation) { if (content == null) { throw new ArgumentNullException(nameof(content)); } if (filePath == null) { throw new ArgumentException("file path can't be null or empty."); } var pipeline = CreateMarkdownPipeline(isInline: false, enableValidation: enableValidation); using (InclusionContext.PushFile((RelativePath)filePath)) { return new MarkupResult { Html = Markdown.ToHtml(content, pipeline), Dependency = InclusionContext.Dependencies.Select(file => (string)(RelativePath)file).ToImmutableArray() }; } } public MarkdownDocument Parse(string content, string filePath) { return Parse(content, filePath, false); } public MarkdownDocument Parse(string content, string filePath, bool isInline) { if (content == null) { throw new ArgumentNullException(nameof(content)); } if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException("file path can't be null or empty."); } var pipeline = CreateMarkdownPipeline(isInline, enableValidation: false); using (InclusionContext.PushFile((RelativePath)filePath)) { var document = Markdown.Parse(content, pipeline); document.SetData("filePath", filePath); return document; } } public MarkupResult Render(MarkdownDocument document) { return Render(document, false); } public MarkupResult Render(MarkdownDocument document, bool isInline) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (!(document.GetData("filePath") is string filePath)) { throw new ArgumentNullException("file path can't be found in AST."); } var pipeline = CreateMarkdownPipeline(isInline, enableValidation: false); using (InclusionContext.PushFile((RelativePath)filePath)) { using var writer = new StringWriter(); var renderer = new HtmlRenderer(writer); pipeline.Setup(renderer); renderer.Render(document); writer.Flush(); return new MarkupResult { Html = writer.ToString(), Dependency = InclusionContext.Dependencies.Select(file => (string)(RelativePath)file).ToImmutableArray() }; } } private MarkdownPipeline CreateMarkdownPipeline(bool isInline, bool enableValidation) { object enableSourceInfoObj = null; _parameters?.Extensions?.TryGetValue("EnableSourceInfo", out enableSourceInfoObj); var enableSourceInfo = !(enableSourceInfoObj is bool enabled) || enabled; var builder = new MarkdownPipelineBuilder(); builder.UseDocfxExtensions(_context); builder.Extensions.Insert(0, new YamlHeaderExtension(_context)); if (enableSourceInfo) { builder.UseLineNumber(file => ((RelativePath)file).RemoveWorkingFolder()); } if (enableValidation) { builder.Extensions.Add(new ValidationExtension(_mvb, _context)); } if (isInline) { builder.UseInlineOnly(); } return builder.Build(); } private (string content, object file) ReadFile(string path, MarkdownObject origin) { if (!PathUtility.IsRelativePath(path)) { return (null, null); } var currentFilePath = ((RelativePath)InclusionContext.File).GetPathFromWorkingFolder(); var includedFilePath = ((RelativePath)path).BasedOn(currentFilePath); var includedFilePathWithoutWorkingFolder = includedFilePath.RemoveWorkingFolder(); var parentFileDirectoryToDocset = Path.GetDirectoryName(Path.Combine(_parameters.BasePath, ((RelativePath)InclusionContext.RootFile).RemoveWorkingFolder())); ReportDependency(includedFilePathWithoutWorkingFolder, parentFileDirectoryToDocset); if (!EnvironmentContext.FileAbstractLayer.Exists(includedFilePathWithoutWorkingFolder)) { return (null, null); } var content = EnvironmentContext.FileAbstractLayer.ReadAllText(includedFilePathWithoutWorkingFolder); return (content, includedFilePath); } private static string GetLink(string path, MarkdownObject origin) { if (InclusionContext.IsInclude && RelativePath.IsRelativePath(path) && PathUtility.IsRelativePath(path) && !RelativePath.IsPathFromWorkingFolder(path) && !path.StartsWith("#", StringComparison.Ordinal)) { return ((RelativePath)InclusionContext.File + (RelativePath)path).GetPathFromWorkingFolder(); } return path; } private string GetImageLink(string href, MarkdownObject origin, string? altText) => GetLink(href, origin); private void ReportDependency(RelativePath filePathToDocset, string parentFileDirectoryToDocset) { var expectedPhysicalPath = EnvironmentContext.FileAbstractLayer.GetExpectedPhysicalPath(filePathToDocset); foreach (var physicalPath in expectedPhysicalPath) { var fallbackFileRelativePath = PathUtility.MakeRelativePath(parentFileDirectoryToDocset, physicalPath); InclusionContext.PushDependency((RelativePath)fallbackFileRelativePath); } } } }
// 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 System.IO; namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc { public class PduBuilder { public DynamicVCPDU ToPdu(byte[] data) { if (null == regsiteredPDUs) { regsiteredPDUs = new List<DynamicVCPDU>(); RegisterDefaultPdus(); } DynamicVCPDU res = null; foreach (DynamicVCPDU pdu in regsiteredPDUs) { if (PduMarshaler.Unmarshal(data, pdu)) { res = pdu; break; } } if (res == null) { DynamicVCException.Throw("UnknownDynamicVCPDU was not registered."); } return res; } protected List<DynamicVCPDU> regsiteredPDUs = null; protected virtual void RegisterDefaultPdus() { } public void RegisterPdu(DynamicVCPDU pdu) { if (null == regsiteredPDUs) { regsiteredPDUs = new List<DynamicVCPDU>(); } regsiteredPDUs.Add(pdu); } public byte[] ToRawData(DynamicVCPDU pdu) { return PduMarshaler.Marshal(pdu); } public UnknownDynamicVCPDU CreateUnknownPdu(byte[] rawData) { return new UnknownDynamicVCPDU(rawData); } public CapsVer1ReqDvcPdu CreateCapsV1ReqPdu() { return new CapsVer1ReqDvcPdu(); } public CapsVer2ReqDvcPdu CreateCapsV2ReqPdu( ushort priorityCharge0, ushort priorityCharge1, ushort priorityCharge2, ushort priorityCharge3 ) { return new CapsVer2ReqDvcPdu( priorityCharge0, priorityCharge1, priorityCharge2, priorityCharge3 ); } public CapsVer2ReqDvcPdu CreateCapsV2ReqPdu() { return new CapsVer2ReqDvcPdu( 936, // 70% 3276, // 20% 9362, // 7% 21845 // 3% ); } public CapsVer3ReqDvcPdu CreateCapsV3ReqPdu( ushort priorityCharge0, ushort priorityCharge1, ushort priorityCharge2, ushort priorityCharge3 ) { return new CapsVer3ReqDvcPdu( priorityCharge0, priorityCharge1, priorityCharge2, priorityCharge3 ); } public CapsVer3ReqDvcPdu CreateCapsV3ReqPdu() { return new CapsVer3ReqDvcPdu( 936, // 70% 3276, // 20% 9362, // 7% 21845 // 3% ); } public CapsRespDvcPdu CreateCapsRespPdu(ushort version) { return new CapsRespDvcPdu(version); } public CreateReqDvcPdu CreateCreateReqDvcPdu(ushort priority, uint channelId, string channelName) { return new CreateReqDvcPdu(priority, channelId, channelName); } public CreateRespDvcPdu CreateCreateRespDvcPdu(uint channelId, int creationStatus) { return new CreateRespDvcPdu(channelId, creationStatus); } public CloseDvcPdu CreateCloseDvcPdu(uint channelId) { return new CloseDvcPdu(channelId); } public DataDvcBasePdu[] CreateDataPdu(uint channelId, byte[] data, int channelChunkLength) { DataFirstDvcPdu first = new DataFirstDvcPdu(channelId, (uint)data.Length, null); DataDvcPdu other = new DataDvcPdu(channelId, null); int firstNonDataSize = first.GetNonDataSize(); int otherNonDataSize = other.GetNonDataSize(); if (data.Length <= channelChunkLength - otherNonDataSize) { other.Data = data; return new DataDvcBasePdu[] { other }; } // TODO: need to test for the following code byte[] buf = new byte[channelChunkLength - firstNonDataSize]; MemoryStream ms = new MemoryStream(data); List<DataDvcBasePdu> pdus = new List<DataDvcBasePdu>(); if (channelChunkLength - firstNonDataSize != ms.Read(buf, 0, channelChunkLength - firstNonDataSize)) { DynamicVCException.Throw("Cannot create correct data PDUs."); } first.Data = buf; pdus.Add(first); buf = new byte[channelChunkLength - otherNonDataSize]; // TODO: Check this logic int readLen = 0; readLen = ms.Read(buf, 0, channelChunkLength - otherNonDataSize); while (readLen == channelChunkLength - otherNonDataSize) { pdus.Add(new DataDvcPdu(channelId, buf)); buf = new byte[channelChunkLength - otherNonDataSize]; readLen = ms.Read(buf, 0, channelChunkLength - otherNonDataSize); } if (readLen > 0) { byte[] newBuf = new byte[readLen]; Array.Copy(buf, newBuf, readLen); pdus.Add(new DataDvcPdu(channelId, newBuf)); } return pdus.ToArray(); } } /// <summary> /// This builder is used to decode all PDU types possibly received by the server role. /// </summary> public class ServerDecodingPduBuilder : PduBuilder { protected override void RegisterDefaultPdus() { regsiteredPDUs.Add(new DataFirstDvcPdu()); regsiteredPDUs.Add(new DataDvcPdu()); // The DYNVC_CAPS_RSP (section 2.2.1.2) PDU is sent by the DVC client manager to // indicate the protocol version level it supports. regsiteredPDUs.Add(new CapsRespDvcPdu()); // The DYNVC_CREATE_RSP (section 2.2.2.2) PDU is sent by the DVC client manager to // indicate the status of the client dynamic virtual channel create operation. regsiteredPDUs.Add(new CreateRespDvcPdu()); regsiteredPDUs.Add(new CloseDvcPdu()); regsiteredPDUs.Add(new UnknownDynamicVCPDU()); } } /// <summary> /// This builder is used to decode all PDU types possibly received by the client role. /// </summary> public class ClientDecodingPduBuilder : PduBuilder { protected override void RegisterDefaultPdus() { regsiteredPDUs.Add(new DataFirstDvcPdu()); regsiteredPDUs.Add(new DataDvcPdu()); // The DYNVC_CAPS_VERSION1 (section 2.2.1.1.1) PDU is sent by the DVC server // manager to indicate that it supports version 1 of the Remote Desktop Protocol: // Dynamic Channel Virtual Channel Extension.<1> regsiteredPDUs.Add(new CapsVer1ReqDvcPdu()); // The DYNVC_CAPS_VERSION2 (section 2.2.1.1.2) PDU is sent by the DVC server manager // to indicate that it supports version 2 of the Remote Desktop Protocol: Dynamic // Channel Virtual Channel Extension.<3> regsiteredPDUs.Add(new CapsVer2ReqDvcPdu()); // The DYNVC_CREATE_REQ (section 2.2.2.1) PDU is sent by the DVC server manager // to the DVC client manager to request that a channel be opened. regsiteredPDUs.Add(new CreateReqDvcPdu()); regsiteredPDUs.Add(new CloseDvcPdu()); regsiteredPDUs.Add(new UnknownDynamicVCPDU()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Xunit; using System.Collections.Immutable; using Microsoft.DotNet.CodeFormatting.Rules; namespace Microsoft.DotNet.CodeFormatting.Tests { /// <summary> /// A test which runs all rules on a given piece of code /// </summary> public sealed class CombinationTest : CodeFormattingTestBase { private FormattingEngineImplementation _formattingEngine; public CombinationTest() { _formattingEngine = (FormattingEngineImplementation)FormattingEngine.Create(); _formattingEngine.CopyrightHeader = ImmutableArray.Create("// header"); _formattingEngine.AllowTables = true; _formattingEngine.FormatLogger = new EmptyFormatLogger(); _formattingEngine.PreprocessorConfigurations = ImmutableArray<string[]>.Empty; } private void DisableAllRules() { foreach (var rule in _formattingEngine.AllRules) { _formattingEngine.ToggleRuleEnabled(rule, enabled: false); } } private void ToggleRule(string name, bool enabled) { var rule = _formattingEngine.AllRules.Where(x => x.Name == name).Single(); _formattingEngine.ToggleRuleEnabled(rule, enabled); } protected override async Task<Document> RewriteDocumentAsync(Document document) { var solution = await _formattingEngine.FormatCoreAsync( document.Project.Solution, new[] { document.Id }, CancellationToken.None); return solution.GetDocument(document.Id); } [Fact] public void FieldUse() { var text = @" class C { int field; void M() { N(this.field); } }"; var expected = @" internal class C { private int _field; private void M() { N(_field); } }"; Verify(text, expected, runFormatter: false); } /// <summary> /// Ensure the engine respects the rule map /// </summary> [Fact] public void FieldOnly() { var text = @" class C { int field; void M() { N(this.field); } }"; var expected = @" class C { int _field; void M() { N(this._field); } }"; DisableAllRules(); ToggleRule(PrivateFieldNamingRule.Name, enabled: true); Verify(text, expected, runFormatter: false); } [Fact] public void FieldNameExcluded() { var text = @" class C { int field; void M() { N(this.field); } }"; var expected = @" internal class C { private int field; private void M() { N(field); } }"; ToggleRule(PrivateFieldNamingRule.Name, enabled: false); Verify(text, expected, runFormatter: false); } [Fact] public void FieldAssignment() { var text = @" class C { int field; void M() { this.field = 42; } }"; var expected = @" internal class C { private int _field; private void M() { _field = 42; } }"; Verify(text, expected, runFormatter: false); } [Fact] public void PreprocessorSymbolNotDefined() { var text = @" class C { #if DOG void M() { } #endif }"; var expected = @" internal class C { #if DOG void M() { } #endif }"; Verify(text, expected, runFormatter: false); } [Fact] public void PreprocessorSymbolDefined() { var text = @" internal class C { #if DOG internal void M() { } #endif }"; var expected = @" internal class C { #if DOG internal void M() { } #endif }"; _formattingEngine.PreprocessorConfigurations = ImmutableArray.CreateRange(new[] { new[] { "DOG" } }); Verify(text, expected, runFormatter: false); } [Fact] public void TableCode() { var text = @" class C { void G() { } #if !DOTNET_FORMATTER void M() { } #endif }"; var expected = @" internal class C { private void G() { } #if !DOTNET_FORMATTER void M() { } #endif }"; Verify(text, expected, runFormatter: false); } /// <summary> /// Make sure the code which deals with additional configurations respects the /// table exception. /// </summary> [Fact] public void TableCodeAndAdditionalConfiguration() { var text = @" class C { #if TEST void G(){ } #endif #if !DOTNET_FORMATTER void M() { } #endif }"; var expected = @" internal class C { #if TEST void G() { } #endif #if !DOTNET_FORMATTER void M() { } #endif }"; _formattingEngine.PreprocessorConfigurations = ImmutableArray.CreateRange(new[] { new[] { "TEST" } }); Verify(text, expected, runFormatter: false); } [Fact] public void WhenBlocks() { var source = @" internal class C { private void M() { try { if(x){ G(); } } catch(Exception e)when(H(e)) { } } }"; var expected = @" internal class C { private void M() { try { if (x) { G(); } } catch (Exception e) when (H(e)) { } } }"; Verify(source, expected, runFormatter: false); } [Fact] public void CSharpHeaderCorrectAfterMovingUsings() { var source = @" namespace Microsoft.Build.UnitTests { using System; using System.Reflection; public class Test { public void RequiredRuntimeAttribute() {} } }"; var expected = @" using System; using System.Reflection; namespace Microsoft.Build.UnitTests { public class Test { public void RequiredRuntimeAttribute() { } } }"; Verify(source, expected); } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using HETSAPI.Models; namespace HETSAPI.Models { /// <summary> /// Attachments that are required as part of the Rental Requests /// </summary> [MetaDataExtension (Description = "Attachments that are required as part of the Rental Requests")] public partial class RentalRequestAttachment : AuditableEntity, IEquatable<RentalRequestAttachment> { /// <summary> /// Default constructor, required by entity framework /// </summary> public RentalRequestAttachment() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="RentalRequestAttachment" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for a RentalRequestAttachment (required).</param> /// <param name="RentalRequest">A foreign key reference to the system-generated unique identifier for a Rental Request (required).</param> /// <param name="Attachment">The name&amp;#x2F;type attachment needed as part of the fulfillment of the request (required).</param> public RentalRequestAttachment(int Id, RentalRequest RentalRequest, string Attachment) { this.Id = Id; this.RentalRequest = RentalRequest; this.Attachment = Attachment; } /// <summary> /// A system-generated unique identifier for a RentalRequestAttachment /// </summary> /// <value>A system-generated unique identifier for a RentalRequestAttachment</value> [MetaDataExtension (Description = "A system-generated unique identifier for a RentalRequestAttachment")] public int Id { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a Rental Request /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a Rental Request</value> [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Rental Request")] public RentalRequest RentalRequest { get; set; } /// <summary> /// Foreign key for RentalRequest /// </summary> [ForeignKey("RentalRequest")] [JsonIgnore] [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Rental Request")] public int? RentalRequestId { get; set; } /// <summary> /// The name&#x2F;type attachment needed as part of the fulfillment of the request /// </summary> /// <value>The name&#x2F;type attachment needed as part of the fulfillment of the request</value> [MetaDataExtension (Description = "The name&#x2F;type attachment needed as part of the fulfillment of the request")] [MaxLength(150)] public string Attachment { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RentalRequestAttachment {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" RentalRequest: ").Append(RentalRequest).Append("\n"); sb.Append(" Attachment: ").Append(Attachment).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((RentalRequestAttachment)obj); } /// <summary> /// Returns true if RentalRequestAttachment instances are equal /// </summary> /// <param name="other">Instance of RentalRequestAttachment to be compared</param> /// <returns>Boolean</returns> public bool Equals(RentalRequestAttachment other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.RentalRequest == other.RentalRequest || this.RentalRequest != null && this.RentalRequest.Equals(other.RentalRequest) ) && ( this.Attachment == other.Attachment || this.Attachment != null && this.Attachment.Equals(other.Attachment) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); if (this.RentalRequest != null) { hash = hash * 59 + this.RentalRequest.GetHashCode(); } if (this.Attachment != null) { hash = hash * 59 + this.Attachment.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(RentalRequestAttachment left, RentalRequestAttachment right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(RentalRequestAttachment left, RentalRequestAttachment right) { return !Equals(left, right); } #endregion Operators } }
/* * Copyright (c) 2015 Jeff Lindberg * * 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Clouseau { public class Search { private List<InstanceRefList> resultsList; private ICollection<Criterion> crit = new HashSet<Criterion>(); private Pipeline pipeline; public Search(Pipeline pipeline) { this.pipeline = pipeline; } public void DoSearch() { DoSearch(null); } /// <summary> /// Search restricted to stations with the specified role. /// </summary> /// <param name="role">if null, not restricted to any role</param> public void DoSearch(string role) { if (pipeline == null) { throw new Exception("Pipeline not set"); } // clear results list from previous search //_resultsList = new List<InstanceRefList>(); // Unnecessary now that we're populating a tempResultsList this.Error = null; // DONE 5/23/2013 JbL: Use multiple threads for parallel processing and faster response. // with a thread-safe _resultsList.Add(irl); -- using a thread safe collection type // // Originally, when I tried this simply, I got file system access errors (network path), // meaning it probably had UNC connections closed randomly while other stations were still using them. // added code to manage a pool of UNC connections and make sure they're kept open during the search process. var tempResultsList = new ConcurrentBag<InstanceRefList>(); // Thread safe Parallel.ForEach(pipeline.Stations, s => SearchStation(role, s, tempResultsList)); // put results lists in same original order as stations var orderedByStations = from s in pipeline.Stations join irl in tempResultsList on s equals irl.Station select irl; resultsList = orderedByStations.ToList(); // populate Public Fields try { foreach (Station s in pipeline.Stations) { // TODO Public Fields - call this on stations not included in search, but still configured with public fields s.SetPublicFieldValues(s.PublicFields, resultsList); } } catch (Exception ex) { this.Error = "Error populating public fields: " + Util.ExceptionMessageIncludingInners(ex); } // TODO PublicFields searching - filter all results by public field criteria // for any criteria field names == public field names } private void SearchStation(string role, Station s, ConcurrentBag<InstanceRefList> results) { // TODO first check if the station supports the object type ??? // or is this part of criteria? e.g. TYPE = 'ORDER' InstanceRefList irl = null; try { s.CheckSupportedCriteria(crit); // will throw exception if not supported if (!UnsupportedCustomFields(s) && (string.IsNullOrEmpty(role) || s.HasRole(role))) irl = DoSearchWithRetry(s); } catch (StationUnsupportedCriterionException ex) { irl = new InstanceRefList(s); irl.Error = "Station skipped: " + Util.ExceptionMessageIncludingInners(ex); } catch (Exception ex) { irl = new InstanceRefList(s); irl.Error = Util.ExceptionMessageIncludingInners(ex); } finally { if (irl != null) results.Add(irl); } } private bool UnsupportedCustomFields(Station s) { var stationCustomFieldNames = s.SearchableFields.Select(sf => sf.Name).ToList(); var searchFieldNames = crit.Select(sf => sf.FieldName); var usedCustomFields = pipeline.ConfiguredSearchableCustomFields .Where(c => searchFieldNames.Contains(c.Name)); foreach (var ucf in usedCustomFields) { if (!stationCustomFieldNames.Contains(ucf.Name)) // silently ignore instead of throwing exception //throw new StationUnsupportedCriterionException( //string.Format("Unsupported custom field: {0} ({1})", ucf.Label, ucf.Name)); return true; } return false; // all fields are OK } private InstanceRefList DoSearchWithRetry(Station s) { InstanceRefList irl; int maxTries = 4; // TODO get from station config file, or default? for (int tries = 1; ; tries++) { try { irl = s.DoSearch(crit); break; } catch (Exception ex) { if (tries >= maxTries || !IsRetriedException(ex, s)) throw; // else try again } } return irl; } private bool IsRetriedException(Exception ex, Station station) { // TODO get list of exception texts from station string[] retryExceptions = { "unexpected network error", // any file folders, maybe any station "file sharing violation", "error occurred while reading from the store provider's data reader" }; var query = from r in retryExceptions where ex.Message.Contains(r) select r; if (query.Any()) return true; // TODO could check actual exception types too return false; } public List<InstanceRefList> ResultsList { get { return resultsList; } } public void ClearResults() { resultsList = null; } public ICollection<Criterion> Crit { get { return crit; } set { this.crit = value; } } public Pipeline Pipeline { get { return pipeline; } } /// <summary> /// Return number of instance results found by search /// </summary> public int Count { get { if (ResultsList != null) { var q = from irl in this.ResultsList select irl.List.Count; return q.Sum(); } else return 0; } } private string error; /// <summary> /// To clear the error, set to null. /// </summary> public string Error { get { return error; } set { this.error = value; } } public bool HasError { get { return error != null; } } /// <summary> /// Return all instance references in one flat list. /// Note: Loses the notion of which station the instance came from. /// </summary> public List<InstanceRef> AllInstanceRefs { get { List<InstanceRef> list = new List<InstanceRef>(); foreach (InstanceRefList irl in ResultsList) { list.AddRange(irl.List); } return list; } } /// <summary> /// Return all instances in one flat list. /// Note: Loses the notion of which station the instance came from. /// </summary> public List<Instance> AllInstances { get { List<Instance> list = new List<Instance>(); foreach (InstanceRefList irl in ResultsList) { list.AddRange(irl.InstanceList); } return list; } } /// <summary> /// Perform a search using the specified criteria. /// But don't change the criteria stored in the Search object. /// </summary> /// <param name="newCrit"></param> /// <param name="role">if null, not restricted to any role</param> /// <returns>List of Instances</returns> public List<Instance> DoSearchWithSpecifiedCriteria(ICollection<Criterion> newCrit, string role) { ICollection<Criterion> origCrit = this.Crit; // remember the original criteria this.Crit = newCrit; DoSearch(role); this.Crit = origCrit; // restore to original return this.AllInstances; } /// <summary> /// Perform search using the existing criteria plus an additional temporary criterion. /// </summary> /// <param name="c">Additional criterion for this search only</param> /// <param name="role">if null, not restricted to any role</param> public List<Instance> DoSearchWithAdditionalCriterion(Criterion c, string role) { ICollection<Criterion> newCrit = new List<Criterion>(this.Crit); // make copy of the current criteria newCrit.Add(c); return DoSearchWithSpecifiedCriteria(newCrit, role); } /// <summary> /// Perform search using the specified temporary criterion. /// But put the Search object's Criteria back to its original set. /// </summary> /// <param name="c">Only criterion to be used for this search</param> /// <param name="role">if null, not restricted to any role</param> public List<Instance> DoSearchWithSpecifiedCriterion(Criterion c, string role) { ICollection<Criterion> newCrit = new List<Criterion>(); newCrit.Add(c); return DoSearchWithSpecifiedCriteria(newCrit, role); } } }
// <copyright file="PushingCollectionBase{T}.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using IX.Abstractions.Collections; using IX.StandardExtensions.Contracts; using IX.StandardExtensions.Threading; using JetBrains.Annotations; using Constants = IX.Abstractions.Collections.Constants; // ReSharper disable once CheckNamespace namespace IX.System.Collections.Generic; /// <summary> /// A base class for pushing collections. /// </summary> /// <typeparam name="T">The type of item in the pushing collection.</typeparam> /// <seealso cref="ReaderWriterSynchronizedBase" /> /// <seealso cref="ICollection" /> [DataContract( Namespace = Constants.DataContractNamespace, Name = "PushOutQueueOf{0}")] [PublicAPI] [SuppressMessage( "Design", "CA1010:Generic interface should also be implemented", Justification = "This is not needed, as we expect derived classes to implement it according to their own needs.")] [SuppressMessage( "Naming", "CA1710:Identifiers should have correct suffix", Justification = "Analyzer misidentified issue.")] public abstract class PushingCollectionBase<T> : ReaderWriterSynchronizedBase, ICollection { #region Internal state /// <summary> /// The internal container. /// </summary> [DataMember(Name = "Items")] private List<T> internalContainer; /// <summary> /// The limit. /// </summary> private int limit; #endregion #region Constructors and destructors #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PushingCollectionBase{T}" /> class. /// </summary> /// <param name="limit">The limit.</param> /// <exception cref="LimitArgumentNegativeException"> /// <paramref name="limit" /> is a negative /// integer. /// </exception> protected PushingCollectionBase(int limit) { if (limit < 0) { throw new LimitArgumentNegativeException(nameof(limit)); } this.limit = limit; this.internalContainer = new List<T>(); } #endregion #endregion #region Properties and indexers /// <summary> /// Gets the number of elements in the push-out queue. /// </summary> /// <value>The current element count.</value> public int Count { get { this.RequiresNotDisposed(); using (this.ReadLock()) { return this.internalContainer.Count; } } } /// <summary> /// Gets a value indicating whether this pushing collection is empty. /// </summary> /// <value> /// <c>true</c> if this pushing collection is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty => this.Count == 0; /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection" /> is synchronized /// (thread safe). /// </summary> /// <value><see langword="true" /> if this instance is synchronized; otherwise, <see langword="false" />.</value> bool ICollection.IsSynchronized => ((ICollection)this.internalContainer).IsSynchronized; /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection" />. /// </summary> /// <value>The synchronize root.</value> object ICollection.SyncRoot => ((ICollection)this.internalContainer).SyncRoot; /// <summary> /// Gets or sets the number of items in the push-down stack. /// </summary> [DataMember] public int Limit { get => this.limit; set { this.RequiresNotDisposed(); if (value < 0) { throw new LimitArgumentNegativeException(); } using (this.WriteLock()) { this.limit = value; if (value != 0) { while (this.internalContainer.Count > value) { this.internalContainer.RemoveAt(0); } } else { this.internalContainer.Clear(); } } } } /// <summary> /// Gets the internal container. /// </summary> /// <value> /// The internal container. /// </value> protected List<T> InternalContainer => this.internalContainer; #endregion #region Methods #region Interface implementations /// <summary> /// Copies the elements of the <see cref="PushingCollectionBase{T}" /> to an <see cref="Array" />, /// starting at a particular <see cref="Array" /> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array" /> that is the destination of the elements copied /// from <see cref="PushingCollectionBase{T}" />. The <see cref="Array" /> must have zero-based /// indexing. /// </param> /// <param name="index">The zero-based index in <paramref name="array" /> at which copying begins.</param> public void CopyTo( Array array, int index) { this.RequiresNotDisposed(); using (this.ReadLock()) { ((ICollection)this.internalContainer).CopyTo( array, index); } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the collection.</returns> [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "Unavoidable.")] [ExcludeFromCodeCoverage] IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); #endregion /// <summary> /// Clears the observable stack. /// </summary> public void Clear() { this.RequiresNotDisposed(); using (this.WriteLock()) { this.internalContainer.Clear(); } } /// <summary> /// Checks whether or not a certain item is in the stack. /// </summary> /// <param name="item">The item to check for.</param> /// <returns><see langword="true" /> if the item was found, <see langword="false" /> otherwise.</returns> public bool Contains(T item) { this.RequiresNotDisposed(); using (this.ReadLock()) { return this.internalContainer.Contains(item); } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An enumerator that can be used to iterate through the collection.</returns> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "We need this allocation here.")] [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "We're returning a class enumerator, so we're expecting an allocation anyway.")] public IEnumerator<T> GetEnumerator() => AtomicEnumerator<T>.FromCollection( this.internalContainer, this.ReadLock); /// <summary> /// Copies all elements of the stack to a new array. /// </summary> /// <returns>An array containing all items in the stack.</returns> public T[] ToArray() { this.RequiresNotDisposed(); using (this.ReadLock()) { return this.internalContainer.ToArray(); } } #region Disposable /// <summary> /// Disposes in the managed context. /// </summary> protected override void DisposeManagedContext() { base.DisposeManagedContext(); Interlocked.Exchange( ref this.internalContainer, null!) ?.Clear(); } #endregion /// <summary> /// Appends the specified item to this pushing collection. /// </summary> /// <param name="item">The item to append.</param> protected void Append(T item) { this.RequiresNotDisposed(); if (this.Limit == 0) { return; } using (this.WriteLock()) { if (this.InternalContainer.Count == this.Limit) { this.InternalContainer.RemoveAt(0); } this.InternalContainer.Add(item); } } /// <summary> /// Appends the specified items to this pushing collection. /// </summary> /// <param name="items">The items to append.</param> protected void Append(T[] items) { // Validate input this.RequiresNotDisposed(); Requires.NotNull( items, nameof(items)); // Check disabled collection if (this.Limit == 0) { return; } // Lock on write using (this.WriteLock()) { foreach (T item in items) { this.InternalContainer.Add(item); if (this.InternalContainer.Count == this.Limit + 1) { this.InternalContainer.RemoveAt(0); } } } } /// <summary> /// Appends the specified items to the pushing collection. /// </summary> /// <param name="items">The items to append.</param> /// <param name="startIndex">The start index in the array to begin taking items from.</param> /// <param name="count">The number of items to append.</param> protected void Append( T[] items, int startIndex, int count) { // Validate input this.RequiresNotDisposed(); Requires.NotNull( items, nameof(items)); Requires.ValidArrayRange( in startIndex, in count, items, nameof(items)); // Check disabled collection var innerLimit = this.Limit; if (innerLimit == 0) { return; } var copiedItems = new ReadOnlySpan<T>( items, startIndex, count); // Lock on write using (this.WriteLock()) { // Add all items List<T> innerInternalContainer = this.InternalContainer; foreach (T item in copiedItems) { innerInternalContainer.Add(item); if (innerInternalContainer.Count == innerLimit + 1) { innerInternalContainer.RemoveAt(0); } } } } #endregion }
using UnityEditor; using UnityEditorInternal; using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Rotorz.ReorderableList; using System.IO; using System.Reflection; namespace Fungus { [CustomEditor (typeof(Block))] public class BlockEditor : Editor { protected class SetEventHandlerOperation { public Block block; public Type eventHandlerType; } protected class AddCommandOperation { public Block block; public Type commandType; public int index; } public static List<Action> actionList = new List<Action>(); protected Texture2D upIcon; protected Texture2D downIcon; protected Texture2D addIcon; protected Texture2D duplicateIcon; protected Texture2D deleteIcon; protected virtual void OnEnable() { upIcon = Resources.Load("Icons/up") as Texture2D; downIcon = Resources.Load("Icons/down") as Texture2D; addIcon = Resources.Load("Icons/add") as Texture2D; duplicateIcon = Resources.Load("Icons/duplicate") as Texture2D; deleteIcon = Resources.Load("Icons/delete") as Texture2D; } public virtual void DrawBlockName(Flowchart flowchart) { serializedObject.Update(); SerializedProperty blockNameProperty = serializedObject.FindProperty("blockName"); Rect blockLabelRect = new Rect(45, 5, 120, 16); EditorGUI.LabelField(blockLabelRect, new GUIContent("Block Name")); Rect blockNameRect = new Rect(45, 21, 180, 16); EditorGUI.PropertyField(blockNameRect, blockNameProperty, new GUIContent("")); // Ensure block name is unique for this Flowchart Block block = target as Block; string uniqueName = flowchart.GetUniqueBlockKey(blockNameProperty.stringValue, block); if (uniqueName != block.blockName) { blockNameProperty.stringValue = uniqueName; } serializedObject.ApplyModifiedProperties(); } public virtual void DrawBlockGUI(Flowchart flowchart) { serializedObject.Update(); // Execute any queued cut, copy, paste, etc. operations from the prevous GUI update // We need to defer applying these operations until the following update because // the ReorderableList control emits GUI errors if you clear the list in the same frame // as drawing the control (e.g. select all and then delete) if (Event.current.type == EventType.Layout) { foreach (Action action in actionList) { if (action != null) { action(); } } actionList.Clear(); } Block block = target as Block; SerializedProperty commandListProperty = serializedObject.FindProperty("commandList"); if (block == flowchart.selectedBlock) { SerializedProperty descriptionProp = serializedObject.FindProperty("description"); EditorGUILayout.PropertyField(descriptionProp); DrawEventHandlerGUI(flowchart); UpdateIndentLevels(block); // Make sure each command has a reference to its parent block foreach (Command command in block.commandList) { if (command == null) // Will be deleted from the list later on { continue; } command.parentBlock = block; } ReorderableListGUI.Title("Commands"); CommandListAdaptor adaptor = new CommandListAdaptor(commandListProperty, 0); adaptor.nodeRect = block.nodeRect; ReorderableListFlags flags = ReorderableListFlags.HideAddButton | ReorderableListFlags.HideRemoveButtons | ReorderableListFlags.DisableContextMenu; if (block.commandList.Count == 0) { EditorGUILayout.HelpBox("Press the + button below to add a command to the list.", MessageType.Info); } else { ReorderableListControl.DrawControlFromState(adaptor, null, flags); } // EventType.contextClick doesn't register since we moved the Block Editor to be inside // a GUI Area, no idea why. As a workaround we just check for right click instead. if (Event.current.type == EventType.mouseUp && Event.current.button == 1) { ShowContextMenu(); Event.current.Use(); } if (GUIUtility.keyboardControl == 0) //Only call keyboard shortcuts when not typing in a text field { Event e = Event.current; // Copy keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Copy") { if (flowchart.selectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Copy") { actionList.Add(Copy); e.Use(); } // Cut keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Cut") { if (flowchart.selectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Cut") { actionList.Add(Cut); e.Use(); } // Paste keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Paste") { CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); if (commandCopyBuffer.HasCommands()) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Paste") { actionList.Add(Paste); e.Use(); } // Duplicate keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Duplicate") { if (flowchart.selectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Duplicate") { actionList.Add(Copy); actionList.Add(Paste); e.Use(); } // Delete keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "Delete") { if (flowchart.selectedCommands.Count > 0) { e.Use(); } } if (e.type == EventType.ExecuteCommand && e.commandName == "Delete") { actionList.Add(Delete); e.Use(); } // SelectAll keyboard shortcut if (e.type == EventType.ValidateCommand && e.commandName == "SelectAll") { e.Use(); } if (e.type == EventType.ExecuteCommand && e.commandName == "SelectAll") { actionList.Add(SelectAll); e.Use(); } } } // Remove any null entries in the command list. // This can happen when a command class is deleted or renamed. for (int i = commandListProperty.arraySize - 1; i >= 0; --i) { SerializedProperty commandProperty = commandListProperty.GetArrayElementAtIndex(i); if (commandProperty.objectReferenceValue == null) { commandListProperty.DeleteArrayElementAtIndex(i); } } serializedObject.ApplyModifiedProperties(); } public virtual void DrawButtonToolbar() { GUILayout.BeginHorizontal(); // Previous Command if ((Event.current.type == EventType.keyDown) && (Event.current.keyCode == KeyCode.PageUp)) { SelectPrevious(); GUI.FocusControl("dummycontrol"); Event.current.Use(); } // Next Command if ((Event.current.type == EventType.keyDown) && (Event.current.keyCode == KeyCode.PageDown)) { SelectNext(); GUI.FocusControl("dummycontrol"); Event.current.Use(); } if (GUILayout.Button(upIcon)) { SelectPrevious(); } // Down Button if (GUILayout.Button(downIcon)) { SelectNext(); } GUILayout.FlexibleSpace(); // Add Button if (GUILayout.Button(addIcon)) { ShowCommandMenu(); } // Duplicate Button if (GUILayout.Button(duplicateIcon)) { Copy(); Paste(); } // Delete Button if (GUILayout.Button(deleteIcon)) { Delete(); } GUILayout.EndHorizontal(); } protected virtual void DrawEventHandlerGUI(Flowchart flowchart) { // Show available Event Handlers in a drop down list with type of current // event handler selected. List<System.Type> eventHandlerTypes = EditorExtensions.FindDerivedTypes(typeof(EventHandler)).ToList(); Block block = target as Block; System.Type currentType = null; if (block.eventHandler != null) { currentType = block.eventHandler.GetType(); } string currentHandlerName = "<None>"; if (currentType != null) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(currentType); if (info != null) { currentHandlerName = info.EventHandlerName; } } EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(new GUIContent("Execute On Event")); if (GUILayout.Button(new GUIContent(currentHandlerName), EditorStyles.popup)) { SetEventHandlerOperation noneOperation = new SetEventHandlerOperation(); noneOperation.block = block; noneOperation.eventHandlerType = null; GenericMenu eventHandlerMenu = new GenericMenu(); eventHandlerMenu.AddItem(new GUIContent("None"), false, OnSelectEventHandler, noneOperation); // Add event handlers with no category first foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info.Category.Length == 0) { SetEventHandlerOperation operation = new SetEventHandlerOperation(); operation.block = block; operation.eventHandlerType = type; eventHandlerMenu.AddItem(new GUIContent(info.EventHandlerName), false, OnSelectEventHandler, operation); } } // Add event handlers with a category afterwards foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info.Category.Length > 0) { SetEventHandlerOperation operation = new SetEventHandlerOperation(); operation.block = block; operation.eventHandlerType = type; string typeName = info.Category + "/" + info.EventHandlerName; eventHandlerMenu.AddItem(new GUIContent(typeName), false, OnSelectEventHandler, operation); } } eventHandlerMenu.ShowAsContext(); } EditorGUILayout.EndHorizontal(); if (block.eventHandler != null) { EventHandlerEditor eventHandlerEditor = Editor.CreateEditor(block.eventHandler) as EventHandlerEditor; if (eventHandlerEditor != null) { eventHandlerEditor.DrawInspectorGUI(); DestroyImmediate(eventHandlerEditor); } } } protected void OnSelectEventHandler(object obj) { SetEventHandlerOperation operation = obj as SetEventHandlerOperation; Block block = operation.block; System.Type selectedType = operation.eventHandlerType; if (block == null) { return; } Undo.RecordObject(block, "Set Event Handler"); if (block.eventHandler != null) { Undo.DestroyObjectImmediate(block.eventHandler); } if (selectedType != null) { EventHandler newHandler = Undo.AddComponent(block.gameObject, selectedType) as EventHandler; newHandler.parentBlock = block; block.eventHandler = newHandler; } } protected virtual void UpdateIndentLevels(Block block) { int indentLevel = 0; foreach(Command command in block.commandList) { if (command == null) { continue; } if (command.CloseBlock()) { indentLevel--; } command.indentLevel = Math.Max(indentLevel, 0); if (command.OpenBlock()) { indentLevel++; } } } static public void BlockField(SerializedProperty property, GUIContent label, GUIContent nullLabel, Flowchart flowchart) { if (flowchart == null) { return; } Block block = property.objectReferenceValue as Block; // Build dictionary of child blocks List<GUIContent> blockNames = new List<GUIContent>(); int selectedIndex = 0; blockNames.Add(nullLabel); Block[] blocks = flowchart.GetComponentsInChildren<Block>(true); for (int i = 0; i < blocks.Length; ++i) { blockNames.Add(new GUIContent(blocks[i].blockName)); if (block == blocks[i]) { selectedIndex = i + 1; } } selectedIndex = EditorGUILayout.Popup(label, selectedIndex, blockNames.ToArray()); if (selectedIndex == 0) { block = null; // Option 'None' } else { block = blocks[selectedIndex - 1]; } property.objectReferenceValue = block; } static public Block BlockField(Rect position, GUIContent nullLabel, Flowchart flowchart, Block block) { if (flowchart == null) { return null; } Block result = block; // Build dictionary of child blocks List<GUIContent> blockNames = new List<GUIContent>(); int selectedIndex = 0; blockNames.Add(nullLabel); Block[] blocks = flowchart.GetComponentsInChildren<Block>(); for (int i = 0; i < blocks.Length; ++i) { blockNames.Add(new GUIContent(blocks[i].name)); if (block == blocks[i]) { selectedIndex = i + 1; } } selectedIndex = EditorGUI.Popup(position, selectedIndex, blockNames.ToArray()); if (selectedIndex == 0) { result = null; // Option 'None' } else { result = blocks[selectedIndex - 1]; } return result; } // Compare delegate for sorting the list of command attributes protected static int CompareCommandAttributes(KeyValuePair<System.Type, CommandInfoAttribute> x, KeyValuePair<System.Type, CommandInfoAttribute> y) { int compare = (x.Value.Category.CompareTo(y.Value.Category)); if (compare == 0) { compare = (x.Value.CommandName.CompareTo(y.Value.CommandName)); } return compare; } [MenuItem("Tools/Fungus/Utilities/Export Reference Docs")] protected static void ExportReferenceDocs() { string path = EditorUtility.SaveFolderPanel("Export Reference Docs", "", ""); if(path.Length == 0) { return; } ExportCommandInfo(path); ExportEventHandlerInfo(path); FlowchartWindow.ShowNotification("Exported Reference Documentation"); } protected static void ExportCommandInfo(string path) { // Dump command info List<System.Type> menuTypes = EditorExtensions.FindDerivedTypes(typeof(Command)).ToList(); List<KeyValuePair<System.Type, CommandInfoAttribute>> filteredAttributes = GetFilteredCommandInfoAttribute(menuTypes); filteredAttributes.Sort( CompareCommandAttributes ); // Build list of command categories List<string> commandCategories = new List<string>(); foreach(var keyPair in filteredAttributes) { CommandInfoAttribute info = keyPair.Value; if (info.Category != "" && !commandCategories.Contains(info.Category)) { commandCategories.Add (info.Category); } } commandCategories.Sort(); // Output the commands in each category foreach (string category in commandCategories) { string markdown = ""; foreach(var keyPair in filteredAttributes) { CommandInfoAttribute info = keyPair.Value; if (info.Category == category || info.Category == "" && category == "Scripting") { markdown += "## " + info.CommandName + "\n"; markdown += info.HelpText + "\n"; markdown += GetPropertyInfo(keyPair.Key); } } string filePath = path + "/commands/" + category.ToLower() + "_commands.md"; Directory.CreateDirectory(Path.GetDirectoryName(filePath)); File.WriteAllText(filePath, markdown); } } protected static void ExportEventHandlerInfo(string path) { List<System.Type> eventHandlerTypes = EditorExtensions.FindDerivedTypes(typeof(EventHandler)).ToList(); List<string> eventHandlerCategories = new List<string>(); eventHandlerCategories.Add("Core"); foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info.Category != "" && !eventHandlerCategories.Contains(info.Category)) { eventHandlerCategories.Add(info.Category); } } eventHandlerCategories.Sort(); // Output the commands in each category foreach (string category in eventHandlerCategories) { string markdown = ""; foreach (System.Type type in eventHandlerTypes) { EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(type); if (info.Category == category || info.Category == "" && category == "Core") { markdown += "## " + info.EventHandlerName + "\n"; markdown += info.HelpText + "\n"; markdown += GetPropertyInfo(type); } } string filePath = path + "/event_handlers/" + category.ToLower() + "_events.md"; Directory.CreateDirectory(Path.GetDirectoryName(filePath)); File.WriteAllText(filePath, markdown); } } protected static string GetPropertyInfo(System.Type type) { string markdown = ""; foreach(FieldInfo field in type.GetFields() ) { TooltipAttribute attribute = (TooltipAttribute)Attribute.GetCustomAttribute(field, typeof(TooltipAttribute)); if (attribute == null ) { continue; } // Change field name to how it's displayed in the inspector string propertyName = Regex.Replace(field.Name, "(\\B[A-Z])", " $1"); if (propertyName.Length > 1) { propertyName = propertyName.Substring(0,1).ToUpper() + propertyName.Substring(1); } else { propertyName = propertyName.ToUpper(); } markdown += propertyName + " | " + field.FieldType + " | " + attribute.tooltip + "\n"; } if (markdown.Length > 0) { markdown = "\nProperty | Type | Description\n --- | --- | ---\n" + markdown + "\n"; } return markdown; } protected virtual void ShowCommandMenu() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); // Use index of last selected command in list, or end of list if nothing selected. int index = -1; foreach (Command command in flowchart.selectedCommands) { if (command.commandIndex + 1 > index) { index = command.commandIndex + 1; } } if (index == -1) { index = block.commandList.Count; } GenericMenu commandMenu = new GenericMenu(); // Build menu list List<System.Type> menuTypes = EditorExtensions.FindDerivedTypes(typeof(Command)).ToList(); List<KeyValuePair<System.Type, CommandInfoAttribute>> filteredAttributes = GetFilteredCommandInfoAttribute(menuTypes); filteredAttributes.Sort( CompareCommandAttributes ); foreach(var keyPair in filteredAttributes) { // Skip command type if the Flowchart doesn't support it if (!flowchart.IsCommandSupported(keyPair.Value)) { continue; } AddCommandOperation commandOperation = new AddCommandOperation(); commandOperation.block = block; commandOperation.commandType = keyPair.Key; commandOperation.index = index; GUIContent menuItem; if (keyPair.Value.Category == "") { menuItem = new GUIContent(keyPair.Value.CommandName); } else { menuItem = new GUIContent (keyPair.Value.Category + "/" + keyPair.Value.CommandName); } commandMenu.AddItem(menuItem, false, AddCommandCallback, commandOperation); } commandMenu.ShowAsContext(); } protected static List<KeyValuePair<System.Type,CommandInfoAttribute>> GetFilteredCommandInfoAttribute(List<System.Type> menuTypes) { Dictionary<string, KeyValuePair<System.Type, CommandInfoAttribute>> filteredAttributes = new Dictionary<string, KeyValuePair<System.Type, CommandInfoAttribute>>(); foreach (System.Type type in menuTypes) { object[] attributes = type.GetCustomAttributes(false); foreach (object obj in attributes) { CommandInfoAttribute infoAttr = obj as CommandInfoAttribute; if (infoAttr != null) { string dictionaryName = string.Format("{0}/{1}", infoAttr.Category, infoAttr.CommandName); int existingItemPriority = -1; if (filteredAttributes.ContainsKey(dictionaryName)) { existingItemPriority = filteredAttributes[dictionaryName].Value.Priority; } if (infoAttr.Priority > existingItemPriority) { KeyValuePair<System.Type, CommandInfoAttribute> keyValuePair = new KeyValuePair<System.Type, CommandInfoAttribute>(type, infoAttr); filteredAttributes[dictionaryName] = keyValuePair; } } } } return filteredAttributes.Values.ToList<KeyValuePair<System.Type,CommandInfoAttribute>>(); } protected static void AddCommandCallback(object obj) { AddCommandOperation commandOperation = obj as AddCommandOperation; Block block = commandOperation.block; if (block == null) { return; } Flowchart flowchart = block.GetFlowchart(); flowchart.ClearSelectedCommands(); Command newCommand = Undo.AddComponent(block.gameObject, commandOperation.commandType) as Command; block.GetFlowchart().AddSelectedCommand(newCommand); newCommand.parentBlock = block; newCommand.itemId = flowchart.NextItemId(); // Let command know it has just been added to the block newCommand.OnCommandAdded(block); Undo.RecordObject(block, "Set command type"); if (commandOperation.index < block.commandList.Count - 1) { block.commandList.Insert(commandOperation.index, newCommand); } else { block.commandList.Add(newCommand); } } public virtual void ShowContextMenu() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null) { return; } bool showCut = false; bool showCopy = false; bool showDelete = false; bool showPaste = false; if (flowchart.selectedCommands.Count > 0) { showCut = true; showCopy = true; showDelete = true; } CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); if (commandCopyBuffer.HasCommands()) { showPaste = true; } GenericMenu commandMenu = new GenericMenu(); if (showCut) { commandMenu.AddItem (new GUIContent ("Cut"), false, Cut); } else { commandMenu.AddDisabledItem(new GUIContent ("Cut")); } if (showCopy) { commandMenu.AddItem (new GUIContent ("Copy"), false, Copy); } else { commandMenu.AddDisabledItem(new GUIContent ("Copy")); } if (showPaste) { commandMenu.AddItem (new GUIContent ("Paste"), false, Paste); } else { commandMenu.AddDisabledItem(new GUIContent ("Paste")); } if (showDelete) { commandMenu.AddItem (new GUIContent ("Delete"), false, Delete); } else { commandMenu.AddDisabledItem(new GUIContent ("Delete")); } commandMenu.AddSeparator(""); commandMenu.AddItem (new GUIContent ("Select All"), false, SelectAll); commandMenu.AddItem (new GUIContent ("Select None"), false, SelectNone); commandMenu.ShowAsContext(); } protected void SelectAll() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } flowchart.ClearSelectedCommands(); Undo.RecordObject(flowchart, "Select All"); foreach (Command command in flowchart.selectedBlock.commandList) { flowchart.AddSelectedCommand(command); } Repaint(); } protected void SelectNone() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } Undo.RecordObject(flowchart, "Select None"); flowchart.ClearSelectedCommands(); Repaint(); } protected void Cut() { Copy(); Delete(); } protected void Copy() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); commandCopyBuffer.Clear(); // Scan through all commands in execution order to see if each needs to be copied foreach (Command command in flowchart.selectedBlock.commandList) { if (flowchart.selectedCommands.Contains(command)) { System.Type type = command.GetType(); Command newCommand = Undo.AddComponent(commandCopyBuffer.gameObject, type) as Command; System.Reflection.FieldInfo[] fields = type.GetFields(); foreach (System.Reflection.FieldInfo field in fields) { field.SetValue(newCommand, field.GetValue(command)); } } } } protected void Paste() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); // Find where to paste commands in block (either at end or after last selected command) int pasteIndex = flowchart.selectedBlock.commandList.Count; if (flowchart.selectedCommands.Count > 0) { for (int i = 0; i < flowchart.selectedBlock.commandList.Count; ++i) { Command command = flowchart.selectedBlock.commandList[i]; foreach (Command selectedCommand in flowchart.selectedCommands) { if (command == selectedCommand) { pasteIndex = i + 1; } } } } foreach (Command command in commandCopyBuffer.GetCommands()) { // Using the Editor copy / paste functionality instead instead of reflection // because this does a deep copy of the command properties. if (ComponentUtility.CopyComponent(command)) { if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject)) { Command[] commands = flowchart.GetComponents<Command>(); Command pastedCommand = commands.Last<Command>(); if (pastedCommand != null) { pastedCommand.itemId = flowchart.NextItemId(); flowchart.selectedBlock.commandList.Insert(pasteIndex++, pastedCommand); } } // This stops the user pasting the command manually into another game object. ComponentUtility.CopyComponent(flowchart.transform); } } Repaint(); } protected void Delete() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); if (flowchart == null || flowchart.selectedBlock == null) { return; } int lastSelectedIndex = 0; for (int i = flowchart.selectedBlock.commandList.Count - 1; i >= 0; --i) { Command command = flowchart.selectedBlock.commandList[i]; foreach (Command selectedCommand in flowchart.selectedCommands) { if (command == selectedCommand) { command.OnCommandRemoved(block); // Order of destruction is important here for undo to work Undo.DestroyObjectImmediate(command); Undo.RecordObject(flowchart.selectedBlock, "Delete"); flowchart.selectedBlock.commandList.RemoveAt(i); lastSelectedIndex = i; break; } } } Undo.RecordObject(flowchart, "Delete"); flowchart.ClearSelectedCommands(); if (lastSelectedIndex < flowchart.selectedBlock.commandList.Count) { Command nextCommand = flowchart.selectedBlock.commandList[lastSelectedIndex]; block.GetFlowchart().AddSelectedCommand(nextCommand); } Repaint(); } protected void SelectPrevious() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); int firstSelectedIndex = flowchart.selectedBlock.commandList.Count; bool firstSelectedCommandFound = false; if (flowchart.selectedCommands.Count > 0) { for (int i = 0; i < flowchart.selectedBlock.commandList.Count; i++) { Command commandInBlock = flowchart.selectedBlock.commandList[i]; foreach (Command selectedCommand in flowchart.selectedCommands) { if (commandInBlock == selectedCommand) { if (!firstSelectedCommandFound) { firstSelectedIndex = i; firstSelectedCommandFound = true; break; } } } if (firstSelectedCommandFound) { break; } } } if (firstSelectedIndex > 0) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(flowchart.selectedBlock.commandList[firstSelectedIndex-1]); } Repaint(); } protected void SelectNext() { Block block = target as Block; Flowchart flowchart = block.GetFlowchart(); int lastSelectedIndex = -1; if (flowchart.selectedCommands.Count > 0) { for (int i = 0; i < flowchart.selectedBlock.commandList.Count; i++) { Command commandInBlock = flowchart.selectedBlock.commandList[i]; foreach (Command selectedCommand in flowchart.selectedCommands) { if (commandInBlock == selectedCommand) { lastSelectedIndex = i; } } } } if (lastSelectedIndex < flowchart.selectedBlock.commandList.Count-1) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(flowchart.selectedBlock.commandList[lastSelectedIndex+1]); } Repaint(); } } }
/* ==================================================================== 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.UserModel { using System; using System.Collections.Generic; using System.Globalization; /** * Utility to identify built-in formats. The following is a list of the formats as * returned by this class.<p/> *<p/> * 0, "General"<br/> * 1, "0"<br/> * 2, "0.00"<br/> * 3, "#,##0"<br/> * 4, "#,##0.00"<br/> * 5, "$#,##0_);($#,##0)"<br/> * 6, "$#,##0_);[Red]($#,##0)"<br/> * 7, "$#,##0.00);($#,##0.00)"<br/> * 8, "$#,##0.00_);[Red]($#,##0.00)"<br/> * 9, "0%"<br/> * 0xa, "0.00%"<br/> * 0xb, "0.00E+00"<br/> * 0xc, "# ?/?"<br/> * 0xd, "# ??/??"<br/> * 0xe, "m/d/yy"<br/> * 0xf, "d-mmm-yy"<br/> * 0x10, "d-mmm"<br/> * 0x11, "mmm-yy"<br/> * 0x12, "h:mm AM/PM"<br/> * 0x13, "h:mm:ss AM/PM"<br/> * 0x14, "h:mm"<br/> * 0x15, "h:mm:ss"<br/> * 0x16, "m/d/yy h:mm"<br/> *<p/> * // 0x17 - 0x24 reserved for international and undocumented * 0x25, "#,##0_);(#,##0)"<br/> * 0x26, "#,##0_);[Red](#,##0)"<br/> * 0x27, "#,##0.00_);(#,##0.00)"<br/> * 0x28, "#,##0.00_);[Red](#,##0.00)"<br/> * 0x29, "_(*#,##0_);_(*(#,##0);_(* \"-\"_);_(@_)"<br/> * 0x2a, "_($*#,##0_);_($*(#,##0);_($* \"-\"_);_(@_)"<br/> * 0x2b, "_(*#,##0.00_);_(*(#,##0.00);_(*\"-\"??_);_(@_)"<br/> * 0x2c, "_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"<br/> * 0x2d, "mm:ss"<br/> * 0x2e, "[h]:mm:ss"<br/> * 0x2f, "mm:ss.0"<br/> * 0x30, "##0.0E+0"<br/> * 0x31, "@" - This is text format.<br/> * 0x31 "text" - Alias for "@"<br/> * <p/> * * @author Yegor Kozlov * * Modified 6/17/09 by Stanislav Shor - positive formats don't need starting '(' * */ internal class BuiltinFormats { /** * The first user-defined format starts at 164. */ public static int FIRST_USER_DEFINED_FORMAT_INDEX = 164; private static String[] _formats; /* 0 General General 18 Time h:mm AM/PM 1 Decimal 0 19 Time h:mm:ss AM/PM 2 Decimal 0.00 20 Time h:mm 3 Decimal #,##0 21 Time h:mm:ss 4 Decimal #,##0.00 2232 Date/Time M/D/YY h:mm 531 Currency "$"#,##0_);("$"#,##0) 37 Account. _(#,##0_);(#,##0) 631 Currency "$"#,##0_);[Red]("$"#,##0) 38 Account. _(#,##0_);[Red](#,##0) 731 Currency "$"#,##0.00_);("$"#,##0.00) 39 Account. _(#,##0.00_);(#,##0.00) 831 Currency "$"#,##0.00_);[Red]("$"#,##0.00) 40 Account. _(#,##0.00_);[Red](#,##0.00) 9 Percent 0% 4131 Currency _("$"* #,##0_);_("$"* (#,##0);_("$"* "-"_);_(@_) 10 Percent 0.00% 4231 33 Currency _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_) 11 Scientific 0.00E+00 4331 Currency _("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_) 12 Fraction # ?/? 4431 33 Currency _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_) 13 Fraction # ??/?? 45 Time mm:ss 1432 Date M/D/YY 46 Time [h]:mm:ss 15 Date D-MMM-YY 47 Time mm:ss.0 16 Date D-MMM 48 Scientific ##0.0E+0 17 Date MMM-YY 49 Text @ * */ static BuiltinFormats() { List<String> m = new List<String>(); PutFormat(m, 0, "General"); PutFormat(m, 1, "0"); PutFormat(m, 2, "0.00"); PutFormat(m, 3, "#,##0"); PutFormat(m, 4, "#,##0.00"); PutFormat(m, 5, "\"$\"#,##0_);(\"$\"#,##0)"); PutFormat(m, 6, "\"$\"#,##0_);[Red](\"$\"#,##0)"); PutFormat(m, 7, "\"$\"#,##0.00_);(\"$\"#,##0.00)"); PutFormat(m, 8, "\"$\"#,##0.00_);[Red](\"$\"#,##0.00)"); PutFormat(m, 9, "0%"); PutFormat(m, 0xa, "0.00%"); PutFormat(m, 0xb, "0.00E+00"); PutFormat(m, 0xc, "# ?/?"); PutFormat(m, 0xd, "# ??/??"); PutFormat(m, 0xe, "m/d/yy"); PutFormat(m, 0xf, "d-mmm-yy"); PutFormat(m, 0x10, "d-mmm"); PutFormat(m, 0x11, "mmm-yy"); PutFormat(m, 0x12, "h:mm AM/PM"); PutFormat(m, 0x13, "h:mm:ss AM/PM"); PutFormat(m, 0x14, "h:mm"); PutFormat(m, 0x15, "h:mm:ss"); PutFormat(m, 0x16, "m/d/yy h:mm"); // 0x17 - 0x24 reserved for international and undocumented for (int i = 0x17; i <= 0x24; i++) { // TODO - one junit relies on these values which seems incorrect PutFormat(m, i, "reserved-0x" + (i).ToString("X", CultureInfo.CurrentCulture)); } PutFormat(m, 0x25, "#,##0_);(#,##0)"); PutFormat(m, 0x26, "#,##0_);[Red](#,##0)"); PutFormat(m, 0x27, "#,##0.00_);(#,##0.00)"); PutFormat(m, 0x28, "#,##0.00_);[Red](#,##0.00)"); PutFormat(m, 0x29, "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)"); PutFormat(m, 0x2a, "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)"); PutFormat(m, 0x2b, "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)"); PutFormat(m, 0x2c, "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)"); PutFormat(m, 0x2d, "mm:ss"); PutFormat(m, 0x2e, "[h]:mm:ss"); PutFormat(m, 0x2f, "mm:ss.0"); PutFormat(m, 0x30, "##0.0E+0"); PutFormat(m, 0x31, "@"); //String[] ss = new String[m.Count]; String[] ss = m.ToArray(); _formats = ss; } private static void PutFormat(List<String> m, int index, String value) { if (m.Count != index) { throw new InvalidOperationException("index " + index + " is wrong"); } m.Add(value); } /** * @deprecated (May 2009) use {@link #getAll()} */ [Obsolete] public static Dictionary<int, String> GetBuiltinFormats() { Dictionary<int, String> result = new Dictionary<int, String>(); for (int i = 0; i < _formats.Length; i++) { result.Add(i, _formats[i]); } return result; } /** * @return array of built-in data formats */ public static String[] GetAll() { return (String[])_formats.Clone(); } /** * Get the format string that matches the given format index * * @param index of a built in format * @return string represented at index of format or <code>null</code> if there is not a built-in format at that index */ public static String GetBuiltinFormat(int index) { if (index < 0 || index >= _formats.Length) { return null; } return _formats[index]; } /** * Get the format index that matches the given format string. * * <p> * Automatically converts "text" to excel's format string to represent text. * </p> * @param pFmt string matching a built-in format * @return index of format or -1 if undefined. */ public static int GetBuiltinFormat(String pFmt) { String fmt; if (string.Compare(pFmt, ("TEXT"), StringComparison.OrdinalIgnoreCase) == 0) { fmt = "@"; } else { fmt = pFmt; } for (int i = 0; i < _formats.Length; i++) { if (fmt.Equals(_formats[i])) { return i; } } return -1; } } }
#region License /* * AuthenticationResponse.cs * * The MIT License * * Copyright (c) 2013 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Security.Cryptography; using System.Text; namespace WebSocketSharp { internal class AuthenticationResponse { #region Private Fields private string _algorithm; private string _cnonce; private string _method; private string _nc; private string _nonce; private string _opaque; private string _password; private string _qop; private string _realm; private string _response; private string _scheme; private string _uri; private string _userName; #endregion #region Private Constructors private AuthenticationResponse() { } #endregion #region Public Constructors public AuthenticationResponse(WsCredential credential) { _userName = credential.UserName; _password = credential.Password; _scheme = "Basic"; } public AuthenticationResponse(WsCredential credential, AuthenticationChallenge challenge) { _userName = credential.UserName; _password = credential.Password; _scheme = challenge.Scheme; _realm = challenge.Realm; if (_scheme == "Digest") initForDigest(credential, challenge); } #endregion #region Public Properties public string Algorithm { get { return _algorithm ?? String.Empty; } private set { _algorithm = value; } } public string Cnonce { get { return _cnonce ?? String.Empty; } private set { _cnonce = value; } } public string Nc { get { return _nc ?? String.Empty; } private set { _nc = value; } } public string Nonce { get { return _nonce ?? String.Empty; } private set { _nonce = value; } } public string Opaque { get { return _opaque ?? String.Empty; } private set { _opaque = value; } } public string Qop { get { return _qop ?? String.Empty; } private set { _qop = value; } } public string Realm { get { return _realm ?? String.Empty; } private set { _realm = value; } } public string Response { get { return _response ?? String.Empty; } private set { _response = value; } } public string Scheme { get { return _scheme ?? String.Empty; } private set { _scheme = value; } } public string Uri { get { return _uri ?? String.Empty; } private set { _uri = value; } } public string UserName { get { return _userName ?? String.Empty; } private set { _userName = value; } } #endregion #region Private Methods private string a1() { var result = String.Format("{0}:{1}:{2}", _userName, _realm, _password); return _algorithm != null && _algorithm.ToLower() == "md5-sess" ? String.Format("{0}:{1}:{2}", hash(result), _nonce, _cnonce) : result; } private string a2() { return String.Format("{0}:{1}", _method, _uri); } private static string createNonceValue() { var src = new byte[16]; var rand = new Random(); rand.NextBytes(src); var nonce = new StringBuilder(32); foreach (var b in src) nonce.Append(b.ToString("x2")); return nonce.ToString(); } private string createRequestDigest() { if (Qop == "auth") { var data = String.Format("{0}:{1}:{2}:{3}:{4}", _nonce, _nc, _cnonce, _qop, hash(a2())); return kd(hash(a1()), data); } return kd(hash(a1()), String.Format("{0}:{1}", _nonce, hash(a2()))); } private static string hash(string value) { var md5 = MD5.Create(); var src = Encoding.UTF8.GetBytes(value); var hashed = md5.ComputeHash(src); var result = new StringBuilder(64); foreach (var b in hashed) result.Append(b.ToString("x2")); return result.ToString(); } private void initForDigest(WsCredential credential, AuthenticationChallenge challenge) { _nonce = challenge.Nonce; _method = "GET"; _uri = credential.Domain; _algorithm = challenge.Algorithm; _opaque = challenge.Opaque; foreach (var qop in challenge.Qop.Split(',')) { if (qop.Trim().ToLower() == "auth") { _qop = "auth"; _nc = "00000001"; break; } } _cnonce = createNonceValue(); _response = createRequestDigest(); } private static string kd(string secret, string data) { var concatenated = String.Format("{0}:{1}", secret, data); return hash(concatenated); } private string toBasicCredentials() { var userPass = String.Format("{0}:{1}", _userName, _password); var base64UserPass = Convert.ToBase64String(Encoding.UTF8.GetBytes(userPass)); return "Basic " + base64UserPass; } private string toDigestCredentials() { var digestResponse = new StringBuilder(64); digestResponse.AppendFormat("username={0}", _userName.Quote()); digestResponse.AppendFormat(", realm={0}", _realm.Quote()); digestResponse.AppendFormat(", nonce={0}", _nonce.Quote()); digestResponse.AppendFormat(", uri={0}", _uri.Quote()); digestResponse.AppendFormat(", response={0}", _response.Quote()); if (!_algorithm.IsNullOrEmpty()) digestResponse.AppendFormat(", algorithm={0}", _algorithm); if (!_opaque.IsNullOrEmpty()) digestResponse.AppendFormat(", opaque={0}", _opaque.Quote()); if (!_qop.IsNullOrEmpty()) digestResponse.AppendFormat(", qop={0}", _qop); if (!_nc.IsNullOrEmpty()) digestResponse.AppendFormat(", nc={0}", _nc); if (!_qop.IsNullOrEmpty()) digestResponse.AppendFormat(", cnonce={0}", _cnonce.Quote()); return "Digest " + digestResponse.ToString(); } #endregion #region Public Methods public static AuthenticationResponse Parse(string response) { throw new NotImplementedException(); } public override string ToString() { return _scheme == "Basic" ? toBasicCredentials() : toDigestCredentials(); } #endregion } }
#if MONO #define __APPLE__ #endif // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Microsoft.Win32; using PermissionSet = System.Security.PermissionSet; using System.Security.Permissions; /*=================================JapaneseCalendar========================== ** ** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as ** Gregorian calendar. However, the year value is an offset to the Gregorian ** year based on the era. ** ** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor, ** and the era begins on the day an emperor ascends the throne and continues until his death. ** The era changes at 12:00AM. ** ** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st. ** 1989/1/8 A.D. is also Heisei 1st 1/8. ** ** Any date in the year during which era is changed can be reckoned in either era. For example, ** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year. ** ** Note: ** The DateTime can be represented by the JapaneseCalendar are limited to two factors: ** 1. The min value and max value of DateTime class. ** 2. The available era information. ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1868/09/08 9999/12/31 ** Japanese Meiji 01/01 Heisei 8011/12/31 ============================================================================*/ [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class JapaneseCalendar : Calendar { internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8); [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Japanese calendar. // [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } // // Using a field initializer rather than a static constructor so that the whole class can be lazy // init. static internal volatile EraInfo[] japaneseEraInfo; #if !__APPLE__ private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras"; private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive; #endif // // Read our era info // // m_EraInfo must be listed in reverse chronological order. The most recent era // should be the first element. // That is, m_EraInfo[0] contains the most recent era. // // We know about 4 built-in eras, however users may add additional era(s) from the // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. // internal static EraInfo[] GetEraInfo() { // See if we need to build it if (japaneseEraInfo == null) { #if !__APPLE__ // See if we have any eras from the registry japaneseEraInfo = GetErasFromRegistry(); #endif // See if we have to use the built-in eras if (japaneseEraInfo == null) { // We know about some built-in ranges EraInfo[] defaultEraRanges = new EraInfo[4]; defaultEraRanges[0] = new EraInfo( 4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988, "\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear defaultEraRanges[1] = new EraInfo( 3, 1926, 12, 25, 1925, 1, 1989-1925, "\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear defaultEraRanges[2] = new EraInfo( 2, 1912, 7, 30, 1911, 1, 1926-1911, "\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear defaultEraRanges[3] = new EraInfo( 1, 1868, 1, 1, 1867, 1, 1912-1867, "\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear // Remember the ranges we built japaneseEraInfo = defaultEraRanges; } } // return the era we found/made return japaneseEraInfo; } #if !__APPLE__ // // GetErasFromRegistry() // // We know about 4 built-in eras, however users may add additional era(s) from the // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. [System.Security.SecuritySafeCritical] // auto-generated private static EraInfo[] GetErasFromRegistry() { // Look in the registry key and see if we can find any ranges int iFoundEras = 0; EraInfo[] registryEraRanges = null; try { // Need to access registry PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_japaneseErasHivePermissionList)); permSet.Assert(); RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false); // Abort if we didn't find anything if (key == null) return null; // Look up the values in our reg key String[] valueNames = key.GetValueNames(); if (valueNames != null && valueNames.Length > 0) { registryEraRanges = new EraInfo[valueNames.Length]; // Loop through the registry and read in all the values for (int i = 0; i < valueNames.Length; i++) { // See if the era is a valid date EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString()); // continue if not valid if (era == null) continue; // Remember we found one. registryEraRanges[iFoundEras] = era; iFoundEras++; } } } catch (System.Security.SecurityException) { // If we weren't allowed to read, then just ignore the error return null; } catch (System.IO.IOException) { // If key is being deleted just ignore the error return null; } catch (System.UnauthorizedAccessException) { // Registry access rights permissions, just ignore the error return null; } // // If we didn't have valid eras, then fail // should have at least 4 eras // if (iFoundEras < 4) return null; // // Now we have eras, clean them up. // // Clean up array length Array.Resize(ref registryEraRanges, iFoundEras); // Sort them Array.Sort(registryEraRanges, CompareEraRanges); // Clean up era information for (int i = 0; i < registryEraRanges.Length; i++) { // eras count backwards from length to 1 (and are 1 based indexes into string arrays) registryEraRanges[i].era = registryEraRanges.Length - i; // update max era year if (i == 0) { // First range is 'til the end of the calendar registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset; } else { // Rest are until the next era (remember most recent era is first in array) registryEraRanges[i].maxEraYear = registryEraRanges[i-1].yearOffset + 1 - registryEraRanges[i].yearOffset; } } // Return our ranges return registryEraRanges; } // // Compare two era ranges, eg just the ticks // Remember the era array is supposed to be in reverse chronological order // private static int CompareEraRanges(EraInfo a, EraInfo b) { return b.ticks.CompareTo(a.ticks); } // // GetEraFromValue // // Parse the registry value name/data pair into an era // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. private static EraInfo GetEraFromValue(String value, String data) { // Need inputs if (value == null || data == null) return null; // // Get Date // // Need exactly 10 characters in name for date // yyyy.mm.dd although the . can be any character if (value.Length != 10) return null; int year; int month; int day; if (!Number.TryParseInt32(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) || !Number.TryParseInt32(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) || !Number.TryParseInt32(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day)) { // Couldn't convert integer, fail return null; } // // Get Strings // // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups) String[] names = data.Split(new char[] {'_'}); // Should have exactly 4 parts // 0 - Era Name // 1 - Abbreviated Era Name // 2 - English Era Name // 3 - Abbreviated English Era Name if (names.Length != 4) return null; // Each part should have data in it if (names[0].Length == 0 || names[1].Length == 0 || names[2].Length == 0 || names[3].Length == 0) return null; // // Now we have an era we can build // Note that the era # and max era year need cleaned up after sorting // Don't use the full English Era Name (names[2]) // return new EraInfo( 0, year, month, day, year - 1, 1, 0, names[0], names[1], names[3]); } #endif // !__APPLE__ internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper helper; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new JapaneseCalendar(); } return (s_defaultInstance); } public JapaneseCalendar() { try { new CultureInfo("ja-JP"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().FullName, e); } helper = new GregorianCalendarHelper(this, GetEraInfo()); } internal override int ID { get { return (CAL_JAPAN); } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } /*=================================GetDaysInMonth========================== **Action: Returns the number of days in the month given by the year and month arguments. **Returns: The number of days in the given month. **Arguments: ** year The year in Japanese calendar. ** month The month ** era The Japanese era value. **Exceptions ** ArgumentException If month is less than 1 or greater * than 12. ============================================================================*/ public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [System.Runtime.InteropServices.ComVisible(false)] public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } /*=================================GetEra========================== **Action: Get the era value of the specified time. **Returns: The era value for the specified time. **Arguments: ** time the specified date time. **Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges. ============================================================================*/ public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } // For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years. // Therefore, for any two digit number, we just return the original number. public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, helper.MaxYear)); } return (year); } public override int[] Eras { get { return (helper.Eras); } } // // Return the various era strings // Note: The arrays are backwards of the eras // internal static String[] EraNames() { EraInfo[] eras = GetEraInfo(); String[] eraNames = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. eraNames[i] = eras[eras.Length - i - 1].eraName; } return eraNames; } internal static String[] AbbrevEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasAbbrev = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName; } return erasAbbrev; } internal static String[] EnglishEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasEnglish = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasEnglish[i] = eras[eras.Length - i - 1].englishEraName; } return erasEnglish; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99; internal override bool IsValidYear(int year, int era) { return helper.IsValidYear(year, era); } public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 99, helper.MaxYear)); } twoDigitYearMax = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Https; using Microsoft.AspNetCore.Server.Kestrel.Https.Internal; using Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests.TestTransport; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Moq; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests { public class HttpsConnectionMiddlewareTests : LoggedTest { private static readonly X509Certificate2 _x509Certificate2 = TestResources.GetTestCertificate(); private static readonly X509Certificate2 _x509Certificate2NoExt = TestResources.GetTestCertificate("no_extensions.pfx"); [Fact] public async Task CanReadAndWriteWithHttpsConnectionMiddleware() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2 }); }; await using (var server = new TestServer(App, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { var result = await server.HttpClientSlim.PostAsync($"https://localhost:{server.Port}/", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("content", "Hello World?") }), validateCertificate: false); Assert.Equal("content=Hello+World%3F", result); } } [Fact] public async Task CanReadAndWriteWithHttpsConnectionMiddlewareWithPemCertificate() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string> { ["Certificates:Default:Path"] = Path.Combine("shared", "TestCertificates", "https-aspnet.crt"), ["Certificates:Default:KeyPath"] = Path.Combine("shared", "TestCertificates", "https-aspnet.key"), ["Certificates:Default:Password"] = "aspnetcore", }).Build(); var options = new KestrelServerOptions(); var env = new Mock<IHostEnvironment>(); env.SetupGet(e => e.ContentRootPath).Returns(Directory.GetCurrentDirectory()); var serviceProvider = new ServiceCollection().AddLogging().BuildServiceProvider(); options.ApplicationServices = serviceProvider; var logger = serviceProvider.GetRequiredService<ILogger<KestrelServer>>(); var httpsLogger = serviceProvider.GetRequiredService<ILogger<HttpsConnectionMiddleware>>(); var loader = new KestrelConfigurationLoader(options, configuration, env.Object, reloadOnChange: false, logger, httpsLogger); loader.Load(); void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.KestrelServerOptions = options; listenOptions.UseHttps(); }; await using (var server = new TestServer(App, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { var result = await server.HttpClientSlim.PostAsync($"https://localhost:{server.Port}/", new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("content", "Hello World?") }), validateCertificate: false); Assert.Equal("content=Hello+World%3F", result); } } [Fact] public async Task HandshakeDetailsAreAvailable() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2 }); }; await using (var server = new TestServer(context => { var tlsFeature = context.Features.Get<ITlsHandshakeFeature>(); Assert.NotNull(tlsFeature); Assert.True(tlsFeature.Protocol > SslProtocols.None, "Protocol"); Assert.True(tlsFeature.CipherAlgorithm > CipherAlgorithmType.Null, "Cipher"); Assert.True(tlsFeature.CipherStrength > 0, "CipherStrength"); Assert.True(tlsFeature.HashAlgorithm >= HashAlgorithmType.None, "HashAlgorithm"); // May be None on Linux. Assert.True(tlsFeature.HashStrength >= 0, "HashStrength"); // May be 0 for some algorithms Assert.True(tlsFeature.KeyExchangeAlgorithm >= ExchangeAlgorithmType.None, "KeyExchangeAlgorithm"); // Maybe None on Windows 7 Assert.True(tlsFeature.KeyExchangeStrength >= 0, "KeyExchangeStrength"); // May be 0 on mac return context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { var result = await server.HttpClientSlim.GetStringAsync($"https://localhost:{server.Port}/", validateCertificate: false); Assert.Equal("hello world", result); } } [Fact] public async Task HandshakeDetailsAreAvailableAfterAsyncCallback() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(async (stream, clientHelloInfo, state, cancellationToken) => { await Task.Yield(); return new SslServerAuthenticationOptions { ServerCertificate = _x509Certificate2, }; }, state: null); } await using (var server = new TestServer(context => { var tlsFeature = context.Features.Get<ITlsHandshakeFeature>(); Assert.NotNull(tlsFeature); Assert.True(tlsFeature.Protocol > SslProtocols.None, "Protocol"); Assert.True(tlsFeature.CipherAlgorithm > CipherAlgorithmType.Null, "Cipher"); Assert.True(tlsFeature.CipherStrength > 0, "CipherStrength"); Assert.True(tlsFeature.HashAlgorithm >= HashAlgorithmType.None, "HashAlgorithm"); // May be None on Linux. Assert.True(tlsFeature.HashStrength >= 0, "HashStrength"); // May be 0 for some algorithms Assert.True(tlsFeature.KeyExchangeAlgorithm >= ExchangeAlgorithmType.None, "KeyExchangeAlgorithm"); // Maybe None on Windows 7 Assert.True(tlsFeature.KeyExchangeStrength >= 0, "KeyExchangeStrength"); // May be 0 on mac return context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { var result = await server.HttpClientSlim.GetStringAsync($"https://localhost:{server.Port}/", validateCertificate: false); Assert.Equal("hello world", result); } } [Fact] public async Task RequireCertificateFailsWhenNoCertificate() { var listenOptions = new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0)); listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2, ClientCertificateMode = ClientCertificateMode.RequireCertificate }); await using (var server = new TestServer(App, new TestServiceContext(LoggerFactory), listenOptions)) { await Assert.ThrowsAnyAsync<Exception>( () => server.HttpClientSlim.GetStringAsync($"https://localhost:{server.Port}/")); } } [Fact] public async Task AllowCertificateContinuesWhenNoCertificate() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2, ClientCertificateMode = ClientCertificateMode.AllowCertificate }); } await using (var server = new TestServer(context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); return context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { var result = await server.HttpClientSlim.GetStringAsync($"https://localhost:{server.Port}/", validateCertificate: false); Assert.Equal("hello world", result); } } [Fact] public async Task AsyncCallbackSettingClientCertificateRequiredContinuesWhenNoCertificate() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps((stream, clientHelloInfo, state, cancellationToken) => new ValueTask<SslServerAuthenticationOptions>(new SslServerAuthenticationOptions { ServerCertificate = _x509Certificate2, ClientCertificateRequired = true, RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true, CertificateRevocationCheckMode = X509RevocationMode.NoCheck }), state: null); } await using (var server = new TestServer(context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); return context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { var result = await server.HttpClientSlim.GetStringAsync($"https://localhost:{server.Port}/", validateCertificate: false); Assert.Equal("hello world", result); } } [Fact] public void ThrowsWhenNoServerCertificateIsProvided() { Assert.Throws<ArgumentException>(() => new HttpsConnectionMiddleware(context => Task.CompletedTask, new HttpsConnectionAdapterOptions()) ); } [Fact] public async Task UsesProvidedServerCertificate() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2 }); }; await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); Assert.True(stream.RemoteCertificate.Equals(_x509Certificate2)); } } } [Fact] public async Task UsesProvidedServerCertificateSelector() { var selectorCalled = 0; void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificateSelector = (connection, name) => { Assert.NotNull(connection); Assert.NotNull(connection.Features.Get<SslStream>()); Assert.Equal("localhost", name); selectorCalled++; return _x509Certificate2; } }); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); Assert.True(stream.RemoteCertificate.Equals(_x509Certificate2)); Assert.Equal(1, selectorCalled); } } } [Fact] public async Task UsesProvidedAsyncCallback() { var selectorCalled = 0; void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(async (stream, clientHelloInfo, state, cancellationToken) => { await Task.Yield(); Assert.NotNull(stream); Assert.Equal("localhost", clientHelloInfo.ServerName); selectorCalled++; return new SslServerAuthenticationOptions { ServerCertificate = _x509Certificate2 }; }, state: null); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); Assert.True(stream.RemoteCertificate.Equals(_x509Certificate2)); Assert.Equal(1, selectorCalled); } } } [Fact] public async Task UsesProvidedServerCertificateSelectorEachTime() { var selectorCalled = 0; void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificateSelector = (connection, name) => { Assert.NotNull(connection); Assert.NotNull(connection.Features.Get<SslStream>()); Assert.Equal("localhost", name); selectorCalled++; if (selectorCalled == 1) { return _x509Certificate2; } return _x509Certificate2NoExt; } }); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); Assert.True(stream.RemoteCertificate.Equals(_x509Certificate2)); Assert.Equal(1, selectorCalled); } using (var connection = server.CreateConnection()) { var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); Assert.True(stream.RemoteCertificate.Equals(_x509Certificate2NoExt)); Assert.Equal(2, selectorCalled); } } } [Fact] public async Task UsesProvidedServerCertificateSelectorValidatesEkus() { var selectorCalled = 0; void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificateSelector = (features, name) => { selectorCalled++; return TestResources.GetTestCertificate("eku.code_signing.pfx"); } }); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStream(connection.Stream); await Assert.ThrowsAsync<IOException>(() => stream.AuthenticateAsClientAsync("localhost", new X509CertificateCollection(), SslProtocols.Tls12 | SslProtocols.Tls11, false)); Assert.Equal(1, selectorCalled); } } } [Fact] public async Task UsesProvidedServerCertificateSelectorOverridesServerCertificate() { var selectorCalled = 0; void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2NoExt, ServerCertificateSelector = (connection, name) => { Assert.NotNull(connection); Assert.NotNull(connection.Features.Get<SslStream>()); Assert.Equal("localhost", name); selectorCalled++; return _x509Certificate2; } }); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); Assert.True(stream.RemoteCertificate.Equals(_x509Certificate2)); Assert.Equal(1, selectorCalled); } } } [Fact] public async Task UsesProvidedServerCertificateSelectorFailsIfYouReturnNull() { var selectorCalled = 0; void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificateSelector = (features, name) => { selectorCalled++; return null; } }); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStream(connection.Stream); await Assert.ThrowsAsync<IOException>(() => stream.AuthenticateAsClientAsync("localhost", new X509CertificateCollection(), SslProtocols.Tls12 | SslProtocols.Tls11, false)); Assert.Equal(1, selectorCalled); } } } [Theory] [InlineData(HttpProtocols.Http1)] [InlineData(HttpProtocols.Http1AndHttp2)] // Make sure Http/1.1 doesn't regress with Http/2 enabled. public async Task CertificatePassedToHttpContext(HttpProtocols httpProtocols) { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.Protocols = httpProtocols; listenOptions.UseHttps(options => { options.ServerCertificate = _x509Certificate2; options.ClientCertificateMode = ClientCertificateMode.RequireCertificate; options.AllowAnyClientCertificate(); }); } await using (var server = new TestServer(context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.NotNull(tlsFeature.ClientCertificate); Assert.NotNull(context.Connection.ClientCertificate); return context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. // Use a random host name to avoid the TLS session resumption cache. var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync(Guid.NewGuid().ToString()); await AssertConnectionResult(stream, true); } } } [Fact] public async Task RenegotiateForClientCertificateOnHttp1DisabledByDefault() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.Protocols = HttpProtocols.Http1; listenOptions.UseHttps(options => { options.ServerCertificate = _x509Certificate2; options.ClientCertificateMode = ClientCertificateMode.NoCertificate; options.AllowAnyClientCertificate(); }); } await using var server = new TestServer(async context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); var clientCert = await context.Connection.GetClientCertificateAsync(); Assert.Null(clientCert); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); await context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. // Use a random host name to avoid the TLS session resumption cache. var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync(Guid.NewGuid().ToString()); await AssertConnectionResult(stream, true); } [ConditionalTheory] [InlineData(HttpProtocols.Http1)] [InlineData(HttpProtocols.Http1AndHttp2)] // Make sure turning on Http/2 doesn't regress HTTP/1 [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "Missing platform support.")] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/33566#issuecomment-892031659", Queues = HelixConstants.RedhatAmd64)] // Outdated OpenSSL client public async Task CanRenegotiateForClientCertificate(HttpProtocols httpProtocols) { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.Protocols = httpProtocols; listenOptions.UseHttps(options => { options.ServerCertificate = _x509Certificate2; options.SslProtocols = SslProtocols.Tls12; // Linux doesn't support renegotiate on TLS1.3 yet. https://github.com/dotnet/runtime/issues/55757 options.ClientCertificateMode = ClientCertificateMode.DelayCertificate; options.AllowAnyClientCertificate(); }); } await using var server = new TestServer(async context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); var clientCert = await context.Connection.GetClientCertificateAsync(); Assert.NotNull(clientCert); Assert.NotNull(tlsFeature.ClientCertificate); Assert.NotNull(context.Connection.ClientCertificate); await context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. // Use a random host name to avoid the TLS session resumption cache. var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync(Guid.NewGuid().ToString()); await AssertConnectionResult(stream, true); } [Fact] public async Task Renegotiate_ServerOptionsSelectionCallback_NotSupported() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps((SslStream stream, SslClientHelloInfo clientHelloInfo, object state, CancellationToken cancellationToken) => { return ValueTask.FromResult(new SslServerAuthenticationOptions() { ServerCertificate = _x509Certificate2, ClientCertificateRequired = false, RemoteCertificateValidationCallback = (_, _, _, _) => true, }); }, state: null); } await using var server = new TestServer(async context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); var clientCert = await context.Connection.GetClientCertificateAsync(); Assert.Null(clientCert); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); await context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. // Use a random host name to avoid the TLS session resumption cache. var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync(Guid.NewGuid().ToString()); await AssertConnectionResult(stream, true); } [ConditionalFact] [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "Missing platform support.")] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/33566#issuecomment-892031659", Queues = HelixConstants.RedhatAmd64)] // Outdated OpenSSL client public async Task CanRenegotiateForTlsCallbackOptions() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new TlsHandshakeCallbackOptions() { OnConnection = context => { context.AllowDelayedClientCertificateNegotation = true; return ValueTask.FromResult(new SslServerAuthenticationOptions() { ServerCertificate = _x509Certificate2, EnabledSslProtocols = SslProtocols.Tls12, // Linux doesn't support renegotiate on TLS1.3 yet. https://github.com/dotnet/runtime/issues/55757 ClientCertificateRequired = false, RemoteCertificateValidationCallback = (_, _, _, _) => true, }); } }); } await using var server = new TestServer(async context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); var clientCert = await context.Connection.GetClientCertificateAsync(); Assert.NotNull(clientCert); Assert.NotNull(tlsFeature.ClientCertificate); Assert.NotNull(context.Connection.ClientCertificate); await context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. // Use a random host name to avoid the TLS session resumption cache. var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync(Guid.NewGuid().ToString()); await AssertConnectionResult(stream, true); } [ConditionalFact] [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "Missing platform support.")] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/33566#issuecomment-892031659", Queues = HelixConstants.RedhatAmd64)] // Outdated OpenSSL client public async Task CanRenegotiateForClientCertificateOnHttp1CanReturnNoCert() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.Protocols = HttpProtocols.Http1; listenOptions.UseHttps(options => { options.ServerCertificate = _x509Certificate2; options.SslProtocols = SslProtocols.Tls12; // Linux doesn't support renegotiate on TLS1.3 yet. https://github.com/dotnet/runtime/issues/55757 options.ClientCertificateMode = ClientCertificateMode.DelayCertificate; options.AllowAnyClientCertificate(); }); } await using var server = new TestServer(async context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); var clientCert = await context.Connection.GetClientCertificateAsync(); Assert.Null(clientCert); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); await context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. // Use a random host name to avoid the TLS session resumption cache. var stream = new SslStream(connection.Stream); var clientOptions = new SslClientAuthenticationOptions() { TargetHost = Guid.NewGuid().ToString(), EnabledSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, }; clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; await stream.AuthenticateAsClientAsync(clientOptions); await AssertConnectionResult(stream, true); } [ConditionalFact] // TLS 1.2 and lower have to renegotiate the whole connection to get a client cert, and if that hits an error // then the connection is aborted. [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "Missing platform support.")] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/33566#issuecomment-892031659", Queues = HelixConstants.RedhatAmd64)] // Outdated OpenSSL client public async Task RenegotiateForClientCertificateOnPostWithoutBufferingThrows_TLS12() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.Protocols = HttpProtocols.Http1; listenOptions.UseHttps(options => { options.SslProtocols = SslProtocols.Tls12; options.ServerCertificate = _x509Certificate2; options.ClientCertificateMode = ClientCertificateMode.DelayCertificate; options.AllowAnyClientCertificate(); }); } // Under 4kb can sometimes work because it fits into Kestrel's header parsing buffer. var expectedBody = new string('a', 1024 * 4); await using var server = new TestServer(async context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => context.Connection.GetClientCertificateAsync()); Assert.Equal("Client stream needs to be drained before renegotiation.", ex.Message); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. // Use a random host name to avoid the TLS session resumption cache. var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync(Guid.NewGuid().ToString()); await AssertConnectionResult(stream, true, expectedBody); } [ConditionalFact] // TLS 1.3 uses a new client cert negotiation extension that doesn't cause the connection to abort // for this error. [MinimumOSVersion(OperatingSystems.Windows, "10.0.20145")] // Needs a preview version with TLS 1.3 enabled. [OSSkipCondition(OperatingSystems.MacOSX | OperatingSystems.Linux, SkipReason = "https://github.com/dotnet/runtime/issues/55757")] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/33566#issuecomment-892031659", Queues = HelixConstants.RedhatAmd64)] // Outdated OpenSSL client public async Task RenegotiateForClientCertificateOnPostWithoutBufferingThrows_TLS13() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.Protocols = HttpProtocols.Http1; listenOptions.UseHttps(options => { options.SslProtocols = SslProtocols.Tls13; options.ServerCertificate = _x509Certificate2; options.ClientCertificateMode = ClientCertificateMode.DelayCertificate; options.AllowAnyClientCertificate(); }); } // Under 4kb can sometimes work because it fits into Kestrel's header parsing buffer. var expectedBody = new string('a', 1024 * 4); await using var server = new TestServer(async context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => context.Connection.GetClientCertificateAsync()); Assert.Equal("Client stream needs to be drained before renegotiation.", ex.Message); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. // Use a random host name to avoid the TLS session resumption cache. var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync(Guid.NewGuid().ToString()); await AssertConnectionResult(stream, true, expectedBody); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] // HTTP/2 requires Win10 [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "ALPN not supported")] public async Task ServerOptionsSelectionCallback_SetsALPN() { static void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps((_, _, _, _) => ValueTask.FromResult(new SslServerAuthenticationOptions() { ServerCertificate = _x509Certificate2, }), state: null); } await using var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions() { // Use a random host name to avoid the TLS session resumption cache. TargetHost = Guid.NewGuid().ToString(), ApplicationProtocols = new() { SslApplicationProtocol.Http2, SslApplicationProtocol.Http11, }, }); Assert.Equal(SslApplicationProtocol.Http2, stream.NegotiatedApplicationProtocol); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] // HTTP/2 requires Win10 [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "ALPN not supported")] public async Task TlsHandshakeCallbackOptionsOverload_SetsALPN() { static void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new TlsHandshakeCallbackOptions() { OnConnection = context => { return ValueTask.FromResult(new SslServerAuthenticationOptions() { ServerCertificate = _x509Certificate2, }); } }); } await using var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions() { // Use a random host name to avoid the TLS session resumption cache. TargetHost = Guid.NewGuid().ToString(), ApplicationProtocols = new() { SslApplicationProtocol.Http2, SslApplicationProtocol.Http11, }, }); Assert.Equal(SslApplicationProtocol.Http2, stream.NegotiatedApplicationProtocol); } [ConditionalFact] [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "ALPN not supported")] public async Task TlsHandshakeCallbackOptionsOverload_EmptyAlpnList_DisablesAlpn() { static void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new TlsHandshakeCallbackOptions() { OnConnection = context => { return ValueTask.FromResult(new SslServerAuthenticationOptions() { ServerCertificate = _x509Certificate2, ApplicationProtocols = new(), }); } }); } await using var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions() { // Use a random host name to avoid the TLS session resumption cache. TargetHost = Guid.NewGuid().ToString(), ApplicationProtocols = new() { SslApplicationProtocol.Http2, SslApplicationProtocol.Http11, }, }); Assert.Equal(default, stream.NegotiatedApplicationProtocol); } [ConditionalFact] [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "Missing platform support.")] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/33566#issuecomment-892031659", Queues = HelixConstants.RedhatAmd64)] // Outdated OpenSSL client public async Task CanRenegotiateForClientCertificateOnPostIfDrained() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.Protocols = HttpProtocols.Http1; listenOptions.UseHttps(options => { options.ServerCertificate = _x509Certificate2; options.SslProtocols = SslProtocols.Tls12; // Linux doesn't support renegotiate on TLS1.3 yet. https://github.com/dotnet/runtime/issues/55757 options.ClientCertificateMode = ClientCertificateMode.DelayCertificate; options.AllowAnyClientCertificate(); }); } var expectedBody = new string('a', 1024 * 4); await using var server = new TestServer(async context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.Null(tlsFeature.ClientCertificate); Assert.Null(context.Connection.ClientCertificate); // Read the body before requesting the client cert var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); Assert.Equal(expectedBody, body); var clientCert = await context.Connection.GetClientCertificateAsync(); Assert.NotNull(clientCert); Assert.NotNull(tlsFeature.ClientCertificate); Assert.NotNull(context.Connection.ClientCertificate); await context.Response.WriteAsync("hello world"); }, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. // Use a random host name to avoid the TLS session resumption cache. var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync(Guid.NewGuid().ToString()); await AssertConnectionResult(stream, true, expectedBody); } [Fact] public async Task HttpsSchemePassedToRequestFeature() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2 }); } await using (var server = new TestServer(context => context.Response.WriteAsync(context.Request.Scheme), new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { var result = await server.HttpClientSlim.GetStringAsync($"https://localhost:{server.Port}/", validateCertificate: false); Assert.Equal("https", result); } } [Fact] public async Task Tls10CanBeDisabled() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(options => { options.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11; options.ServerCertificate = _x509Certificate2; options.ClientCertificateMode = ClientCertificateMode.RequireCertificate; options.AllowAnyClientCertificate(); }); } await using (var server = new TestServer(context => context.Response.WriteAsync("hello world"), new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { // SslStream is used to ensure the certificate is actually passed to the server // HttpClient might not send the certificate because it is invalid or it doesn't match any // of the certificate authorities sent by the server in the SSL handshake. using (var connection = server.CreateConnection()) { var stream = OpenSslStreamWithCert(connection.Stream); var ex = await Assert.ThrowsAnyAsync<Exception>( async () => await stream.AuthenticateAsClientAsync("localhost", new X509CertificateCollection(), SslProtocols.Tls, false)); } } } [Theory] [InlineData(ClientCertificateMode.AllowCertificate)] [InlineData(ClientCertificateMode.RequireCertificate)] public async Task ClientCertificateValidationGetsCalledWithNotNullParameters(ClientCertificateMode mode) { var clientCertificateValidationCalled = false; void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2, ClientCertificateMode = mode, ClientCertificateValidation = (certificate, chain, sslPolicyErrors) => { clientCertificateValidationCalled = true; Assert.NotNull(certificate); Assert.NotNull(chain); return true; } }); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); await AssertConnectionResult(stream, true); Assert.True(clientCertificateValidationCalled); } } } [ConditionalTheory] [InlineData(ClientCertificateMode.AllowCertificate)] [InlineData(ClientCertificateMode.RequireCertificate)] public async Task ValidationFailureRejectsConnection(ClientCertificateMode mode) { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2, ClientCertificateMode = mode, ClientCertificateValidation = (certificate, chain, sslPolicyErrors) => false }); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); await AssertConnectionResult(stream, false); } } } [Theory] [InlineData(ClientCertificateMode.AllowCertificate)] [InlineData(ClientCertificateMode.RequireCertificate)] public async Task RejectsConnectionOnSslPolicyErrorsWhenNoValidation(ClientCertificateMode mode) { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2, ClientCertificateMode = mode }); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); await AssertConnectionResult(stream, false); } } } [Fact] public async Task AllowAnyCertOverridesCertificateValidation() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(options => { options.ServerCertificate = _x509Certificate2; options.ClientCertificateMode = ClientCertificateMode.RequireCertificate; options.ClientCertificateValidation = (certificate, x509Chain, sslPolicyErrors) => false; options.AllowAnyClientCertificate(); }); } await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); await AssertConnectionResult(stream, true); } } } [Fact] public async Task CertificatePassedToHttpContextIsNotDisposed() { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(options => { options.ServerCertificate = _x509Certificate2; options.ClientCertificateMode = ClientCertificateMode.RequireCertificate; options.AllowAnyClientCertificate(); }); } RequestDelegate app = context => { var tlsFeature = context.Features.Get<ITlsConnectionFeature>(); Assert.NotNull(tlsFeature); Assert.NotNull(tlsFeature.ClientCertificate); Assert.NotNull(context.Connection.ClientCertificate); Assert.NotNull(context.Connection.ClientCertificate.PublicKey); return context.Response.WriteAsync("hello world"); }; await using (var server = new TestServer(app, new TestServiceContext(LoggerFactory), ConfigureListenOptions)) { using (var connection = server.CreateConnection()) { var stream = OpenSslStreamWithCert(connection.Stream); await stream.AuthenticateAsClientAsync("localhost"); await AssertConnectionResult(stream, true); } } } [Theory] [InlineData("no_extensions.pfx")] public void AcceptsCertificateWithoutExtensions(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); var cert = new X509Certificate2(certPath, "testPassword"); Assert.Empty(cert.Extensions.OfType<X509EnhancedKeyUsageExtension>()); new HttpsConnectionMiddleware(context => Task.CompletedTask, new HttpsConnectionAdapterOptions { ServerCertificate = cert, }); } [Theory] [InlineData("eku.server.pfx")] [InlineData("eku.multiple_usages.pfx")] public void ValidatesEnhancedKeyUsageOnCertificate(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); var cert = new X509Certificate2(certPath, "testPassword"); Assert.NotEmpty(cert.Extensions); var eku = Assert.Single(cert.Extensions.OfType<X509EnhancedKeyUsageExtension>()); Assert.NotEmpty(eku.EnhancedKeyUsages); new HttpsConnectionMiddleware(context => Task.CompletedTask, new HttpsConnectionAdapterOptions { ServerCertificate = cert, }); } [Theory] [InlineData("eku.code_signing.pfx")] [InlineData("eku.client.pfx")] public void ThrowsForCertificatesMissingServerEku(string testCertName) { var certPath = TestResources.GetCertPath(testCertName); TestOutputHelper.WriteLine("Loading " + certPath); var cert = new X509Certificate2(certPath, "testPassword"); Assert.NotEmpty(cert.Extensions); var eku = Assert.Single(cert.Extensions.OfType<X509EnhancedKeyUsageExtension>()); Assert.NotEmpty(eku.EnhancedKeyUsages); var ex = Assert.Throws<InvalidOperationException>(() => new HttpsConnectionMiddleware(context => Task.CompletedTask, new HttpsConnectionAdapterOptions { ServerCertificate = cert, })); Assert.Equal(CoreStrings.FormatInvalidServerCertificateEku(cert.Thumbprint), ex.Message); } [ConditionalTheory] [InlineData(HttpProtocols.Http1)] [InlineData(HttpProtocols.Http2)] [InlineData(HttpProtocols.Http1AndHttp2)] [OSSkipCondition(OperatingSystems.MacOSX, SkipReason = "Missing SslStream ALPN support: https://github.com/dotnet/runtime/issues/27727")] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] public async Task ListenOptionsProtolsCanBeSetAfterUseHttps(HttpProtocols httpProtocols) { void ConfigureListenOptions(ListenOptions listenOptions) { listenOptions.UseHttps(_x509Certificate2); listenOptions.Protocols = httpProtocols; } await using var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory), ConfigureListenOptions); using var connection = server.CreateConnection(); var sslOptions = new SslClientAuthenticationOptions { TargetHost = "localhost", EnabledSslProtocols = SslProtocols.None, ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, }; using var stream = OpenSslStream(connection.Stream); await stream.AuthenticateAsClientAsync(sslOptions); Assert.Equal( httpProtocols.HasFlag(HttpProtocols.Http2) ? SslApplicationProtocol.Http2 : SslApplicationProtocol.Http11, stream.NegotiatedApplicationProtocol); } [ConditionalFact] [OSSkipCondition(OperatingSystems.MacOSX | OperatingSystems.Linux, SkipReason = "Downgrade logic only applies on Windows")] [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win81)] public void Http1AndHttp2DowngradeToHttp1ForHttpsOnIncompatibleWindowsVersions() { var httpConnectionAdapterOptions = new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2, HttpProtocols = HttpProtocols.Http1AndHttp2 }; new HttpsConnectionMiddleware(context => Task.CompletedTask, httpConnectionAdapterOptions); Assert.Equal(HttpProtocols.Http1, httpConnectionAdapterOptions.HttpProtocols); } [ConditionalFact] [OSSkipCondition(OperatingSystems.MacOSX | OperatingSystems.Linux, SkipReason = "Downgrade logic only applies on Windows")] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] public void Http1AndHttp2DoesNotDowngradeOnCompatibleWindowsVersions() { var httpConnectionAdapterOptions = new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2, HttpProtocols = HttpProtocols.Http1AndHttp2 }; new HttpsConnectionMiddleware(context => Task.CompletedTask, httpConnectionAdapterOptions); Assert.Equal(HttpProtocols.Http1AndHttp2, httpConnectionAdapterOptions.HttpProtocols); } [ConditionalFact] [OSSkipCondition(OperatingSystems.MacOSX | OperatingSystems.Linux, SkipReason = "Error logic only applies on Windows")] [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win81)] public void Http2ThrowsOnIncompatibleWindowsVersions() { var httpConnectionAdapterOptions = new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2, HttpProtocols = HttpProtocols.Http2 }; Assert.Throws<NotSupportedException>(() => new HttpsConnectionMiddleware(context => Task.CompletedTask, httpConnectionAdapterOptions)); } [ConditionalFact] [OSSkipCondition(OperatingSystems.MacOSX | OperatingSystems.Linux, SkipReason = "Error logic only applies on Windows")] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10)] public void Http2DoesNotThrowOnCompatibleWindowsVersions() { var httpConnectionAdapterOptions = new HttpsConnectionAdapterOptions { ServerCertificate = _x509Certificate2, HttpProtocols = HttpProtocols.Http2 }; // Does not throw new HttpsConnectionMiddleware(context => Task.CompletedTask, httpConnectionAdapterOptions); } private static async Task App(HttpContext httpContext) { var request = httpContext.Request; var response = httpContext.Response; while (true) { var buffer = new byte[8192]; var count = await request.Body.ReadAsync(buffer, 0, buffer.Length); if (count == 0) { break; } await response.Body.WriteAsync(buffer, 0, count); } } private static SslStream OpenSslStream(Stream rawStream) { return new SslStream(rawStream, false, (sender, certificate, chain, errors) => true); } /// <summary> /// SslStream is used to ensure the certificate is actually passed to the server /// HttpClient might not send the certificate because it is invalid or it doesn't match any /// of the certificate authorities sent by the server in the SSL handshake. /// </summary> private static SslStream OpenSslStreamWithCert(Stream rawStream, X509Certificate2 clientCertificate = null) { return new SslStream(rawStream, false, (sender, certificate, chain, errors) => true, (sender, host, certificates, certificate, issuers) => clientCertificate ?? _x509Certificate2); } private static async Task AssertConnectionResult(SslStream stream, bool success, string body = null) { var request = body == null ? Encoding.UTF8.GetBytes("GET / HTTP/1.0\r\n\r\n") : Encoding.UTF8.GetBytes($"POST / HTTP/1.0\r\nContent-Length: {body.Length}\r\n\r\n{body}"); await stream.WriteAsync(request, 0, request.Length); var reader = new StreamReader(stream); string line = null; if (success) { line = await reader.ReadLineAsync(); Assert.Equal("HTTP/1.1 200 OK", line); } else { try { line = await reader.ReadLineAsync(); } catch (IOException) { } Assert.Null(line); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace System.Net { internal class NetworkStreamWrapper : Stream { private readonly TcpClient _client; private NetworkStream _networkStream; internal NetworkStreamWrapper(TcpClient client) { _client = client; _networkStream = client.GetStream(); } protected bool UsingSecureStream { get { return (_networkStream is TlsStream); } } internal IPAddress ServerAddress { get { return ((IPEndPoint)Socket.RemoteEndPoint).Address; } } internal Socket Socket { get { return _client.Client; } } internal NetworkStream NetworkStream { get { return _networkStream; } set { _networkStream = value; } } public override bool CanRead { get { return _networkStream.CanRead; } } public override bool CanSeek { get { return _networkStream.CanSeek; } } public override bool CanWrite { get { return _networkStream.CanWrite; } } public override bool CanTimeout { get { return _networkStream.CanTimeout; } } public override int ReadTimeout { get { return _networkStream.ReadTimeout; } set { _networkStream.ReadTimeout = value; } } public override int WriteTimeout { get { return _networkStream.WriteTimeout; } set { _networkStream.WriteTimeout = value; } } public override long Length { get { return _networkStream.Length; } } public override long Position { get { return _networkStream.Position; } set { _networkStream.Position = value; } } public override long Seek(long offset, SeekOrigin origin) { return _networkStream.Seek(offset, origin); } public override int Read(byte[] buffer, int offset, int size) { return _networkStream.Read(buffer, offset, size); } public override void Write(byte[] buffer, int offset, int size) { _networkStream.Write(buffer, offset, size); } protected override void Dispose(bool disposing) { try { if (disposing) { // no timeout so that socket will close gracefully CloseSocket(); } } finally { base.Dispose(disposing); } } internal void CloseSocket() { _networkStream.Close(); _client.Dispose(); } public void Close(int timeout) { _networkStream.Close(timeout); _client.Dispose(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { return _networkStream.BeginRead(buffer, offset, size, callback, state); } public override int EndRead(IAsyncResult asyncResult) { return _networkStream.EndRead(asyncResult); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _networkStream.ReadAsync(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { return _networkStream.BeginWrite(buffer, offset, size, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { _networkStream.EndWrite(asyncResult); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _networkStream.WriteAsync(buffer, offset, count, cancellationToken); } public override void Flush() { _networkStream.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { return _networkStream.FlushAsync(cancellationToken); } public override void SetLength(long value) { _networkStream.SetLength(value); } internal void SetSocketTimeoutOption(int timeout) { _networkStream.ReadTimeout = timeout; _networkStream.WriteTimeout = timeout; } } } // System.Net
//------------------------------------------------------------------------------ // <copyright file="FileSystemWatcher.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.IO { using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.ComponentModel; using System.ComponentModel.Design; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Security.Permissions; using System.Security; using System.Globalization; using System.Runtime.Versioning; /// <devdoc> /// <para>Listens to the system directory change notifications and /// raises events when a directory or file within a directory changes.</para> /// </devdoc> [ DefaultEvent("Changed"), // Disabling partial trust scenarios PermissionSet(SecurityAction.LinkDemand, Name="FullTrust"), PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust"), IODescription(SR.FileSystemWatcherDesc) ] public class FileSystemWatcher : Component, ISupportInitialize { /// <devdoc> /// Private instance variables /// </devdoc> // Directory being monitored private string directory; // Filter for name matching private string filter; // Unmanaged handle to monitored directory private SafeFileHandle directoryHandle; // The watch filter for the API call. private const NotifyFilters defaultNotifyFilters = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; private NotifyFilters notifyFilters = defaultNotifyFilters; // Flag to watch subtree of this directory private bool includeSubdirectories = false; // Flag to note whether we are attached to the thread pool and responding to changes private bool enabled = false; // Are we in init? private bool initializing = false; // Buffer size private int internalBufferSize = 8192; // Used for synchronization private WaitForChangedResult changedResult; private bool isChanged = false; private ISynchronizeInvoke synchronizingObject; private bool readGranted; private bool disposed; // Current "session" ID to ignore old events whenever we stop then // restart. private int currentSession; // Event handlers private FileSystemEventHandler onChangedHandler = null; private FileSystemEventHandler onCreatedHandler = null; private FileSystemEventHandler onDeletedHandler = null; private RenamedEventHandler onRenamedHandler = null; private ErrorEventHandler onErrorHandler = null; // Thread gate holder and constats private bool stopListening = false; // Used for async method private bool runOnce = false; // To validate the input for "path" private static readonly char[] wildcards = new char[] { '?', '*' }; private static int notifyFiltersValidMask; // Additional state information to pass to callback. Note that we // never return this object to users, but we do pass state in it. private sealed class FSWAsyncResult : IAsyncResult { internal int session; internal byte[] buffer; public bool IsCompleted { get { throw new NotImplementedException(); } } public WaitHandle AsyncWaitHandle { get { throw new NotImplementedException(); } } public Object AsyncState { get { throw new NotImplementedException(); } } public bool CompletedSynchronously { get { throw new NotImplementedException(); } } } static FileSystemWatcher() { notifyFiltersValidMask = 0; foreach (int enumValue in Enum.GetValues(typeof(NotifyFilters))) notifyFiltersValidMask |= enumValue; } /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class.</para> /// </devdoc> public FileSystemWatcher() { this.directory = String.Empty; this.filter = "*.*"; } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory to monitor. /// </para> /// </devdoc> [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileSystemWatcher(string path) : this(path, "*.*") { } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory and type of files to monitor. /// </para> /// </devdoc> [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public FileSystemWatcher(string path, string filter) { if (path == null) throw new ArgumentNullException("path"); if (filter == null) throw new ArgumentNullException("filter"); // Early check for directory parameter so that an exception can be thrown as early as possible. if (path.Length == 0 || !Directory.Exists(path)) throw new ArgumentException(SR.GetString(SR.InvalidDirName, path)); this.directory = path; this.filter = filter; } /// <devdoc> /// <para> /// Gets or sets the type of changes to watch for. /// </para> /// </devdoc> [ DefaultValue(defaultNotifyFilters), IODescription(SR.FSW_ChangedFilter) ] public NotifyFilters NotifyFilter { get { return notifyFilters; } set { if (((int) value & ~notifyFiltersValidMask) != 0) throw new InvalidEnumArgumentException("value", (int)value, typeof(NotifyFilters)); if (notifyFilters != value) { notifyFilters = value; Restart(); } } } /// <devdoc> /// <para>Gets or sets a value indicating whether the component is enabled.</para> /// </devdoc> [ DefaultValue(false), IODescription(SR.FSW_Enabled) ] public bool EnableRaisingEvents { get { return enabled; } set { if (enabled == value) { return; } enabled = value; if (!IsSuspended()) { if (enabled) { StartRaisingEvents(); } else { StopRaisingEvents(); } } } } /// <devdoc> /// <para>Gets or sets the filter string, used to determine what files are monitored in a directory.</para> /// </devdoc> [ DefaultValue("*.*"), IODescription(SR.FSW_Filter), TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign), SettingsBindable(true), ] public string Filter { get { return filter; } set { if (String.IsNullOrEmpty(value)) { value = "*.*"; } if (String.Compare(filter, value, StringComparison.OrdinalIgnoreCase) != 0) { filter = value; } } } /// <devdoc> /// <para> /// Gets or sets a /// value indicating whether subdirectories within the specified path should be monitored. /// </para> /// </devdoc> [ DefaultValue(false), IODescription(SR.FSW_IncludeSubdirectories) ] public bool IncludeSubdirectories { get { return includeSubdirectories; } set { if (includeSubdirectories != value) { includeSubdirectories = value; Restart(); } } } /// <devdoc> /// <para>Gets or /// sets the size of the internal buffer.</para> /// </devdoc> [ Browsable(false), DefaultValue(8192) ] public int InternalBufferSize { get { return internalBufferSize; } set { if (internalBufferSize != value) { if (value < 4096) { value = 4096; } internalBufferSize = value; Restart(); } } } private bool IsHandleInvalid { get { return (directoryHandle == null || directoryHandle.IsInvalid); } } /// <devdoc> /// <para>Gets or sets the path of the directory to watch.</para> /// </devdoc> [ DefaultValue(""), IODescription(SR.FSW_Path), Editor("System.Diagnostics.Design.FSWPathEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign), SettingsBindable(true) ] public string Path { [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] get { return directory; } [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] set { value = (value == null) ? string.Empty : value; if (String.Compare(directory, value, StringComparison.OrdinalIgnoreCase) != 0) { if (DesignMode) { // Don't check the path if in design mode, try to do simple syntax check if (value.IndexOfAny(FileSystemWatcher.wildcards) != -1 || value.IndexOfAny(System.IO.Path.GetInvalidPathChars()) != -1) { throw new ArgumentException(SR.GetString(SR.InvalidDirName, value)); } } else { if (!Directory.Exists(value)) throw new ArgumentException(SR.GetString(SR.InvalidDirName, value)); } directory = value; readGranted = false; Restart(); } } } /// <internalonly/> /// <devdoc> /// </devdoc> [Browsable(false)] public override ISite Site { get { return base.Site; } set { base.Site = value; // set EnableRaisingEvents to true at design time so the user // doesn't have to manually. We can't do this in // the constructor because in code it should // default to false. if (Site != null && Site.DesignMode) EnableRaisingEvents = true; } } /// <devdoc> /// <para> /// Gets or sets the object used to marshal the event handler calls issued as a /// result of a directory change. /// </para> /// </devdoc> [ Browsable(false), DefaultValue(null), IODescription(SR.FSW_SynchronizingObject) ] public ISynchronizeInvoke SynchronizingObject { get { if (this.synchronizingObject == null && DesignMode) { IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost)); if (host != null) { object baseComponent = host.RootComponent; if (baseComponent != null && baseComponent is ISynchronizeInvoke) this.synchronizingObject = (ISynchronizeInvoke)baseComponent; } } return this.synchronizingObject; } set { this.synchronizingObject = value; } } /// <devdoc> /// <para> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> /// is changed. /// </para> /// </devdoc> [IODescription(SR.FSW_Changed)] public event FileSystemEventHandler Changed { add { onChangedHandler += value; } remove { onChangedHandler -= value; } } /// <devdoc> /// <para> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> /// is created. /// </para> /// </devdoc> [IODescription(SR.FSW_Created)] public event FileSystemEventHandler Created { add { onCreatedHandler += value; } remove { onCreatedHandler -= value; } } /// <devdoc> /// <para> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> /// is deleted. /// </para> /// </devdoc> [IODescription(SR.FSW_Deleted)] public event FileSystemEventHandler Deleted { add{ onDeletedHandler += value; } remove { onDeletedHandler -= value; } } /// <devdoc> /// <para> /// Occurs when the internal buffer overflows. /// </para> /// </devdoc> [Browsable(false)] public event ErrorEventHandler Error { add { onErrorHandler += value; } remove { onErrorHandler -= value; } } /// <devdoc> /// <para> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> /// is renamed. /// </para> /// </devdoc> [IODescription(SR.FSW_Renamed)] public event RenamedEventHandler Renamed { add { onRenamedHandler += value; } remove { onRenamedHandler -= value; } } /// <devdoc> /// <para>Notifies the object that initialization is beginning and tells it to standby.</para> /// </devdoc> public void BeginInit() { bool oldEnabled = enabled; StopRaisingEvents(); enabled = oldEnabled; initializing = true; } /// <devdoc> /// Callback from thread pool. /// </devdoc> /// <internalonly/> private unsafe void CompletionStatusChanged(uint errorCode, uint numBytes, NativeOverlapped * overlappedPointer) { Overlapped overlapped = Overlapped.Unpack(overlappedPointer); FSWAsyncResult asyncResult = (FSWAsyncResult) overlapped.AsyncResult; try { if (stopListening) { return; } lock (this) { if (errorCode != 0) { if (errorCode == 995 /* ERROR_OPERATION_ABORTED */) { //Win2000 inside a service the first completion status is false //cannot return without monitoring again. //Because this return statement is inside a try/finally block, //the finally block will execute. It does restart the monitoring. return; } else { OnError(new ErrorEventArgs(new Win32Exception((int)errorCode))); EnableRaisingEvents = false; return; } } // Ignore any events that occurred before this "session", // so we don't get changed or error events after we // told FSW to stop. if (asyncResult.session != currentSession) return; if (numBytes == 0) { NotifyInternalBufferOverflowEvent(); } else { // Else, parse each of them and notify appropriate delegates /****** Format for the buffer is the following C struct: typedef struct _FILE_NOTIFY_INFORMATION { DWORD NextEntryOffset; DWORD Action; DWORD FileNameLength; WCHAR FileName[1]; } FILE_NOTIFY_INFORMATION; NOTE1: FileNameLength is length in bytes. NOTE2: The Filename is a Unicode string that's NOT NULL terminated. NOTE3: A NextEntryOffset of zero means that it's the last entry *******/ // Parse the file notify buffer: int offset = 0; int nextOffset, action, nameLength; string oldName = null; string name = null; do { fixed (byte * buffPtr = asyncResult.buffer) { // Get next offset: nextOffset = *( (int *) (buffPtr + offset) ); // Get change flag: action = *( (int *) (buffPtr + offset + 4) ); // Get filename length (in bytes): nameLength = *( (int *) (buffPtr + offset + 8) ); name = new String( (char *) (buffPtr + offset + 12), 0, nameLength / 2); } /* A slightly convoluted piece of code follows. Here's what's happening: We wish to collapse the poorly done rename notifications from the ReadDirectoryChangesW API into a nice rename event. So to do that, it's assumed that a FILE_ACTION_RENAMED_OLD_NAME will be followed immediately by a FILE_ACTION_RENAMED_NEW_NAME in the buffer, which is all that the following code is doing. On a FILE_ACTION_RENAMED_OLD_NAME, it asserts that no previous one existed and saves its name. If there are no more events in the buffer, it'll assert and fire a RenameEventArgs with the Name field null. If a NEW_NAME action comes in with no previous OLD_NAME, we assert and fire a rename event with the OldName field null. If the OLD_NAME and NEW_NAME actions are indeed there one after the other, we'll fire the RenamedEventArgs normally and clear oldName. If the OLD_NAME is followed by another action, we assert and then fire the rename event with the Name field null and then fire the next action. In case it's not a OLD_NAME or NEW_NAME action, we just fire the event normally. (Phew!) */ // If the action is RENAMED_FROM, save the name of the file if (action == Direct.FILE_ACTION_RENAMED_OLD_NAME) { Debug.Assert(oldName == null, "FileSystemWatcher: Two FILE_ACTION_RENAMED_OLD_NAME " + "in a row! [" + oldName + "], [ " + name + "]"); oldName = name; } else if (action == Direct.FILE_ACTION_RENAMED_NEW_NAME) { if (oldName != null) { NotifyRenameEventArgs(WatcherChangeTypes.Renamed, name, oldName); oldName = null; } else { Debug.Assert(false, "FileSystemWatcher: FILE_ACTION_RENAMED_NEW_NAME with no" + "old name! [ " + name + "]"); NotifyRenameEventArgs(WatcherChangeTypes.Renamed, name, oldName); oldName = null; } } else { if (oldName != null) { Debug.Assert(false, "FileSystemWatcher: FILE_ACTION_RENAMED_OLD_NAME with no" + "new name! [" + oldName + "]"); NotifyRenameEventArgs(WatcherChangeTypes.Renamed, null, oldName); oldName = null; } // Notify each file of change NotifyFileSystemEventArgs(action, name); } offset += nextOffset; } while (nextOffset != 0); if (oldName != null) { Debug.Assert(false, "FileSystemWatcher: FILE_ACTION_RENAMED_OLD_NAME with no" + "new name! [" + oldName + "]"); NotifyRenameEventArgs(WatcherChangeTypes.Renamed, null, oldName); oldName = null; } } } } finally { Overlapped.Free(overlappedPointer); if (!stopListening && !runOnce) { Monitor(asyncResult.buffer); } } } /// <devdoc> /// </devdoc> protected override void Dispose(bool disposing) { try { if (disposing) { //Stop raising events cleans up managed and //unmanaged resources. StopRaisingEvents(); // Clean up managed resources onChangedHandler = null; onCreatedHandler = null; onDeletedHandler = null; onRenamedHandler = null; onErrorHandler = null; readGranted = false; } else { stopListening = true; // Clean up unmanaged resources if (!IsHandleInvalid) { directoryHandle.Close(); } } } finally { this.disposed = true; base.Dispose(disposing); } } /// <devdoc> /// <para> /// Notifies the object that initialization is complete. /// </para> /// </devdoc> public void EndInit() { initializing = false; // Unless user told us NOT to start after initialization, we'll start listening // to events if (directory.Length != 0 && enabled == true) StartRaisingEvents(); } /// <devdoc> /// Returns true if the component is either in a Begin/End Init block or in design mode. /// </devdoc> // <internalonly/> // private bool IsSuspended() { return initializing || DesignMode; } /// <devdoc> /// Sees if the name given matches the name filter we have. /// </devdoc> /// <internalonly/> private bool MatchPattern(string relativePath) { string name = System.IO.Path.GetFileName(relativePath); if (name != null) return PatternMatcher.StrictMatchPattern(filter.ToUpper(CultureInfo.InvariantCulture), name.ToUpper(CultureInfo.InvariantCulture)); else return false; } /// <devdoc> /// Calls native API and sets up handle with the directory change API. /// </devdoc> /// <internalonly/> [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private unsafe void Monitor(byte[] buffer) { if (!enabled || IsHandleInvalid) { return; } Overlapped overlapped = new Overlapped(); if (buffer == null) { try { buffer = new byte[internalBufferSize]; } catch (OutOfMemoryException) { throw new OutOfMemoryException(SR.GetString(SR.BufferSizeTooLarge, internalBufferSize.ToString(CultureInfo.CurrentCulture))); } } // Pass "session" counter to callback: FSWAsyncResult asyncResult = new FSWAsyncResult(); asyncResult.session = currentSession; asyncResult.buffer = buffer; // Pack overlapped. The buffer will be pinned by Overlapped: overlapped.AsyncResult = asyncResult; NativeOverlapped* overlappedPointer = overlapped.Pack(new IOCompletionCallback(this.CompletionStatusChanged), buffer); // Can now call OS: int size; bool ok = false; try { // There could be a ---- in user code between calling StopRaisingEvents (where we close the handle) // and when we get here from CompletionStatusChanged. // We might need to take a lock to prevent ---- absolutely, instead just catch // ObjectDisposedException from SafeHandle in case it is disposed if (!IsHandleInvalid) { // An interrupt is possible here fixed (byte * buffPtr = buffer) { ok = UnsafeNativeMethods.ReadDirectoryChangesW(directoryHandle, new HandleRef(this, (IntPtr) buffPtr), internalBufferSize, includeSubdirectories ? 1 : 0, (int) notifyFilters, out size, overlappedPointer, NativeMethods.NullHandleRef); } } } catch (ObjectDisposedException ) { //Ignore Debug.Assert(IsHandleInvalid, "ObjectDisposedException from something other than SafeHandle?"); } catch (ArgumentNullException ) { //Ignore Debug.Assert(IsHandleInvalid, "ArgumentNullException from something other than SafeHandle?"); } finally { if (! ok) { Overlapped.Free(overlappedPointer); // If the handle was for some reason changed or closed during this call, then don't throw an // exception. Else, it's a valid error. if (!IsHandleInvalid) { OnError(new ErrorEventArgs(new Win32Exception())); } } } } /// <devdoc> /// Raises the event to each handler in the list. /// </devdoc> /// <internalonly/> private void NotifyFileSystemEventArgs(int action, string name) { if (!MatchPattern(name)) { return; } switch (action) { case Direct.FILE_ACTION_ADDED: OnCreated(new FileSystemEventArgs(WatcherChangeTypes.Created, directory, name)); break; case Direct.FILE_ACTION_REMOVED: OnDeleted(new FileSystemEventArgs(WatcherChangeTypes.Deleted, directory, name)); break; case Direct.FILE_ACTION_MODIFIED: OnChanged(new FileSystemEventArgs(WatcherChangeTypes.Changed, directory, name)); break; default: Debug.Fail("Unknown FileSystemEvent action type! Value: "+action); break; } } /// <devdoc> /// Raises the event to each handler in the list. /// </devdoc> /// <internalonly/> private void NotifyInternalBufferOverflowEvent() { InternalBufferOverflowException ex = new InternalBufferOverflowException(SR.GetString(SR.FSW_BufferOverflow, directory)); ErrorEventArgs errevent = new ErrorEventArgs(ex); OnError(errevent); } /// <devdoc> /// Raises the event to each handler in the list. /// </devdoc> /// <internalonly/> private void NotifyRenameEventArgs(WatcherChangeTypes action, string name, string oldName) { //filter if neither new name or old name are a match a specified pattern if (!MatchPattern(name) && !MatchPattern(oldName)) { return; } RenamedEventArgs renevent = new RenamedEventArgs(action, directory, name, oldName); OnRenamed(renevent); } /// <devdoc> /// <para> /// Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event. /// </para> /// </devdoc> [SuppressMessage("Microsoft.Security","CA2109:ReviewVisibleEventHandlers", MessageId="0#", Justification="Changing from protected to private would be a breaking change")] protected void OnChanged(FileSystemEventArgs e) { // To avoid ---- between remove handler and raising the event FileSystemEventHandler changedHandler = onChangedHandler; if (changedHandler != null) { if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) this.SynchronizingObject.BeginInvoke(changedHandler, new object[]{this, e}); else changedHandler(this, e); } } /// <devdoc> /// <para> /// Raises the <see cref='System.IO.FileSystemWatcher.Created'/> event. /// </para> /// </devdoc> [SuppressMessage("Microsoft.Security","CA2109:ReviewVisibleEventHandlers", MessageId="0#", Justification="Changing from protected to private would be a breaking change")] protected void OnCreated(FileSystemEventArgs e) { // To avoid ---- between remove handler and raising the event FileSystemEventHandler createdHandler = onCreatedHandler; if (createdHandler != null) { if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) this.SynchronizingObject.BeginInvoke(createdHandler, new object[]{this, e}); else createdHandler(this, e); } } /// <devdoc> /// <para> /// Raises the <see cref='System.IO.FileSystemWatcher.Deleted'/> event. /// </para> /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnDeleted(FileSystemEventArgs e) { // To avoid ---- between remove handler and raising the event FileSystemEventHandler deletedHandler = onDeletedHandler; if (deletedHandler != null) { if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) this.SynchronizingObject.BeginInvoke(deletedHandler, new object[]{this, e}); else deletedHandler(this, e); } } /// <devdoc> /// <para> /// Raises the <see cref='System.IO.FileSystemWatcher.Error'/> event. /// </para> /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnError(ErrorEventArgs e) { // To avoid ---- between remove handler and raising the event ErrorEventHandler errorHandler = onErrorHandler; if (errorHandler != null) { if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) this.SynchronizingObject.BeginInvoke(errorHandler, new object[]{this, e}); else errorHandler(this, e); } } /// <devdoc> /// Internal method used for synchronous notification. /// </devdoc> /// <internalonly/> private void OnInternalFileSystemEventArgs(object sender, FileSystemEventArgs e) { lock (this) { // Only change the state of the changed result if it doesn't contain a previous one. if (isChanged != true) { changedResult = new WaitForChangedResult(e.ChangeType, e.Name, false); isChanged = true; System.Threading.Monitor.Pulse(this); } } } /// <devdoc> /// Internal method used for synchronous notification. /// </devdoc> /// <internalonly/> private void OnInternalRenameEventArgs(object sender, RenamedEventArgs e) { lock (this) { // Only change the state of the changed result if it doesn't contain a previous one. if (isChanged != true) { changedResult = new WaitForChangedResult(e.ChangeType, e.Name, e.OldName, false); isChanged = true; System.Threading.Monitor.Pulse(this); } } } /// <devdoc> /// <para> /// Raises the <see cref='System.IO.FileSystemWatcher.Renamed'/> event. /// </para> /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnRenamed(RenamedEventArgs e) { RenamedEventHandler renamedHandler = onRenamedHandler; if (renamedHandler != null) { if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) this.SynchronizingObject.BeginInvoke(renamedHandler, new object[]{this, e}); else renamedHandler(this, e); } } /// <devdoc> /// Stops and starts this object. /// </devdoc> /// <internalonly/> private void Restart() { if ((!IsSuspended()) && enabled) { StopRaisingEvents(); StartRaisingEvents(); } } /// <devdoc> /// <para> /// Starts monitoring the specified directory. /// </para> /// </devdoc> [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private void StartRaisingEvents() { //Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed. if (this.disposed) throw new ObjectDisposedException(GetType().Name); try { new EnvironmentPermission(PermissionState.Unrestricted).Assert(); if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired)); } } finally { CodeAccessPermission.RevertAssert(); } // If we're called when "Initializing" is true, set enabled to true if (IsSuspended()) { enabled = true; return; } if (!readGranted) { string fullPath; // Consider asserting path discovery permission here. fullPath = System.IO.Path.GetFullPath(directory); FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, fullPath); permission.Demand(); readGranted = true; } // If we're attached, don't do anything. if (!IsHandleInvalid) { return; } // Create handle to directory being monitored directoryHandle = NativeMethods.CreateFile(directory, // Directory name UnsafeNativeMethods.FILE_LIST_DIRECTORY, // access (read-write) mode UnsafeNativeMethods.FILE_SHARE_READ | UnsafeNativeMethods.FILE_SHARE_DELETE | UnsafeNativeMethods.FILE_SHARE_WRITE, // share mode null, // security descriptor UnsafeNativeMethods.OPEN_EXISTING, // how to create UnsafeNativeMethods.FILE_FLAG_BACKUP_SEMANTICS | UnsafeNativeMethods.FILE_FLAG_OVERLAPPED, // file attributes new SafeFileHandle(IntPtr.Zero, false) // file with attributes to copy ); if (IsHandleInvalid) { throw new FileNotFoundException(SR.GetString(SR.FSW_IOError, directory)); } stopListening = false; // Start ignoring all events that were initiated before this. Interlocked.Increment(ref currentSession); // Attach handle to thread pool //SECREVIEW: At this point at least FileIOPermission has already been demanded. SecurityPermission secPermission = new SecurityPermission(PermissionState.Unrestricted); secPermission.Assert(); try { ThreadPool.BindHandle(directoryHandle); } finally { SecurityPermission.RevertAssert(); } enabled = true; // Setup IO completion port Monitor(null); } /// <devdoc> /// <para> /// Stops monitoring the specified directory. /// </para> /// </devdoc> private void StopRaisingEvents() { if (IsSuspended()) { enabled = false; return; } // If we're not attached, do nothing. if (IsHandleInvalid) { return; } // Close directory handle // This operation doesn't need to be atomic because the API will deal with a closed // handle appropriately. // Ensure that the directoryHandle is set to INVALID_HANDLE before closing it, so that // the Monitor() can shutdown appropriately. // If we get here while asynchronously waiting on a change notification, closing the // directory handle should cause CompletionStatusChanged be be called // thus freeing the pinned buffer. stopListening = true; directoryHandle.Close(); directoryHandle = null; // Start ignoring all events occurring after this. Interlocked.Increment(ref currentSession); // Set enabled to false enabled = false; } /// <devdoc> /// <para> /// A synchronous method that returns a structure that /// contains specific information on the change that occurred, given the type /// of change that you wish to monitor. /// </para> /// </devdoc> public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) { return WaitForChanged(changeType, -1); } /// <devdoc> /// <para> /// A synchronous /// method that returns a structure that contains specific information on the change that occurred, given the /// type of change that you wish to monitor and the time (in milliseconds) to wait before timing out. /// </para> /// </devdoc> public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) { FileSystemEventHandler dirHandler = new FileSystemEventHandler(this.OnInternalFileSystemEventArgs); RenamedEventHandler renameHandler = new RenamedEventHandler(this.OnInternalRenameEventArgs); this.isChanged = false; this.changedResult = WaitForChangedResult.TimedOutResult; // Register the internal event handler from the given change types. if ((changeType & WatcherChangeTypes.Created) != 0) { this.Created += dirHandler; } if ((changeType & WatcherChangeTypes.Deleted) != 0) { this.Deleted += dirHandler; } if ((changeType & WatcherChangeTypes.Changed) != 0) { this.Changed += dirHandler; } if ((changeType & WatcherChangeTypes.Renamed) != 0) { this.Renamed += renameHandler; } // Save the Enabled state of this component to revert back to it later (if needed). bool savedEnabled = EnableRaisingEvents; if (savedEnabled == false) { runOnce = true; EnableRaisingEvents = true; } // For each thread entering this wait loop, addref it and wait. When the last one // exits, reset the waiterObject. WaitForChangedResult retVal = WaitForChangedResult.TimedOutResult; lock (this) { if (timeout == -1) { while (!isChanged) { System.Threading.Monitor.Wait(this); } } else { System.Threading.Monitor.Wait(this, timeout, true); } retVal = changedResult; } // Revert the Enabled flag to its previous state. EnableRaisingEvents = savedEnabled; runOnce = false; // Decouple the event handlers added above. if ((changeType & WatcherChangeTypes.Created) != 0) { this.Created -= dirHandler; } if ((changeType & WatcherChangeTypes.Deleted) != 0) { this.Deleted -= dirHandler; } if ((changeType & WatcherChangeTypes.Changed) != 0) { this.Changed -= dirHandler; } if ((changeType & WatcherChangeTypes.Renamed) != 0) { this.Renamed -= renameHandler; } // Return the struct. return retVal; } } /// <devdoc> /// Helper class to hold to N/Direct call declaration and flags. /// </devdoc> [ System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] internal static class Direct { // All possible action flags public const int FILE_ACTION_ADDED = 1; public const int FILE_ACTION_REMOVED = 2; public const int FILE_ACTION_MODIFIED = 3; public const int FILE_ACTION_RENAMED_OLD_NAME = 4; public const int FILE_ACTION_RENAMED_NEW_NAME = 5; // All possible notifications flags public const int FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001; public const int FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002; public const int FILE_NOTIFY_CHANGE_NAME = 0x00000003; public const int FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004; public const int FILE_NOTIFY_CHANGE_SIZE = 0x00000008; public const int FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010; public const int FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020; public const int FILE_NOTIFY_CHANGE_CREATION = 0x00000040; public const int FILE_NOTIFY_CHANGE_SECURITY = 0x00000100; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Threading; using System.Xml; using System.Net; using System.Text; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.BlogClient.Providers; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.CoreServices; namespace OpenLiveWriter.BlogClient.Clients { [BlogClient("LiveJournal", "LiveJournal")] public class LiveJournalClient : BloggerCompatibleClient { public LiveJournalClient(Uri postApiUrl, IBlogCredentialsAccessor credentials) : base(postApiUrl, credentials) { } protected override void ConfigureClientOptions(BlogClientOptions clientOptions) { clientOptions.SupportsFileUpload = true; clientOptions.SupportsCustomDate = false; clientOptions.SupportsExtendedEntries = true; } protected override string NodeToText(XmlNode node) { XmlElement childNode = node.FirstChild as XmlElement; if (childNode != null && childNode.LocalName == "base64") { try { return Encoding.UTF8.GetString(Convert.FromBase64String(childNode.InnerText)); } catch (Exception e) { Trace.Fail(e.ToString()); } } return node.InnerText; } public override BlogPostCategory[] GetCategories(string blogId) { // LiveJournal does not support client posting of categories return new BlogPostCategory[] { }; } public override BlogPostKeyword[] GetKeywords(string blogId) { Trace.Fail("LiveJournal does not support GetKeywords!"); return new BlogPostKeyword[] { }; } public override BlogPost GetPost(string blogId, string postId) { // query for post XmlNode postResult = CallMethod("blogger.getPost", new XmlRpcString(APP_KEY), new XmlRpcString(postId), new XmlRpcString(Username), new XmlRpcString(Password, true)); // parse results try { // get the post struct XmlNode postNode = postResult.SelectSingleNode("struct"); // create a post to return BlogPost blogPost = new BlogPost(); // extract content ExtractStandardPostFields(postNode, blogPost); // return the post return blogPost; } catch (Exception ex) { string response = postResult != null ? postResult.OuterXml : "(empty response)"; Trace.Fail("Exception occurred while parsing blogger.getPost response: " + response + "\r\n" + ex.ToString()); throw new BlogClientInvalidServerResponseException("blogger.getPost", ex.Message, response); } } public override BlogPost[] GetRecentPosts(string blogId, int maxPosts, bool includeCategories, DateTime? now) { // posts to return ArrayList posts = new ArrayList(); // call the method XmlNode result = CallMethod("blogger.getRecentPosts", new XmlRpcString(APP_KEY), new XmlRpcString(blogId), new XmlRpcString(Username), new XmlRpcString(Password, true), new XmlRpcInt(maxPosts)); // parse results try { XmlNodeList postNodes = result.SelectNodes("array/data/value/struct"); foreach (XmlNode postNode in postNodes) { // create blog post BlogPost blogPost = new BlogPost(); ExtractStandardPostFields(postNode, blogPost); // add to our list of posts if (!now.HasValue || blogPost.DatePublished.CompareTo(now.Value) < 0) posts.Add(blogPost); } } catch (Exception ex) { string response = result != null ? result.OuterXml : "(empty response)"; Trace.Fail("Exception occurred while parsing GetRecentPosts response: " + response + "\r\n" + ex.ToString()); throw new BlogClientInvalidServerResponseException("blogger.getRecentPosts", ex.Message, response); } // return list of posts return (BlogPost[])posts.ToArray(typeof(BlogPost)); } public override string NewPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish) { if (!publish && !Options.SupportsPostAsDraft) { Trace.Fail("Post to draft not supported on this provider"); throw new BlogClientPostAsDraftUnsupportedException(); } // call the method XmlNode result = CallMethod("blogger.newPost", new XmlRpcString(APP_KEY), new XmlRpcString(blogId), new XmlRpcString(Username), new XmlRpcString(Password, true), FormatBlogPost(post), new XmlRpcBoolean(publish)); // return the blog-id return result.InnerText; } public override bool EditPost(string blogId, BlogPost post, INewCategoryContext newCategoryContext, bool publish) { if (!publish && !Options.SupportsPostAsDraft) { Trace.Fail("Post to draft not supported on this provider"); throw new BlogClientPostAsDraftUnsupportedException(); } // call the method XmlNode result = CallMethod("blogger.editPost", new XmlRpcString(APP_KEY), new XmlRpcString(post.Id), new XmlRpcString(Username), new XmlRpcString(Password, true), FormatBlogPost(post), new XmlRpcBoolean(publish)); return (result.InnerText == "1"); } public override string DoBeforePublishUploadWork(IFileUploadContext uploadContext) { const int REQUEST_COUNT = 2; // get as many challenge tokens as we'll need (one for each authenticated request) FotobilderRequestManager frm = new FotobilderRequestManager(Username, Password); XmlDocument doc = frm.PerformGet("GetChallenges", null, "GetChallenges.Qty", REQUEST_COUNT.ToString(CultureInfo.InvariantCulture)); XmlNodeList challengeNodes = doc.SelectNodes(@"/FBResponse/GetChallengesResponse/Challenge"); Trace.Assert(challengeNodes.Count == REQUEST_COUNT); Stack challenges = new Stack(challengeNodes.Count); foreach (XmlNode node in challengeNodes) challenges.Push(node.InnerText); // login long bytesAvailable = long.MaxValue; doc = frm.PerformGet("Login", (string)challenges.Pop(), "Login.ClientVersion", ApplicationEnvironment.UserAgent); XmlNode remainingQuotaNode = doc.SelectSingleNode("/FBResponse/LoginResponse/Quota/Remaining"); if (remainingQuotaNode != null) bytesAvailable = long.Parse(remainingQuotaNode.InnerText, CultureInfo.InvariantCulture); // upload picture using (Stream fileContents = uploadContext.GetContents()) { doc = frm.PerformPut("UploadPic", (string)challenges.Pop(), fileContents, "UploadPic.PicSec", "255", "UploadPic.Meta.Filename", uploadContext.FormatFileName(uploadContext.PreferredFileName), "UploadPic.Gallery._size", "1", "UploadPic.Gallery.0.GalName", ApplicationEnvironment.ProductName, "UploadPic.Gallery.0.GalSec", "0"); } XmlNode picUrlNode = doc.SelectSingleNode("/FBResponse/UploadPicResponse/URL"); if (picUrlNode != null) { return picUrlNode.InnerText; } else { throw new BlogClientInvalidServerResponseException("LiveJournal.UploadPic", "No URL returned from server", doc.OuterXml); } } protected override BlogClientProviderException ExceptionForFault(string faultCode, string faultString) { if ( (faultCode == "100") || (faultCode == "101") || (faultCode.ToUpperInvariant() == "SERVER" && faultString.StartsWith("invalid login", StringComparison.OrdinalIgnoreCase))) { return new BlogClientAuthenticationException(faultCode, faultString); } else { return null; } } private void ExtractStandardPostFields(XmlNode postNode, BlogPost blogPost) { // post id blogPost.Id = NodeText(postNode.SelectSingleNode("member[name='postId']/value")); // contents and title ParsePostContent(postNode.SelectSingleNode("member[name='content']/value"), blogPost); // date published blogPost.DatePublished = ParseBlogDate(postNode.SelectSingleNode("member[name='dateCreated']/value")); } private void ParsePostContent(XmlNode xmlNode, BlogPost blogPost) { // get raw content (decode base64 if necessary) string content; XmlNode base64Node = xmlNode.SelectSingleNode("base64"); if (base64Node != null) { byte[] contentBytes = Convert.FromBase64String(base64Node.InnerText); content = _utf8EncodingNoBOM.GetString(contentBytes); } else // no base64 encoding, just read text { content = xmlNode.InnerText; } // parse out the title and contents of the post HtmlExtractor ex = new HtmlExtractor(content); if (ex.Seek("<title>").Success) { SetPostTitleFromXmlValue(blogPost, ex.CollectTextUntil("title")); content = content.Substring(ex.Parser.Position).TrimStart('\r', '\n'); } if (content.Trim() != string.Empty) { HtmlExtractor ex2 = new HtmlExtractor(content); if (Options.SupportsExtendedEntries && ex2.Seek("<lj-cut>").Success) blogPost.SetContents(content.Substring(0, ex2.Element.Offset), content.Substring(ex2.Element.Offset + ex2.Element.Length)); else blogPost.Contents = content; } } private XmlRpcValue FormatBlogPost(BlogPost post) { string content = post.MainContents; if (post.ExtendedContents != null && post.ExtendedContents.Length > 0) content += "<lj-cut>" + post.ExtendedContents; string blogPostBody = String.Format(CultureInfo.InvariantCulture, "<title>{0}</title>{1}", GetPostTitleForXmlValue(post), content); return new XmlRpcBase64(_utf8EncodingNoBOM.GetBytes(blogPostBody)); } private Encoding _utf8EncodingNoBOM = new UTF8Encoding(false); private class FotobilderRequestManager { private const string ENDPOINT = "http://pics.livejournal.com/interface/simple"; private readonly string username; private readonly string password; public FotobilderRequestManager(string username, string password) { this.username = username; this.password = password; } public XmlDocument PerformGet(string mode, string challenge, params string[] addlParams) { HttpWebRequest request = CreateRequest(mode, challenge, addlParams); request.Method = "GET"; return GetResponse(request, mode); } public XmlDocument PerformPut(string mode, string challenge, Stream requestBody, params string[] addlParams) { HttpWebRequest request = CreateRequest(mode, challenge, addlParams); request.Method = "PUT"; using (Stream requestStream = request.GetRequestStream()) StreamHelper.Transfer(requestBody, requestStream); return GetResponse(request, mode); } private HttpWebRequest CreateRequest(string mode, string challenge, params string[] addlParams) { HttpWebRequest request = HttpRequestHelper.CreateHttpWebRequest(ENDPOINT, true, Timeout.Infinite, Timeout.Infinite); request.Headers.Add("X-FB-User", username); if (challenge != null) request.Headers.Add("X-FB-Auth", CreateAuthString(challenge)); request.Headers.Add("X-FB-Mode", mode); if (addlParams != null) { for (int i = 0; i < addlParams.Length; i += 2) { string name = addlParams[i]; string value = addlParams[i + 1]; if (name != null) request.Headers.Add("X-FB-" + name, value); } } return request; } private static XmlDocument GetResponse(HttpWebRequest request, string mode) { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(responseReader); CheckForErrors(xmlDoc, mode); return xmlDoc; } } } private string CreateAuthString(string challenge) { return string.Format(CultureInfo.InvariantCulture, "crp:{0}:{1}", challenge, MD5Hash(challenge + MD5Hash(password))); } private static string MD5Hash(string str) { byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(str)); StringBuilder sb = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) sb.AppendFormat("{0:x2}", b); return sb.ToString(); } private static void CheckForErrors(XmlDocument doc, string mode) { XmlNode errorNode; if ((errorNode = doc.SelectSingleNode("//Error")) != null) { /* Possible errors: 1xx: User Errors 100 User error 101 No user specified 102 Invalid user 103 Unknown user 2xx: Client Errors 200 Client error 201 Invalid request 202 Invalid mode 203 GetChallenge(s) is exclusive as primary mode 210 Unknown argument 211 Invalid argument 212 Missing required argument 213 Invalid image for upload 3xx: Access Errors 300 Access error 301 No auth specified 302 Invalid auth 303 Account status does not allow upload 4xx: Limit Errors 400 Limit error 401 No disk space remaining 402 Insufficient disk space remaining 403 File upload limit exceeded 5xx: Server Errors 500 Internal Server Error 501 Cannot connect to database 502 Database Error 503 Application Error 510 Error creating gpic 511 Error creating upic 512 Error creating gallery 513 Error adding to gallery */ string errorCode = errorNode.Attributes["code"].Value; string errorString = errorNode.InnerText; switch (errorCode) { case "301": case "302": throw new BlogClientAuthenticationException(errorCode, errorString); case "303": throw new BlogClientFileUploadNotSupportedException(errorCode, errorString); default: throw new BlogClientProviderException(errorCode, errorString); } } } } } }
using System; using Eto.Forms; using Eto.Drawing; using System.Runtime.InteropServices; using GLib; namespace Eto.GtkSharp.Forms.Controls { public class TextBoxHandler : GtkControl<Gtk.Entry, TextBox, TextBox.ICallback>, TextBox.IHandler { string placeholderText; public TextBoxHandler() { Control = new Gtk.Entry(); Control.SetSizeRequest(100, -1); Control.ActivatesDefault = true; } public override void AttachEvent(string id) { switch (id) { case TextControl.TextChangedEvent: Control.Changed += Connector.HandleTextChanged; break; case TextBox.TextChangingEvent: Control.ClipboardPasted += Connector.HandleClipboardPasted; Control.TextDeleted += Connector.HandleTextDeleted; Widget.TextInput += Connector.HandleTextInput; break; default: base.AttachEvent(id); break; } } protected new TextBoxConnector Connector { get { return (TextBoxConnector)base.Connector; } } protected override WeakConnector CreateConnector() { return new TextBoxConnector(); } protected class TextBoxConnector : GtkControlConnector { public new TextBoxHandler Handler { get { return (TextBoxHandler)base.Handler; } } public void HandleTextChanged(object sender, EventArgs e) { Handler.Callback.OnTextChanged(Handler.Widget, EventArgs.Empty); } static Clipboard clipboard; static Clipboard Clipboard { get { return clipboard ?? (clipboard = new Clipboard()); } } public void HandleTextInput(object sender, TextInputEventArgs e) { var tia = new TextChangingEventArgs(e.Text, Handler.Selection); Handler.Callback.OnTextChanging(Handler.Widget, tia); e.Cancel = tia.Cancel; } [GLib.ConnectBefore] public void HandleClipboardPasted(object sender, EventArgs e) { var tia = new TextChangingEventArgs(Clipboard.Text, Handler.Selection); Handler.Callback.OnTextChanging(Handler.Widget, tia); if (tia.Cancel) NativeMethods.StopEmissionByName(Handler.Control, "paste-clipboard"); } bool deleting; [GLib.ConnectBefore] public void HandleTextDeleted(object o, Gtk.TextDeletedArgs args) { if (!deleting) { deleting = true; if (args.StartPos < args.EndPos) { var tia = new TextChangingEventArgs(string.Empty, new Range<int>(args.StartPos, Math.Min(args.EndPos - 1, Handler.Control.Text.Length - 1))); Handler.Callback.OnTextChanging(Handler.Widget, tia); if (tia.Cancel) NativeMethods.StopEmissionByName(Handler.Control, "delete-text"); } deleting = false; } } #if GTK2 public void HandleExposeEvent(object o, Gtk.ExposeEventArgs args) { var control = Handler.Control; if (!string.IsNullOrEmpty(control.Text) || args.Event.Window == control.GdkWindow) return; if (Handler.placeholderLayout == null) { Handler.placeholderLayout = new Pango.Layout(control.PangoContext); Handler.placeholderLayout.FontDescription = control.PangoContext.FontDescription.Copy(); } Handler.placeholderLayout.SetText(Handler.placeholderText); int currentHeight, currentWidth; args.Event.Window.GetSize(out currentWidth, out currentHeight); int width, height; Handler.placeholderLayout.GetPixelSize(out width, out height); var style = control.Style; var bc = style.Base(Gtk.StateType.Normal); var tc = style.Text(Gtk.StateType.Normal); using (var gc = new Gdk.GC(args.Event.Window)) { gc.Copy(style.TextGC(Gtk.StateType.Normal)); gc.RgbFgColor = new Gdk.Color((byte)(((int)bc.Red + tc.Red) / 2 / 256), (byte)(((int)bc.Green + (int)tc.Green) / 2 / 256), (byte)((bc.Blue + tc.Blue) / 2 / 256)); args.Event.Window.DrawLayout(gc, 2, (currentHeight - height) / 2 + 1, Handler.placeholderLayout); } } #endif } #if GTK2 Pango.Layout placeholderLayout; public override Eto.Drawing.Font Font { get { return base.Font; } set { base.Font = value; placeholderLayout = null; } } #else protected override void SetBackgroundColor(Eto.Drawing.Color? color) { } #endif public override string Text { get { return Control.Text; } set { Control.Text = value ?? string.Empty; } } public bool ReadOnly { get { return !Control.IsEditable; } set { Control.IsEditable = !value; } } public int MaxLength { get { return Control.MaxLength; } set { Control.MaxLength = value; } } public string PlaceholderText { get { return placeholderText; } set { #if GTK2 if (!string.IsNullOrEmpty(placeholderText)) Control.ExposeEvent -= Connector.HandleExposeEvent; placeholderText = value; if (!string.IsNullOrEmpty(placeholderText)) Control.ExposeEvent += Connector.HandleExposeEvent; #else placeholderText = value; NativeMethods.gtk_entry_set_placeholder_text(Control, value); #endif } } public void SelectAll() { Control.GrabFocus(); if (!string.IsNullOrEmpty(Control.Text)) Control.SelectRegion(0, Control.Text.Length); } public Color TextColor { get { return Control.GetTextColor(); } set { Control.SetTextColor(value); } } public override Color BackgroundColor { get { return Control.GetBackground(); } set { Control.SetBackground(value); Control.SetBase(value); } } public int CaretIndex { get { int start, end; Control.GetSelectionBounds(out start, out end); return Math.Min(start, end); } set { Control.SelectRegion(value, value); } } public Range<int> Selection { get { int start, end; Control.GetSelectionBounds(out start, out end); return new Range<int>(Math.Min(start, end), Math.Max(start, end) - 1); } set { Control.SelectRegion(value.Start, value.End + 1); } } } }
/* * Copyright 2021 Google LLC All Rights Reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/logging.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/logging.proto</summary> public static partial class LoggingReflection { #region Descriptor /// <summary>File descriptor for google/api/logging.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static LoggingReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chhnb29nbGUvYXBpL2xvZ2dpbmcucHJvdG8SCmdvb2dsZS5hcGki1wEKB0xv", "Z2dpbmcSRQoVcHJvZHVjZXJfZGVzdGluYXRpb25zGAEgAygLMiYuZ29vZ2xl", "LmFwaS5Mb2dnaW5nLkxvZ2dpbmdEZXN0aW5hdGlvbhJFChVjb25zdW1lcl9k", "ZXN0aW5hdGlvbnMYAiADKAsyJi5nb29nbGUuYXBpLkxvZ2dpbmcuTG9nZ2lu", "Z0Rlc3RpbmF0aW9uGj4KEkxvZ2dpbmdEZXN0aW5hdGlvbhIaChJtb25pdG9y", "ZWRfcmVzb3VyY2UYAyABKAkSDAoEbG9ncxgBIAMoCUJuCg5jb20uZ29vZ2xl", "LmFwaUIMTG9nZ2luZ1Byb3RvUAFaRWdvb2dsZS5nb2xhbmcub3JnL2dlbnBy", "b3RvL2dvb2dsZWFwaXMvYXBpL3NlcnZpY2Vjb25maWc7c2VydmljZWNvbmZp", "Z6ICBEdBUEliBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Logging), global::Google.Api.Logging.Parser, new[]{ "ProducerDestinations", "ConsumerDestinations" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Logging.Types.LoggingDestination), global::Google.Api.Logging.Types.LoggingDestination.Parser, new[]{ "MonitoredResource", "Logs" }, null, null, null, null)}) })); } #endregion } #region Messages /// <summary> /// Logging configuration of the service. /// /// The following example shows how to configure logs to be sent to the /// producer and consumer projects. In the example, the `activity_history` /// log is sent to both the producer and consumer projects, whereas the /// `purchase_history` log is only sent to the producer project. /// /// monitored_resources: /// - type: library.googleapis.com/branch /// labels: /// - key: /city /// description: The city where the library branch is located in. /// - key: /name /// description: The name of the branch. /// logs: /// - name: activity_history /// labels: /// - key: /customer_id /// - name: purchase_history /// logging: /// producer_destinations: /// - monitored_resource: library.googleapis.com/branch /// logs: /// - activity_history /// - purchase_history /// consumer_destinations: /// - monitored_resource: library.googleapis.com/branch /// logs: /// - activity_history /// </summary> public sealed partial class Logging : pb::IMessage<Logging> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Logging> _parser = new pb::MessageParser<Logging>(() => new Logging()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Logging> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.LoggingReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Logging() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Logging(Logging other) : this() { producerDestinations_ = other.producerDestinations_.Clone(); consumerDestinations_ = other.consumerDestinations_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Logging Clone() { return new Logging(this); } /// <summary>Field number for the "producer_destinations" field.</summary> public const int ProducerDestinationsFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Api.Logging.Types.LoggingDestination> _repeated_producerDestinations_codec = pb::FieldCodec.ForMessage(10, global::Google.Api.Logging.Types.LoggingDestination.Parser); private readonly pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination> producerDestinations_ = new pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination>(); /// <summary> /// Logging configurations for sending logs to the producer project. /// There can be multiple producer destinations, each one must have a /// different monitored resource type. A log can be used in at most /// one producer destination. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination> ProducerDestinations { get { return producerDestinations_; } } /// <summary>Field number for the "consumer_destinations" field.</summary> public const int ConsumerDestinationsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Api.Logging.Types.LoggingDestination> _repeated_consumerDestinations_codec = pb::FieldCodec.ForMessage(18, global::Google.Api.Logging.Types.LoggingDestination.Parser); private readonly pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination> consumerDestinations_ = new pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination>(); /// <summary> /// Logging configurations for sending logs to the consumer project. /// There can be multiple consumer destinations, each one must have a /// different monitored resource type. A log can be used in at most /// one consumer destination. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination> ConsumerDestinations { get { return consumerDestinations_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Logging); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Logging other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!producerDestinations_.Equals(other.producerDestinations_)) return false; if(!consumerDestinations_.Equals(other.consumerDestinations_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; hash ^= producerDestinations_.GetHashCode(); hash ^= consumerDestinations_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else producerDestinations_.WriteTo(output, _repeated_producerDestinations_codec); consumerDestinations_.WriteTo(output, _repeated_consumerDestinations_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { producerDestinations_.WriteTo(ref output, _repeated_producerDestinations_codec); consumerDestinations_.WriteTo(ref output, _repeated_consumerDestinations_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; size += producerDestinations_.CalculateSize(_repeated_producerDestinations_codec); size += consumerDestinations_.CalculateSize(_repeated_consumerDestinations_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Logging other) { if (other == null) { return; } producerDestinations_.Add(other.producerDestinations_); consumerDestinations_.Add(other.consumerDestinations_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { producerDestinations_.AddEntriesFrom(input, _repeated_producerDestinations_codec); break; } case 18: { consumerDestinations_.AddEntriesFrom(input, _repeated_consumerDestinations_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { producerDestinations_.AddEntriesFrom(ref input, _repeated_producerDestinations_codec); break; } case 18: { consumerDestinations_.AddEntriesFrom(ref input, _repeated_consumerDestinations_codec); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the Logging message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Configuration of a specific logging destination (the producer project /// or the consumer project). /// </summary> public sealed partial class LoggingDestination : pb::IMessage<LoggingDestination> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<LoggingDestination> _parser = new pb::MessageParser<LoggingDestination>(() => new LoggingDestination()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<LoggingDestination> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Logging.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LoggingDestination() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LoggingDestination(LoggingDestination other) : this() { monitoredResource_ = other.monitoredResource_; logs_ = other.logs_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public LoggingDestination Clone() { return new LoggingDestination(this); } /// <summary>Field number for the "monitored_resource" field.</summary> public const int MonitoredResourceFieldNumber = 3; private string monitoredResource_ = ""; /// <summary> /// The monitored resource type. The type must be defined in the /// [Service.monitored_resources][google.api.Service.monitored_resources] section. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string MonitoredResource { get { return monitoredResource_; } set { monitoredResource_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "logs" field.</summary> public const int LogsFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_logs_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> logs_ = new pbc::RepeatedField<string>(); /// <summary> /// Names of the logs to be sent to this destination. Each name must /// be defined in the [Service.logs][google.api.Service.logs] section. If the log name is /// not a domain scoped name, it will be automatically prefixed with /// the service name followed by "/". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> Logs { get { return logs_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as LoggingDestination); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(LoggingDestination other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (MonitoredResource != other.MonitoredResource) return false; if(!logs_.Equals(other.logs_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (MonitoredResource.Length != 0) hash ^= MonitoredResource.GetHashCode(); hash ^= logs_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else logs_.WriteTo(output, _repeated_logs_codec); if (MonitoredResource.Length != 0) { output.WriteRawTag(26); output.WriteString(MonitoredResource); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { logs_.WriteTo(ref output, _repeated_logs_codec); if (MonitoredResource.Length != 0) { output.WriteRawTag(26); output.WriteString(MonitoredResource); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (MonitoredResource.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MonitoredResource); } size += logs_.CalculateSize(_repeated_logs_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(LoggingDestination other) { if (other == null) { return; } if (other.MonitoredResource.Length != 0) { MonitoredResource = other.MonitoredResource; } logs_.Add(other.logs_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { logs_.AddEntriesFrom(input, _repeated_logs_codec); break; } case 26: { MonitoredResource = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { logs_.AddEntriesFrom(ref input, _repeated_logs_codec); break; } case 26: { MonitoredResource = input.ReadString(); break; } } } } #endif } } #endregion } #endregion } #endregion Designer generated code
using System; using System.ComponentModel; using System.Data.SqlClient; using System.Windows.Forms; namespace CslaGenerator.Data { /// <summary> /// Summary description for ConnectionForm. /// </summary> public class ConnectionForm : Form { private SqlConnection _conn; private TextBox txtServer; private Label lblServer; private Label lblDatabase; private TextBox txtDatabase; private Label lblUser; private TextBox txtUser; private Label lblPassword; private TextBox txtPassword; private Button btnOK; private Button btnCancel; private CheckBox chkSecurityWindows; /*/// <summary> /// Required designer variable. /// </summary> private Container components;*/ public ConnectionForm() { InitializeComponent(); txtServer.Text = ConnectionFactory.Server; txtDatabase.Text = ConnectionFactory.Database; txtUser.Text = ConnectionFactory.User; txtPassword.Text = ConnectionFactory.Password; chkSecurityWindows.Checked = ConnectionFactory.IntegratedSecurity; } /*/// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); }*/ #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.txtServer = new System.Windows.Forms.TextBox(); this.lblServer = new System.Windows.Forms.Label(); this.lblDatabase = new System.Windows.Forms.Label(); this.txtDatabase = new System.Windows.Forms.TextBox(); this.lblUser = new System.Windows.Forms.Label(); this.txtUser = new System.Windows.Forms.TextBox(); this.lblPassword = new System.Windows.Forms.Label(); this.txtPassword = new System.Windows.Forms.TextBox(); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.chkSecurityWindows = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // txtServer // this.txtServer.Location = new System.Drawing.Point(80, 16); this.txtServer.Name = "txtServer"; this.txtServer.Size = new System.Drawing.Size(192, 23); this.txtServer.TabIndex = 0; this.txtServer.Text = ""; // // lblServer // this.lblServer.Location = new System.Drawing.Point(32, 16); this.lblServer.Name = "lblServer"; this.lblServer.Size = new System.Drawing.Size(48, 23); this.lblServer.TabIndex = 1; this.lblServer.Text = "Server"; // // lblDatabase // this.lblDatabase.Location = new System.Drawing.Point(16, 48); this.lblDatabase.Name = "lblDatabase"; this.lblDatabase.Size = new System.Drawing.Size(64, 23); this.lblDatabase.TabIndex = 3; this.lblDatabase.Text = "Database"; // // txtDatabase // this.txtDatabase.Location = new System.Drawing.Point(80, 48); this.txtDatabase.Name = "txtDatabase"; this.txtDatabase.Size = new System.Drawing.Size(192, 23); this.txtDatabase.TabIndex = 1; this.txtDatabase.Text = ""; // // lblUser // this.lblUser.Location = new System.Drawing.Point(40, 112); this.lblUser.Name = "lblUser"; this.lblUser.Size = new System.Drawing.Size(32, 23); this.lblUser.TabIndex = 5; this.lblUser.Text = "User"; // // txtUser // this.txtUser.Location = new System.Drawing.Point(80, 112); this.txtUser.Name = "txtUser"; this.txtUser.Size = new System.Drawing.Size(192, 23); this.txtUser.TabIndex = 3; this.txtUser.Text = ""; // // lblPassword // this.lblPassword.Location = new System.Drawing.Point(16, 144); this.lblPassword.Name = "lblPassword"; this.lblPassword.Size = new System.Drawing.Size(64, 23); this.lblPassword.TabIndex = 7; this.lblPassword.Text = "Password"; // // txtPassword // this.txtPassword.Location = new System.Drawing.Point(80, 144); this.txtPassword.Name = "txtPassword"; this.txtPassword.PasswordChar = '*'; this.txtPassword.Size = new System.Drawing.Size(192, 23); this.txtPassword.TabIndex = 4; this.txtPassword.Text = ""; // // btnOK // this.btnOK.Location = new System.Drawing.Point(56, 184); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(88, 32); this.btnOK.TabIndex = 5; this.btnOK.Text = "OK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(152, 184); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(88, 32); this.btnCancel.TabIndex = 6; this.btnCancel.Text = "Cancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // chkSecurityWindows // this.chkSecurityWindows.Location = new System.Drawing.Point(80, 80); this.chkSecurityWindows.Name = "chkSecurityWindows"; this.chkSecurityWindows.Size = new System.Drawing.Size(184, 24); this.chkSecurityWindows.TabIndex = 2; this.chkSecurityWindows.Text = "Use Integrated Security"; this.chkSecurityWindows.CheckedChanged += new System.EventHandler(this.chkSecurityWindows_CheckedChanged); // // ConnectionForm // this.AcceptButton = this.btnOK; this.AutoScaleBaseSize = new System.Drawing.Size(7, 16); this.ClientSize = new System.Drawing.Size(292, 228); this.Controls.Add(this.chkSecurityWindows); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.lblPassword); this.Controls.Add(this.txtPassword); this.Controls.Add(this.lblUser); this.Controls.Add(this.txtUser); this.Controls.Add(this.lblDatabase); this.Controls.Add(this.txtDatabase); this.Controls.Add(this.lblServer); this.Controls.Add(this.txtServer); this.Font = new System.Drawing.Font("Trebuchet MS", 10F); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "ConnectionForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Connect to database"; this.ResumeLayout(false); } #endregion public SqlConnection Connection { get { return _conn; } } private void btnOK_Click(object sender, EventArgs e) { if (TryConnection()) { DialogResult = DialogResult.OK; } } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } private bool TryConnection() { try { if (txtServer.Text == String.Empty && txtDatabase.Text == String.Empty) { MessageBox.Show(this, @"You must specify a Server and a Database."); return false; } if (!chkSecurityWindows.Checked && txtUser.Text == String.Empty) { MessageBox.Show(this, @"You must specify a Username."); return false; } ConnectionFactory.Server = txtServer.Text; ConnectionFactory.Database = txtDatabase.Text; ConnectionFactory.User = txtUser.Text; ConnectionFactory.Password = txtPassword.Text; ConnectionFactory.IntegratedSecurity = chkSecurityWindows.Checked; _conn = ConnectionFactory.NewConnection; _conn.Open(); _conn.Close(); return true; } catch (SqlException e) { MessageBox.Show(this, @"Error while attempting to connect. " + Environment.NewLine + e.Message); return false; } } private void chkSecurityWindows_CheckedChanged(object sender, EventArgs e) { txtUser.Enabled = !chkSecurityWindows.Checked; txtPassword.Enabled = !chkSecurityWindows.Checked; } } }
// 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 NullableArrayIndexTests { #region NullableBool tests [Fact] public static void CheckNullableBoolArrayIndexTest() { CheckNullableBoolArrayIndex(GenerateNullableBoolArray(0)); CheckNullableBoolArrayIndex(GenerateNullableBoolArray(1)); CheckNullableBoolArrayIndex(GenerateNullableBoolArray(5)); } [Fact] public static void CheckExceptionNullableBoolArrayIndexTest() { // null arrays CheckExceptionNullableBoolArrayIndex(null, -1); CheckExceptionNullableBoolArrayIndex(null, 0); CheckExceptionNullableBoolArrayIndex(null, 1); // index out of bounds CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(0), -1); CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(0), 0); CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(1), -1); CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(1), 1); CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(5), -1); CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(5), 5); } #endregion #region NullableByte tests [Fact] public static void CheckNullableByteArrayIndexTest() { CheckNullableByteArrayIndex(GenerateNullableByteArray(0)); CheckNullableByteArrayIndex(GenerateNullableByteArray(1)); CheckNullableByteArrayIndex(GenerateNullableByteArray(5)); } [Fact] public static void CheckExceptionNullableByteArrayIndexTest() { // null arrays CheckExceptionNullableByteArrayIndex(null, -1); CheckExceptionNullableByteArrayIndex(null, 0); CheckExceptionNullableByteArrayIndex(null, 1); // index out of bounds CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(0), -1); CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(0), 0); CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(1), -1); CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(1), 1); CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(5), -1); CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(5), 5); } #endregion #region NullableChar tests [Fact] public static void CheckNullableCharArrayIndexTest() { CheckNullableCharArrayIndex(GenerateNullableCharArray(0)); CheckNullableCharArrayIndex(GenerateNullableCharArray(1)); CheckNullableCharArrayIndex(GenerateNullableCharArray(5)); } [Fact] public static void CheckExceptionNullableCharArrayIndexTest() { // null arrays CheckExceptionNullableCharArrayIndex(null, -1); CheckExceptionNullableCharArrayIndex(null, 0); CheckExceptionNullableCharArrayIndex(null, 1); // index out of bounds CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(0), -1); CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(0), 0); CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(1), -1); CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(1), 1); CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(5), -1); CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(5), 5); } #endregion #region NullableDecimal tests [Fact] public static void CheckNullableDecimalArrayIndexTest() { CheckNullableDecimalArrayIndex(GenerateNullableDecimalArray(0)); CheckNullableDecimalArrayIndex(GenerateNullableDecimalArray(1)); CheckNullableDecimalArrayIndex(GenerateNullableDecimalArray(5)); } [Fact] public static void CheckExceptionNullableDecimalArrayIndexTest() { // null arrays CheckExceptionNullableDecimalArrayIndex(null, -1); CheckExceptionNullableDecimalArrayIndex(null, 0); CheckExceptionNullableDecimalArrayIndex(null, 1); // index out of bounds CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(0), -1); CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(0), 0); CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(1), -1); CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(1), 1); CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(5), -1); CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(5), 5); } #endregion #region NullableDouble tests [Fact] public static void CheckNullableDoubleArrayIndexTest() { CheckNullableDoubleArrayIndex(GenerateNullableDoubleArray(0)); CheckNullableDoubleArrayIndex(GenerateNullableDoubleArray(1)); CheckNullableDoubleArrayIndex(GenerateNullableDoubleArray(9)); } [Fact] public static void CheckExceptionNullableDoubleArrayIndexTest() { // null arrays CheckExceptionNullableDoubleArrayIndex(null, -1); CheckExceptionNullableDoubleArrayIndex(null, 0); CheckExceptionNullableDoubleArrayIndex(null, 1); // index out of bounds CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(0), -1); CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(0), 0); CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(1), -1); CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(1), 1); CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(9), -1); CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(9), 9); } #endregion #region NullableEnum tests [Fact] public static void CheckNullableEnumArrayIndexTest() { CheckNullableEnumArrayIndex(GenerateNullableEnumArray(0)); CheckNullableEnumArrayIndex(GenerateNullableEnumArray(1)); CheckNullableEnumArrayIndex(GenerateNullableEnumArray(5)); } [Fact] public static void CheckExceptionNullableEnumArrayIndexTest() { // null arrays CheckExceptionNullableEnumArrayIndex(null, -1); CheckExceptionNullableEnumArrayIndex(null, 0); CheckExceptionNullableEnumArrayIndex(null, 1); // index out of bounds CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(0), -1); CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(0), 0); CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(1), -1); CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(1), 1); CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(5), -1); CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(5), 5); } #endregion #region NullableLongEnum tests [Fact] public static void CheckNullableLongEnumArrayIndexTest() { CheckNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(0)); CheckNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(1)); CheckNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(5)); } [Fact] public static void CheckExceptionNullableLongEnumArrayIndexTest() { // null arrays CheckExceptionNullableLongEnumArrayIndex(null, -1); CheckExceptionNullableLongEnumArrayIndex(null, 0); CheckExceptionNullableLongEnumArrayIndex(null, 1); // index out of bounds CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(0), -1); CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(0), 0); CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(1), -1); CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(1), 1); CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(5), -1); CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(5), 5); } #endregion #region NullableFloat tests [Fact] public static void CheckNullableFloatArrayIndexTest() { CheckNullableFloatArrayIndex(GenerateNullableFloatArray(0)); CheckNullableFloatArrayIndex(GenerateNullableFloatArray(1)); CheckNullableFloatArrayIndex(GenerateNullableFloatArray(9)); } [Fact] public static void CheckExceptionNullableFloatArrayIndexTest() { // null arrays CheckExceptionNullableFloatArrayIndex(null, -1); CheckExceptionNullableFloatArrayIndex(null, 0); CheckExceptionNullableFloatArrayIndex(null, 1); // index out of bounds CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(0), -1); CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(0), 0); CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(1), -1); CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(1), 1); CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(9), -1); CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(9), 9); } #endregion #region NullableInt tests [Fact] public static void CheckNullableIntArrayIndexTest() { CheckNullableIntArrayIndex(GenerateNullableIntArray(0)); CheckNullableIntArrayIndex(GenerateNullableIntArray(1)); CheckNullableIntArrayIndex(GenerateNullableIntArray(5)); } [Fact] public static void CheckExceptionNullableIntArrayIndexTest() { // null arrays CheckExceptionNullableIntArrayIndex(null, -1); CheckExceptionNullableIntArrayIndex(null, 0); CheckExceptionNullableIntArrayIndex(null, 1); // index out of bounds CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(0), -1); CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(0), 0); CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(1), -1); CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(1), 1); CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(5), -1); CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(5), 5); } #endregion #region NullableLong tests [Fact] public static void CheckNullableLongArrayIndexTest() { CheckNullableLongArrayIndex(GenerateNullableLongArray(0)); CheckNullableLongArrayIndex(GenerateNullableLongArray(1)); CheckNullableLongArrayIndex(GenerateNullableLongArray(5)); } [Fact] public static void CheckExceptionNullableLongArrayIndexTest() { // null arrays CheckExceptionNullableLongArrayIndex(null, -1); CheckExceptionNullableLongArrayIndex(null, 0); CheckExceptionNullableLongArrayIndex(null, 1); // index out of bounds CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(0), -1); CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(0), 0); CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(1), -1); CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(1), 1); CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(5), -1); CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(5), 5); } #endregion #region NullableSByte tests [Fact] public static void CheckNullableSByteArrayIndexTest() { CheckNullableSByteArrayIndex(GenerateNullableSByteArray(0)); CheckNullableSByteArrayIndex(GenerateNullableSByteArray(1)); CheckNullableSByteArrayIndex(GenerateNullableSByteArray(5)); } [Fact] public static void CheckExceptionNullableSByteArrayIndexTest() { // null arrays CheckExceptionNullableSByteArrayIndex(null, -1); CheckExceptionNullableSByteArrayIndex(null, 0); CheckExceptionNullableSByteArrayIndex(null, 1); // index out of bounds CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(0), -1); CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(0), 0); CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(1), -1); CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(1), 1); CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(5), -1); CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(5), 5); } #endregion #region NullableShort tests [Fact] public static void CheckNullableShortArrayIndexTest() { CheckNullableShortArrayIndex(GenerateNullableShortArray(0)); CheckNullableShortArrayIndex(GenerateNullableShortArray(1)); CheckNullableShortArrayIndex(GenerateNullableShortArray(5)); } [Fact] public static void CheckExceptionNullableShortArrayIndexTest() { // null arrays CheckExceptionNullableShortArrayIndex(null, -1); CheckExceptionNullableShortArrayIndex(null, 0); CheckExceptionNullableShortArrayIndex(null, 1); // index out of bounds CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(0), -1); CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(0), 0); CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(1), -1); CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(1), 1); CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(5), -1); CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(5), 5); } #endregion #region NullableStruct tests [Fact] public static void CheckNullableStructArrayIndexTest() { CheckNullableStructArrayIndex(GenerateNullableStructArray(0)); CheckNullableStructArrayIndex(GenerateNullableStructArray(1)); CheckNullableStructArrayIndex(GenerateNullableStructArray(5)); } [Fact] public static void CheckExceptionNullableStructArrayIndexTest() { // null arrays CheckExceptionNullableStructArrayIndex(null, -1); CheckExceptionNullableStructArrayIndex(null, 0); CheckExceptionNullableStructArrayIndex(null, 1); // index out of bounds CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(0), -1); CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(0), 0); CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(1), -1); CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(1), 1); CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(5), -1); CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(5), 5); } #endregion #region NullableStructWithString tests [Fact] public static void CheckNullableStructWithStringArrayIndexTest() { CheckNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(0)); CheckNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(1)); CheckNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(5)); } [Fact] public static void CheckExceptionNullableStructWithStringArrayIndexTest() { // null arrays CheckExceptionNullableStructWithStringArrayIndex(null, -1); CheckExceptionNullableStructWithStringArrayIndex(null, 0); CheckExceptionNullableStructWithStringArrayIndex(null, 1); // index out of bounds CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(0), -1); CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(0), 0); CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(1), -1); CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(1), 1); CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(5), -1); CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(5), 5); } #endregion #region NullableStructWithStringAndValue tests [Fact] public static void CheckNullableStructWithStringAndValueArrayIndexTest() { CheckNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(0)); CheckNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(1)); CheckNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(5)); } [Fact] public static void CheckExceptionNullableStructWithStringAndValueArrayIndexTest() { // null arrays CheckExceptionNullableStructWithStringAndValueArrayIndex(null, -1); CheckExceptionNullableStructWithStringAndValueArrayIndex(null, 0); CheckExceptionNullableStructWithStringAndValueArrayIndex(null, 1); // index out of bounds CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(0), -1); CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(0), 0); CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(1), -1); CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(1), 1); CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(5), -1); CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(5), 5); } #endregion #region NullableStructWithTwoValues tests [Fact] public static void CheckNullableStructWithTwoValuesArrayIndexTest() { CheckNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(0)); CheckNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(1)); CheckNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(5)); } [Fact] public static void CheckExceptionNullableStructWithTwoValuesArrayIndexTest() { // null arrays CheckExceptionNullableStructWithTwoValuesArrayIndex(null, -1); CheckExceptionNullableStructWithTwoValuesArrayIndex(null, 0); CheckExceptionNullableStructWithTwoValuesArrayIndex(null, 1); // index out of bounds CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(0), -1); CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(0), 0); CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(1), -1); CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(1), 1); CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(5), -1); CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(5), 5); } #endregion #region NullableStructWithStruct tests [Fact] public static void CheckNullableStructWithStructArrayIndexTest() { CheckNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(0)); CheckNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(1)); CheckNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(5)); } [Fact] public static void CheckExceptionNullableStructWithStructArrayIndexTest() { // null arrays CheckExceptionNullableStructWithStructArrayIndex(null, -1); CheckExceptionNullableStructWithStructArrayIndex(null, 0); CheckExceptionNullableStructWithStructArrayIndex(null, 1); // index out of bounds CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(0), -1); CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(0), 0); CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(1), -1); CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(1), 1); CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(5), -1); CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(5), 5); } #endregion #region NullableUInt tests [Fact] public static void CheckNullableUIntArrayIndexTest() { CheckNullableUIntArrayIndex(GenerateNullableUIntArray(0)); CheckNullableUIntArrayIndex(GenerateNullableUIntArray(1)); CheckNullableUIntArrayIndex(GenerateNullableUIntArray(5)); } [Fact] public static void CheckExceptionNullableUIntArrayIndexTest() { // null arrays CheckExceptionNullableUIntArrayIndex(null, -1); CheckExceptionNullableUIntArrayIndex(null, 0); CheckExceptionNullableUIntArrayIndex(null, 1); // index out of bounds CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(0), -1); CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(0), 0); CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(1), -1); CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(1), 1); CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(5), -1); CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(5), 5); } #endregion #region NullableULong tests [Fact] public static void CheckNullableULongArrayIndexTest() { CheckNullableULongArrayIndex(GenerateNullableULongArray(0)); CheckNullableULongArrayIndex(GenerateNullableULongArray(1)); CheckNullableULongArrayIndex(GenerateNullableULongArray(5)); } [Fact] public static void CheckExceptionNullableULongArrayIndexTest() { // null arrays CheckExceptionNullableULongArrayIndex(null, -1); CheckExceptionNullableULongArrayIndex(null, 0); CheckExceptionNullableULongArrayIndex(null, 1); // index out of bounds CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(0), -1); CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(0), 0); CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(1), -1); CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(1), 1); CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(5), -1); CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(5), 5); } #endregion #region NullableUShort tests [Fact] public static void CheckNullableUShortArrayIndexTest() { CheckNullableUShortArrayIndex(GenerateNullableUShortArray(0)); CheckNullableUShortArrayIndex(GenerateNullableUShortArray(1)); CheckNullableUShortArrayIndex(GenerateNullableUShortArray(5)); } [Fact] public static void CheckExceptionNullableUShortArrayIndexTest() { // null arrays CheckExceptionNullableUShortArrayIndex(null, -1); CheckExceptionNullableUShortArrayIndex(null, 0); CheckExceptionNullableUShortArrayIndex(null, 1); // index out of bounds CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(0), -1); CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(0), 0); CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(1), -1); CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(1), 1); CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(5), -1); CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(5), 5); } #endregion #region Generic tests [Fact] public static void CheckNullableGenericWithStructRestriction() { CheckNullableGenericWithStructRestrictionHelper<E>(); } [Fact] public static void CheckExceptionNullableGenericWithStructRestriction() { CheckExceptionNullableGenericWithStructRestrictionHelper<E>(); } [Fact] public static void CheckNullableGenericWithStructRestriction2() { CheckNullableGenericWithStructRestrictionHelper<S>(); } [Fact] public static void CheckExceptionNullableGenericWithStructRestriction2() { CheckExceptionNullableGenericWithStructRestrictionHelper<S>(); } [Fact] public static void CheckNullableGenericWithStructRestriction3() { CheckNullableGenericWithStructRestrictionHelper<Scs>(); } [Fact] public static void CheckExceptionNullableGenericWithStructRestriction3() { CheckExceptionNullableGenericWithStructRestrictionHelper<Scs>(); } #endregion #region Generic helpers private static void CheckNullableGenericWithStructRestrictionHelper<Ts>() where Ts : struct { CheckNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(0)); CheckNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(1)); CheckNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(5)); } private static void CheckExceptionNullableGenericWithStructRestrictionHelper<Ts>() where Ts : struct { // null arrays CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(null, -1); CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(null, 0); CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(null, 1); // index out of bounds CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(0), -1); CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(0), 0); CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(1), -1); CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(1), 1); CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(5), -1); CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(5), 5); } #endregion #region Generate array private static bool?[] GenerateNullableBoolArray(int size) { bool?[] array = new bool?[] { true, false }; bool?[] result = new bool?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static byte?[] GenerateNullableByteArray(int size) { byte?[] array = new byte?[] { 0, 1, byte.MaxValue }; byte?[] result = new byte?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static char?[] GenerateNullableCharArray(int size) { char?[] array = new char?[] { '\0', '\b', 'A', '\uffff' }; char?[] result = new char?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static decimal?[] GenerateNullableDecimalArray(int size) { decimal?[] array = new decimal?[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; decimal?[] result = new decimal?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static double?[] GenerateNullableDoubleArray(int size) { double?[] array = new double?[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; double?[] result = new double?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static E?[] GenerateNullableEnumArray(int size) { E?[] array = new E?[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }; E?[] result = new E?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static El?[] GenerateNullableLongEnumArray(int size) { El?[] array = new El?[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }; El?[] result = new El?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static float?[] GenerateNullableFloatArray(int size) { float?[] array = new float?[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; float?[] result = new float?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static int?[] GenerateNullableIntArray(int size) { int?[] array = new int?[] { 0, 1, -1, int.MinValue, int.MaxValue }; int?[] result = new int?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static long?[] GenerateNullableLongArray(int size) { long?[] array = new long?[] { 0, 1, -1, long.MinValue, long.MaxValue }; long?[] result = new long?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static sbyte?[] GenerateNullableSByteArray(int size) { sbyte?[] array = new sbyte?[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; sbyte?[] result = new sbyte?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static short?[] GenerateNullableShortArray(int size) { short?[] array = new short?[] { 0, 1, -1, short.MinValue, short.MaxValue }; short?[] result = new short?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static S?[] GenerateNullableStructArray(int size) { S?[] array = new S?[] { default(S), new S() }; S?[] result = new S?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Sc?[] GenerateNullableStructWithStringArray(int size) { Sc?[] array = new Sc?[] { default(Sc), new Sc(), new Sc(null) }; Sc?[] result = new Sc?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Scs?[] GenerateNullableStructWithStringAndValueArray(int size) { Scs?[] array = new Scs?[] { default(Scs), new Scs(), new Scs(null, new S()) }; Scs?[] result = new Scs?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Sp?[] GenerateNullableStructWithTwoValuesArray(int size) { Sp?[] array = new Sp?[] { default(Sp), new Sp(), new Sp(5, 5.0) }; Sp?[] result = new Sp?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Ss?[] GenerateNullableStructWithStructArray(int size) { Ss?[] array = new Ss?[] { default(Ss), new Ss(), new Ss(new S()) }; Ss?[] result = new Ss?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static uint?[] GenerateNullableUIntArray(int size) { uint?[] array = new uint?[] { 0, 1, uint.MaxValue }; uint?[] result = new uint?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static ulong?[] GenerateNullableULongArray(int size) { ulong?[] array = new ulong?[] { 0, 1, ulong.MaxValue }; ulong?[] result = new ulong?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static ushort?[] GenerateNullableUShortArray(int size) { ushort?[] array = new ushort?[] { 0, 1, ushort.MaxValue }; ushort?[] result = new ushort?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } private static Ts?[] GenerateNullableGenericWithStructRestrictionArray<Ts>(int size) where Ts : struct { Ts?[] array = new Ts?[] { default(Ts), new Ts() }; Ts?[] result = new Ts?[size]; for (int i = 0; i < size; i++) { result[i] = array[i % array.Length]; } return result; } #endregion #region Check array index private static void CheckNullableBoolArrayIndex(bool?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableBoolArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableByteArrayIndex(byte?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableByteArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableCharArrayIndex(char?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableCharArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableDecimalArrayIndex(decimal?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableDecimalArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableDoubleArrayIndex(double?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableDoubleArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableEnumArrayIndex(E?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableEnumArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableLongEnumArrayIndex(El?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableLongEnumArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableFloatArrayIndex(float?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableFloatArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableIntArrayIndex(int?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableIntArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableLongArrayIndex(long?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableLongArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableSByteArrayIndex(sbyte?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableSByteArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableShortArrayIndex(short?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableShortArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableStructArrayIndex(S?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableStructArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableStructWithStringArrayIndex(Sc?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableStructWithStringArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableStructWithStringAndValueArrayIndex(Scs?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableStructWithStringAndValueArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableStructWithTwoValuesArrayIndex(Sp?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableStructWithTwoValuesArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableStructWithStructArrayIndex(Ss?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableStructWithStructArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableUIntArrayIndex(uint?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableUIntArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableULongArrayIndex(ulong?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableULongArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableUShortArrayIndex(ushort?[] array) { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableUShortArrayIndexExpression(array, i); } Assert.True(success); } private static void CheckNullableGenericWithStructRestrictionArrayIndex<Ts>(Ts?[] array) where Ts : struct { bool success = true; for (int i = 0; i < array.Length; i++) { success &= CheckNullableGenericWithStructRestrictionArrayIndexExpression<Ts>(array, i); } Assert.True(success); } #endregion #region Check index expression private static bool CheckNullableBoolArrayIndexExpression(bool?[] array, int index) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(bool?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableByteArrayIndexExpression(byte?[] array, int index) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(byte?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<byte?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableCharArrayIndexExpression(char?[] array, int index) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(char?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<char?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableDecimalArrayIndexExpression(decimal?[] array, int index) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(decimal?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableDoubleArrayIndexExpression(double?[] array, int index) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(double?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableEnumArrayIndexExpression(E?[] array, int index) { Expression<Func<E?>> e = Expression.Lambda<Func<E?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(E?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<E?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableLongEnumArrayIndexExpression(El?[] array, int index) { Expression<Func<El?>> e = Expression.Lambda<Func<El?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(El?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<El?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableFloatArrayIndexExpression(float?[] array, int index) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(float?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableIntArrayIndexExpression(int?[] array, int index) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(int?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableLongArrayIndexExpression(long?[] array, int index) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(long?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableSByteArrayIndexExpression(sbyte?[] array, int index) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(sbyte?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<sbyte?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableShortArrayIndexExpression(short?[] array, int index) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(short?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableStructArrayIndexExpression(S?[] array, int index) { Expression<Func<S?>> e = Expression.Lambda<Func<S?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(S?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<S?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableStructWithStringArrayIndexExpression(Sc?[] array, int index) { Expression<Func<Sc?>> e = Expression.Lambda<Func<Sc?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(Sc?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<Sc?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableStructWithStringAndValueArrayIndexExpression(Scs?[] array, int index) { Expression<Func<Scs?>> e = Expression.Lambda<Func<Scs?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(Scs?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<Scs?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableStructWithTwoValuesArrayIndexExpression(Sp?[] array, int index) { Expression<Func<Sp?>> e = Expression.Lambda<Func<Sp?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(Sp?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<Sp?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableStructWithStructArrayIndexExpression(Ss?[] array, int index) { Expression<Func<Ss?>> e = Expression.Lambda<Func<Ss?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(Ss?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<Ss?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableUIntArrayIndexExpression(uint?[] array, int index) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(uint?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableULongArrayIndexExpression(ulong?[] array, int index) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(ulong?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableUShortArrayIndexExpression(ushort?[] array, int index) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(ushort?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(); return object.Equals(f(), array[index]); } private static bool CheckNullableGenericWithStructRestrictionArrayIndexExpression<Ts>(Ts?[] array, int index) where Ts : struct { Expression<Func<Ts?>> e = Expression.Lambda<Func<Ts?>>( Expression.ArrayIndex(Expression.Constant(array, typeof(Ts?[])), Expression.Constant(index, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<Ts?> f = e.Compile(); return object.Equals(f(), array[index]); } #endregion #region Check exception array index private static void CheckExceptionNullableBoolArrayIndex(bool?[] array, int index) { bool success = true; try { CheckNullableBoolArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableByteArrayIndex(byte?[] array, int index) { bool success = true; try { CheckNullableByteArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableCharArrayIndex(char?[] array, int index) { bool success = true; try { CheckNullableCharArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableDecimalArrayIndex(decimal?[] array, int index) { bool success = true; try { CheckNullableDecimalArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableDoubleArrayIndex(double?[] array, int index) { bool success = true; try { CheckNullableDoubleArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableEnumArrayIndex(E?[] array, int index) { bool success = true; try { CheckNullableEnumArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableLongEnumArrayIndex(El?[] array, int index) { bool success = true; try { CheckNullableLongEnumArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableFloatArrayIndex(float?[] array, int index) { bool success = true; try { CheckNullableFloatArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableIntArrayIndex(int?[] array, int index) { bool success = true; try { CheckNullableIntArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableLongArrayIndex(long?[] array, int index) { bool success = true; try { CheckNullableLongArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableSByteArrayIndex(sbyte?[] array, int index) { bool success = true; try { CheckNullableSByteArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableShortArrayIndex(short?[] array, int index) { bool success = true; try { CheckNullableShortArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableStructArrayIndex(S?[] array, int index) { bool success = true; try { CheckNullableStructArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableStructWithStringArrayIndex(Sc?[] array, int index) { bool success = true; try { CheckNullableStructWithStringArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableStructWithStringAndValueArrayIndex(Scs?[] array, int index) { bool success = true; try { CheckNullableStructWithStringAndValueArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableStructWithTwoValuesArrayIndex(Sp?[] array, int index) { bool success = true; try { CheckNullableStructWithTwoValuesArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableStructWithStructArrayIndex(Ss?[] array, int index) { bool success = true; try { CheckNullableStructWithStructArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableUIntArrayIndex(uint?[] array, int index) { bool success = true; try { CheckNullableUIntArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableULongArrayIndex(ulong?[] array, int index) { bool success = true; try { CheckNullableULongArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableUShortArrayIndex(ushort?[] array, int index) { bool success = true; try { CheckNullableUShortArrayIndexExpression(array, index); // expect to fail success = false; } catch { } Assert.True(success); } private static void CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(Ts?[] array, int index) where Ts : struct { bool success = true; try { CheckNullableGenericWithStructRestrictionArrayIndexExpression<Ts>(array, index); // expect to fail success = false; } catch { } Assert.True(success); } #endregion } }
using System.Collections.Generic; using System.Linq; using Moq; using Palmmedia.ReportGenerator.Core.Parser.Analysis; using Palmmedia.ReportGenerator.Core.Parser.FileReading; using Xunit; namespace Palmmedia.ReportGenerator.Core.Test.Parser.Analysis { /// <summary> /// This is a test class for CodeFile and is intended /// to contain all CodeFile Unit Tests /// </summary> [Collection("FileManager")] public class CodeFileTest { /// <summary> /// A test for the Constructor /// </summary> [Fact] public void Constructor() { var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, 0, 2 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }); Assert.Equal(2, sut.CoverableLines); Assert.Equal(1, sut.CoveredLines); Assert.Null(sut.CoveredBranches); Assert.Null(sut.TotalBranches); } /// <summary> /// A test for the Constructor /// </summary> [Fact] public void Constructor_WithBranches() { var branches = new Dictionary<int, ICollection<Branch>>() { { 1, new List<Branch>() { new Branch(1, "1"), new Branch(0, "2") } }, { 2, new List<Branch>() { new Branch(0, "3"), new Branch(2, "4") } } }; var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered }, branches); Assert.Equal(2, sut.CoveredBranches); Assert.Equal(4, sut.TotalBranches); } /// <summary> /// A test for Merge /// </summary> [Fact] public void Merge_MergeOneMethodMetric_MethodMetricIsStored() { var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered }); var methodMetric = new MethodMetric("Test", "Test", Enumerable.Empty<Metric>()); sut.AddMethodMetric(methodMetric); var codeFileToMerge = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }); sut.Merge(codeFileToMerge); Assert.Equal(methodMetric, sut.MethodMetrics.First()); Assert.Single(sut.MethodMetrics); } /// <summary> /// A test for Merge /// </summary> [Fact] public void Merge_CodeFileToMergeHasNoBranches_BranchCoverageInformationIsUpdated() { var branches = new Dictionary<int, ICollection<Branch>>() { { 1, new List<Branch>() { new Branch(1, "1"), new Branch(0, "2") } }, { 2, new List<Branch>() { new Branch(0, "3"), new Branch(2, "4") } } }; var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered }, branches); var codeFileToMerge = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }); sut.Merge(codeFileToMerge); Assert.Equal(2, sut.CoveredBranches); Assert.Equal(4, sut.TotalBranches); } /// <summary> /// A test for Merge /// </summary> [Fact] public void Merge_TargetCodeFileHasNoBranches_BranchCoverageInformationIsUpdated() { var branches = new Dictionary<int, ICollection<Branch>>() { { 1, new List<Branch>() { new Branch(1, "1"), new Branch(0, "2") } }, { 2, new List<Branch>() { new Branch(0, "3"), new Branch(2, "4") } } }; var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered }); var codeFileToMerge = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }, branches); sut.Merge(codeFileToMerge); Assert.Equal(2, sut.CoveredBranches); Assert.Equal(4, sut.TotalBranches); } /// <summary> /// A test for Merge /// </summary> [Fact] public void Merge_AllBranchesCovered_LineVisitStatusUpdated() { var branches = new Dictionary<int, ICollection<Branch>>() { { 1, new List<Branch>() { new Branch(1, "1"), new Branch(0, "2") } }, { 2, new List<Branch>() { new Branch(0, "3"), new Branch(0, "4") } } }; var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, 1, 0 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.PartiallyCovered, LineVisitStatus.NotCovered }, branches); var branches2 = new Dictionary<int, ICollection<Branch>>() { { 1, new List<Branch>() { new Branch(0, "1"), new Branch(1, "2") } }, { 2, new List<Branch>() { new Branch(0, "3"), new Branch(2, "4") } } }; var codeFileToMerge = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, 1, 0 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.PartiallyCovered, LineVisitStatus.PartiallyCovered }, branches2); sut.Merge(codeFileToMerge); Assert.Equal(3, sut.CoveredBranches); Assert.Equal(4, sut.TotalBranches); Assert.Equal(LineVisitStatus.Covered, sut.LineVisitStatus[1]); Assert.Equal(LineVisitStatus.PartiallyCovered, sut.LineVisitStatus[2]); } /// <summary> /// A test for Merge /// </summary> [Fact] public void Merge_MergeCodeFileWithEqualLengthCoverageArray_CoverageInformationIsUpdated() { var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered }); var codeFileToMerge = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, 0, 1, -1, 0, 1, -1, 0, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }); var testMethod = new TestMethod("TestFull", "Test"); codeFileToMerge.AddCoverageByTestMethod(testMethod, new CoverageByTrackedMethod() { Coverage = new int[] { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, LineVisitStatus = new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered } }); sut.Merge(codeFileToMerge); Assert.Equal(8, sut.CoverableLines); Assert.Equal(5, sut.CoveredLines); Assert.Null(sut.CoveredBranches); Assert.Null(sut.TotalBranches); Assert.Contains(testMethod, sut.TestMethods); } /// <summary> /// A test for Merge /// </summary> [Fact] public void Merge_MergeCodeFileWithLongerCoverageArray_CoverageInformationIsUpdated() { var branches = new Dictionary<int, ICollection<Branch>>() { { 1, new List<Branch>() { new Branch(1, "1"), new Branch(0, "2") } }, { 2, new List<Branch>() { new Branch(0, "3"), new Branch(2, "4") } } }; var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered }, branches); var testMethod = new TestMethod("TestFull", "Test"); sut.AddCoverageByTestMethod(testMethod, new CoverageByTrackedMethod() { Coverage = new int[] { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, LineVisitStatus = new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered } }); var branches2 = new Dictionary<int, ICollection<Branch>>() { { 1, new List<Branch>() { new Branch(4, "1"), new Branch(3, "5") } }, { 3, new List<Branch>() { new Branch(0, "3"), new Branch(2, "4") } } }; var codeFileToMerge = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }, branches2); testMethod = new TestMethod("TestFull", "Test"); codeFileToMerge.AddCoverageByTestMethod(testMethod, new CoverageByTrackedMethod() { Coverage = new int[] { -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1 }, LineVisitStatus = new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered } }); sut.Merge(codeFileToMerge); Assert.Equal(10, sut.CoverableLines); Assert.Equal(6, sut.CoveredLines); Assert.Equal(4, sut.CoveredBranches); Assert.Equal(7, sut.TotalBranches); } /// <summary> /// A test for AnalyzeFile /// </summary> [Fact] public void AnalyzeFile_ExistingFile_AnalysisIsReturned() { var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -2, -1, 0, 1, 2 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.PartiallyCovered, LineVisitStatus.Covered }); Assert.Null(sut.TotalLines); var fileAnalysis = sut.AnalyzeFile(new CachingFileReader(new LocalFileReader(), 0, null)); Assert.NotNull(fileAnalysis); Assert.Null(fileAnalysis.Error); Assert.Equal(fileAnalysis.Path, fileAnalysis.Path); Assert.Equal(84, sut.TotalLines); Assert.Equal(84, fileAnalysis.Lines.Count()); Assert.Equal(1, fileAnalysis.Lines.ElementAt(0).LineNumber); Assert.Equal(-1, fileAnalysis.Lines.ElementAt(0).LineVisits); Assert.Equal(LineVisitStatus.NotCoverable, fileAnalysis.Lines.ElementAt(0).LineVisitStatus); Assert.Equal(2, fileAnalysis.Lines.ElementAt(1).LineNumber); Assert.Equal(0, fileAnalysis.Lines.ElementAt(1).LineVisits); Assert.Equal(LineVisitStatus.NotCovered, fileAnalysis.Lines.ElementAt(1).LineVisitStatus); Assert.Equal(3, fileAnalysis.Lines.ElementAt(2).LineNumber); Assert.Equal(1, fileAnalysis.Lines.ElementAt(2).LineVisits); Assert.Equal(LineVisitStatus.PartiallyCovered, fileAnalysis.Lines.ElementAt(2).LineVisitStatus); Assert.Equal(4, fileAnalysis.Lines.ElementAt(3).LineNumber); Assert.Equal(2, fileAnalysis.Lines.ElementAt(3).LineVisits); Assert.Equal(LineVisitStatus.Covered, fileAnalysis.Lines.ElementAt(3).LineVisitStatus); } /// <summary> /// A test for AnalyzeFile /// </summary> [Fact] public void AnalyzeFile_ExistingFileWithTrackedMethods_AnalysisIsReturned() { var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -2, -1, 0, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }); var testMethod = new TestMethod("TestFull", "Test"); sut.AddCoverageByTestMethod(testMethod, new CoverageByTrackedMethod() { Coverage = new int[] { -2, 2, -1, 0 }, LineVisitStatus = new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered } }); var fileAnalysis = sut.AnalyzeFile(new CachingFileReader(new LocalFileReader(), 0, null)); Assert.Equal(2, fileAnalysis.Lines.First().LineCoverageByTestMethod[testMethod].LineVisits); Assert.Equal(LineVisitStatus.Covered, fileAnalysis.Lines.First().LineCoverageByTestMethod[testMethod].LineVisitStatus); } /// <summary> /// A test for AnalyzeFile /// </summary> [Fact] public void AnalyzeFile_NonExistingFile_AnalysisIsReturned() { var sut = new CodeFile("C:\\temp\\Other.cs", new int[] { -2, -1, 0, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }); Assert.Null(sut.TotalLines); var fileAnalysis = sut.AnalyzeFile(new CachingFileReader(new LocalFileReader(), 0, null)); Assert.NotNull(fileAnalysis); Assert.NotNull(fileAnalysis.Error); Assert.Equal(fileAnalysis.Path, fileAnalysis.Path); Assert.Null(sut.TotalLines); Assert.Empty(fileAnalysis.Lines); } /// <summary> /// A test for AnalyzeFile /// </summary> [Fact] public void AnalyzeFile_AdditionFileReaderNoError_RegularFileReaderIgnored() { var additionalFileReaderMock = new Mock<IFileReader>(); string error = null; additionalFileReaderMock.Setup(f => f.LoadFile(It.IsAny<string>(), out error)) .Returns(new[] { "Test" }); var fileReaderMock = new Mock<IFileReader>(); var sut = new CodeFile("C:\\temp\\Other.cs", new int[] { -2, -1, 0, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }, additionalFileReaderMock.Object); Assert.Null(sut.TotalLines); var fileAnalysis = sut.AnalyzeFile(fileReaderMock.Object); Assert.NotNull(fileAnalysis); Assert.Null(fileAnalysis.Error); additionalFileReaderMock.Verify(f => f.LoadFile(It.IsAny<string>(), out error), Times.Once); fileReaderMock.Verify(f => f.LoadFile(It.IsAny<string>(), out error), Times.Never); } /// <summary> /// A test for AnalyzeFile /// </summary> [Fact] public void AnalyzeFile_AdditionFileReaderReturnsError_RegularFileReaderUsed() { var additionalFileReaderMock = new Mock<IFileReader>(); string error = "Some error"; additionalFileReaderMock.Setup(f => f.LoadFile(It.IsAny<string>(), out error)) .Returns((string[])null); var fileReaderMock = new Mock<IFileReader>(); fileReaderMock.Setup(f => f.LoadFile(It.IsAny<string>(), out error)) .Returns(new[] { "Test" }); var sut = new CodeFile("C:\\temp\\Other.cs", new int[] { -2, -1, 0, 1 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }, additionalFileReaderMock.Object); Assert.Null(sut.TotalLines); var fileAnalysis = sut.AnalyzeFile(fileReaderMock.Object); Assert.NotNull(fileAnalysis); Assert.NotNull(fileAnalysis.Error); Assert.Equal(fileAnalysis.Path, fileAnalysis.Path); Assert.Null(sut.TotalLines); Assert.Empty(fileAnalysis.Lines); additionalFileReaderMock.Verify(f => f.LoadFile(It.IsAny<string>(), out error), Times.Once); fileReaderMock.Verify(f => f.LoadFile(It.IsAny<string>(), out error), Times.Once); } /// <summary> /// A test for Equals /// </summary> [Fact] public void CodeFile_Equals() { var target1 = new CodeFile("C:\\temp\\Program.cs", System.Array.Empty<int>(), System.Array.Empty<LineVisitStatus>()); var target2 = new CodeFile("C:\\temp\\Program.cs", System.Array.Empty<int>(), System.Array.Empty<LineVisitStatus>()); var target3 = new CodeFile("C:\\temp\\Other.cs", System.Array.Empty<int>(), System.Array.Empty<LineVisitStatus>()); Assert.True(target1.Equals(target2), "Objects are not equal"); Assert.False(target1.Equals(target3), "Objects are equal"); Assert.False(target1.Equals(null), "Objects are equal"); Assert.False(target1.Equals(new object()), "Objects are equal"); } /// <summary> /// A test for AddCoverageByTestMethod /// </summary> [Fact] public void AddCoverageByTestMethod_AddCoverageByTestMethodForExistingMethod_CoverageInformationIsMerged() { var sut = new CodeFile("C:\\temp\\Program.cs", System.Array.Empty<int>(), System.Array.Empty<LineVisitStatus>()); var testMethod = new TestMethod("TestFull", "Test"); var coverageByTrackedMethod = new CoverageByTrackedMethod() { Coverage = new int[] { -1, -1, -1, -1, 0, 0, 0, 1, 1, 1 }, LineVisitStatus = new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered } }; var repeatedCoverageByTrackedMethod = new CoverageByTrackedMethod() { Coverage = new int[] { -1, 0, 1, -1, 1, 0, 1, -1, 1, 0 }, LineVisitStatus = new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.Covered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.Covered, LineVisitStatus.NotCovered } }; sut.AddCoverageByTestMethod(testMethod, coverageByTrackedMethod); sut.AddCoverageByTestMethod(testMethod, repeatedCoverageByTrackedMethod); Assert.Contains(testMethod, sut.TestMethods); // using AnalyseFile() to retrieve merged coverage by test method var lineAnalyses = sut.AnalyzeFile(new CachingFileReader(new LocalFileReader(), 0, null)).Lines; var testMethodCoverage = lineAnalyses.Take(9).Select(l => l.LineCoverageByTestMethod).ToArray(); Assert.True(testMethodCoverage.All(coverage => coverage.ContainsKey(testMethod)), "All lines should be covered by given test method"); var actualLineVisits = testMethodCoverage.Select(c => c[testMethod].LineVisits).ToArray(); var actualLineVisitStatuses = testMethodCoverage.Select(c => c[testMethod].LineVisitStatus).ToArray(); Assert.Equal(new int[] { 0, 1, -1, 1, 0, 1, 1, 2, 1 }, actualLineVisits); Assert.Equal(new LineVisitStatus[] { LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.NotCoverable, LineVisitStatus.Covered, LineVisitStatus.NotCovered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered, LineVisitStatus.Covered }, actualLineVisitStatuses); } /// <summary> /// A test for the CoveredCodeElements /// </summary> [Fact] public void CoveredCodeElements() { var sut = new CodeFile("C:\\temp\\Program.cs", new int[] { -1, 0, 2 }, new LineVisitStatus[] { LineVisitStatus.NotCoverable, LineVisitStatus.NotCovered, LineVisitStatus.Covered }); sut.AddCodeElement(new CodeElement("NotCoverable", CodeElementType.Method, 1, 1, null)); sut.AddCodeElement(new CodeElement("NotCovered", CodeElementType.Method, 2, 2, null)); sut.AddCodeElement(new CodeElement("Covered", CodeElementType.Method, 3, 3, null)); Assert.Equal(1, sut.CoveredCodeElements); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Drawing.Imaging.ImageFormat.cs // // Authors: // Everaldo Canuto ([email protected]) // Andreas Nahr ([email protected]) // Dennis Hayes ([email protected]) // Jordi Mas i Hernandez ([email protected]) // Sebastien Pouliot <[email protected]> // // (C) 2002-4 Ximian, Inc. http://www.ximian.com // Copyright (C) 2004,2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.ComponentModel; namespace System.Drawing.Imaging { #if !NETCORE [TypeConverter (typeof (ImageFormatConverter))] #endif public sealed class ImageFormat { private Guid guid; private string name; private const string BmpGuid = "b96b3cab-0728-11d3-9d7b-0000f81ef32e"; private const string EmfGuid = "b96b3cac-0728-11d3-9d7b-0000f81ef32e"; private const string ExifGuid = "b96b3cb2-0728-11d3-9d7b-0000f81ef32e"; private const string GifGuid = "b96b3cb0-0728-11d3-9d7b-0000f81ef32e"; private const string TiffGuid = "b96b3cb1-0728-11d3-9d7b-0000f81ef32e"; private const string PngGuid = "b96b3caf-0728-11d3-9d7b-0000f81ef32e"; private const string MemoryBmpGuid = "b96b3caa-0728-11d3-9d7b-0000f81ef32e"; private const string IconGuid = "b96b3cb5-0728-11d3-9d7b-0000f81ef32e"; private const string JpegGuid = "b96b3cae-0728-11d3-9d7b-0000f81ef32e"; private const string WmfGuid = "b96b3cad-0728-11d3-9d7b-0000f81ef32e"; // lock(this) is bad // http://msdn.microsoft.com/library/en-us/dnaskdr/html/askgui06032003.asp?frame=true private static object locker = new object(); private static ImageFormat BmpImageFormat; private static ImageFormat EmfImageFormat; private static ImageFormat ExifImageFormat; private static ImageFormat GifImageFormat; private static ImageFormat TiffImageFormat; private static ImageFormat PngImageFormat; private static ImageFormat MemoryBmpImageFormat; private static ImageFormat IconImageFormat; private static ImageFormat JpegImageFormat; private static ImageFormat WmfImageFormat; // constructors public ImageFormat(Guid guid) { this.guid = guid; } private ImageFormat(string name, string guid) { this.name = name; this.guid = new Guid(guid); } // methods public override bool Equals(object o) { ImageFormat f = (o as ImageFormat); if (f == null) return false; return f.Guid.Equals(guid); } public override int GetHashCode() { return guid.GetHashCode(); } public override string ToString() { if (name != null) return name; return ("[ImageFormat: " + guid.ToString() + "]"); } // properties public Guid Guid { get { return guid; } } public static ImageFormat Bmp { get { lock (locker) { if (BmpImageFormat == null) BmpImageFormat = new ImageFormat("Bmp", BmpGuid); return BmpImageFormat; } } } public static ImageFormat Emf { get { lock (locker) { if (EmfImageFormat == null) EmfImageFormat = new ImageFormat("Emf", EmfGuid); return EmfImageFormat; } } } public static ImageFormat Exif { get { lock (locker) { if (ExifImageFormat == null) ExifImageFormat = new ImageFormat("Exif", ExifGuid); return ExifImageFormat; } } } public static ImageFormat Gif { get { lock (locker) { if (GifImageFormat == null) GifImageFormat = new ImageFormat("Gif", GifGuid); return GifImageFormat; } } } public static ImageFormat Icon { get { lock (locker) { if (IconImageFormat == null) IconImageFormat = new ImageFormat("Icon", IconGuid); return IconImageFormat; } } } public static ImageFormat Jpeg { get { lock (locker) { if (JpegImageFormat == null) JpegImageFormat = new ImageFormat("Jpeg", JpegGuid); return JpegImageFormat; } } } public static ImageFormat MemoryBmp { get { lock (locker) { if (MemoryBmpImageFormat == null) MemoryBmpImageFormat = new ImageFormat("MemoryBMP", MemoryBmpGuid); return MemoryBmpImageFormat; } } } public static ImageFormat Png { get { lock (locker) { if (PngImageFormat == null) PngImageFormat = new ImageFormat("Png", PngGuid); return PngImageFormat; } } } public static ImageFormat Tiff { get { lock (locker) { if (TiffImageFormat == null) TiffImageFormat = new ImageFormat("Tiff", TiffGuid); return TiffImageFormat; } } } public static ImageFormat Wmf { get { lock (locker) { if (WmfImageFormat == null) WmfImageFormat = new ImageFormat("Wmf", WmfGuid); return WmfImageFormat; } } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; #if !(NET20 || NET35 || PORTABLE) using System.Numerics; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif using Newtonsoft.Json.Linq; using System.IO; using System.Collections; #if !NETFX_CORE using System.Web.UI; #endif #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JObjectTests : TestFixtureBase { [Test] public void WritePropertyWithNoValue() { var o = new JObject(); o.Add(new JProperty("novalue")); Assert.AreEqual(@"{ ""novalue"": null }", o.ToString()); } [Test] public void Keys() { var o = new JObject(); var d = (IDictionary<string, JToken>)o; Assert.AreEqual(0, d.Keys.Count); o["value"] = true; Assert.AreEqual(1, d.Keys.Count); } [Test] public void TryGetValue() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(false, o.TryGetValue("sdf", out t)); Assert.AreEqual(null, t); Assert.AreEqual(false, o.TryGetValue(null, out t)); Assert.AreEqual(null, t); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); } [Test] public void DictionaryItemShouldSet() { JObject o = new JObject(); o["PropertyNameValue"] = new JValue(1); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); o["PropertyNameValue"] = new JValue(2); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t)); o["PropertyNameValue"] = null; Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue((object)null), t)); } [Test] public void Remove() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, o.Remove("sdf")); Assert.AreEqual(false, o.Remove(null)); Assert.AreEqual(true, o.Remove("PropertyNameValue")); Assert.AreEqual(0, o.Children().Count()); } [Test] public void GenericCollectionRemove() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)))); Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v))); Assert.AreEqual(0, o.Children().Count()); } [Test] public void DuplicatePropertyNameShouldThrow() { ExceptionAssert.Throws<ArgumentException>( "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", () => { JObject o = new JObject(); o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null); }); } [Test] public void GenericDictionaryAdd() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, (int)o["PropertyNameValue"]); o.Add("PropertyNameValue1", null); Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value); Assert.AreEqual(2, o.Children().Count()); } [Test] public void GenericCollectionAdd() { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(1, (int)o["PropertyNameValue"]); Assert.AreEqual(1, o.Children().Count()); } [Test] public void GenericCollectionClear() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JProperty p = (JProperty)o.Children().ElementAt(0); ((ICollection<KeyValuePair<string, JToken>>)o).Clear(); Assert.AreEqual(0, o.Children().Count()); Assert.AreEqual(null, p.Parent); } [Test] public void GenericCollectionContains() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v)); Assert.AreEqual(true, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>)); Assert.AreEqual(false, contains); } [Test] public void GenericDictionaryContains() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue"); Assert.AreEqual(true, contains); } [Test] public void GenericCollectionCopyTo() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); Assert.AreEqual(3, o.Children().Count()); KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5]; ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[0]); Assert.AreEqual("PropertyNameValue", a[1].Key); Assert.AreEqual(1, (int)a[1].Value); Assert.AreEqual("PropertyNameValue2", a[2].Key); Assert.AreEqual(2, (int)a[2].Value); Assert.AreEqual("PropertyNameValue3", a[3].Key); Assert.AreEqual(3, (int)a[3].Value); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]); } [Test] public void GenericCollectionCopyToNullArrayShouldThrow() { ExceptionAssert.Throws<ArgumentException>( @"Value cannot be null. Parameter name: array", () => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0); }); } [Test] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { ExceptionAssert.Throws<ArgumentOutOfRangeException>( @"arrayIndex is less than 0. Parameter name: arrayIndex", () => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1); }); } [Test] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { ExceptionAssert.Throws<ArgumentException>( @"arrayIndex is equal to or greater than the length of array.", () => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1); }); } [Test] public void GenericCollectionCopyToInsufficientArrayCapacity() { ExceptionAssert.Throws<ArgumentException>( @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.", () => { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1); }); } [Test] public void FromObjectRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); Assert.AreEqual("FirstNameValue", (string)o["first_name"]); Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type); Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]); Assert.AreEqual("LastNameValue", (string)o["last_name"]); } [Test] public void JTokenReader() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Raw, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void DeserializeFromRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); JsonSerializer serializer = new JsonSerializer(); raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw)); Assert.AreEqual("FirstNameValue", raw.FirstName); Assert.AreEqual("LastNameValue", raw.LastName); Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value); } [Test] public void Parse_ShouldThrowOnUnexpectedToken() { ExceptionAssert.Throws<JsonReaderException>("Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.", () => { string json = @"[""prop""]"; JObject.Parse(json); }); } [Test] public void ParseJavaScriptDate() { string json = @"[new Date(1207285200000)]"; JArray a = (JArray)JsonConvert.DeserializeObject(json); JValue v = (JValue)a[0]; Assert.AreEqual(DateTimeUtils.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v); } [Test] public void GenericValueCast() { string json = @"{""foo"":true}"; JObject o = (JObject)JsonConvert.DeserializeObject(json); bool? value = o.Value<bool?>("foo"); Assert.AreEqual(true, value); json = @"{""foo"":null}"; o = (JObject)JsonConvert.DeserializeObject(json); value = o.Value<bool?>("foo"); Assert.AreEqual(null, value); } [Test] public void Blog() { ExceptionAssert.Throws<JsonReaderException>( "Invalid property identifier character: ]. Path 'name', line 3, position 5.", () => { JObject.Parse(@"{ ""name"": ""James"", ]!#$THIS IS: BAD JSON![{}}}}] }"); }); } [Test] public void RawChildValues() { JObject o = new JObject(); o["val1"] = new JRaw("1"); o["val2"] = new JRaw("1"); string json = o.ToString(); Assert.AreEqual(@"{ ""val1"": 1, ""val2"": 1 }", json); } [Test] public void Iterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); JToken t = o; int i = 1; foreach (JProperty property in t) { Assert.AreEqual("PropertyNameValue" + i, property.Name); Assert.AreEqual(i, (int)property.Value); i++; } } [Test] public void KeyValuePairIterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); int i = 1; foreach (KeyValuePair<string, JToken> pair in o) { Assert.AreEqual("PropertyNameValue" + i, pair.Key); Assert.AreEqual(i, (int)pair.Value); i++; } } [Test] public void WriteObjectNullStringValue() { string s = null; JValue v = new JValue(s); Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.String, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); Assert.AreEqual(@"{ ""title"": null }", output); } [Test] public void Example() { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small Console.WriteLine(name); Console.WriteLine(smallest); } [Test] public void DeserializeClassManually() { string jsonText = @"{ ""short"": { ""original"":""http://www.foo.com/"", ""short"":""krehqk"", ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Console.WriteLine(shortie.Original); // http://www.foo.com/ Console.WriteLine(shortie.Error.ErrorMessage); // No action taken Assert.AreEqual("http://www.foo.com/", shortie.Original); Assert.AreEqual("krehqk", shortie.Short); Assert.AreEqual(null, shortie.Shortened); Assert.AreEqual(0, shortie.Error.Code); Assert.AreEqual("No action taken", shortie.Error.ErrorMessage); } [Test] public void JObjectContainingHtml() { JObject o = new JObject(); o["rc"] = new JValue(200); o["m"] = new JValue(""); o["o"] = new JValue(@"<div class='s1'> <div class='avatar'> <a href='asdf'>asdf</a><br /> <strong>0</strong> </div> <div class='sl'> <p> 444444444 </p> </div> <div class='clear'> </div> </div>"); Assert.AreEqual(@"{ ""rc"": 200, ""m"": """", ""o"": ""<div class='s1'>\r\n <div class='avatar'> \r\n <a href='asdf'>asdf</a><br />\r\n <strong>0</strong>\r\n </div>\r\n <div class='sl'>\r\n <p>\r\n 444444444\r\n </p>\r\n </div>\r\n <div class='clear'>\r\n </div> \r\n</div>"" }", o.ToString()); } [Test] public void ImplicitValueConversions() { JObject moss = new JObject(); moss["FirstName"] = new JValue("Maurice"); moss["LastName"] = new JValue("Moss"); moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30)); moss["Department"] = new JValue("IT"); moss["JobTitle"] = new JValue("Support"); Console.WriteLine(moss.ToString()); //{ // "FirstName": "Maurice", // "LastName": "Moss", // "BirthDate": "\/Date(252241200000+1300)\/", // "Department": "IT", // "JobTitle": "Support" //} JObject jen = new JObject(); jen["FirstName"] = "Jen"; jen["LastName"] = "Barber"; jen["BirthDate"] = new DateTime(1978, 3, 15); jen["Department"] = "IT"; jen["JobTitle"] = "Manager"; Console.WriteLine(jen.ToString()); //{ // "FirstName": "Jen", // "LastName": "Barber", // "BirthDate": "\/Date(258721200000+1300)\/", // "Department": "IT", // "JobTitle": "Manager" //} } [Test] public void ReplaceJPropertyWithJPropertyWithSameName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); IList l = o; Assert.AreEqual(p1, l[0]); Assert.AreEqual(p2, l[1]); JProperty p3 = new JProperty("Test1", "III"); p1.Replace(p3); Assert.AreEqual(null, p1.Parent); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); Assert.AreEqual(2, l.Count); Assert.AreEqual(2, o.Properties().Count()); JProperty p4 = new JProperty("Test4", "IV"); p2.Replace(p4); Assert.AreEqual(null, p2.Parent); Assert.AreEqual(l, p4.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p4, l[1]); } #if !(NET20 || NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void PropertyChanging() { object changing = null; object changed = null; int changingCount = 0; int changedCount = 0; JObject o = new JObject(); o.PropertyChanging += (sender, args) => { JObject s = (JObject)sender; changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changingCount++; }; o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual(null, changing); Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value1", changing); Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changingCount); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual("value2", changing); Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changingCount); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changing); Assert.AreEqual(null, changed); Assert.AreEqual(new JValue((object)null), o["NullValue"]); Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); } #endif [Test] public void PropertyChanged() { object changed = null; int changedCount = 0; JObject o = new JObject(); o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(new JValue((object)null), o["NullValue"]); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changedCount); } [Test] public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void IListIndexOf() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void IListClear() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void IListCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); object[] a = new object[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void IListAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void IListAddBadToken() { ExceptionAssert.Throws<ArgumentException>( "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", () => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }); } [Test] public void IListAddBadValue() { ExceptionAssert.Throws<ArgumentException>( "Argument is not a JToken.", () => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add("Bad!"); }); } [Test] public void IListAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>( "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", () => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }); } [Test] public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.AreEqual(2, l.Count); l.Remove(p1); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); l.Remove(p2); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void IListRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void IListInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void IListIsReadOnly() { IList l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void IListIsFixedSize() { IList l = new JObject(); Assert.IsFalse(l.IsFixedSize); } [Test] public void IListSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void IListSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>( "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", () => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }); } [Test] public void IListSetItemInvalid() { ExceptionAssert.Throws<ArgumentException>( @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", () => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l[0] = new JValue(true); }); } [Test] public void IListSyncRoot() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsNotNull(l.SyncRoot); } [Test] public void IListIsSynchronized() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsFalse(l.IsSynchronized); } [Test] public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void GenericListJTokenIndexOf() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void GenericListJTokenClear() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JToken[] a = new JToken[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void GenericListJTokenAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void GenericListJTokenAddBadToken() { ExceptionAssert.Throws<ArgumentException>("Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", () => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }); } [Test] public void GenericListJTokenAddBadValue() { ExceptionAssert.Throws<ArgumentException>("Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", () => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // string is implicitly converted to JValue l.Add("Bad!"); }); } [Test] public void GenericListJTokenAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>("Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", () => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }); } [Test] public void GenericListJTokenRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything Assert.IsFalse(l.Remove(p3)); Assert.AreEqual(2, l.Count); Assert.IsTrue(l.Remove(p1)); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); Assert.IsTrue(l.Remove(p2)); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void GenericListJTokenRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void GenericListJTokenIsReadOnly() { IList<JToken> l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void GenericListJTokenSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void GenericListJTokenSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>("Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", () => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void IBindingListSortDirection() { IBindingList l = new JObject(); Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection); } [Test] public void IBindingListSortProperty() { IBindingList l = new JObject(); Assert.AreEqual(null, l.SortProperty); } [Test] public void IBindingListSupportsChangeNotification() { IBindingList l = new JObject(); Assert.AreEqual(true, l.SupportsChangeNotification); } [Test] public void IBindingListSupportsSearching() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSearching); } [Test] public void IBindingListSupportsSorting() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSorting); } [Test] public void IBindingListAllowEdit() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowEdit); } [Test] public void IBindingListAllowNew() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowNew); } [Test] public void IBindingListAllowRemove() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowRemove); } [Test] public void IBindingListAddIndex() { IBindingList l = new JObject(); // do nothing l.AddIndex(null); } [Test] public void IBindingListApplySort() { ExceptionAssert.Throws<NotSupportedException>( "Specified method is not supported.", () => { IBindingList l = new JObject(); l.ApplySort(null, ListSortDirection.Ascending); }); } [Test] public void IBindingListRemoveSort() { ExceptionAssert.Throws<NotSupportedException>( "Specified method is not supported.", () => { IBindingList l = new JObject(); l.RemoveSort(); }); } [Test] public void IBindingListRemoveIndex() { IBindingList l = new JObject(); // do nothing l.RemoveIndex(null); } [Test] public void IBindingListFind() { ExceptionAssert.Throws<NotSupportedException>( "Specified method is not supported.", () => { IBindingList l = new JObject(); l.Find(null, null); }); } [Test] public void IBindingListIsSorted() { IBindingList l = new JObject(); Assert.AreEqual(false, l.IsSorted); } [Test] public void IBindingListAddNew() { ExceptionAssert.Throws<JsonException>( "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.", () => { IBindingList l = new JObject(); l.AddNew(); }); } [Test] public void IBindingListAddNewWithEvent() { JObject o = new JObject(); o._addingNew += (s, e) => e.NewObject = new JProperty("Property!"); IBindingList l = o; object newObject = l.AddNew(); Assert.IsNotNull(newObject); JProperty p = (JProperty)newObject; Assert.AreEqual("Property!", p.Name); Assert.AreEqual(o, p.Parent); } [Test] public void ITypedListGetListName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); Assert.AreEqual(string.Empty, l.GetListName(null)); } [Test] public void ITypedListGetItemProperties() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); Assert.IsNull(propertyDescriptors); } [Test] public void ListChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); ListChangedType? changedType = null; int? index = null; o.ListChanged += (s, a) => { changedType = a.ListChangedType; index = a.NewIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, ListChangedType.ItemAdded); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif #if !(NET20 || NET35 || PORTABLE40) [Test] public void CollectionChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); NotifyCollectionChangedAction? changedType = null; int? index = null; o._collectionChanged += (s, a) => { changedType = a.Action; index = a.NewStartingIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif [Test] public void GetGeocodeAddress() { string json = @"{ ""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"", ""Status"": { ""code"": 200, ""request"": ""geocode"" }, ""Placemark"": [ { ""id"": ""p1"", ""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"", ""AddressDetails"": { ""Accuracy"" : 8, ""Country"" : { ""AdministrativeArea"" : { ""AdministrativeAreaName"" : ""IL"", ""SubAdministrativeArea"" : { ""Locality"" : { ""LocalityName"" : ""Rockford"", ""PostalCode"" : { ""PostalCodeNumber"" : ""61107"" }, ""Thoroughfare"" : { ""ThoroughfareName"" : ""435 N Mulford Rd"" } }, ""SubAdministrativeAreaName"" : ""Winnebago"" } }, ""CountryName"" : ""USA"", ""CountryNameCode"" : ""US"" } }, ""ExtendedData"": { ""LatLonBox"": { ""north"": 42.2753076, ""south"": 42.2690124, ""east"": -88.9964645, ""west"": -89.0027597 } }, ""Point"": { ""coordinates"": [ -88.9995886, 42.2721596, 0 ] } } ] }"; JObject o = JObject.Parse(json); string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"]; Assert.AreEqual("435 N Mulford Rd", searchAddress); } [Test] public void SetValueWithInvalidPropertyName() { ExceptionAssert.Throws<ArgumentException>("Set JObject values with invalid key value: 0. Object property name expected.", () => { JObject o = new JObject(); o[0] = new JValue(3); }); } [Test] public void SetValue() { object key = "TestKey"; JObject o = new JObject(); o[key] = new JValue(3); Assert.AreEqual(3, (int)o[key]); } [Test] public void ParseMultipleProperties() { string json = @"{ ""Name"": ""Name1"", ""Name"": ""Name2"" }"; JObject o = JObject.Parse(json); string value = (string)o["Name"]; Assert.AreEqual("Name2", value); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void WriteObjectNullDBNullValue() { DBNull dbNull = DBNull.Value; JValue v = new JValue(dbNull); Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); Assert.AreEqual(@"{ ""title"": null }", output); } #endif [Test] public void InvalidValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>("Can not convert Object to String.", () => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o["responseData"]; }); } [Test] public void InvalidPropertyValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>("Can not convert Object to String.", () => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o.Property("responseData"); }); } [Test] public void ParseIncomplete() { ExceptionAssert.Throws<Exception>("Unexpected end of content while loading JObject. Path 'foo', line 1, position 6.", () => { JObject.Parse("{ foo:"); }); } [Test] public void LoadFromNestedObject() { string jsonText = @"{ ""short"": { ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JObject o = (JObject)JToken.ReadFrom(reader); Assert.IsNotNull(o); Assert.AreEqual(@"{ ""code"": 0, ""msg"": ""No action taken"" }", o.ToString(Formatting.Indented)); } [Test] public void LoadFromNestedObjectIncomplete() { ExceptionAssert.Throws<JsonReaderException>("Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 15.", () => { string jsonText = @"{ ""short"": { ""error"": { ""code"":0"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JToken.ReadFrom(reader); }); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void GetProperties() { JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}"); ICustomTypeDescriptor descriptor = o; PropertyDescriptorCollection properties = descriptor.GetProperties(); Assert.AreEqual(4, properties.Count); PropertyDescriptor prop1 = properties[0]; Assert.AreEqual("prop1", prop1.Name); Assert.AreEqual(typeof(long), prop1.PropertyType); Assert.AreEqual(typeof(JObject), prop1.ComponentType); Assert.AreEqual(false, prop1.CanResetValue(o)); Assert.AreEqual(false, prop1.ShouldSerializeValue(o)); PropertyDescriptor prop2 = properties[1]; Assert.AreEqual("prop2", prop2.Name); Assert.AreEqual(typeof(string), prop2.PropertyType); Assert.AreEqual(typeof(JObject), prop2.ComponentType); Assert.AreEqual(false, prop2.CanResetValue(o)); Assert.AreEqual(false, prop2.ShouldSerializeValue(o)); PropertyDescriptor prop3 = properties[2]; Assert.AreEqual("prop3", prop3.Name); Assert.AreEqual(typeof(object), prop3.PropertyType); Assert.AreEqual(typeof(JObject), prop3.ComponentType); Assert.AreEqual(false, prop3.CanResetValue(o)); Assert.AreEqual(false, prop3.ShouldSerializeValue(o)); PropertyDescriptor prop4 = properties[3]; Assert.AreEqual("prop4", prop4.Name); Assert.AreEqual(typeof(JArray), prop4.PropertyType); Assert.AreEqual(typeof(JObject), prop4.ComponentType); Assert.AreEqual(false, prop4.CanResetValue(o)); Assert.AreEqual(false, prop4.ShouldSerializeValue(o)); } #endif [Test] public void ParseEmptyObjectWithComment() { JObject o = JObject.Parse("{ /* A Comment */ }"); Assert.AreEqual(0, o.Count); } [Test] public void FromObjectTimeSpan() { JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1)); Assert.AreEqual(v.Value, TimeSpan.FromDays(1)); Assert.AreEqual("1.00:00:00", v.ToString()); } [Test] public void FromObjectUri() { JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz")); Assert.AreEqual(v.Value, new Uri("http://www.stuff.co.nz")); Assert.AreEqual("http://www.stuff.co.nz/", v.ToString()); } [Test] public void FromObjectGuid() { JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString()); } [Test] public void ParseAdditionalContent() { ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 2.", () => { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }, 987987"; JObject o = JObject.Parse(json); }); } [Test] public void DeepEqualsIgnoreOrder() { JObject o1 = new JObject( new JProperty("null", null), new JProperty("integer", 1), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o1)); JObject o2 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o2)); JObject o3 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 2), new JProperty("array", new JArray(1, 2))); Assert.IsFalse(o1.DeepEquals(o3)); JObject o4 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(2, 1))); Assert.IsFalse(o1.DeepEquals(o4)); JObject o5 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1)); Assert.IsFalse(o1.DeepEquals(o5)); Assert.IsFalse(o1.DeepEquals(null)); } [Test] public void ToListOnEmptyObject() { JObject o = JObject.Parse(@"{}"); IList<JToken> l1 = o.ToList<JToken>(); Assert.AreEqual(0, l1.Count); IList<KeyValuePair<string, JToken>> l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(0, l2.Count); o = JObject.Parse(@"{'hi':null}"); l1 = o.ToList<JToken>(); Assert.AreEqual(1, l1.Count); l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(1, l2.Count); } [Test] public void EmptyObjectDeepEquals() { Assert.IsTrue(JToken.DeepEquals(new JObject(), new JObject())); JObject a = new JObject(); JObject b = new JObject(); b.Add("hi", "bye"); b.Remove("hi"); Assert.IsTrue(JToken.DeepEquals(a, b)); Assert.IsTrue(JToken.DeepEquals(b, a)); } [Test] public void GetValueBlogExample() { JObject o = JObject.Parse(@"{ 'name': 'Lower', 'NAME': 'Upper' }"); string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase); // Upper string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase); // Lower Assert.AreEqual("Upper", exactMatch); Assert.AreEqual("Lower", ignoreCase); } [Test] public void GetValue() { JObject a = new JObject(); a["Name"] = "Name!"; a["name"] = "name!"; a["title"] = "Title!"; Assert.AreEqual(null, a.GetValue("NAME", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue("NAME")); Assert.AreEqual(null, a.GetValue("TITLE")); Assert.AreEqual("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase)); Assert.AreEqual("name!", (string)a.GetValue("name", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null, StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null)); JToken v; Assert.IsFalse(a.TryGetValue("NAME", StringComparison.Ordinal, out v)); Assert.AreEqual(null, v); Assert.IsFalse(a.TryGetValue("NAME", out v)); Assert.IsFalse(a.TryGetValue("TITLE", out v)); Assert.IsTrue(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v)); Assert.AreEqual("Name!", (string)v); Assert.IsTrue(a.TryGetValue("name", StringComparison.Ordinal, out v)); Assert.AreEqual("name!", (string)v); Assert.IsFalse(a.TryGetValue(null, StringComparison.Ordinal, out v)); } public class FooJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var token = JToken.FromObject(value, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); if (token.Type == JTokenType.Object) { var o = (JObject)token; o.AddFirst(new JProperty("foo", "bar")); o.WriteTo(writer); } else token.WriteTo(writer); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotSupportedException("This custom converter only supportes serialization and not deserialization."); } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return true; } } [Test] public void FromObjectInsideConverterWithCustomSerializer() { var p = new Person { Name = "Daniel Wertheim", }; var settings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new FooJsonConverter() }, ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(p, settings); Assert.AreEqual(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/groups/group_booking_room_type_quantity.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking.Groups { /// <summary>Holder for reflection information generated from booking/groups/group_booking_room_type_quantity.proto</summary> public static partial class GroupBookingRoomTypeQuantityReflection { #region Descriptor /// <summary>File descriptor for booking/groups/group_booking_room_type_quantity.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GroupBookingRoomTypeQuantityReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjVib29raW5nL2dyb3Vwcy9ncm91cF9ib29raW5nX3Jvb21fdHlwZV9xdWFu", "dGl0eS5wcm90bxIaaG9sbXMudHlwZXMuYm9va2luZy5ncm91cHMaK3N1cHBs", "eS9yb29tX3R5cGVzL3Jvb21fdHlwZV9pbmRpY2F0b3IucHJvdG8ilQEKHEdy", "b3VwQm9va2luZ1Jvb21UeXBlUXVhbnRpdHkSQwoJcm9vbV90eXBlGAEgASgL", "MjAuaG9sbXMudHlwZXMuc3VwcGx5LnJvb21fdHlwZXMuUm9vbVR5cGVJbmRp", "Y2F0b3ISFwoPaG9sZHNfcmVxdWVzdGVkGAIgASgNEhcKD2hvbGRzX2NvbW1p", "dHRlZBgDIAEoDUItWg5ib29raW5nL2dyb3Vwc6oCGkhPTE1TLlR5cGVzLkJv", "b2tpbmcuR3JvdXBzYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Groups.GroupBookingRoomTypeQuantity), global::HOLMS.Types.Booking.Groups.GroupBookingRoomTypeQuantity.Parser, new[]{ "RoomType", "HoldsRequested", "HoldsCommitted" }, null, null, null) })); } #endregion } #region Messages public sealed partial class GroupBookingRoomTypeQuantity : pb::IMessage<GroupBookingRoomTypeQuantity> { private static readonly pb::MessageParser<GroupBookingRoomTypeQuantity> _parser = new pb::MessageParser<GroupBookingRoomTypeQuantity>(() => new GroupBookingRoomTypeQuantity()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GroupBookingRoomTypeQuantity> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Groups.GroupBookingRoomTypeQuantityReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBookingRoomTypeQuantity() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBookingRoomTypeQuantity(GroupBookingRoomTypeQuantity other) : this() { RoomType = other.roomType_ != null ? other.RoomType.Clone() : null; holdsRequested_ = other.holdsRequested_; holdsCommitted_ = other.holdsCommitted_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBookingRoomTypeQuantity Clone() { return new GroupBookingRoomTypeQuantity(this); } /// <summary>Field number for the "room_type" field.</summary> public const int RoomTypeFieldNumber = 1; private global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator roomType_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator RoomType { get { return roomType_; } set { roomType_ = value; } } /// <summary>Field number for the "holds_requested" field.</summary> public const int HoldsRequestedFieldNumber = 2; private uint holdsRequested_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint HoldsRequested { get { return holdsRequested_; } set { holdsRequested_ = value; } } /// <summary>Field number for the "holds_committed" field.</summary> public const int HoldsCommittedFieldNumber = 3; private uint holdsCommitted_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint HoldsCommitted { get { return holdsCommitted_; } set { holdsCommitted_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GroupBookingRoomTypeQuantity); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GroupBookingRoomTypeQuantity other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(RoomType, other.RoomType)) return false; if (HoldsRequested != other.HoldsRequested) return false; if (HoldsCommitted != other.HoldsCommitted) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (roomType_ != null) hash ^= RoomType.GetHashCode(); if (HoldsRequested != 0) hash ^= HoldsRequested.GetHashCode(); if (HoldsCommitted != 0) hash ^= HoldsCommitted.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (roomType_ != null) { output.WriteRawTag(10); output.WriteMessage(RoomType); } if (HoldsRequested != 0) { output.WriteRawTag(16); output.WriteUInt32(HoldsRequested); } if (HoldsCommitted != 0) { output.WriteRawTag(24); output.WriteUInt32(HoldsCommitted); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (roomType_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomType); } if (HoldsRequested != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(HoldsRequested); } if (HoldsCommitted != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(HoldsCommitted); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GroupBookingRoomTypeQuantity other) { if (other == null) { return; } if (other.roomType_ != null) { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator(); } RoomType.MergeFrom(other.RoomType); } if (other.HoldsRequested != 0) { HoldsRequested = other.HoldsRequested; } if (other.HoldsCommitted != 0) { HoldsCommitted = other.HoldsCommitted; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator(); } input.ReadMessage(roomType_); break; } case 16: { HoldsRequested = input.ReadUInt32(); break; } case 24: { HoldsCommitted = input.ReadUInt32(); break; } } } } } #endregion } #endregion Designer generated code
// 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.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; namespace System.Runtime.CompilerServices.Tests { public static class RuntimeHelpersTests { [Fact] public static void GetHashCodeTest() { // Int32 RuntimeHelpers.GetHashCode(Object) object obj1 = new object(); int h1 = RuntimeHelpers.GetHashCode(obj1); int h2 = RuntimeHelpers.GetHashCode(obj1); Assert.Equal(h1, h2); object obj2 = new object(); int h3 = RuntimeHelpers.GetHashCode(obj2); Assert.NotEqual(h1, h3); // Could potentially clash but very unlikely int i123 = 123; int h4 = RuntimeHelpers.GetHashCode(i123); Assert.NotEqual(i123.GetHashCode(), h4); int h5 = RuntimeHelpers.GetHashCode(null); Assert.Equal(0, h5); } public struct TestStruct { public int i1; public int i2; public override bool Equals(object obj) { if (!(obj is TestStruct)) return false; TestStruct that = (TestStruct)obj; return i1 == that.i1 && i2 == that.i2; } public override int GetHashCode() => i1 ^ i2; } [Fact] public static unsafe void GetObjectValue() { // Object RuntimeHelpers.GetObjectValue(Object) TestStruct t = new TestStruct() { i1 = 2, i2 = 4 }; object tOV = RuntimeHelpers.GetObjectValue(t); Assert.Equal(t, (TestStruct)tOV); object o = new object(); object oOV = RuntimeHelpers.GetObjectValue(o); Assert.Equal(o, oOV); int i = 3; object iOV = RuntimeHelpers.GetObjectValue(i); Assert.Equal(i, (int)iOV); } [Fact] public static unsafe void OffsetToStringData() { // RuntimeHelpers.OffsetToStringData char[] expectedValues = new char[] { 'a', 'b', 'c', 'd', 'e', 'f' }; string s = "abcdef"; fixed (char* values = s) // Compiler will use OffsetToStringData with fixed statements { for (int i = 0; i < expectedValues.Length; i++) { Assert.Equal(expectedValues[i], values[i]); } } } [Fact] public static void InitializeArray() { // Void RuntimeHelpers.InitializeArray(Array, RuntimeFieldHandle) char[] expected = new char[] { 'a', 'b', 'c' }; // Compiler will use RuntimeHelpers.InitializeArrary these } [Fact] public static void RunClassConstructor() { RuntimeTypeHandle t = typeof(HasCctor).TypeHandle; RuntimeHelpers.RunClassConstructor(t); Assert.Equal("Hello", HasCctorReceiver.S); return; } internal class HasCctor { static HasCctor() { HasCctorReceiver.S = "Hello" + (Guid.NewGuid().ToString().Substring(string.Empty.Length, 0)); // Make sure the preinitialization optimization doesn't eat this. } } internal class HasCctorReceiver { public static string S; } [Fact] public static void PrepareMethod() { foreach (MethodInfo m in typeof(RuntimeHelpersTests).GetMethods()) RuntimeHelpers.PrepareMethod(m.MethodHandle); Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(default(RuntimeMethodHandle))); Assert.ThrowsAny<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(IList).GetMethod("Add").MethodHandle)); } [Fact] public static void PrepareGenericMethod() { Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(default(RuntimeMethodHandle), null)); // // Type instantiations // // Generic definition with instantiation is valid RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle }); // Instantiated method without instantiation is valid RuntimeHelpers.PrepareMethod(typeof(List<int>).GetMethod("Add").MethodHandle, null); // Generic definition without instantiation is invalid Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, null)); // Wrong instantiation Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle })); // // Method instantiations // // Generic definition with instantiation is valid RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle }); // Instantiated method without instantiation is valid RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize") .MakeGenericMethod(new Type[] { typeof(TestStruct) }).MethodHandle, null); // Generic definition without instantiation is invalid Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, null)); // Wrong instantiation Assert.Throws<ArgumentException>(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle })); } [Fact] public static void PrepareDelegate() { RuntimeHelpers.PrepareDelegate((Action)(() => { })); RuntimeHelpers.PrepareDelegate((Func<int>)(() => 1) + (Func<int>)(() => 2)); RuntimeHelpers.PrepareDelegate(null); } [Fact] public static void TryEnsureSufficientExecutionStack_SpaceAvailable_ReturnsTrue() { Assert.True(RuntimeHelpers.TryEnsureSufficientExecutionStack()); } [Fact] public static void TryEnsureSufficientExecutionStack_NoSpaceAvailable_ReturnsFalse() { FillStack(depth: 0); } [MethodImpl(MethodImplOptions.NoInlining)] private static void FillStack(int depth) { // This test will fail with a StackOverflowException if TryEnsureSufficientExecutionStack() doesn't // return false. No exception is thrown and the test finishes when TryEnsureSufficientExecutionStack() // returns true. if (!RuntimeHelpers.TryEnsureSufficientExecutionStack()) { Assert.Throws<InsufficientExecutionStackException>(() => RuntimeHelpers.EnsureSufficientExecutionStack()); return; } else if (depth < 2048) { FillStack(depth + 1); } } [Fact] public static void GetUninitializedObject_InvalidArguments_ThrowsException() { AssertExtensions.Throws<ArgumentNullException>("type", () => RuntimeHelpers.GetUninitializedObject(null)); AssertExtensions.Throws<ArgumentException>(null, () => RuntimeHelpers.GetUninitializedObject(typeof(string))); // special type Assert.Throws<MemberAccessException>(() => RuntimeHelpers.GetUninitializedObject(typeof(System.IO.Stream))); // abstract type Assert.Throws<MemberAccessException>(() => RuntimeHelpers.GetUninitializedObject(typeof(System.Collections.IEnumerable))); // interface Assert.Throws<MemberAccessException>(() => RuntimeHelpers.GetUninitializedObject(typeof(System.Collections.Generic.List<>))); // generic definition Assert.Throws<NotSupportedException>(() => RuntimeHelpers.GetUninitializedObject(typeof(TypedReference))); // byref-like type } [Fact] public static void GetUninitializedObject_DoesNotRunConstructor() { Assert.Equal(42, new ObjectWithDefaultCtor().Value); Assert.Equal(0, ((ObjectWithDefaultCtor)RuntimeHelpers.GetUninitializedObject(typeof(ObjectWithDefaultCtor))).Value); } [Fact] public static void GetUninitializedObject_Nullable() { // Nullable returns the underlying type instead Assert.Equal(typeof(int), RuntimeHelpers.GetUninitializedObject(typeof(Nullable<int>)).GetType()); } private class ObjectWithDefaultCtor { public int Value = 42; } [Fact] public static void IsReferenceOrContainsReferences() { Assert.False(RuntimeHelpers.IsReferenceOrContainsReferences<int>()); Assert.True(RuntimeHelpers.IsReferenceOrContainsReferences<string>()); Assert.False(RuntimeHelpers.IsReferenceOrContainsReferences<Guid>()); Assert.False(RuntimeHelpers.IsReferenceOrContainsReferences<StructWithoutReferences>()); Assert.True(RuntimeHelpers.IsReferenceOrContainsReferences<StructWithReferences>()); } [Fact] public static void ArrayRangeHelperTest() { int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Range range = Range.All; Assert.Equal(a, RuntimeHelpers.GetSubArray(a, range)); range = new Range(Index.FromStart(1), Index.FromEnd(5)); Assert.Equal(new int [] { 2, 3, 4, 5}, RuntimeHelpers.GetSubArray(a, range)); range = new Range(Index.FromStart(0), Index.FromStart(a.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => { int [] array = RuntimeHelpers.GetSubArray(a, range); }); } [StructLayoutAttribute(LayoutKind.Sequential)] private struct StructWithoutReferences { public int a, b, c; } [StructLayoutAttribute(LayoutKind.Sequential)] private struct StructWithReferences { public int a, b, c; public object d; } [Fact] public static void FixedAddressValueTypeTest() { // Get addresses of static Age fields. IntPtr fixedPtr1 = FixedClass.AddressOfFixedAge(); // Garbage collection. GC.Collect(3, GCCollectionMode.Forced, true, true); GC.WaitForPendingFinalizers(); // Get addresses of static Age fields after garbage collection. IntPtr fixedPtr2 = FixedClass.AddressOfFixedAge(); Assert.Equal(fixedPtr1, fixedPtr2); } } public struct Age { public int years; public int months; } public class FixedClass { [FixedAddressValueType] public static Age FixedAge; public static unsafe IntPtr AddressOfFixedAge() { fixed (Age* pointer = &FixedAge) { return (IntPtr)pointer; } } } }
// // DiagnosticsConfigurationHandlerTest.cs: // NUnit Test Cases for System.Diagnostics.DiagnosticsConfigurationHandler // // Authors: // Jonathan Pryor ([email protected]) // Martin Willemoes Hansen ([email protected]) // // (C) Jonathan Pryor // (C) 2003 Martin Willemoes Hansen // using NUnit.Framework; using System; using System.Configuration; using System.Diagnostics; using System.Xml; namespace MonoTests.System.Diagnostics { [TestFixture] public class DiagnosticsConfigurationHandlerTest : Assertion { private const string XmlFormat = "{0}"; /* "<system.diagnostics>" + "{0}" + "</system.diagnostics>"; */ private DiagnosticsConfigurationHandler handler = new DiagnosticsConfigurationHandler (); [Test, Category ("NotDotNet")] public void SwitchesTag_Attributes () { string[] attrs = {"invalid=\"yes\""}; ValidateExceptions ("#TST:A", "<switches {0}></switches>", attrs); } private void ValidateExceptions (string name, string format, string[] args) { foreach (string arg in args) { string xml = string.Format (XmlFormat, string.Format (format, arg)); try { CreateHandler (xml); Fail (string.Format ("{0}:{1}: no exception generated", name, arg)); } catch (ConfigurationException) { } catch (AssertionException) { // This is generated by the Assertion.Fail() statement in the try block. throw; } catch (Exception e) { Fail (string.Format ("{0}:{1}: wrong exception generated: {2} ({3}).", // name, arg, e.Message, name, arg, e.ToString(), // e.InnerException == null ? "" : e.InnerException.Message)); e.InnerException == null ? "" : e.InnerException.ToString())); } } } private void ValidateSuccess (string name, string format, string[] args) { foreach (string arg in args) { string xml = string.Format (XmlFormat, string.Format (format, arg)); try { CreateHandler (xml); } catch (Exception e) { Fail (string.Format ("{0}:{1}: exception generated: {2} ({3}).", // name, arg, e.Message, name, arg, e.ToString(), // e.InnerException == null ? "" : e.InnerException.Message)); e.InnerException == null ? "" : e.InnerException.ToString())); } } } private object CreateHandler (string xml) { XmlDocument d = new XmlDocument (); d.LoadXml (xml); return handler.Create (null, null, d); } [Test, Category ("NotDotNet")] public void SwitchesTag_Elements () { string[] badElements = { // not enough arguments "<add />", "<add name=\"a\"/>", "<add value=\"b\"/>", // non-integral value "<add name=\"string-value\" value=\"string-value\"/>", // too many arguments "<add name=\"a\" value=\"b\" extra=\"c\"/>", // wrong casing "<add Name=\"a\" value=\"b\"/>", "<Add Name=\"a\" value=\"b\"/>", // missing args "<remove />", "<remove value=\"b\"/>", // too many args "<remove name=\"a\" value=\"b\"/>", "<clear name=\"a\"/>", // invalid element "<invalid element=\"a\" here=\"b\"/>" }; ValidateExceptions ("#TST:IE:Bad", "<switches>{0}</switches>", badElements); string[] goodElements = { "<add name=\"a\" value=\"4\"/>", "<add name=\"a\" value=\"-2\"/>", "<remove name=\"a\"/>", "<clear/>" }; ValidateSuccess ("#TST:IE:Good", "<switches>{0}</switches>", goodElements); } [Test, Category ("NotDotNet")] public void AssertTag () { string[] goodAttributes = { "", "assertuienabled=\"true\"", "assertuienabled=\"false\" logfilename=\"some file name\"", "logfilename=\"some file name\"" }; ValidateSuccess ("#TAT:Good", "<assert {0}/>", goodAttributes); string[] badAttributes = { "AssertUiEnabled=\"true\"", "LogFileName=\"foo\"", "assertuienabled=\"\"", "assertuienabled=\"non-boolean-value\"" }; ValidateExceptions ("#TAT:BadAttrs", "<assert {0}/>", badAttributes); string[] badChildren = { "<any element=\"here\"/>" }; ValidateExceptions ("#TAT:BadChildren", "<assert>{0}</assert>", badChildren); } [Test, Category ("NotDotNet")] public void TraceTag_Attributes () { string[] good = { "", "autoflush=\"true\"", "indentsize=\"4\"", "autoflush=\"false\" indentsize=\"10\"" }; ValidateSuccess ("#TTT:A:Good", "<trace {0}/>", good); string[] bad = { "AutoFlush=\"true\"", "IndentSize=\"false\"", "autoflush=\"non-boolean-value\"", "autoflush=\"\"", "indentsize=\"non-integral-value\"", "indentsize=\"\"", "extra=\"invalid\"" }; ValidateExceptions ("#TTT:A:Bad", "<trace {0}/>", bad); } [Test, Category ("NotDotNet")] public void TraceTag_Children () { string[] good = { // more about listeners in a different function... "<listeners />" }; ValidateSuccess ("#TTT:C:Good", "<trace>{0}</trace>", good); string[] bad = { "<listeners with=\"attribute\"/>", "<invalid element=\"here\"/>" }; ValidateExceptions ("#TTT:C:Bad", "<trace>{0}</trace>", bad); } [Test, Category ("NotDotNet")] public void TraceTag_Listeners () { const string format = "<trace><listeners>{0}</listeners></trace>"; string[] good = { "<clear/>", "<add name=\"foo\" " + "type=\"System.Diagnostics.TextWriterTraceListener, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" " + "initializeData=\"argument.txt\"/>", "<remove name=\"foo\"/>", "<add name=\"foo\" " + "type=\"System.Diagnostics.TextWriterTraceListener, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />", "<remove name=\"foo\"/>" }; ValidateSuccess ("#TTT:L:Good", format, good); string[] bad = { "<invalid tag=\"here\"/>", "<clear with=\"args\"/>", "<remove/>", "<add/>", "<remove name=\"foo\" extra=\"arg\"/>", "<add name=\"foo\"/>", "<add type=\"foo\"/>", "<add name=\"foo\" type=\"invalid-type\"/>", }; ValidateExceptions ("#TTT:L:Bad", format, bad); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; namespace Platform.Support.Windows { public class Advapi32 { [DllImport(ExternDll.Advapi32, CharSet = CharSet.Auto, SetLastError = true)] public static extern int RegOpenKeyEx( UIntPtr hKey, [MarshalAs(UnmanagedType.LPTStr)] string lpSubKey, uint ulOptions, uint samDesired, out UIntPtr phkResult ); [DllImport(ExternDll.Advapi32, SetLastError = true)] public static extern int RegCloseKey( UIntPtr hKey ); [DllImport(ExternDll.Advapi32, SetLastError = true)] public static extern int RegNotifyChangeKeyValue( UIntPtr hKey, bool bWatchSubtree, uint dwNotifyFilter, SafeWaitHandle hEvent, bool fAsynchronous ); [DllImport(ExternDll.Advapi32, EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern bool CreateProcessAsUser( IntPtr hToken, String lpApplicationName, String lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandle, uint dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation ); [DllImport(ExternDll.Advapi32, EntryPoint = "DuplicateTokenEx")] public static extern bool DuplicateTokenEx( IntPtr ExistingTokenHandle, uint dwDesiredAccess, IntPtr lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle); #region Win32 Constants private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400; private const int CREATE_NO_WINDOW = 0x08000000; private const int CREATE_NEW_CONSOLE = 0x00000010; private const uint INVALID_SESSION_ID = 0xFFFFFFFF; private static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero; #endregion Win32 Constants /// <summary> /// Gets the user token from the currently active session /// </summary> /// <param name="phUserToken"></param> /// <returns></returns> public static bool GetSessionUserToken(ref IntPtr phUserToken) { var bResult = false; var hImpersonationToken = IntPtr.Zero; var activeSessionId = INVALID_SESSION_ID; var pSessionInfo = IntPtr.Zero; var sessionCount = 0; // Get a handle to the user access token for the current active session. if (Wtsapi32.WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pSessionInfo, ref sessionCount) != 0) { var arrayElementSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); var current = pSessionInfo; for (var i = 0; i < sessionCount; i++) { var si = (WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)current, typeof(WTS_SESSION_INFO)); current += arrayElementSize; if (si.State == WTS_CONNECTSTATE_CLASS.WTSActive) { activeSessionId = si.SessionID; } } } // If enumerating did not work, fall back to the old method if (activeSessionId == INVALID_SESSION_ID) { activeSessionId = Kernel32.WTSGetActiveConsoleSessionId(); } if (Wtsapi32.WTSQueryUserToken(activeSessionId, ref hImpersonationToken) != 0) { // Convert the impersonation token to a primary token bResult = Advapi32.DuplicateTokenEx(hImpersonationToken, 0, IntPtr.Zero, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int)TOKEN_TYPE.TokenPrimary, ref phUserToken); Kernel32.CloseHandle(hImpersonationToken); } return bResult; } public static bool StartProcessAsCurrentUser(string appPath, out uint pID, string cmdLine = null, string workDir = null, bool visible = true) { var hUserToken = IntPtr.Zero; var startInfo = new STARTUPINFO(); var procInfo = new PROCESS_INFORMATION(); var pEnv = IntPtr.Zero; int iResultOfCreateProcessAsUser; startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO)); try { if (!GetSessionUserToken(ref hUserToken)) { throw new Exception("StartProcessAsCurrentUser: GetSessionUserToken failed."); } uint dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW); startInfo.wShowWindow = (short)(visible ? SW.SHOW : SW.HIDE); startInfo.lpDesktop = "winsta0\\default"; if (!UserEnv.CreateEnvironmentBlock(ref pEnv, hUserToken, false)) { throw new Exception("StartProcessAsCurrentUser: CreateEnvironmentBlock failed."); } if (!Advapi32.CreateProcessAsUser(hUserToken, appPath, // Application Name cmdLine, // Command Line IntPtr.Zero, IntPtr.Zero, false, dwCreationFlags, pEnv, workDir, // Working directory ref startInfo, out procInfo)) { iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error(); throw new Exception("StartProcessAsCurrentUser: CreateProcessAsUser failed. Error Code -" + iResultOfCreateProcessAsUser); } pID = procInfo.dwProcessId; iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error(); } finally { Kernel32.CloseHandle(hUserToken); if (pEnv != IntPtr.Zero) { UserEnv.DestroyEnvironmentBlock(pEnv); } Kernel32.CloseHandle(procInfo.hThread); Kernel32.CloseHandle(procInfo.hProcess); } return true; } } public struct STANDARD_RIGHTS { public const uint READ = 0x00020000; public const uint SYNCHRONIZE = 0x00100000; } public struct KEY { public const uint QUERY_VALUE = 0x0001; public const uint ENUMERATE_SUB_KEYS = 0x0008; public const uint NOTIFY = 0x0010; public const uint READ = (STANDARD_RIGHTS.READ | KEY.QUERY_VALUE | KEY.ENUMERATE_SUB_KEYS | KEY.NOTIFY) & ~(STANDARD_RIGHTS.SYNCHRONIZE); } //from WinReg.h public struct HKEY { public static readonly UIntPtr CLASSES_ROOT = new UIntPtr(0x80000000); public static readonly UIntPtr CURRENT_USER = new UIntPtr(0x80000001); public static readonly UIntPtr LOCAL_MACHINE = new UIntPtr(0x80000002); public static readonly UIntPtr USERS = new UIntPtr(0x80000003); public static readonly UIntPtr PERFORMANCE_DATA = new UIntPtr(0x80000004); public static readonly UIntPtr CURRENT_CONFIG = new UIntPtr(0x80000005); public static readonly UIntPtr DYN_DATA = new UIntPtr(0x80000006); } public struct REG_NOTIFY_CHANGE { public const uint NAME = 0x00000001; public const uint ATTRIBUTES = 0x00000002; public const uint LAST_SET = 0x00000004; public const uint SECURITY = 0x00000008; } [StructLayout(LayoutKind.Sequential)] public struct STARTUPINFO { public int cb; public String lpReserved; public String lpDesktop; public String lpTitle; public uint dwX; public uint dwY; public uint dwXSize; public uint dwYSize; public uint dwXCountChars; public uint dwYCountChars; public uint dwFillAttribute; public uint dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public uint dwProcessId; public uint dwThreadId; } public enum SECURITY_IMPERSONATION_LEVEL { SecurityAnonymous = 0, SecurityIdentification = 1, SecurityImpersonation = 2, SecurityDelegation = 3, } public enum TOKEN_TYPE { TokenPrimary = 1, TokenImpersonation = 2 } }
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using Microsoft.Samples.CodeDomTestSuite; public class ImplementingStructsTest : CodeDomTestTree { public override TestTypes TestType { get { return TestTypes.Everett; } } public override bool ShouldCompile { get { return true; } } public override bool ShouldVerify { get { return true; } } public override string Name { get { return "ImplementingStructsTest"; } } public override string Description { get { return "Tests structs that implement other things."; } } public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (nspace); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TestingStructs"); cd.IsClass = true; nspace.Types.Add (cd); if (Supports (provider, GeneratorSupport.DeclareValueTypes)) { // GENERATES (C#): // public int CallingStructMethod(int i) { // StructImplementation o = new StructImplementation (); // return o.StructMethod(i); // } AddScenario ("CheckCallingStructMethod"); CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "CallingStructMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("StructImplementation"), "o", new CodeObjectCreateExpression (new CodeTypeReference ("StructImplementation")))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeMethodReferenceExpression ( new CodeVariableReferenceExpression ("o"), "StructMethod"), new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); // GENERATES (C#): // public int UsingValueStruct(int i) { // ValueStruct StructObject = new ValueStruct(); // StructObject.x = i; // return StructObject.x; // } AddScenario ("CheckUsingValueStruct"); cmm = new CodeMemberMethod (); cmm.Name = "UsingValueStruct"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement ("ValueStruct", "StructObject", new CodeObjectCreateExpression ("ValueStruct"))); cmm.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "x"), new CodeArgumentReferenceExpression ("i"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "x"))); cd.Members.Add (cmm); // GENERATES (C#): // public int UsingStructProperty(int i) { // StructImplementation StructObject = new StructImplementation(); // StructObject.UseIField = i; // return StructObject.UseIField; // } AddScenario ("CheckUsingStructProperty"); cmm = new CodeMemberMethod (); cmm.Name = "UsingStructProperty"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement ("StructImplementation", "StructObject", new CodeObjectCreateExpression ("StructImplementation"))); cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ("StructObject"), "UseIField"), new CodeArgumentReferenceExpression ("i"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("StructObject"), "UseIField"))); cd.Members.Add (cmm); // GENERATES (C#): // public int UsingInterfaceStruct(int i) { // ImplementInterfaceStruct IStructObject = new ImplementInterfaceStruct(); // return IStructObject.InterfaceMethod(i); // } if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { AddScenario ("CheckUsingInterfaceStruct"); // method to test struct implementing interfaces cmm = new CodeMemberMethod (); cmm.Name = "UsingInterfaceStruct"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeVariableDeclarationStatement ("ImplementInterfaceStruct", "IStructObject", new CodeObjectCreateExpression ("ImplementInterfaceStruct"))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression ( new CodeVariableReferenceExpression ("IStructObject"), "InterfaceMethod", new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); } // GENERATES (C#): // public struct StructImplementation { // int i; // public int UseIField { // get { // return i; // } // set { // i = value; // } // } // public int StructMethod(int i) { // return (5 + i); // } // } cd = new CodeTypeDeclaration ("StructImplementation"); cd.IsStruct = true; nspace.Types.Add (cd); // declare an integer field CodeMemberField field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i"); field.Attributes = MemberAttributes.Public; cd.Members.Add (field); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = "UseIField"; prop.Type = new CodeTypeReference (typeof (int)); prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; CodeFieldReferenceExpression fref = new CodeFieldReferenceExpression (); fref.FieldName = "i"; prop.GetStatements.Add (new CodeMethodReturnStatement (fref)); prop.SetStatements.Add (new CodeAssignStatement (fref, new CodePropertySetValueReferenceExpression ())); cd.Members.Add (prop); cmm = new CodeMemberMethod (); cmm.Name = "StructMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (5), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); // GENERATES (C#): // public struct ValueStruct { // public int x; // } cd = new CodeTypeDeclaration ("ValueStruct"); cd.IsStruct = true; nspace.Types.Add (cd); // declare an integer field field = new CodeMemberField (new CodeTypeReference (typeof (int)), "x"); field.Attributes = MemberAttributes.Public; cd.Members.Add (field); if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { // interface to be implemented // GENERATES (C#): // public interface InterfaceStruct { // int InterfaceMethod(int i); // } cd = new CodeTypeDeclaration ("InterfaceStruct"); cd.IsInterface = true; nspace.Types.Add (cd); // method in the interface cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cd.Members.Add (cmm); // struct to implement an interface // GENERATES (C#): // public struct ImplementInterfaceStruct : InterfaceStruct { // public int InterfaceMethod(int i) { // return (8 + i); // } // } cd = new CodeTypeDeclaration ("ImplementInterfaceStruct"); cd.BaseTypes.Add (new CodeTypeReference ("InterfaceStruct")); cd.IsStruct = true; nspace.Types.Add (cd); field = new CodeMemberField (new CodeTypeReference (typeof (int)), "i"); field.Attributes = MemberAttributes.Public; cd.Members.Add (field); // implement interface method cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceStruct")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (new CodePrimitiveExpression (8), CodeBinaryOperatorType.Add, new CodeArgumentReferenceExpression ("i")))); cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i")); cd.Members.Add (cmm); } } } public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) { if (Supports (provider, GeneratorSupport.DeclareValueTypes)) { object genObject; Type genType; AddScenario ("InstantiateTestingStructs", "Find and instantiate TestingStructs."); if (!FindAndInstantiate ("NSPC.TestingStructs", asm, out genObject, out genType)) return; VerifyScenario ("InstantiateTestingStructs"); // verify method return value for method which calls struct method if (VerifyMethod (genType, genObject, "CallingStructMethod", new object[] {6}, 11)) { VerifyScenario ("CheckCallingStructMethod"); } // verify method return value for method which uses struct property if (VerifyMethod (genType, genObject, "UsingStructProperty", new object[] {6}, 6)) { VerifyScenario ("CheckUsingStructProperty"); } // verify method return value for using struct as value if (VerifyMethod (genType, genObject, "UsingValueStruct", new object[] {8}, 8)) { VerifyScenario ("CheckUsingValueStruct"); } // verify method return value for method which uses struct that implements and interface if (Supports (provider, GeneratorSupport.DeclareInterfaces) && VerifyMethod (genType, genObject, "UsingInterfaceStruct", new object[] {6}, 14)) VerifyScenario ("CheckUsingInterfaceStruct"); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// Operations for managing service certificates for your subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx for /// more information) /// </summary> internal partial class ServiceCertificateOperations : IServiceOperations<ComputeManagementClient>, IServiceCertificateOperations { /// <summary> /// Initializes a new instance of the ServiceCertificateOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServiceCertificateOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// The Begin Creating Service Certificate operation adds a certificate /// to a hosted service. This operation is an asynchronous operation. /// To determine whether the management service has finished /// processing the request, call Get Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Creating Service /// Certificate operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginCreatingAsync(string serviceName, ServiceCertificateCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Data == null) { throw new ArgumentNullException("parameters.Data"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement certificateFileElement = new XElement(XName.Get("CertificateFile", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(certificateFileElement); XElement dataElement = new XElement(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); dataElement.Value = Convert.ToBase64String(parameters.Data); certificateFileElement.Add(dataElement); XElement certificateFormatElement = new XElement(XName.Get("CertificateFormat", "http://schemas.microsoft.com/windowsazure")); certificateFormatElement.Value = ComputeManagementClient.CertificateFormatToString(parameters.CertificateFormat); certificateFileElement.Add(certificateFormatElement); if (parameters.Password != null) { XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.microsoft.com/windowsazure")); passwordElement.Value = parameters.Password; certificateFileElement.Add(passwordElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Begin Deleting Service Certificate operation deletes a service /// certificate from the certificate store of a hosted service. This /// operation is an asynchronous operation. To determine whether the /// management service has finished processing the request, call Get /// Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Deleting Service /// Certificate operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginDeletingAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } // TODO: Validate parameters.ServiceName is a valid DNS name. if (parameters.Thumbprint == null) { throw new ArgumentNullException("parameters.Thumbprint"); } if (parameters.ThumbprintAlgorithm == null) { throw new ArgumentNullException("parameters.ThumbprintAlgorithm"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(parameters.ServiceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(parameters.ThumbprintAlgorithm); url = url + "-"; url = url + Uri.EscapeDataString(parameters.Thumbprint); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Create Service Certificate operation adds a certificate to a /// hosted service. This operation is an asynchronous operation. To /// determine whether the management service has finished processing /// the request, call Get Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> CreateAsync(string serviceName, ServiceCertificateCreateParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.ServiceCertificates.BeginCreatingAsync(serviceName, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Delete Service Certificate operation deletes a service /// certificate from the certificate store of a hosted service. This /// operation is an asynchronous operation. To determine whether the /// management service has finished processing the request, call Get /// Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Delete Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> DeleteAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.ServiceCertificates.BeginDeletingAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Get Service Certificate operation returns the public data for /// the specified X.509 certificate associated with a hosted service. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Get Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Service Certificate operation response. /// </returns> public async Task<ServiceCertificateGetResponse> GetAsync(ServiceCertificateGetParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } // TODO: Validate parameters.ServiceName is a valid DNS name. if (parameters.Thumbprint == null) { throw new ArgumentNullException("parameters.Thumbprint"); } if (parameters.ThumbprintAlgorithm == null) { throw new ArgumentNullException("parameters.ThumbprintAlgorithm"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(parameters.ServiceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(parameters.ThumbprintAlgorithm); url = url + "-"; url = url + Uri.EscapeDataString(parameters.Thumbprint); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceCertificateGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceCertificateGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement certificateElement = responseDoc.Element(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure")); if (certificateElement != null) { XElement dataElement = certificateElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { byte[] dataInstance = Convert.FromBase64String(dataElement.Value); result.Data = dataInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Service Certificates operation lists all of the service /// certificates associated with the specified hosted service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your hosted service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Service Certificates operation response. /// </returns> public async Task<ServiceCertificateListResponse> ListAsync(string serviceName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceCertificateListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceCertificateListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement certificatesSequenceElement = responseDoc.Element(XName.Get("Certificates", "http://schemas.microsoft.com/windowsazure")); if (certificatesSequenceElement != null) { foreach (XElement certificatesElement in certificatesSequenceElement.Elements(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure"))) { ServiceCertificateListResponse.Certificate certificateInstance = new ServiceCertificateListResponse.Certificate(); result.Certificates.Add(certificateInstance); XElement certificateUrlElement = certificatesElement.Element(XName.Get("CertificateUrl", "http://schemas.microsoft.com/windowsazure")); if (certificateUrlElement != null) { Uri certificateUrlInstance = TypeConversion.TryParseUri(certificateUrlElement.Value); certificateInstance.CertificateUri = certificateUrlInstance; } XElement thumbprintElement = certificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure")); if (thumbprintElement != null) { string thumbprintInstance = thumbprintElement.Value; certificateInstance.Thumbprint = thumbprintInstance; } XElement thumbprintAlgorithmElement = certificatesElement.Element(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure")); if (thumbprintAlgorithmElement != null) { string thumbprintAlgorithmInstance = thumbprintAlgorithmElement.Value; certificateInstance.ThumbprintAlgorithm = thumbprintAlgorithmInstance; } XElement dataElement = certificatesElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { byte[] dataInstance = Convert.FromBase64String(dataElement.Value); certificateInstance.Data = dataInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using UnityEngine; using System; using System.Collections; namespace UMA { /// <summary> /// Overlay color data. /// </summary> [System.Serializable] public class OverlayColorData : System.IEquatable<OverlayColorData> { public const string UNSHARED = "-"; public string name; public Color[] channelMask; public Color[] channelAdditiveMask; public Color color { get { return channelMask[0]; } set { channelMask[0] = value; } } /// <summary> /// Default constructor /// </summary> public OverlayColorData() { } /// <summary> /// Constructor for a given number of channels. /// </summary> /// <param name="channels">Channels.</param> public OverlayColorData(int channels) { channelMask = new Color[channels]; channelAdditiveMask = new Color[channels]; for(int i= 0; i < channels; i++ ) { channelMask[i] = Color.white; channelAdditiveMask[i] = new Color(0,0,0,0); } } /// <summary> /// Deep copy of the OverlayColorData. /// </summary> public OverlayColorData Duplicate() { var res = new OverlayColorData(); res.name = name; res.channelMask = new Color[channelMask.Length]; for (int i = 0; i < channelMask.Length; i++) { res.channelMask[i] = channelMask[i]; } res.channelAdditiveMask = new Color[channelAdditiveMask.Length]; for (int i = 0; i < channelAdditiveMask.Length; i++) { res.channelAdditiveMask[i] = channelAdditiveMask[i]; } return res; } /// <summary> /// This needs to be better /// </summary> /// <returns><c>true</c> if this instance is A shared color; otherwise, <c>false</c>.</returns> public bool IsASharedColor { get { if (HasName() && name != UNSHARED) return true; return false; } } /// <summary> /// Does the OverlayColorData have a valid name? /// </summary> /// <returns><c>true</c> if this instance has a valid name; otherwise, <c>false</c>.</returns> public bool HasName() { return ((name != null) && (name.Length > 0)); } /// <summary> /// Are two Unity Colors the same? /// </summary> /// <returns><c>true</c>, if colors are identical, <c>false</c> otherwise.</returns> /// <param name="color1">Color1.</param> /// <param name="color2">Color2.</param> public static bool SameColor(Color color1, Color color2) { return (Mathf.Approximately(color1.r, color2.r) && Mathf.Approximately(color1.g, color2.g) && Mathf.Approximately(color1.b, color2.b) && Mathf.Approximately(color1.a, color2.a)); } /// <summary> /// Are two Unity Colors different? /// </summary> /// <returns><c>true</c>, if colors are different, <c>false</c> otherwise.</returns> /// <param name="color1">Color1.</param> /// <param name="color2">Color2.</param> public static bool DifferentColor(Color color1, Color color2) { return (!Mathf.Approximately(color1.r, color2.r) || !Mathf.Approximately(color1.g, color2.g) || !Mathf.Approximately(color1.b, color2.b) || !Mathf.Approximately(color1.a, color2.a)); } public static implicit operator bool(OverlayColorData obj) { return ((System.Object)obj) != null; } public bool Equals(OverlayColorData other) { return (this == other); } public override bool Equals(object other) { return Equals(other as OverlayColorData); } public static bool operator == (OverlayColorData cd1, OverlayColorData cd2) { if (cd1) { if (cd2) { if (cd2.channelMask.Length != cd1.channelMask.Length) return false; for (int i = 0; i < cd1.channelMask.Length; i++) { if (DifferentColor(cd1.channelMask[i], cd2.channelMask[i])) return false; } for (int i = 0; i < cd1.channelAdditiveMask.Length; i++) { if (DifferentColor(cd1.channelAdditiveMask[i], cd2.channelAdditiveMask[i])) return false; } return true; } return false; } return (!(bool)cd2); } public static bool operator != (OverlayColorData cd1, OverlayColorData cd2) { if (cd1) { if (cd2) { if (cd2.channelMask.Length != cd1.channelMask.Length) return true; for (int i = 0; i < cd1.channelMask.Length; i++) { if (DifferentColor(cd1.channelMask[i], cd2.channelMask[i])) return true; } for (int i = 0; i < cd1.channelAdditiveMask.Length; i++) { if (DifferentColor(cd1.channelAdditiveMask[i], cd2.channelAdditiveMask[i])) return true; } return false; } return true; } return ((bool)cd2); } public override int GetHashCode() { return base.GetHashCode(); } public void EnsureChannels(int channels) { if (channelMask == null) { channelMask = new Color[channels]; channelAdditiveMask = new Color[channels]; for (int i = 0; i < channels; i++) { channelMask[i] = Color.white; channelAdditiveMask[i] = new Color(0, 0, 0, 0); } } else { if (channelMask.Length < channels) { var newMask = new Color[channels]; System.Array.Copy(channelMask, newMask, channelMask.Length); for (int i = channelMask.Length; i < channels; i++) { newMask[i] = Color.white; } channelMask = newMask; } if (channelAdditiveMask.Length < channels) { var newAdditiveMask = new Color[channels]; System.Array.Copy(channelAdditiveMask, newAdditiveMask, channelAdditiveMask.Length); for (int i = channelAdditiveMask.Length; i < channels; i++) { newAdditiveMask[i] = new Color(0,0,0,0); } channelAdditiveMask = newAdditiveMask; } } } public void AssignTo(OverlayColorData dest) { if (name != null) { dest.name = String.Copy(name); } dest.channelMask = new Color[channelMask.Length]; for (int i = 0; i < channelMask.Length; i++) { dest.channelMask[i] = channelMask[i]; } dest.channelAdditiveMask = new Color[channelAdditiveMask.Length]; for (int i = 0; i < channelAdditiveMask.Length; i++) { dest.channelAdditiveMask[i] = channelAdditiveMask[i]; } } public void AssignFrom(OverlayColorData src) { if (src.name != null) { name = String.Copy(src.name); } EnsureChannels(src.channelMask.Length); for (int i = 0; i < src.channelMask.Length; i++) { channelMask[i] = src.channelMask[i]; } for (int i = 0; i < src.channelAdditiveMask.Length; i++) { channelAdditiveMask[i] = src.channelAdditiveMask[i]; } } } }
// // RandomExtensions.cs // // Author: // Ehouarn Perret <[email protected]> // // Copyright (c) Ehouarn Perret // // 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; namespace EhouarnPerret.CSharp.Utilities.Core { public static class RandomExtensions { public static byte[] NextBytes(this Random random, int byteCount) { var value = new byte[byteCount]; random.NextBytes(value); return value; } public static bool NextBoolean(this Random random) { var value = random.NextByte(0, 1) == 1; return value; } public static byte NextByte(this Random random) { return random.NextBytes(1)[0]; } public static byte NextByte(this Random random, byte lowerBound, byte upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); var value = (byte)(random.NextByte() % (upperBound + 1 - lowerBound) + lowerBound); return value; } public static ushort NextUInt16(this Random random) { return BitConverter.ToUInt16(random.NextBytes(NumberHelpers.UInt16ByteCount), 0); } public static ushort NextUInt16(this Random random, ushort lowerBound, ushort upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); var value = (ushort)(random.NextUInt16() % (upperBound + 1 - lowerBound) + lowerBound); return value; } public static uint NextUInt32(this Random random) { return BitConverter.ToUInt32(random.NextBytes(NumberHelpers.UInt32ByteCount), 0); } public static uint NextUInt32(this Random random, uint lowerBound, uint upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); var value = random.NextUInt32() % (upperBound + 1 - lowerBound) + lowerBound; return value; } public static ulong NextUInt64(this Random random) { return BitConverter.ToUInt64(random.NextBytes(NumberHelpers.UInt64ByteCount), 0); } public static ulong NextUInt64(this Random random, ulong lowerBound, ulong upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); var value = random.NextUInt64() % (upperBound + 1 - lowerBound) + lowerBound; return value; } public static sbyte NextSByte(this Random random) { return random.NextByte().AsSByte(); } public static sbyte NextSByte(this Random random, sbyte lowerBound, sbyte upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); var value = (sbyte)(random.NextSByte() % (upperBound + 1 - lowerBound) + lowerBound); return value; } public static short NextInt16(this Random random) { return BitConverter.ToInt16(random.NextBytes(NumberHelpers.Int16ByteCount), 0); } public static short NextInt16(this Random random, short lowerBound, short upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); var value = (short)(random.NextInt16() % (upperBound + 1 - lowerBound) + lowerBound); return value; } public static int NextInt32(this Random random) { return BitConverter.ToInt32(random.NextBytes(NumberHelpers.Int32ByteCount), 0); } public static int NextInt32(this Random random, int lowerBound, int upperBound) { lowerBound.ThrowIfGreaterThan(upperBound, nameof(lowerBound)); var value = random.NextInt32() % (upperBound + 1 - lowerBound) + lowerBound; return value; } public static long NextInt64(this Random random) { return BitConverter.ToInt64(random.NextBytes(NumberHelpers.Int64ByteCount), 0); } public static long NextInt64(this Random random, long lowerBound, long upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); var value = random.NextInt64() % (upperBound + 1 - lowerBound) + lowerBound; return value; } public static float NextSingle(this Random random) { return BitConverter.ToSingle(random.NextBytes(NumberHelpers.SingleByteCount), 0); } public static float NextSingle(this Random random, float lowerBound, float upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); var value = random.NextSingle() * (upperBound - lowerBound) + lowerBound; return value; } public static double NextDouble(this Random random) { return BitConverter.ToDouble(random.NextBytes(NumberHelpers.DoubleByteCount), 0); } public static double NextDouble(this Random random, double lowerBound, double upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); // Analysis disable once InvokeAsExtensionMethod var value = NextDouble(random) * (upperBound - lowerBound) + lowerBound; return value; } public static decimal NextDecimal(this Random random) { var bytes = random.NextBytes(12); var low = BitConverter.ToInt32(bytes, 0); var mid = BitConverter.ToInt32(bytes, 4); var high = BitConverter.ToInt32(bytes, 8); var scale = random.NextByte(0, 28); var isNegative = random.NextBoolean(); var value = new decimal(low, mid, high, isNegative, scale); return value; } public static decimal NextDecimal(this Random random, decimal lowerBound, decimal upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound, nameof(lowerBound)); var value = random.NextDecimal() * (upperBound - lowerBound) + lowerBound; return value; } public static DateTime NextDateTime(this Random random) { return random.NextDateTime(DateTime.MinValue, DateTime.MaxValue); } public static DateTime NextDateTime(this Random random, DateTime lowerBound, DateTime upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound); var timeSpan = random.NextTimeSpan(TimeSpan.Zero, upperBound - lowerBound); var value = lowerBound.AddTicks(timeSpan.Ticks); return value; } public static TimeSpan NextTimeSpan(this Random random) { return random.NextTimeSpan(TimeSpan.MinValue, TimeSpan.MaxValue); } public static TimeSpan NextTimeSpan(this Random random, TimeSpan lowerBound, TimeSpan upperBound) { lowerBound.ThrowIfStrictlyGreaterThan(upperBound); var ratio = random.NextDouble(); var value = new TimeSpan((long) (ratio*(upperBound.Ticks - lowerBound.Ticks))); return value; } } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace IO.Swagger.Client { /// <summary> /// Represents a set of configuration settings /// </summary> public class Configuration { /// <summary> /// Initializes a new instance of the Configuration class with different settings /// </summary> /// <param name="apiClient">Api client</param> /// <param name="defaultHeader">Dictionary of default HTTP header</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="accessToken">accessToken</param> /// <param name="apiKey">Dictionary of API key</param> /// <param name="apiKeyPrefix">Dictionary of API key prefix</param> /// <param name="tempFolderPath">Temp folder path</param> /// <param name="dateTimeFormat">DateTime format string</param> /// <param name="timeout">HTTP connection timeout (in milliseconds)</param> /// <param name="userAgent">HTTP user agent</param> public Configuration(ApiClient apiClient = null, Dictionary<String, String> defaultHeader = null, string username = null, string password = null, string accessToken = null, Dictionary<String, String> apiKey = null, Dictionary<String, String> apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, int timeout = 100000, string userAgent = "Swagger-Codegen/1.0.0/csharp" ) { setApiClientUsingDefault(apiClient); Username = username; Password = password; AccessToken = accessToken; UserAgent = userAgent; if (defaultHeader != null) DefaultHeader = defaultHeader; if (apiKey != null) ApiKey = apiKey; if (apiKeyPrefix != null) ApiKeyPrefix = apiKeyPrefix; TempFolderPath = tempFolderPath; DateTimeFormat = dateTimeFormat; Timeout = timeout; } /// <summary> /// Initializes a new instance of the Configuration class. /// </summary> /// <param name="apiClient">Api client.</param> public Configuration(ApiClient apiClient) { setApiClientUsingDefault(apiClient); } /// <summary> /// Version of the package. /// </summary> /// <value>Version of the package.</value> public const string Version = "1.0.0"; /// <summary> /// Gets or sets the default Configuration. /// </summary> /// <value>Configuration.</value> public static Configuration Default = new Configuration(); /// <summary> /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// </summary> /// <value>Timeout.</value> public int Timeout { get { return ApiClient.RestClient.Timeout; } set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; } } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The API client.</value> public ApiClient ApiClient; /// <summary> /// Set the ApiClient using Default or ApiClient instance. /// </summary> /// <param name="apiClient">An instance of ApiClient.</param> /// <returns></returns> public void setApiClientUsingDefault (ApiClient apiClient = null) { if (apiClient == null) { if (Default != null && Default.ApiClient == null) Default.ApiClient = new ApiClient(); ApiClient = Default != null ? Default.ApiClient : new ApiClient(); } else { if (Default != null && Default.ApiClient == null) Default.ApiClient = apiClient; ApiClient = apiClient; } } private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); /// <summary> /// Gets or sets the default header. /// </summary> public Dictionary<String, String> DefaultHeader { get { return _defaultHeaderMap; } set { _defaultHeaderMap = value; } } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string key, string value) { _defaultHeaderMap.Add(key, value); } /// <summary> /// Gets or sets the HTTP user agent. /// </summary> /// <value>Http user agent.</value> public String UserAgent { get; set; } /// <summary> /// Gets or sets the username (HTTP basic authentication). /// </summary> /// <value>The username.</value> public String Username { get; set; } /// <summary> /// Gets or sets the password (HTTP basic authentication). /// </summary> /// <value>The password.</value> public String Password { get; set; } /// <summary> /// Gets or sets the access token for OAuth2 authentication. /// </summary> /// <value>The access token.</value> public String AccessToken { get; set; } /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> public Dictionary<String, String> ApiKey = new Dictionary<String, String>(); /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>(); /// <summary> /// Get the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix (string apiKeyIdentifier) { var apiKeyValue = ""; ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); var apiKeyPrefix = ""; if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; else return apiKeyValue; } private string _tempFolderPath = Path.GetTempPath(); /// <summary> /// Gets or sets the temporary folder path to store the files downloaded from the server. /// </summary> /// <value>Folder path.</value> public String TempFolderPath { get { return _tempFolderPath; } set { if (String.IsNullOrEmpty(value)) { _tempFolderPath = value; return; } // create the directory if it does not exist if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end if (value[value.Length - 1] == Path.DirectorySeparatorChar) _tempFolderPath = value; else _tempFolderPath = value + Path.DirectorySeparatorChar; } } private const string ISO8601_DATETIME_FORMAT = "o"; private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; /// <summary> /// Gets or sets the the date time format used when serializing in the ApiClient /// By default, it's set to ISO 8601 - "o", for others see: /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// No validation is done to ensure that the string you're providing is valid /// </summary> /// <value>The DateTimeFormat string</value> public String DateTimeFormat { get { return _dateTimeFormat; } set { if (string.IsNullOrEmpty(value)) { // Never allow a blank or null string, go back to the default _dateTimeFormat = ISO8601_DATETIME_FORMAT; return; } // Caution, no validation when you choose date time format other than ISO 8601 // Take a look at the above links _dateTimeFormat = value; } } /// <summary> /// Returns a string with essential information for debugging. /// </summary> public static String ToDebugReport() { String report = "C# SDK (IO.Swagger) Debug Report:\n"; report += " OS: " + Environment.OSVersion + "\n"; report += " .NET Framework Version: " + Assembly .GetExecutingAssembly() .GetReferencedAssemblies() .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; report += " Version of the API: 1.0.0\n"; report += " SDK Package Version: 1.0.0\n"; return report; } } }
using System.ComponentModel.Composition; using System.Linq; using System.Reflection; using Magecrawl.GameUI.Dialogs; using Magecrawl.Utilities; namespace Magecrawl.Keyboard { [Export(typeof(IKeystrokeHandler))] [ExportMetadata("RequireAllActionsMapped", "true")] [ExportMetadata("HandlerName", "Default")] internal class DefaultKeystrokeHandler : BaseKeystrokeHandler { private PlayerActions m_playerActions; public DefaultKeystrokeHandler() { m_playerActions = null; } public override void NowPrimaried(object request) { if (m_playerActions == null) m_playerActions = new PlayerActions(m_engine, m_gameInstance); } private NamedKey GetNamedKeyForMethodInfo(MethodInfo info) { return m_keyMappings.Keys.Where(k => m_keyMappings[k] == info).Single(); } // This is used by GameInstance to put up a tutorial-like message up with whatever key you mapped. internal char GetCommandKey(string command) { return GetNamedKeyForMethodInfo(typeof(DefaultKeystrokeHandler).GetMethod(command, BindingFlags.Instance | BindingFlags.NonPublic)).Character; } #region Mappable key commands /* * BCL: see file MageCrawl/dist/KeyMappings.xml. To add a new mappable action, define a private method for it here, * then map it to an unused key in KeyMappings.xml. The action should take no parameters and should return nothing. */ // If you add new non-debug commands, remember to update HelpPainter.cs private void North() { m_playerActions.Move(Direction.North); } private void South() { m_playerActions.Move(Direction.South); } private void East() { m_playerActions.Move(Direction.East); } private void West() { m_playerActions.Move(Direction.West); } private void Northeast() { m_playerActions.Move(Direction.Northeast); } private void Northwest() { m_playerActions.Move(Direction.Northwest); } private void Southeast() { m_playerActions.Move(Direction.Southeast); } private void Southwest() { m_playerActions.Move(Direction.Southwest); } private void RunNorth() { m_playerActions.Run(Direction.North); } private void RunSouth() { m_playerActions.Run(Direction.South); } private void RunEast() { m_playerActions.Run(Direction.East); } private void RunWest() { m_playerActions.Run(Direction.West); } private void RunNortheast() { m_playerActions.Run(Direction.Northeast); } private void RunNorthwest() { m_playerActions.Run(Direction.Northwest); } private void RunSoutheast() { m_playerActions.Run(Direction.Southeast); } private void RunSouthwest() { m_playerActions.Run(Direction.Southwest); } private void Quit() { m_gameInstance.SetHandlerName("QuitGame", QuitReason.quitAction); } private void Operate() { NamedKey operateKey = GetNamedKeyForMethodInfo((MethodInfo)MethodInfo.GetCurrentMethod()); m_playerActions.Operate(operateKey); } private void GetItem() { m_playerActions.GetItem(); } private void Save() { m_gameInstance.SetHandlerName("SaveGame"); } private void DebugMode() { if (Preferences.Instance.DebuggingMode) { m_gameInstance.SetHandlerName("DebugMode"); m_gameInstance.UpdatePainters(); } } private void Wait() { m_playerActions.Wait(); } private void RestTillHealed() { m_playerActions.RestUntilHealed(); } private void Attack() { NamedKey attackKey = GetNamedKeyForMethodInfo((MethodInfo)MethodInfo.GetCurrentMethod()); m_playerActions.Attack(attackKey); } private void ViewMode() { m_gameInstance.SetHandlerName("Viewmode"); } private void Inventory() { m_gameInstance.SetHandlerName("Inventory"); } private void Equipment() { m_gameInstance.SetHandlerName("Equipment"); } private void SwapWeapon() { m_playerActions.SwapWeapon(); } private void TextBoxPageUp() { m_gameInstance.TextBox.TextBoxScrollUp(); } private void TextBoxPageDown() { m_gameInstance.TextBox.TextBoxScrollDown(); } private void TextBoxClear() { m_gameInstance.TextBox.Clear(); } private void CastSpell() { NamedKey castKey = GetNamedKeyForMethodInfo((MethodInfo)MethodInfo.GetCurrentMethod()); m_gameInstance.SetHandlerName("SpellList", castKey); } private void Escape() { } private void Select() { } private void Help() { m_gameInstance.SetHandlerName("Help", m_keyMappings); } private void DownStairs() { m_playerActions.DownStairs(); } private void UpStairs() { m_playerActions.UpStairs(); } private void MoveToLocation() { NamedKey movementKey = GetNamedKeyForMethodInfo((MethodInfo)MethodInfo.GetCurrentMethod()); m_playerActions.MoveToLocation(movementKey); } private void ShowSkillTree() { m_gameInstance.SetHandlerName("SkillTree"); } private void ShowEffects() { m_gameInstance.SetHandlerName("ShowEffects"); } // If you add new non-debug commands, remember to update HelpPainter.cs #endregion } }
// // System.Security.Cryptography.SHA1CryptoServiceProvider.cs // // Authors: // Matthew S. Ford ([email protected]) // Sebastien Pouliot ([email protected]) // // Copyright 2001 by Matthew S. Ford. // Copyright (C) 2004, 2005, 2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Note: // The MS Framework includes two (almost) identical class for SHA1. // SHA1Managed is a 100% managed implementation. // SHA1CryptoServiceProvider (this file) is a wrapper on CryptoAPI. // Mono must provide those two class for binary compatibility. // In our case both class are wrappers around a managed internal class SHA1Internal. #if PCL namespace System.Security.Cryptography { internal class SHA1Internal { private const int BLOCK_SIZE_BYTES = 64; private uint[] _H; // these are my chaining variables private ulong count; private byte[] _ProcessingBuffer; // Used to start data when passed less than a block worth. private int _ProcessingBufferCount; // Counts how much data we have stored that still needs processed. private uint[] buff; public SHA1Internal () { _H = new uint[5]; _ProcessingBuffer = new byte[BLOCK_SIZE_BYTES]; buff = new uint[80]; Initialize(); } public void HashCore (byte[] rgb, int ibStart, int cbSize) { int i; if (_ProcessingBufferCount != 0) { if (cbSize < (BLOCK_SIZE_BYTES - _ProcessingBufferCount)) { System.Buffer.BlockCopy (rgb, ibStart, _ProcessingBuffer, _ProcessingBufferCount, cbSize); _ProcessingBufferCount += cbSize; return; } else { i = (BLOCK_SIZE_BYTES - _ProcessingBufferCount); System.Buffer.BlockCopy (rgb, ibStart, _ProcessingBuffer, _ProcessingBufferCount, i); ProcessBlock (_ProcessingBuffer, 0); _ProcessingBufferCount = 0; ibStart += i; cbSize -= i; } } for (i = 0; i < cbSize - cbSize % BLOCK_SIZE_BYTES; i += BLOCK_SIZE_BYTES) { ProcessBlock (rgb, (uint)(ibStart + i)); } if (cbSize % BLOCK_SIZE_BYTES != 0) { System.Buffer.BlockCopy (rgb, cbSize - cbSize % BLOCK_SIZE_BYTES + ibStart, _ProcessingBuffer, 0, cbSize % BLOCK_SIZE_BYTES); _ProcessingBufferCount = cbSize % BLOCK_SIZE_BYTES; } } public byte[] HashFinal () { byte[] hash = new byte[20]; ProcessFinalBlock (_ProcessingBuffer, 0, _ProcessingBufferCount); for (int i=0; i<5; i++) { for (int j=0; j<4; j++) { hash [i*4+j] = (byte)(_H[i] >> (8*(3-j))); } } return hash; } public void Initialize () { count = 0; _ProcessingBufferCount = 0; _H[0] = 0x67452301; _H[1] = 0xefcdab89; _H[2] = 0x98badcfe; _H[3] = 0x10325476; _H[4] = 0xC3D2E1F0; } private void ProcessBlock(byte[] inputBuffer, uint inputOffset) { uint a, b, c, d, e; count += BLOCK_SIZE_BYTES; // abc removal would not work on the fields uint[] _H = this._H; uint[] buff = this.buff; InitialiseBuff(buff, inputBuffer, inputOffset); FillBuff(buff); a = _H[0]; b = _H[1]; c = _H[2]; d = _H[3]; e = _H[4]; // This function was unrolled because it seems to be doubling our performance with current compiler/VM. // Possibly roll up if this changes. // ---- Round 1 -------- int i=0; while (i < 20) { e += ((a << 5) | (a >> 27)) + (((c ^ d) & b) ^ d) + 0x5A827999 + buff[i]; b = (b << 30) | (b >> 2); d += ((e << 5) | (e >> 27)) + (((b ^ c) & a) ^ c) + 0x5A827999 + buff[i+1]; a = (a << 30) | (a >> 2); c += ((d << 5) | (d >> 27)) + (((a ^ b) & e) ^ b) + 0x5A827999 + buff[i+2]; e = (e << 30) | (e >> 2); b += ((c << 5) | (c >> 27)) + (((e ^ a) & d) ^ a) + 0x5A827999 + buff[i+3]; d = (d << 30) | (d >> 2); a += ((b << 5) | (b >> 27)) + (((d ^ e) & c) ^ e) + 0x5A827999 + buff[i+4]; c = (c << 30) | (c >> 2); i += 5; } // ---- Round 2 -------- while (i < 40) { e += ((a << 5) | (a >> 27)) + (b ^ c ^ d) + 0x6ED9EBA1 + buff[i]; b = (b << 30) | (b >> 2); d += ((e << 5) | (e >> 27)) + (a ^ b ^ c) + 0x6ED9EBA1 + buff[i + 1]; a = (a << 30) | (a >> 2); c += ((d << 5) | (d >> 27)) + (e ^ a ^ b) + 0x6ED9EBA1 + buff[i + 2]; e = (e << 30) | (e >> 2); b += ((c << 5) | (c >> 27)) + (d ^ e ^ a) + 0x6ED9EBA1 + buff[i + 3]; d = (d << 30) | (d >> 2); a += ((b << 5) | (b >> 27)) + (c ^ d ^ e) + 0x6ED9EBA1 + buff[i + 4]; c = (c << 30) | (c >> 2); i += 5; } // ---- Round 3 -------- while (i < 60) { e += ((a << 5) | (a >> 27)) + ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC + buff[i]; b = (b << 30) | (b >> 2); d += ((e << 5) | (e >> 27)) + ((a & b) | (a & c) | (b & c)) + 0x8F1BBCDC + buff[i + 1]; a = (a << 30) | (a >> 2); c += ((d << 5) | (d >> 27)) + ((e & a) | (e & b) | (a & b)) + 0x8F1BBCDC + buff[i + 2]; e = (e << 30) | (e >> 2); b += ((c << 5) | (c >> 27)) + ((d & e) | (d & a) | (e & a)) + 0x8F1BBCDC + buff[i + 3]; d = (d << 30) | (d >> 2); a += ((b << 5) | (b >> 27)) + ((c & d) | (c & e) | (d & e)) + 0x8F1BBCDC + buff[i + 4]; c = (c << 30) | (c >> 2); i += 5; } // ---- Round 4 -------- while (i < 80) { e += ((a << 5) | (a >> 27)) + (b ^ c ^ d) + 0xCA62C1D6 + buff[i]; b = (b << 30) | (b >> 2); d += ((e << 5) | (e >> 27)) + (a ^ b ^ c) + 0xCA62C1D6 + buff[i + 1]; a = (a << 30) | (a >> 2); c += ((d << 5) | (d >> 27)) + (e ^ a ^ b) + 0xCA62C1D6 + buff[i + 2]; e = (e << 30) | (e >> 2); b += ((c << 5) | (c >> 27)) + (d ^ e ^ a) + 0xCA62C1D6 + buff[i + 3]; d = (d << 30) | (d >> 2); a += ((b << 5) | (b >> 27)) + (c ^ d ^ e) + 0xCA62C1D6 + buff[i + 4]; c = (c << 30) | (c >> 2); i += 5; } _H[0] += a; _H[1] += b; _H[2] += c; _H[3] += d; _H[4] += e; } private static void InitialiseBuff(uint[] buff, byte[] input, uint inputOffset) { buff[0] = (uint)((input[inputOffset + 0] << 24) | (input[inputOffset + 1] << 16) | (input[inputOffset + 2] << 8) | (input[inputOffset + 3])); buff[1] = (uint)((input[inputOffset + 4] << 24) | (input[inputOffset + 5] << 16) | (input[inputOffset + 6] << 8) | (input[inputOffset + 7])); buff[2] = (uint)((input[inputOffset + 8] << 24) | (input[inputOffset + 9] << 16) | (input[inputOffset + 10] << 8) | (input[inputOffset + 11])); buff[3] = (uint)((input[inputOffset + 12] << 24) | (input[inputOffset + 13] << 16) | (input[inputOffset + 14] << 8) | (input[inputOffset + 15])); buff[4] = (uint)((input[inputOffset + 16] << 24) | (input[inputOffset + 17] << 16) | (input[inputOffset + 18] << 8) | (input[inputOffset + 19])); buff[5] = (uint)((input[inputOffset + 20] << 24) | (input[inputOffset + 21] << 16) | (input[inputOffset + 22] << 8) | (input[inputOffset + 23])); buff[6] = (uint)((input[inputOffset + 24] << 24) | (input[inputOffset + 25] << 16) | (input[inputOffset + 26] << 8) | (input[inputOffset + 27])); buff[7] = (uint)((input[inputOffset + 28] << 24) | (input[inputOffset + 29] << 16) | (input[inputOffset + 30] << 8) | (input[inputOffset + 31])); buff[8] = (uint)((input[inputOffset + 32] << 24) | (input[inputOffset + 33] << 16) | (input[inputOffset + 34] << 8) | (input[inputOffset + 35])); buff[9] = (uint)((input[inputOffset + 36] << 24) | (input[inputOffset + 37] << 16) | (input[inputOffset + 38] << 8) | (input[inputOffset + 39])); buff[10] = (uint)((input[inputOffset + 40] << 24) | (input[inputOffset + 41] << 16) | (input[inputOffset + 42] << 8) | (input[inputOffset + 43])); buff[11] = (uint)((input[inputOffset + 44] << 24) | (input[inputOffset + 45] << 16) | (input[inputOffset + 46] << 8) | (input[inputOffset + 47])); buff[12] = (uint)((input[inputOffset + 48] << 24) | (input[inputOffset + 49] << 16) | (input[inputOffset + 50] << 8) | (input[inputOffset + 51])); buff[13] = (uint)((input[inputOffset + 52] << 24) | (input[inputOffset + 53] << 16) | (input[inputOffset + 54] << 8) | (input[inputOffset + 55])); buff[14] = (uint)((input[inputOffset + 56] << 24) | (input[inputOffset + 57] << 16) | (input[inputOffset + 58] << 8) | (input[inputOffset + 59])); buff[15] = (uint)((input[inputOffset + 60] << 24) | (input[inputOffset + 61] << 16) | (input[inputOffset + 62] << 8) | (input[inputOffset + 63])); } private static void FillBuff(uint[] buff) { uint val; for (int i = 16; i < 80; i += 8) { val = buff[i - 3] ^ buff[i - 8] ^ buff[i - 14] ^ buff[i - 16]; buff[i] = (val << 1) | (val >> 31); val = buff[i - 2] ^ buff[i - 7] ^ buff[i - 13] ^ buff[i - 15]; buff[i + 1] = (val << 1) | (val >> 31); val = buff[i - 1] ^ buff[i - 6] ^ buff[i - 12] ^ buff[i - 14]; buff[i + 2] = (val << 1) | (val >> 31); val = buff[i + 0] ^ buff[i - 5] ^ buff[i - 11] ^ buff[i - 13]; buff[i + 3] = (val << 1) | (val >> 31); val = buff[i + 1] ^ buff[i - 4] ^ buff[i - 10] ^ buff[i - 12]; buff[i + 4] = (val << 1) | (val >> 31); val = buff[i + 2] ^ buff[i - 3] ^ buff[i - 9] ^ buff[i - 11]; buff[i + 5] = (val << 1) | (val >> 31); val = buff[i + 3] ^ buff[i - 2] ^ buff[i - 8] ^ buff[i - 10]; buff[i + 6] = (val << 1) | (val >> 31); val = buff[i + 4] ^ buff[i - 1] ^ buff[i - 7] ^ buff[i - 9]; buff[i + 7] = (val << 1) | (val >> 31); } } private void ProcessFinalBlock (byte[] inputBuffer, int inputOffset, int inputCount) { ulong total = count + (ulong)inputCount; int paddingSize = (56 - (int)(total % BLOCK_SIZE_BYTES)); if (paddingSize < 1) paddingSize += BLOCK_SIZE_BYTES; int length = inputCount+paddingSize+8; byte[] fooBuffer = (length == 64) ? _ProcessingBuffer : new byte[length]; for (int i=0; i<inputCount; i++) { fooBuffer[i] = inputBuffer[i+inputOffset]; } fooBuffer[inputCount] = 0x80; for (int i=inputCount+1; i<inputCount+paddingSize; i++) { fooBuffer[i] = 0x00; } // I deal in bytes. The algorithm deals in bits. ulong size = total << 3; AddLength (size, fooBuffer, inputCount+paddingSize); ProcessBlock (fooBuffer, 0); if (length == 128) ProcessBlock (fooBuffer, 64); } internal void AddLength (ulong length, byte[] buffer, int position) { buffer [position++] = (byte)(length >> 56); buffer [position++] = (byte)(length >> 48); buffer [position++] = (byte)(length >> 40); buffer [position++] = (byte)(length >> 32); buffer [position++] = (byte)(length >> 24); buffer [position++] = (byte)(length >> 16); buffer [position++] = (byte)(length >> 8); buffer [position] = (byte)(length); } } class SHA1Managed { private SHA1Internal sha; public SHA1Managed () { sha = new SHA1Internal (); } public byte[] ComputeHash (byte[] buffer) { if (buffer == null) throw new ArgumentNullException ("buffer"); return ComputeHash (buffer, 0, buffer.Length); } public byte[] ComputeHash (byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException ("offset", "< 0"); if (count < 0) throw new ArgumentException ("count", "< 0"); // ordered to avoid possible integer overflow if (offset > buffer.Length - count) { throw new ArgumentException ("offset + count", "Overflow"); } HashCore (buffer, offset, count); var hash_value = HashFinal (); Initialize (); return hash_value; } protected void HashCore (byte[] rgb, int ibStart, int cbSize) { sha.HashCore (rgb, ibStart, cbSize); } protected byte[] HashFinal () { return sha.HashFinal (); } protected void Initialize () { sha.Initialize (); } } } #endif
using System.Diagnostics.Contracts; // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // SymmetricAlgorithm.cs // namespace System.Security.Cryptography { [System.Runtime.InteropServices.ComVisible(true)] public abstract class SymmetricAlgorithm : IDisposable { protected int BlockSizeValue; protected int FeedbackSizeValue; protected byte[] IVValue; protected byte[] KeyValue; protected KeySizes[] LegalBlockSizesValue; protected KeySizes[] LegalKeySizesValue; protected int KeySizeValue; protected CipherMode ModeValue; protected PaddingMode PaddingValue; // // protected constructors // protected SymmetricAlgorithm() { // Default to cipher block chaining (CipherMode.CBC) and // PKCS-style padding (pad n bytes with value n) ModeValue = CipherMode.CBC; PaddingValue = PaddingMode.PKCS7; } // SymmetricAlgorithm implements IDisposable // To keep mscorlib compatibility with Orcas, CoreCLR's SymmetricAlgorithm has an explicit IDisposable // implementation. Post-Orcas the desktop has an implicit IDispoable implementation. #if FEATURE_CORECLR void IDisposable.Dispose() { Dispose(); } #endif // FEATURE_CORECLR public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Clear() { (this as IDisposable).Dispose(); } protected virtual void Dispose(bool disposing) { if (disposing) { // Note: we always want to zeroize the sensitive key material if (KeyValue != null) { Array.Clear(KeyValue, 0, KeyValue.Length); KeyValue = null; } if (IVValue != null) { Array.Clear(IVValue, 0, IVValue.Length); IVValue = null; } } } // // public properties // public virtual int BlockSize { get { return BlockSizeValue; } set { int i; int j; for (i=0; i<LegalBlockSizesValue.Length; i++) { // If a cipher has only one valid key size, MinSize == MaxSize and SkipSize will be 0 if (LegalBlockSizesValue[i].SkipSize == 0) { if (LegalBlockSizesValue[i].MinSize == value) { // assume MinSize = MaxSize BlockSizeValue = value; IVValue = null; return; } } else { for (j = LegalBlockSizesValue[i].MinSize; j<=LegalBlockSizesValue[i].MaxSize; j += LegalBlockSizesValue[i].SkipSize) { if (j == value) { if (BlockSizeValue != value) { BlockSizeValue = value; IVValue = null; // Wrong length now } return; } } } } throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidBlockSize")); } } public virtual int FeedbackSize { get { return FeedbackSizeValue; } set { if (value <= 0 || value > BlockSizeValue || (value % 8) != 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFeedbackSize")); FeedbackSizeValue = value; } } public virtual byte[] IV { get { if (IVValue == null) GenerateIV(); return (byte[]) IVValue.Clone(); } set { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); if (value.Length != BlockSizeValue / 8) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidIVSize")); IVValue = (byte[]) value.Clone(); } } public virtual byte[] Key { get { if (KeyValue == null) GenerateKey(); return (byte[]) KeyValue.Clone(); } set { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); if (!ValidKeySize(value.Length * 8)) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize")); // must convert bytes to bits KeyValue = (byte[]) value.Clone(); KeySizeValue = value.Length * 8; } } public virtual KeySizes[] LegalBlockSizes { get { return (KeySizes[]) LegalBlockSizesValue.Clone(); } } public virtual KeySizes[] LegalKeySizes { get { return (KeySizes[]) LegalKeySizesValue.Clone(); } } public virtual int KeySize { get { return KeySizeValue; } set { if (!ValidKeySize(value)) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize")); KeySizeValue = value; KeyValue = null; } } public virtual CipherMode Mode { get { return ModeValue; } set { if ((value < CipherMode.CBC) || (CipherMode.CFB < value)) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidCipherMode")); ModeValue = value; } } public virtual PaddingMode Padding { get { return PaddingValue; } set { if ((value < PaddingMode.None) || (PaddingMode.ISO10126 < value)) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidPaddingMode")); PaddingValue = value; } } // // public methods // // The following method takes a bit length input and returns whether that length is a valid size // according to LegalKeySizes public bool ValidKeySize(int bitLength) { KeySizes[] validSizes = this.LegalKeySizes; int i,j; if (validSizes == null) return false; for (i=0; i< validSizes.Length; i++) { if (validSizes[i].SkipSize == 0) { if (validSizes[i].MinSize == bitLength) { // assume MinSize = MaxSize return true; } } else { for (j = validSizes[i].MinSize; j<= validSizes[i].MaxSize; j += validSizes[i].SkipSize) { if (j == bitLength) { return true; } } } } return false; } static public SymmetricAlgorithm Create() { #if FULL_AOT_RUNTIME return new System.Security.Cryptography.RijndaelManaged (); #else // use the crypto config system to return an instance of // the default SymmetricAlgorithm on this machine return Create("System.Security.Cryptography.SymmetricAlgorithm"); #endif } static public SymmetricAlgorithm Create(String algName) { return (SymmetricAlgorithm) CryptoConfig.CreateFromName(algName); } public virtual ICryptoTransform CreateEncryptor() { return CreateEncryptor(Key, IV); } public abstract ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV); public virtual ICryptoTransform CreateDecryptor() { return CreateDecryptor(Key, IV); } public abstract ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV); public abstract void GenerateKey(); public abstract void GenerateIV(); } }