content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using Microsoft.DotNet.XUnitExtensions; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Algorithms.Tests { [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")] public abstract class HKDFTests { protected abstract byte[] Extract(HashAlgorithmName hash, int prkLength, byte[] ikm, byte[] salt); protected abstract byte[] Expand(HashAlgorithmName hash, byte[] prk, int outputLength, byte[] info); protected abstract byte[] DeriveKey(HashAlgorithmName hash, byte[] ikm, int outputLength, byte[] salt, byte[] info); [Theory] [MemberData(nameof(GetRfc5869TestCases))] public void Rfc5869ExtractTests(Rfc5869TestCase test) { byte[] prk = Extract(test.Hash, test.Prk.Length, test.Ikm, test.Salt); Assert.Equal(test.Prk, prk); } [Theory] [MemberData(nameof(GetRfc5869TestCases))] public void Rfc5869ExtractTamperHashTests(Rfc5869TestCase test) { byte[] prk = Extract(HashAlgorithmName.MD5, 128 / 8, test.Ikm, test.Salt); Assert.NotEqual(test.Prk, prk); } [Theory] [MemberData(nameof(GetRfc5869TestCases))] public void Rfc5869ExtractTamperIkmTests(Rfc5869TestCase test) { byte[] ikm = test.Ikm.ToArray(); ikm[0] ^= 1; byte[] prk = Extract(test.Hash, test.Prk.Length, ikm, test.Salt); Assert.NotEqual(test.Prk, prk); } [Theory] [MemberData(nameof(GetRfc5869TestCasesWithNonEmptySalt))] public void Rfc5869ExtractTamperSaltTests(Rfc5869TestCase test) { byte[] salt = test.Salt.ToArray(); salt[0] ^= 1; byte[] prk = Extract(test.Hash, test.Prk.Length, test.Ikm, salt); Assert.NotEqual(test.Prk, prk); } [Fact] public void Rfc5869ExtractDefaultHash() { byte[] ikm = new byte[20]; byte[] salt = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "hashAlgorithmName", () => Extract(default(HashAlgorithmName), 20, ikm, salt)); } [Fact] public void Rfc5869ExtractNonsensicalHash() { byte[] ikm = new byte[20]; byte[] salt = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "hashAlgorithmName", () => Extract(new HashAlgorithmName("foo"), 20, ikm, salt)); } [Fact] public void Rfc5869ExtractEmptyIkm() { byte[] salt = new byte[20]; byte[] ikm = Array.Empty<byte>(); // Ensure does not throw byte[] prk = Extract(HashAlgorithmName.SHA1, 20, ikm, salt); Assert.Equal("FBDB1D1B18AA6C08324B7D64B71FB76370690E1D", prk.ByteArrayToHex()); } [Fact] public void Rfc5869ExtractEmptySalt() { byte[] ikm = new byte[20]; byte[] salt = Array.Empty<byte>(); byte[] prk = Extract(HashAlgorithmName.SHA1, 20, ikm, salt); Assert.Equal("A3CBF4A40F51A53E046F07397E52DF9286AE93A2", prk.ByteArrayToHex()); } [Theory] [MemberData(nameof(GetRfc5869TestCases))] public void Rfc5869ExpandTests(Rfc5869TestCase test) { byte[] okm = Expand(test.Hash, test.Prk, test.Okm.Length, test.Info); Assert.Equal(test.Okm, okm); } [Fact] public void Rfc5869ExpandDefaultHash() { byte[] prk = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "hashAlgorithmName", () => Expand(default(HashAlgorithmName), prk, 20, null)); } [Fact] public void Rfc5869ExpandNonsensicalHash() { byte[] prk = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "hashAlgorithmName", () => Expand(new HashAlgorithmName("foo"), prk, 20, null)); } [Theory] [MemberData(nameof(GetRfc5869TestCases))] public void Rfc5869ExpandTamperPrkTests(Rfc5869TestCase test) { byte[] prk = test.Prk.ToArray(); prk[0] ^= 1; byte[] okm = Expand(test.Hash, prk, test.Okm.Length, test.Info); Assert.NotEqual(test.Okm, okm); } [Theory] [MemberData(nameof(GetPrkTooShortTestCases))] public void Rfc5869ExpandPrkTooShort(HashAlgorithmName hash, int prkSize) { byte[] prk = new byte[prkSize]; AssertExtensions.Throws<ArgumentException>( "prk", () => Expand(hash, prk, 17, Array.Empty<byte>())); } [Fact] public void Rfc5869ExpandOkmMaxSize() { byte[] prk = new byte[20]; // Does not throw byte[] okm = Expand(HashAlgorithmName.SHA1, prk, 20 * 255, Array.Empty<byte>()); Assert.Equal(20 * 255, okm.Length); } [Theory] [MemberData(nameof(GetRfc5869TestCases))] public void Rfc5869DeriveKeyTests(Rfc5869TestCase test) { byte[] okm = DeriveKey(test.Hash, test.Ikm, test.Okm.Length, test.Salt, test.Info); Assert.Equal(test.Okm, okm); } [Fact] public void Rfc5869DeriveKeyDefaultHash() { byte[] ikm = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "hashAlgorithmName", () => DeriveKey(default(HashAlgorithmName), ikm, 20, Array.Empty<byte>(), Array.Empty<byte>())); } [Fact] public void Rfc5869DeriveKeyNonSensicalHash() { byte[] ikm = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "hashAlgorithmName", () => DeriveKey(new HashAlgorithmName("foo"), ikm, 20, Array.Empty<byte>(), Array.Empty<byte>())); } [Theory] [MemberData(nameof(GetRfc5869TestCases))] public void Rfc5869DeriveKeyTamperIkmTests(Rfc5869TestCase test) { byte[] ikm = test.Ikm.ToArray(); ikm[0] ^= 1; byte[] okm = DeriveKey(test.Hash, ikm, test.Okm.Length, test.Salt, test.Info); Assert.NotEqual(test.Okm, okm); } [Theory] [MemberData(nameof(GetRfc5869TestCasesWithNonEmptySalt))] public void Rfc5869DeriveKeyTamperSaltTests(Rfc5869TestCase test) { byte[] salt = test.Salt.ToArray(); salt[0] ^= 1; byte[] okm = DeriveKey(test.Hash, test.Ikm, test.Okm.Length, salt, test.Info); Assert.NotEqual(test.Okm, okm); } [Theory] [MemberData(nameof(GetRfc5869TestCasesWithNonEmptyInfo))] public void Rfc5869DeriveKeyTamperInfoTests(Rfc5869TestCase test) { byte[] info = test.Info.ToArray(); info[0] ^= 1; byte[] okm = DeriveKey(test.Hash, test.Ikm, test.Okm.Length, test.Salt, info); Assert.NotEqual(test.Okm, okm); } public static IEnumerable<object[]> GetRfc5869TestCases() { foreach (Rfc5869TestCase test in Rfc5869TestCases) { yield return new object[] { test }; } } public static IEnumerable<object[]> GetRfc5869TestCasesWithNonEmptySalt() { foreach (Rfc5869TestCase test in Rfc5869TestCases) { if (test.Salt != null && test.Salt.Length != 0) { yield return new object[] { test }; } } } public static IEnumerable<object[]> GetRfc5869TestCasesWithNonEmptyInfo() { foreach (Rfc5869TestCase test in Rfc5869TestCases) { if (test.Info != null && test.Info.Length != 0) { yield return new object[] { test }; } } } public static IEnumerable<object[]> GetPrkTooShortTestCases() { yield return new object[] { HashAlgorithmName.SHA1, 0 }; yield return new object[] { HashAlgorithmName.SHA1, 1 }; yield return new object[] { HashAlgorithmName.SHA1, 160 / 8 - 1 }; yield return new object[] { HashAlgorithmName.SHA256, 256 / 8 - 1 }; yield return new object[] { HashAlgorithmName.SHA512, 512 / 8 - 1 }; yield return new object[] { HashAlgorithmName.MD5, 128 / 8 - 1 }; } private static Rfc5869TestCase[] Rfc5869TestCases { get; } = new Rfc5869TestCase[7] { new Rfc5869TestCase() { Name = "Basic test case with SHA-256", Hash = HashAlgorithmName.SHA256, Ikm = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b".HexToByteArray(), Salt = "000102030405060708090a0b0c".HexToByteArray(), Info = "f0f1f2f3f4f5f6f7f8f9".HexToByteArray(), Prk = ( "077709362c2e32df0ddc3f0dc47bba63" + "90b6c73bb50f9c3122ec844ad7c2b3e5").HexToByteArray(), Okm = ( "3cb25f25faacd57a90434f64d0362f2a" + "2d2d0a90cf1a5a4c5db02d56ecc4c5bf" + "34007208d5b887185865").HexToByteArray(), }, new Rfc5869TestCase() { Name = "Test with SHA-256 and longer inputs/outputs", Hash = HashAlgorithmName.SHA256, Ikm = ( "000102030405060708090a0b0c0d0e0f" + "101112131415161718191a1b1c1d1e1f" + "202122232425262728292a2b2c2d2e2f" + "303132333435363738393a3b3c3d3e3f" + "404142434445464748494a4b4c4d4e4f").HexToByteArray(), Salt = ( "606162636465666768696a6b6c6d6e6f" + "707172737475767778797a7b7c7d7e7f" + "808182838485868788898a8b8c8d8e8f" + "909192939495969798999a9b9c9d9e9f" + "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf").HexToByteArray(), Info = ( "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" + "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" + "e0e1e2e3e4e5e6e7e8e9eaebecedeeef" + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff").HexToByteArray(), Prk = ( "06a6b88c5853361a06104c9ceb35b45c" + "ef760014904671014a193f40c15fc244").HexToByteArray(), Okm = ( "b11e398dc80327a1c8e7f78c596a4934" + "4f012eda2d4efad8a050cc4c19afa97c" + "59045a99cac7827271cb41c65e590e09" + "da3275600c2f09b8367793a9aca3db71" + "cc30c58179ec3e87c14c01d5c1f3434f" + "1d87").HexToByteArray(), }, new Rfc5869TestCase() { Name = "Test with SHA-256 and zero-length salt/info", Hash = HashAlgorithmName.SHA256, Ikm = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b".HexToByteArray(), Salt = Array.Empty<byte>(), Info = Array.Empty<byte>(), Prk = ( "19ef24a32c717b167f33a91d6f648bdf" + "96596776afdb6377ac434c1c293ccb04").HexToByteArray(), Okm = ( "8da4e775a563c18f715f802a063c5a31" + "b8a11f5c5ee1879ec3454e5f3c738d2d" + "9d201395faa4b61a96c8").HexToByteArray(), }, new Rfc5869TestCase() { Name = "Basic test case with SHA-1", Hash = HashAlgorithmName.SHA1, Ikm = "0b0b0b0b0b0b0b0b0b0b0b".HexToByteArray(), Salt = "000102030405060708090a0b0c".HexToByteArray(), Info = "f0f1f2f3f4f5f6f7f8f9".HexToByteArray(), Prk = "9b6c18c432a7bf8f0e71c8eb88f4b30baa2ba243".HexToByteArray(), Okm = ( "085a01ea1b10f36933068b56efa5ad81" + "a4f14b822f5b091568a9cdd4f155fda2" + "c22e422478d305f3f896").HexToByteArray(), }, new Rfc5869TestCase() { Name = "Test with SHA-1 and longer inputs/outputs", Hash = HashAlgorithmName.SHA1, Ikm = ( "000102030405060708090a0b0c0d0e0f" + "101112131415161718191a1b1c1d1e1f" + "202122232425262728292a2b2c2d2e2f" + "303132333435363738393a3b3c3d3e3f" + "404142434445464748494a4b4c4d4e4f").HexToByteArray(), Salt = ( "606162636465666768696a6b6c6d6e6f" + "707172737475767778797a7b7c7d7e7f" + "808182838485868788898a8b8c8d8e8f" + "909192939495969798999a9b9c9d9e9f" + "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf").HexToByteArray(), Info = ( "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" + "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" + "e0e1e2e3e4e5e6e7e8e9eaebecedeeef" + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff").HexToByteArray(), Prk = "8adae09a2a307059478d309b26c4115a224cfaf6".HexToByteArray(), Okm = ( "0bd770a74d1160f7c9f12cd5912a06eb" + "ff6adcae899d92191fe4305673ba2ffe" + "8fa3f1a4e5ad79f3f334b3b202b2173c" + "486ea37ce3d397ed034c7f9dfeb15c5e" + "927336d0441f4c4300e2cff0d0900b52" + "d3b4").HexToByteArray(), }, new Rfc5869TestCase() { Name = "Test with SHA-1 and zero-length salt/info", Hash = HashAlgorithmName.SHA1, Ikm = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b".HexToByteArray(), Salt = Array.Empty<byte>(), Info = Array.Empty<byte>(), Prk = "da8c8a73c7fa77288ec6f5e7c297786aa0d32d01".HexToByteArray(), Okm = ( "0ac1af7002b3d761d1e55298da9d0506" + "b9ae52057220a306e07b6b87e8df21d0" + "ea00033de03984d34918").HexToByteArray(), }, new Rfc5869TestCase() { Name = "Test with SHA-1, salt not provided (defaults to HashLen zero octets), zero-length info", Hash = HashAlgorithmName.SHA1, Ikm = "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c".HexToByteArray(), Salt = null, Info = Array.Empty<byte>(), Prk = "2adccada18779e7c2077ad2eb19d3f3e731385dd".HexToByteArray(), Okm = ( "2c91117204d745f3500d636a62f64f0a" + "b3bae548aa53d423b0d1f27ebba6f5e5" + "673a081d70cce7acfc48").HexToByteArray(), }, }; public struct Rfc5869TestCase { public string Name { get; set; } public HashAlgorithmName Hash { get; set; } public byte[] Ikm { get; set; } public byte[] Salt { get; set; } public byte[] Info { get; set; } public byte[] Prk { get; set; } public byte[] Okm { get; set; } public override string ToString() => Name; } public class HkdfByteArrayTests : HKDFTests { protected override byte[] Extract(HashAlgorithmName hash, int prkLength, byte[] ikm, byte[] salt) { return HKDF.Extract(hash, ikm, salt); } protected override byte[] Expand(HashAlgorithmName hash, byte[] prk, int outputLength, byte[] info) { return HKDF.Expand(hash, prk, outputLength, info); } protected override byte[] DeriveKey(HashAlgorithmName hash, byte[] ikm, int outputLength, byte[] salt, byte[] info) { return HKDF.DeriveKey(hash, ikm, outputLength, salt, info); } [Fact] public void Rfc5869ExtractNullIkm() { byte[] salt = new byte[20]; AssertExtensions.Throws<ArgumentNullException>( "ikm", () => HKDF.Extract(HashAlgorithmName.SHA1, null, salt)); } [Fact] public void Rfc5869ExpandOkmMaxSizePlusOne() { byte[] prk = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "outputLength", () => HKDF.Expand(HashAlgorithmName.SHA1, prk, 20 * 255 + 1, Array.Empty<byte>())); } [Fact] public void Rfc5869ExpandOkmPotentiallyOverflowingValue() { byte[] prk = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "outputLength", () => HKDF.Expand(HashAlgorithmName.SHA1, prk, 8421505, Array.Empty<byte>())); } [Fact] public void Rfc5869ExpandOutputLengthZero() { byte[] prk = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "outputLength", () => HKDF.Expand(HashAlgorithmName.SHA1, prk, 0, Array.Empty<byte>())); } [Fact] public void Rfc5869ExpandOutputLengthLessThanZero() { byte[] prk = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "outputLength", () => HKDF.Expand(HashAlgorithmName.SHA1, prk, -1, Array.Empty<byte>())); } [Fact] public void Rfc5869DeriveKeyNullIkm() { AssertExtensions.Throws<ArgumentNullException>( "ikm", () => HKDF.DeriveKey(HashAlgorithmName.SHA1, null, 20, Array.Empty<byte>(), Array.Empty<byte>())); } [Fact] public void Rfc5869DeriveKeyOkmMaxSizePlusOne() { byte[] ikm = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "outputLength", () => HKDF.DeriveKey(HashAlgorithmName.SHA1, ikm, 20 * 255 + 1, Array.Empty<byte>(), Array.Empty<byte>())); } [Fact] public void Rfc5869DeriveKeyOkmPotentiallyOverflowingValue() { byte[] ikm = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "outputLength", () => HKDF.DeriveKey(HashAlgorithmName.SHA1, ikm, 8421505, Array.Empty<byte>(), Array.Empty<byte>())); } [Fact] public void Rfc5869DeriveOutputLengthZero() { byte[] ikm = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "outputLength", () => HKDF.DeriveKey(HashAlgorithmName.SHA1, ikm, 0, Array.Empty<byte>(), Array.Empty<byte>())); } [Fact] public void Rfc5869DeriveOutputLengthLessThanZero() { byte[] ikm = new byte[20]; AssertExtensions.Throws<ArgumentOutOfRangeException>( "outputLength", () => HKDF.DeriveKey(HashAlgorithmName.SHA1, ikm, -1, Array.Empty<byte>(), Array.Empty<byte>())); } } public class HkdfSpanTests : HKDFTests { protected override byte[] Extract(HashAlgorithmName hash, int prkLength, byte[] ikm, byte[] salt) { byte[] prk = new byte[prkLength]; Assert.Equal(prkLength, HKDF.Extract(hash, ikm, salt, prk)); return prk; } protected override byte[] Expand(HashAlgorithmName hash, byte[] prk, int outputLength, byte[] info) { byte[] output = new byte[outputLength]; HKDF.Expand(hash, prk, output, info); return output; } protected override byte[] DeriveKey(HashAlgorithmName hash, byte[] ikm, int outputLength, byte[] salt, byte[] info) { byte[] output = new byte[outputLength]; HKDF.DeriveKey(hash, ikm, output, salt, info); return output; } [Fact] public void Rfc5869ExtractPrkTooLong() { byte[] prk = new byte[24]; for (int i = 0; i < 4; i++) { prk[20 + i] = (byte)(i + 5); } byte[] ikm = new byte[20]; byte[] salt = new byte[20]; Assert.Equal(20, HKDF.Extract(HashAlgorithmName.SHA1, ikm, salt, prk)); Assert.Equal("A3CBF4A40F51A53E046F07397E52DF9286AE93A2", prk.AsSpan(0, 20).ByteArrayToHex()); for (int i = 0; i < 4; i++) { // ensure we didn't modify anything further Assert.Equal((byte)(i + 5), prk[20 + i]); } } [Fact] public void Rfc5869OkmMaxSizePlusOne() { byte[] prk = new byte[20]; byte[] okm = new byte[20 * 255 + 1]; AssertExtensions.Throws<ArgumentException>( "output", () => HKDF.Expand(HashAlgorithmName.SHA1, prk, okm, Array.Empty<byte>())); } [Fact] public void Rfc5869OkmMaxSizePotentiallyOverflowingValue() { byte[] prk = new byte[20]; byte[] okm = new byte[8421505]; AssertExtensions.Throws<ArgumentException>( "output", () => HKDF.Expand(HashAlgorithmName.SHA1, prk, okm, Array.Empty<byte>())); } [Fact] public void Rfc5869ExpandOutputLengthZero() { byte[] prk = new byte[20]; byte[] okm = new byte[0]; AssertExtensions.Throws<ArgumentException>( "output", () => HKDF.Expand(HashAlgorithmName.SHA1, prk, okm, Array.Empty<byte>())); } [Fact] public void Rfc5869DeriveKeySpanOkmMaxSizePlusOne() { byte[] ikm = new byte[20]; byte[] okm = new byte[20 * 255 + 1]; AssertExtensions.Throws<ArgumentException>( "output", () => HKDF.DeriveKey(HashAlgorithmName.SHA1, ikm, okm, Array.Empty<byte>(), Array.Empty<byte>())); } [Fact] public void Rfc5869DeriveKeySpanOkmPotentiallyOverflowingValue() { byte[] ikm = new byte[20]; byte[] okm = new byte[8421505]; AssertExtensions.Throws<ArgumentException>( "output", () => HKDF.DeriveKey(HashAlgorithmName.SHA1, ikm, okm, Array.Empty<byte>(), Array.Empty<byte>())); } [Fact] public void Rfc5869DeriveKeyOutputLengthZero() { byte[] ikm = new byte[20]; byte[] okm = new byte[0]; AssertExtensions.Throws<ArgumentException>( "output", () => HKDF.DeriveKey(HashAlgorithmName.SHA1, ikm, okm, Array.Empty<byte>(), Array.Empty<byte>())); } [Theory] [InlineData(0, 0)] // Overlap exactly [InlineData(0, 10)] // Output +10 offset over ikm [InlineData(10, 0)] // ikm +10 offset over output [InlineData(10, 20)] // Both offset, output +10 over ikm public void Rfc5869ExtractOverlapsPrkOverKeyMaterial(int ikmOffset, int outputOffset) { ReadOnlySpan<byte> ikm = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b".HexToByteArray(); ReadOnlySpan<byte> salt = "000102030405060708090a0b0c".HexToByteArray(); byte[] expectedPrk = "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5".HexToByteArray(); int length = Math.Max(ikm.Length, expectedPrk.Length) + Math.Max(ikmOffset, outputOffset); Span<byte> buffer = new byte[length]; Span<byte> ikmBuffer = buffer.Slice(ikmOffset, ikm.Length); Span<byte> outputBuffer = buffer.Slice(outputOffset, expectedPrk.Length); ikm.CopyTo(ikmBuffer); HKDF.Extract(HashAlgorithmName.SHA256, ikmBuffer, salt, outputBuffer); Assert.Equal(expectedPrk, outputBuffer.ToArray()); } [Theory] [InlineData(0, 0)] // Overlap exactly [InlineData(0, 10)] // Output +10 offset over salt [InlineData(10, 0)] // salt +10 offset over output [InlineData(10, 20)] // Both offset, output +10 over salt public void Rfc5869ExtractOverlapsPrkOverSalt(int saltOffset, int outputOffset) { ReadOnlySpan<byte> ikm = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b".HexToByteArray(); ReadOnlySpan<byte> salt = "000102030405060708090a0b0c".HexToByteArray(); byte[] expectedPrk = "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5".HexToByteArray(); int length = Math.Max(ikm.Length, expectedPrk.Length) + Math.Max(saltOffset, outputOffset); Span<byte> buffer = new byte[length]; Span<byte> saltBuffer = buffer.Slice(saltOffset, salt.Length); Span<byte> outputBuffer = buffer.Slice(outputOffset, expectedPrk.Length); salt.CopyTo(saltBuffer); HKDF.Extract(HashAlgorithmName.SHA256, ikm, saltBuffer, outputBuffer); Assert.Equal(expectedPrk, outputBuffer.ToArray()); } [Theory] [InlineData(0, 0)] // Overlap exactly [InlineData(0, 10)] // Output +10 offset over info [InlineData(10, 0)] // Info +10 offset over output [InlineData(10, 20)] // Both offset, output +10 over info public void Rfc5869ExpandOverlapsOutputOverInfo(int infoOffset, int outputOffset) { ReadOnlySpan<byte> info = ( "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecf" + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeef" + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff").HexToByteArray(); ReadOnlySpan<byte> prk = "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244".HexToByteArray(); byte[] expectedOkm = ( "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c" + "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71" + "cc30c58179ec3e87c14c01d5c1f3434f1d87").HexToByteArray(); int length = Math.Max(info.Length, expectedOkm.Length) + Math.Max(infoOffset, outputOffset); Span<byte> buffer = new byte[length]; Span<byte> infoBuffer = buffer.Slice(infoOffset, info.Length); Span<byte> outputBuffer = buffer.Slice(outputOffset, expectedOkm.Length); info.CopyTo(infoBuffer); HKDF.Expand(HashAlgorithmName.SHA256, prk, output: outputBuffer, info: infoBuffer); Assert.Equal(expectedOkm, outputBuffer.ToArray()); } [Theory] [InlineData(0, 0)] // Overlap exactly [InlineData(0, 10)] // Output +10 offset over info [InlineData(10, 0)] // Info +10 offset over output [InlineData(10, 20)] // Both offset, output +10 over info public void Rfc5869ExpandOverlapsOutputOverInfoShortOkm(int infoOffset, int outputOffset) { ReadOnlySpan<byte> info = ( "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecf" + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeef" + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff").HexToByteArray(); ReadOnlySpan<byte> prk = "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244".HexToByteArray(); byte[] expectedOkm = "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c".HexToByteArray(); int length = Math.Max(info.Length, expectedOkm.Length) + Math.Max(infoOffset, outputOffset); Span<byte> buffer = new byte[length]; Span<byte> infoBuffer = buffer.Slice(infoOffset, info.Length); Span<byte> outputBuffer = buffer.Slice(outputOffset, expectedOkm.Length); info.CopyTo(infoBuffer); HKDF.Expand(HashAlgorithmName.SHA256, prk, output: outputBuffer, info: infoBuffer); Assert.Equal(expectedOkm, outputBuffer.ToArray()); } [Theory] [InlineData(0, 0)] // Overlap exactly [InlineData(0, 10)] // Output +10 offset over prk [InlineData(10, 0)] // Prk +10 offset over output [InlineData(10, 20)] // Both offset, output +10 over prk public void Rfc5869ExpandOverlapsOutputOverPrk(int prkOffset, int outputOffset) { ReadOnlySpan<byte> info = ( "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecf" + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeef" + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff").HexToByteArray(); ReadOnlySpan<byte> prk = "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244".HexToByteArray(); byte[] expectedOkm = ( "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c" + "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71" + "cc30c58179ec3e87c14c01d5c1f3434f1d87").HexToByteArray(); int length = Math.Max(prk.Length, expectedOkm.Length) + Math.Max(prkOffset, outputOffset); Span<byte> buffer = new byte[length]; Span<byte> prkBuffer = buffer.Slice(prkOffset, prk.Length); Span<byte> outputBuffer = buffer.Slice(outputOffset, expectedOkm.Length); prk.CopyTo(prkBuffer); HKDF.Expand(HashAlgorithmName.SHA256, prkBuffer, output: outputBuffer, info: info); Assert.Equal(expectedOkm, outputBuffer.ToArray()); } } } }
43.232022
127
0.550687
[ "MIT" ]
3DCloud/runtime
src/libraries/System.Security.Cryptography.Algorithms/tests/HKDFTests.cs
31,862
C#
namespace WinterIsComing.Models.Spells { class Blizzard:Spell { private const int DefaultEnergyConst = 40; public Blizzard(int damage) : base(damage, DefaultEnergyConst) { } } }
18.230769
50
0.586498
[ "MIT" ]
didimitrov/Algo
SortingAlgorithmsDemo/OOP/Exam/WinterIsComing/WinterIsComing/Models/Spells/Blizzard.cs
239
C#
// <auto-generated> // 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. // </auto-generated> namespace Microsoft.Azure.Management.Compute { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// VirtualMachinesOperations operations. /// </summary> public partial interface IVirtualMachinesOperations { /// <summary> /// Gets all the virtual machines under the specified subscription for /// the specified location. /// </summary> /// <param name='location'> /// The location for which virtual machines under the subscription are /// queried. /// </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<VirtualMachine>>> ListByLocationWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Captures the VM by copying virtual hard disks of the VM and outputs /// a template that can be used to create similar VMs. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Capture Virtual Machine 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<VirtualMachineCaptureResult>> CaptureWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to create or update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine 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<VirtualMachine>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachine parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Virtual Machine 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<VirtualMachine>> UpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineUpdate parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to delete a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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 vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieves information about the model view or the instance view of /// a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='expand'> /// The expand expression to apply on the operation. Possible values /// include: 'instanceView' /// </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<VirtualMachine>> GetWithHttpMessagesAsync(string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieves information about the run-time state of a virtual /// machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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<VirtualMachineInstanceView>> InstanceViewWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Converts virtual machine disks from blob-based to managed disks. /// Virtual machine must be stop-deallocated before invoking this /// operation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> ConvertToManagedDisksWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Shuts down the virtual machine and releases the compute resources. /// You are not billed for the compute resources that this virtual /// machine uses. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> DeallocateWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Sets the state of the virtual machine to generalized. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> GeneralizeWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all of the virtual machines in the specified resource group. /// Use the nextLink property in the response to get the next page of /// virtual machines. /// </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<VirtualMachine>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all of the virtual machines in the specified subscription. /// Use the nextLink property in the response to get the next page of /// virtual machines. /// </summary> /// <param name='statusOnly'> /// statusOnly=true enables fetching run time status of all Virtual /// Machines in the subscription. /// </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<VirtualMachine>>> ListAllWithHttpMessagesAsync(string statusOnly = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all available virtual machine sizes to which the specified /// virtual machine can be resized. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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<IEnumerable<VirtualMachineSize>>> ListAvailableSizesWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to power off (stop) a virtual machine. The virtual /// machine can be restarted with the same provisioned resources. You /// are still charged for this virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='skipShutdown'> /// The parameter to request non-graceful VM shutdown. True value for /// this flag indicates non-graceful shutdown whereas false indicates /// otherwise. Default value for this flag is false if not specified /// </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> PowerOffWithHttpMessagesAsync(string resourceGroupName, string vmName, bool? skipShutdown = false, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to reapply a virtual machine's state. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> ReapplyWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to restart a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> RestartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to start a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> StartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Shuts down the virtual machine, moves it to a new node, and powers /// it back on. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> RedeployWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Reimages the virtual machine which has an ephemeral OS disk back to /// its initial state. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='tempDisk'> /// Specifies whether to reimage temp disk. Default value: false. Note: /// This temp disk reimage parameter is only supported for VM/VMSS with /// Ephemeral OS disk. /// </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> ReimageWithHttpMessagesAsync(string resourceGroupName, string vmName, bool? tempDisk = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to perform maintenance on a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> PerformMaintenanceWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Run command on the VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Run command 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<RunCommandResult>> RunCommandWithHttpMessagesAsync(string resourceGroupName, string vmName, RunCommandInput parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Captures the VM by copying virtual hard disks of the VM and outputs /// a template that can be used to create similar VMs. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Capture Virtual Machine 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<VirtualMachineCaptureResult>> BeginCaptureWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to create or update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine 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<VirtualMachine>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachine parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to update a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Virtual Machine 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<VirtualMachine>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string vmName, VirtualMachineUpdate parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to delete a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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 vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Converts virtual machine disks from blob-based to managed disks. /// Virtual machine must be stop-deallocated before invoking this /// operation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> BeginConvertToManagedDisksWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Shuts down the virtual machine and releases the compute resources. /// You are not billed for the compute resources that this virtual /// machine uses. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> BeginDeallocateWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to power off (stop) a virtual machine. The virtual /// machine can be restarted with the same provisioned resources. You /// are still charged for this virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='skipShutdown'> /// The parameter to request non-graceful VM shutdown. True value for /// this flag indicates non-graceful shutdown whereas false indicates /// otherwise. Default value for this flag is false if not specified /// </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> BeginPowerOffWithHttpMessagesAsync(string resourceGroupName, string vmName, bool? skipShutdown = false, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to reapply a virtual machine's state. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> BeginReapplyWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to restart a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> BeginRestartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to start a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> BeginStartWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Shuts down the virtual machine, moves it to a new node, and powers /// it back on. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> BeginRedeployWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Reimages the virtual machine which has an ephemeral OS disk back to /// its initial state. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='tempDisk'> /// Specifies whether to reimage temp disk. Default value: false. Note: /// This temp disk reimage parameter is only supported for VM/VMSS with /// Ephemeral OS disk. /// </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> BeginReimageWithHttpMessagesAsync(string resourceGroupName, string vmName, bool? tempDisk = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The operation to perform maintenance on a virtual machine. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </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> BeginPerformMaintenanceWithHttpMessagesAsync(string resourceGroupName, string vmName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Run command on the VM. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmName'> /// The name of the virtual machine. /// </param> /// <param name='parameters'> /// Parameters supplied to the Run command 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<RunCommandResult>> BeginRunCommandWithHttpMessagesAsync(string resourceGroupName, string vmName, RunCommandInput parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the virtual machines under the specified subscription for /// the specified location. /// </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<VirtualMachine>>> ListByLocationNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all of the virtual machines in the specified resource group. /// Use the nextLink property in the response to get the next page of /// virtual machines. /// </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<VirtualMachine>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all of the virtual machines in the specified subscription. /// Use the nextLink property in the response to get the next page of /// virtual machines. /// </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<VirtualMachine>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
49.693252
306
0.618169
[ "MIT" ]
Azkel/azure-sdk-for-net
sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/IVirtualMachinesOperations.cs
48,600
C#
using CodeHelpers.Mathematics; using EchoRenderer.Mathematics; using EchoRenderer.Mathematics.Primitives; using EchoRenderer.Objects.Lights; using EchoRenderer.Rendering.Materials; using EchoRenderer.Rendering.Memory; using EchoRenderer.Rendering.Scattering; namespace EchoRenderer.Rendering.Pixels { public class BruteForceWorker : PixelWorker { public override Sample Render(Float2 uv, Arena arena) { Float3 energy = Float3.one; Float3 radiance = Float3.zero; TraceQuery query = arena.Scene.camera.GetRay(uv, arena.Random); for (int bounce = 0; bounce < arena.profile.BounceLimit; bounce++) { if (!arena.Scene.Trace(ref query)) break; Interaction interaction = arena.Scene.Interact(query, out Material material); material.Scatter(ref interaction, arena); if (interaction.bsdf == null) { query = query.SpawnTrace(); arena.allocator.Release(); continue; } Float3 scatter = interaction.bsdf.Sample(interaction.outgoingWorld, arena.distribution.NextTwo(), out Float3 incidentWorld, out float pdf, out FunctionType sampledType); // radiance += energy * emission; if (pdf <= 0f) energy = Float3.zero; else energy *= scatter * (FastMath.Abs(incidentWorld.Dot(interaction.normal)) / pdf); if (arena.profile.IsZero(energy)) break; query = query.SpawnTrace(incidentWorld); arena.allocator.Release(); } if (!arena.profile.IsZero(energy)) { foreach (AmbientLight ambient in arena.Scene.AmbientSources) radiance += energy * ambient.Evaluate(query.ray.direction); } return radiance; } } }
28.571429
173
0.72375
[ "MIT" ]
MMXXX-VIII/EchoRenderer
EchoRenderer/src/Rendering/Pixels/BruteForceWorker.cs
1,602
C#
#region License /* Copyright © 2014-2021 European Support Limited Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using CommandLine; namespace Amdocs.Ginger.CoreNET.RunLib.CLILib { [Verb("grid", HelpText = "Start Service Grid")] public class GridOptions : OptionsBase { public static string Verb { get { return CLIOptionClassHelper.GetClassVerb<GridOptions>(); } } // TODO: set default [Option('p', "port", Required = false, HelpText = "Port to listen", Default = 15001)] public int Port { get; set; } [Option('t', "tracker", HelpText = "Show nodes tracker window")] public bool Tracker { get; set; } } }
30.710526
102
0.709512
[ "Apache-2.0" ]
Ginger-Automation/Ginger
Ginger/GingerCoreNET/RunLib/CLILib/GridOptions.cs
1,168
C#
namespace NServiceBus.Attachments #if FileShare .FileShare #elif Sql .Sql #endif ; /// <summary> /// Provides access to write attachments. /// </summary> public interface IOutgoingAttachments { /// <summary> /// Returns <code>true</code> if there are pending attachments to be written in the current outgoing pipeline. /// </summary> bool HasPendingAttachments { get; } /// <summary> /// All attachment names for the current outgoing pipeline. /// </summary> IReadOnlyList<string> Names { get; } /// <summary> /// Add an attachment with <paramref name="name"/> to the current outgoing pipeline. /// </summary> void Add<T>(string name, Func<Task<T>> streamFactory, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null) where T : Stream; /// <summary> /// Add an attachment with <paramref name="name"/> to the current outgoing pipeline. /// </summary> void Add(string name, Func<Stream> streamFactory, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with <paramref name="name"/> to the current outgoing pipeline. /// </summary> void Add(string name, Stream stream, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with the default name of `default` to the current outgoing pipeline. /// </summary> void Add<T>(Func<Task<T>> streamFactory, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null) where T : Stream; /// <summary> /// Add an attachment with the default name of `default` to the current outgoing pipeline. /// </summary> void Add(Func<Stream> streamFactory, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with the default name of `default` to the current outgoing pipeline. /// </summary> void Add(Stream stream, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with <paramref name="name"/> to the current outgoing pipeline. /// </summary> /// <remarks> /// This should only be used when the data size is know to be small as it causes the full size of the attachment to be allocated in memory. /// </remarks> void AddBytes(string name, Func<byte[]> byteFactory, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with <paramref name="name"/> to the current outgoing pipeline. /// </summary> /// <remarks> /// This should only be used when the data size is know to be small as it causes the full size of the attachment to be allocated in memory. /// </remarks> void AddBytes(string name, byte[] bytes, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with <paramref name="name"/> to the current outgoing pipeline. /// </summary> /// <remarks> /// This should only be used when the data size is know to be small as it causes the full size of the attachment to be allocated in memory. /// </remarks> void AddString(string name, string value, Encoding? encoding = null, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with the default name of `default` to the current outgoing pipeline. /// </summary> /// <remarks> /// This should only be used when the data size is know to be small as it causes the full size of the attachment to be allocated in memory. /// </remarks> void AddString(string value, Encoding? encoding = null, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with the default name of `default` to the current outgoing pipeline. /// </summary> /// <remarks> /// This should only be used when the data size is know to be small as it causes the full size of the attachment to be allocated in memory. /// </remarks> void AddBytes(Func<Task<byte[]>> bytesFactory, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with <paramref name="name"/> to the current outgoing pipeline. /// </summary> /// <remarks> /// This should only be used when the data size is know to be small as it causes the full size of the attachment to be allocated in memory. /// </remarks> void AddBytes(string name, Func<Task<byte[]>> bytesFactory, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Add an attachment with the default name of `default` to the current outgoing pipeline. /// </summary> /// <remarks> /// This should only be used when the data size is know to be small as it causes the full size of the attachment to be allocated in memory. /// </remarks> void AddBytes(Func<byte[]> byteFactory, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Save an attachment with the default name of `default`. /// </summary> /// <remarks> /// This should only be used when the data size is know to be small as it causes the full size of the attachment to be allocated in memory. /// </remarks> void AddBytes(byte[] bytes, GetTimeToKeep? timeToKeep = null, Action? cleanup = null, IReadOnlyDictionary<string, string>? metadata = null); /// <summary> /// Duplicates the incoming attachments to the current outgoing pipeline. /// </summary> void DuplicateIncoming(); /// <summary> /// Duplicates the incoming attachments to the current outgoing pipeline. /// </summary> void DuplicateIncoming(string fromName, string toName); }
49.728682
185
0.682931
[ "MIT" ]
SimonCropp/NServiceBus.Attachments
src/Shared/Outgoing/IOutgoingAttachments.cs
6,417
C#
namespace System.Security.Cryptography { class GostR3411_2012_256_Digest : Asn1OctetString { public GostR3411_2012_256_Digest () : base() { } /// <summary> /// This constructor initializes an octet string from the given /// byte array by setting the 'value' public member variable in the /// base class to the given value. /// </summary> /// <param name="data"> Byte array containing an octet string /// in binary form. </param> public GostR3411_2012_256_Digest (byte[] data) : base (data) { } /// <summary> /// This constructor initializes an octet string from a portion /// of the given byte array. A new byte array is created starting /// at the given offset and consisting of the given number of bytes. /// </summary> /// <param name="data"> Byte array containing an octet string /// in binary form.</param> /// <param name="offset"> Starting offset in data from which to copy bytes</param> /// <param name="nbytes"> Number of bytes to copy from target array</param> public GostR3411_2012_256_Digest (byte[] data, int offset, int nbytes) : base (data, offset, nbytes) { } /// <summary> /// This constructor parses the given ASN.1 value text (either a /// binary or hex data string) and assigns the values to the internal /// bit string. /// /// Examples of valid value formats are as follows: /// Binary string: "'11010010111001'B" /// Hex string: "'0fa56920014abc'H" /// Char string: "'abcdefg'" /// /// Note: if the text contains no internal single-quote /// Marks ('), it is assumed to be a character string. /// </summary> /// <param name="value"> The ASN.1 value specification text</param> public GostR3411_2012_256_Digest (string value) : base (value) { } public override void Decode (Asn1BerDecodeBuffer buffer, bool explicitTagging, int implicitLength) { base.Decode (buffer, explicitTagging, implicitLength); if (!(Length == 32)) { throw new Exception("Asn1ConsVioException (Length, Length)"); } } public override int Encode (Asn1BerEncodeBuffer buffer, bool explicitTagging) { if (!(Length == 32)) { throw new Exception("Asn1ConsVioException (Length, Length)"); } int _aal = base.Encode (buffer, false); if (explicitTagging) { _aal += buffer.EncodeTagAndLength (Tag, _aal); } return (_aal); } } }
33.835443
88
0.597456
[ "MIT" ]
CryptoPro/corefx
src/Common/src/System/Security/Cryptography/GostR3411_2012_DigestSyntax/GostR3411_2012_256_Digest.cs
2,673
C#
// Automatically generated by xdrgen // DO NOT EDIT or your changes may be overwritten using System; namespace stellar_dotnet_sdk.xdr { // === xdr source ============================================================ // struct LedgerEntry // { // uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed // // union switch (LedgerEntryType type) // { // case ACCOUNT: // AccountEntry account; // case TRUSTLINE: // TrustLineEntry trustLine; // case OFFER: // OfferEntry offer; // case DATA: // DataEntry data; // case CLAIMABLE_BALANCE: // ClaimableBalanceEntry claimableBalance; // } // data; // // // reserved for future use // union switch (int v) // { // case 0: // void; // case 1: // LedgerEntryExtensionV1 v1; // } // ext; // }; // =========================================================================== public class LedgerEntry { public LedgerEntry() { } public Uint32 LastModifiedLedgerSeq { get; set; } public LedgerEntryData Data { get; set; } public LedgerEntryExt Ext { get; set; } public static void Encode(XdrDataOutputStream stream, LedgerEntry encodedLedgerEntry) { Uint32.Encode(stream, encodedLedgerEntry.LastModifiedLedgerSeq); LedgerEntryData.Encode(stream, encodedLedgerEntry.Data); LedgerEntryExt.Encode(stream, encodedLedgerEntry.Ext); } public static LedgerEntry Decode(XdrDataInputStream stream) { LedgerEntry decodedLedgerEntry = new LedgerEntry(); decodedLedgerEntry.LastModifiedLedgerSeq = Uint32.Decode(stream); decodedLedgerEntry.Data = LedgerEntryData.Decode(stream); decodedLedgerEntry.Ext = LedgerEntryExt.Decode(stream); return decodedLedgerEntry; } public class LedgerEntryData { public LedgerEntryData() { } public LedgerEntryType Discriminant { get; set; } = new LedgerEntryType(); public AccountEntry Account { get; set; } public TrustLineEntry TrustLine { get; set; } public OfferEntry Offer { get; set; } public DataEntry Data { get; set; } public ClaimableBalanceEntry ClaimableBalance { get; set; } public static void Encode(XdrDataOutputStream stream, LedgerEntryData encodedLedgerEntryData) { stream.WriteInt((int)encodedLedgerEntryData.Discriminant.InnerValue); switch (encodedLedgerEntryData.Discriminant.InnerValue) { case LedgerEntryType.LedgerEntryTypeEnum.ACCOUNT: AccountEntry.Encode(stream, encodedLedgerEntryData.Account); break; case LedgerEntryType.LedgerEntryTypeEnum.TRUSTLINE: TrustLineEntry.Encode(stream, encodedLedgerEntryData.TrustLine); break; case LedgerEntryType.LedgerEntryTypeEnum.OFFER: OfferEntry.Encode(stream, encodedLedgerEntryData.Offer); break; case LedgerEntryType.LedgerEntryTypeEnum.DATA: DataEntry.Encode(stream, encodedLedgerEntryData.Data); break; case LedgerEntryType.LedgerEntryTypeEnum.CLAIMABLE_BALANCE: ClaimableBalanceEntry.Encode(stream, encodedLedgerEntryData.ClaimableBalance); break; } } public static LedgerEntryData Decode(XdrDataInputStream stream) { LedgerEntryData decodedLedgerEntryData = new LedgerEntryData(); LedgerEntryType discriminant = LedgerEntryType.Decode(stream); decodedLedgerEntryData.Discriminant = discriminant; switch (decodedLedgerEntryData.Discriminant.InnerValue) { case LedgerEntryType.LedgerEntryTypeEnum.ACCOUNT: decodedLedgerEntryData.Account = AccountEntry.Decode(stream); break; case LedgerEntryType.LedgerEntryTypeEnum.TRUSTLINE: decodedLedgerEntryData.TrustLine = TrustLineEntry.Decode(stream); break; case LedgerEntryType.LedgerEntryTypeEnum.OFFER: decodedLedgerEntryData.Offer = OfferEntry.Decode(stream); break; case LedgerEntryType.LedgerEntryTypeEnum.DATA: decodedLedgerEntryData.Data = DataEntry.Decode(stream); break; case LedgerEntryType.LedgerEntryTypeEnum.CLAIMABLE_BALANCE: decodedLedgerEntryData.ClaimableBalance = ClaimableBalanceEntry.Decode(stream); break; } return decodedLedgerEntryData; } } public class LedgerEntryExt { public LedgerEntryExt() { } public int Discriminant { get; set; } = new int(); public LedgerEntryExtensionV1 V1 { get; set; } public static void Encode(XdrDataOutputStream stream, LedgerEntryExt encodedLedgerEntryExt) { stream.WriteInt((int)encodedLedgerEntryExt.Discriminant); switch (encodedLedgerEntryExt.Discriminant) { case 0: break; case 1: LedgerEntryExtensionV1.Encode(stream, encodedLedgerEntryExt.V1); break; } } public static LedgerEntryExt Decode(XdrDataInputStream stream) { LedgerEntryExt decodedLedgerEntryExt = new LedgerEntryExt(); int discriminant = stream.ReadInt(); decodedLedgerEntryExt.Discriminant = discriminant; switch (decodedLedgerEntryExt.Discriminant) { case 0: break; case 1: decodedLedgerEntryExt.V1 = LedgerEntryExtensionV1.Decode(stream); break; } return decodedLedgerEntryExt; } } } }
41.291925
105
0.545277
[ "Apache-2.0" ]
mootz12/dotnet-stellar-sdk
stellar-dotnet-sdk-xdr/generated/LedgerEntry.cs
6,648
C#
namespace Animals { interface IAnimal { string Diet { get; } string Home { get; } string Name { get; } bool Omnivore { get; } string Sound { get; } } }
18.545455
30
0.490196
[ "MIT" ]
OCDAmmo3/Lab06-Zoo
Animals/IAnimal.cs
206
C#
using System; using System.Collections.Generic; using System.Text; namespace Afx.Map { /// <summary> /// map to model /// </summary> public interface IToObject { /// <summary> /// to model /// </summary> /// <param name="o"></param> /// <returns></returns> object To(object fromObj); } }
18.1
36
0.522099
[ "Apache-2.0" ]
jerrylai/Afx.Base
src/Afx.Base/Map/IToObject.cs
364
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("EnhancedQuickStart")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EnhancedQuickStart")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b46126ee-0033-4c0c-b22b-89ab57f8ccc7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.945946
84
0.75
[ "MIT" ]
BlueG81/PowerApps-Samples
cds/webapi/C#/EnhancedQuickStart/Properties/AssemblyInfo.cs
1,407
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ namespace System.Dynamic { /// <summary> /// Represents information about a dynamic get member operation, indicating /// if the get member should invoke properties when performing the get. /// </summary> public interface IInvokeOnGetBinder { /// <summary> /// Gets the value indicating if this GetMember should invoke properties /// when performing the get. The default value when this interface is not present /// is true. /// </summary> /// <remarks> /// This property is used by some languages to get a better COM interop experience. /// When the value is set to false, the dynamic COM object won't invoke the object /// but will instead bind to the name, and return an object that can be invoked or /// indexed later. This is useful for indexed properties and languages that don't /// produce InvokeMember call sites. /// </remarks> bool InvokeOnGet { get; } } }
45.972973
98
0.610229
[ "Apache-2.0" ]
121468615/mono
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs
1,701
C#
using System; using Unity.Burst; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs; using Unity.Mathematics; using Debug = UnityEngine.Debug; using ReadOnlyAttribute = Unity.Collections.ReadOnlyAttribute; namespace Chisel.Core { [BurstCompile(CompileSynchronously = true)] unsafe struct FindModifiedBrushesJob : IJob { public void InitializeHierarchy(ref CompactHierarchy hierarchy) { compactHierarchyPtr = (CompactHierarchy*)UnsafeUtility.AddressOf(ref hierarchy); } // Read [NativeDisableUnsafePtrRestriction] [NoAlias, ReadOnly] public CompactHierarchy* compactHierarchyPtr; [NoAlias, ReadOnly] public NativeList<CompactNodeID> brushes; [NoAlias, ReadOnly] public int brushCount; [NoAlias, ReadOnly] public NativeList<IndexOrder> allTreeBrushIndexOrders; // Read/Write [NoAlias] public NativeList<IndexOrder> rebuildTreeBrushIndexOrders; // Write [NoAlias, WriteOnly] public NativeList<NodeOrderNodeID>.ParallelWriter transformTreeBrushIndicesList; [NoAlias, WriteOnly] public NativeList<NodeOrderNodeID>.ParallelWriter brushBoundsUpdateList; public void Execute() { ref var compactHierarchy = ref UnsafeUtility.AsRef<CompactHierarchy>(compactHierarchyPtr); if (rebuildTreeBrushIndexOrders.Capacity < brushCount) rebuildTreeBrushIndexOrders.Capacity = brushCount; using (var usedBrushes = new NativeBitArray(brushes.Length, Allocator.Temp, NativeArrayOptions.ClearMemory)) { for (int nodeOrder = 0; nodeOrder < brushes.Length; nodeOrder++) { var brushCompactNodeID = brushes[nodeOrder]; if (compactHierarchy.IsAnyStatusFlagSet(brushCompactNodeID)) { var indexOrder = allTreeBrushIndexOrders[nodeOrder]; Debug.Assert(indexOrder.nodeOrder == nodeOrder); if (!usedBrushes.IsSet(nodeOrder)) { usedBrushes.Set(nodeOrder, true); rebuildTreeBrushIndexOrders.AddNoResize(indexOrder); } // Fix up all flags if (compactHierarchy.IsStatusFlagSet(brushCompactNodeID, NodeStatusFlags.ShapeModified) || compactHierarchy.IsStatusFlagSet(brushCompactNodeID, NodeStatusFlags.TransformationModified)) { if (compactHierarchy.IsValidCompactNodeID(brushCompactNodeID)) brushBoundsUpdateList.AddNoResize(new NodeOrderNodeID { nodeOrder = indexOrder.nodeOrder, compactNodeID = brushCompactNodeID }); } if (compactHierarchy.IsStatusFlagSet(brushCompactNodeID, NodeStatusFlags.ShapeModified)) { // Need to update the basePolygons for this node compactHierarchy.ClearStatusFlag(brushCompactNodeID, NodeStatusFlags.ShapeModified); compactHierarchy.SetStatusFlag(brushCompactNodeID, NodeStatusFlags.NeedAllTouchingUpdated); } if (compactHierarchy.IsStatusFlagSet(brushCompactNodeID, NodeStatusFlags.HierarchyModified)) compactHierarchy.SetStatusFlag(brushCompactNodeID, NodeStatusFlags.NeedAllTouchingUpdated); if (compactHierarchy.IsStatusFlagSet(brushCompactNodeID, NodeStatusFlags.TransformationModified)) { if (compactHierarchy.IsValidCompactNodeID(brushCompactNodeID)) { transformTreeBrushIndicesList.AddNoResize(new NodeOrderNodeID { nodeOrder = indexOrder.nodeOrder, compactNodeID = brushCompactNodeID }); } compactHierarchy.ClearStatusFlag(brushCompactNodeID, NodeStatusFlags.TransformationModified); compactHierarchy.SetStatusFlag(brushCompactNodeID, NodeStatusFlags.NeedAllTouchingUpdated); } } } } } } }
50.370787
168
0.608075
[ "MIT" ]
JarrodDoyle/Chisel.Prototype
Packages/com.chisel.core/Chisel/Core/API.private/Unmanaged/Jobs/FindModifiedBrushesJob.cs
4,483
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; namespace TZInfo { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ); // ---------------------------------------------------------------- // Apply our own labels, which incorporate mnemonic accelerators. // ---------------------------------------------------------------- lblTimeZone.Text = Properties.Resources.LABEL_TEXT_LBLTIMEZONE; lblDisplayName.Text = Properties.Resources.LABEL_TEXT_LBLDISPLAYNAME; lblStandardName.Text = Properties.Resources.LABEL_TEXT_LBLSTANDARDNAME; lblDaylightName.Text = Properties.Resources.LABEL_TEXT_LBLDAYLIGHTNAME; lblBaseUTCoffset.Text = Properties.Resources.LABEL_TEXT_LBLBASEUTCOFFSET; lblSupportsDST.Text = Properties.Resources.LABEL_TEXT_LBLSUPPORTSDST; lblOutputFile.Text = Properties.Resources.LABEL_TEXT_LBLOUTPUTFILE; cmdBrowseForFile.Text = Properties.Resources.LABEL_TEXT_CMDBROWSEFORFILE; cmdGo.Text = Properties.Resources.LABEL_TEXT_CMDGO; // ---------------------------------------------------------------- // Populate the combo box from the time zones collection, and set // its default value to the local time zone. // ---------------------------------------------------------------- ReadOnlyCollection<TimeZoneInfo> tzCollection; tzCollection = TimeZoneInfo.GetSystemTimeZones ( ); cboTimeZone.DataSource = tzCollection; cboTimeZone.DisplayMember = @"Id"; cboTimeZone.ValueMember = @"Id"; cboTimeZone.SelectedValue = TimeZoneInfo.Local.Id; } // public Form1 constructor } // public partial class Form1 : Form } // partial namespace TZInfo
38.085106
76
0.663687
[ "BSD-3-Clause" ]
txwizard/TimeZoneLab
TZInfo/Form1.cs
1,792
C#
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Runtime.CompilerServices; using System.ComponentModel; namespace NGenericDimensions.Durations { public class Minutes : StandardDurationUnitOfMeasure, IDefinedUnitOfMeasure { protected override double GetMultiplier(bool stayWithinFamily) { return 600000000; } public override string UnitSymbol { get { return "min"; } } } } namespace NGenericDimensions.Extensions { public static class MinutesExtensionMethods { [EditorBrowsable(EditorBrowsableState.Always)] public static T MinutesValue<T>(this Duration<Durations.Minutes, T> duration) where T : struct, IComparable, IFormattable, IComparable<T>, IEquatable<T> { return duration.DurationValue; } [EditorBrowsable(EditorBrowsableState.Always)] public static Nullable<T> MinutesValue<T>(this Nullable<Duration<Durations.Minutes, T>> duration) where T : struct, IComparable, IFormattable, IComparable<T>, IEquatable<T> { if (duration.HasValue) { return duration.Value.DurationValue; } else { return null; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public static Speed<TUnitOfMeasure, Durations.Minutes, TDataType> minute<TUnitOfMeasure, TDataType>(this DimensionPerExtension<Length<TUnitOfMeasure, TDataType>> length) where TUnitOfMeasure : Lengths.Length1DUnitOfMeasure, IDefinedUnitOfMeasure where TDataType : struct, IComparable, IFormattable, IComparable<TDataType>, IEquatable<TDataType> { return length.PerValue.LengthValue; } } } namespace NGenericDimensions.Extensions.Numbers { public static class MinutesNumberExtensionMethods { [EditorBrowsable(EditorBrowsableState.Advanced)] public static Duration<Durations.Minutes, T> minutes<T>(this T duration) where T : struct, IComparable, IFormattable, IComparable<T>, IEquatable<T> { return duration; } } }
28.134146
180
0.656697
[ "MIT" ]
MafuJosh/NGenericDimensions
old-DOTNETFramework/NGenericDimensions/Durations/Minutes.cs
2,309
C#
// Copyright (C) 2009-2020 Xtensive LLC. // This code is distributed under MIT license terms. // See the License.txt file in the project root for more information. // Created by: Denis Krjuchkov // Created: 2009.07.17 using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Threading; using System.Threading.Tasks; using Oracle.ManagedDataAccess.Client; using Xtensive.Sql.Model; using Xtensive.Sql.Drivers.Oracle.Resources; using Constraint=Xtensive.Sql.Model.Constraint; using Index = Xtensive.Sql.Model.Index; namespace Xtensive.Sql.Drivers.Oracle.v09 { internal partial class Extractor : Model.Extractor { private struct ColumnReaderState<TOwner> { public readonly Catalog Catalog; public TOwner Owner; public int LastColumnIndex; public ColumnReaderState(Catalog catalog) : this() { Catalog = catalog; LastColumnIndex = int.MaxValue; } } private struct IndexColumnReaderState { public readonly Catalog Catalog; public Table Table; public Index Index; public int LastColumnIndex; public IndexColumnReaderState(Catalog catalog) : this() { Catalog = catalog; LastColumnIndex = int.MaxValue; } } private struct ForeignKeyReaderState { public readonly Catalog Catalog; public Table ReferencingTable; public Table ReferencedTable; public ForeignKey ForeignKey; public int LastColumnIndex; public ForeignKeyReaderState(Catalog catalog) : this() { Catalog = catalog; LastColumnIndex = int.MaxValue; } } private struct IndexBasedConstraintReaderState { public readonly Catalog Catalog; public readonly List<TableColumn> Columns; public Table Table; public string ConstraintName; public string ConstraintType; public int LastColumnIndex; public IndexBasedConstraintReaderState(Catalog catalog) : this() { Catalog = catalog; Columns = new List<TableColumn>(); LastColumnIndex = -1; } } protected class ExtractionContext { private readonly Dictionary<string, string> replacementsRegistry; public readonly Catalog Catalog; public string PerformReplacements(string query) { foreach (var registry in replacementsRegistry) { query = query.Replace(registry.Key, registry.Value); } return query; } public ExtractionContext(Catalog catalog, Dictionary<string, string> replacementRegistry) { Catalog = catalog; this.replacementsRegistry = replacementRegistry; } } private const int DefaultPrecision = 38; private const int DefaultScale = 0; private readonly object accessGuard = new object(); private string nonSystemSchemasFilter; public override Catalog ExtractCatalog(string catalogName) => ExtractSchemes(catalogName, Array.Empty<string>()); public override Task<Catalog> ExtractCatalogAsync(string catalogName, CancellationToken token = default) => ExtractSchemesAsync(catalogName, Array.Empty<string>(), token); public override Catalog ExtractSchemes(string catalogName, string[] schemaNames) { var context = CreateContext(catalogName, schemaNames); ExtractSchemas(context); EnsureSchemasExist(context.Catalog, schemaNames); ExtractCatalogContents(context); return context.Catalog; } public override async Task<Catalog> ExtractSchemesAsync(string catalogName, string[] schemaNames, CancellationToken token = default) { var context = CreateContext(catalogName, schemaNames); await ExtractSchemasAsync(context, token).ConfigureAwait(false); EnsureSchemasExist(context.Catalog, schemaNames); await ExtractCatalogContentsAsync(context, token).ConfigureAwait(false); return context.Catalog; } private ExtractionContext CreateContext(string catalogName, string[] schemaNames) { var catalog = new Catalog(catalogName); for(var i = 0; i < schemaNames.Length; i++) { schemaNames[i] = schemaNames[i].ToUpperInvariant(); } var replacements = new Dictionary<string, string>(); RegisterReplacements(replacements, schemaNames); return new ExtractionContext(catalog, replacements); } private void ExtractSchemas(ExtractionContext context) { // oracle does not clearly distinct users and schemas. // so we extract just users. using (var reader = ExecuteReader(context.PerformReplacements(GetExtractSchemasQuery()))) { while (reader.Read()) { context.Catalog.CreateSchema(reader.GetString(0)); } } AssignCatalogDefaultSchema(context.Catalog); } private async Task ExtractSchemasAsync(ExtractionContext context, CancellationToken token) { // oracle does not clearly distinct users and schemas. // so we extract just users. var query = context.PerformReplacements(GetExtractSchemasQuery()); var reader = await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { while (await reader.ReadAsync(token).ConfigureAwait(false)) { context.Catalog.CreateSchema(reader.GetString(0)); } } AssignCatalogDefaultSchema(context.Catalog); } private void AssignCatalogDefaultSchema(Catalog catalog) { // choosing the default schema var defaultSchemaName = Driver.CoreServerInfo.DefaultSchemaName.ToUpperInvariant(); var defaultSchema = catalog.Schemas[defaultSchemaName]; catalog.DefaultSchema = defaultSchema; } private void ExtractCatalogContents(ExtractionContext context) { ExtractTables(context); ExtractTableColumns(context); ExtractViews(context); ExtractViewColumns(context); ExtractIndexes(context); ExtractForeignKeys(context); ExtractCheckConstraints(context); ExtractUniqueAndPrimaryKeyConstraints(context); ExtractSequences(context); } private async Task ExtractCatalogContentsAsync(ExtractionContext context, CancellationToken token) { await ExtractTablesAsync(context, token).ConfigureAwait(false); await ExtractTableColumnsAsync(context, token).ConfigureAwait(false); await ExtractViewsAsync(context, token).ConfigureAwait(false); await ExtractViewColumnsAsync(context, token).ConfigureAwait(false); await ExtractIndexesAsync(context, token).ConfigureAwait(false); await ExtractForeignKeysAsync(context, token).ConfigureAwait(false); await ExtractCheckConstraintsAsync(context, token).ConfigureAwait(false); await ExtractUniqueAndPrimaryKeyConstraintsAsync(context, token).ConfigureAwait(false); await ExtractSequencesAsync(context, token).ConfigureAwait(false); } private void ExtractTables(ExtractionContext context) { using var reader = ExecuteReader(context.PerformReplacements(GetExtractTablesQuery())); while (reader.Read()) { ReadTableData(reader, context.Catalog); } } private async Task ExtractTablesAsync(ExtractionContext context, CancellationToken token) { var query = context.PerformReplacements(GetExtractTablesQuery()); var reader = await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { while (await reader.ReadAsync(token).ConfigureAwait(false)) { ReadTableData(reader, context.Catalog); } } } private void ExtractTableColumns(ExtractionContext context) { using var reader = ExecuteReader(context.PerformReplacements(GetExtractTableColumnsQuery())); var state = new ColumnReaderState<Table>(context.Catalog); while (reader.Read()) { ReadTableColumnData(reader, ref state); } } private async Task ExtractTableColumnsAsync(ExtractionContext context, CancellationToken token) { var query = context.PerformReplacements(GetExtractTableColumnsQuery()); var reader = await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { var state = new ColumnReaderState<Table>(context.Catalog); while (await reader.ReadAsync(token).ConfigureAwait(false)) { ReadTableColumnData(reader, ref state); } } } private void ExtractViews(ExtractionContext context) { using var reader = ExecuteReader(context.PerformReplacements(GetExtractViewsQuery())); while (reader.Read()) { ReadViewData(reader, context.Catalog); } } private async Task ExtractViewsAsync(ExtractionContext context, CancellationToken token) { var query = context.PerformReplacements(GetExtractViewsQuery()); var reader = await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { while (await reader.ReadAsync(token).ConfigureAwait(false)) { ReadViewData(reader, context.Catalog); } } } private void ExtractViewColumns(ExtractionContext context) { using var reader = ExecuteReader(context.PerformReplacements(GetExtractViewColumnsQuery())); var state = new ColumnReaderState<View>(context.Catalog); while (reader.Read()) { ReadViewColumnData(reader, ref state); } } private async Task ExtractViewColumnsAsync(ExtractionContext context, CancellationToken token) { var query = context.PerformReplacements(GetExtractViewColumnsQuery()); var reader = await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { var state = new ColumnReaderState<View>(context.Catalog); while (await reader.ReadAsync(token).ConfigureAwait(false)) { ReadViewColumnData(reader, ref state); } } } private void ExtractIndexes(ExtractionContext context) { var query = context.PerformReplacements(GetExtractIndexesQuery()); using var reader = (OracleDataReader) ExecuteReader(query); var state = new IndexColumnReaderState(context.Catalog); while (reader.Read()) { ReadIndexColumnData(reader, ref state); } } private async Task ExtractIndexesAsync(ExtractionContext context, CancellationToken token) { var query = context.PerformReplacements(GetExtractIndexesQuery()); var reader = (OracleDataReader) await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { var state = new IndexColumnReaderState(context.Catalog); while (await reader.ReadAsync(token).ConfigureAwait(false)) { ReadIndexColumnData(reader, ref state); } } } private void ExtractForeignKeys(ExtractionContext context) { using var reader = ExecuteReader(context.PerformReplacements(GetExtractForeignKeysQuery())); var state = new ForeignKeyReaderState(context.Catalog); while (reader.Read()) { ReadForeignKeyColumnData(reader, ref state); } } private async Task ExtractForeignKeysAsync(ExtractionContext context, CancellationToken token) { var query = context.PerformReplacements(GetExtractForeignKeysQuery()); var reader = await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { var state = new ForeignKeyReaderState(context.Catalog); while (await reader.ReadAsync(token).ConfigureAwait(false)) { ReadForeignKeyColumnData(reader, ref state); } } } private void ExtractUniqueAndPrimaryKeyConstraints(ExtractionContext context) { var query = context.PerformReplacements(GetExtractUniqueAndPrimaryKeyConstraintsQuery()); using var reader = ExecuteReader(query); var state = new IndexBasedConstraintReaderState(context.Catalog); bool readingCompleted; do { readingCompleted = !reader.Read(); ReadIndexBasedConstraintData(reader, ref state, readingCompleted); } while (!readingCompleted); } private async Task ExtractUniqueAndPrimaryKeyConstraintsAsync(ExtractionContext context, CancellationToken token) { var query = context.PerformReplacements(GetExtractUniqueAndPrimaryKeyConstraintsQuery()); var reader = await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { var state = new IndexBasedConstraintReaderState(context.Catalog); bool readingCompleted; do { readingCompleted = !await reader.ReadAsync(token).ConfigureAwait(false); ReadIndexBasedConstraintData(reader, ref state, readingCompleted); } while (!readingCompleted); } } private void ExtractCheckConstraints(ExtractionContext context) { using var reader = ExecuteReader(context.PerformReplacements(GetExtractCheckConstraintsQuery())); while (reader.Read()) { ReadCheckConstraintData(reader, context.Catalog); } } private async Task ExtractCheckConstraintsAsync(ExtractionContext context, CancellationToken token) { var query = context.PerformReplacements(GetExtractCheckConstraintsQuery()); var reader = await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { while (await reader.ReadAsync(token).ConfigureAwait(false)) { ReadCheckConstraintData(reader, context.Catalog); } } } private void ExtractSequences(ExtractionContext context) { using var reader = ExecuteReader(context.PerformReplacements(GetExtractSequencesQuery())); while (reader.Read()) { ReadSequenceData(reader, context.Catalog); } } private async Task ExtractSequencesAsync(ExtractionContext context, CancellationToken token) { var query = context.PerformReplacements(GetExtractSequencesQuery()); var reader = await ExecuteReaderAsync(query, token).ConfigureAwait(false); await using (reader.ConfigureAwait(false)) { while (await reader.ReadAsync(token).ConfigureAwait(false)) { ReadSequenceData(reader, context.Catalog); } } } private void ReadTableData(DbDataReader reader, Catalog catalog) { var schema = catalog.Schemas[reader.GetString(0)]; var tableName = reader.GetString(1); var isTemporary = ReadBool(reader, 2); if (isTemporary) { var table = schema.CreateTemporaryTable(tableName); table.PreserveRows = reader.GetString(3) == "SYS$SESSION"; table.IsGlobal = true; } else { _ = schema.CreateTable(tableName); } } private void ReadTableColumnData(DbDataReader reader, ref ColumnReaderState<Table> state) { var columnIndex = ReadInt(reader, 9); if (columnIndex <= state.LastColumnIndex) { var schema = state.Catalog.Schemas[reader.GetString(0)]; state.Owner = schema.Tables[reader.GetString(1)]; } var column = state.Owner.CreateColumn(reader.GetString(2)); column.DataType = CreateValueType(reader, 3, 4, 5, 6); column.IsNullable = ReadBool(reader, 7); var defaultValue = ReadStringOrNull(reader, 8); if (!string.IsNullOrEmpty(defaultValue)) { column.DefaultValue = SqlDml.Native(defaultValue); } state.LastColumnIndex = columnIndex; } private static void ReadViewData(DbDataReader reader, Catalog catalog) { var schema = catalog.Schemas[reader.GetString(0)]; var view = reader.GetString(1); var definition = ReadStringOrNull(reader, 2); if (string.IsNullOrEmpty(definition)) { _ = schema.CreateView(view); } else { _ = schema.CreateView(view, SqlDml.Native(definition)); } } private static void ReadViewColumnData(DbDataReader reader, ref ColumnReaderState<View> state) { var columnId = ReadInt(reader, 3); if (columnId <= state.LastColumnIndex) { var schema = state.Catalog.Schemas[reader.GetString(0)]; state.Owner = schema.Views[reader.GetString(1)]; } _ = state.Owner.CreateColumn(reader.GetString(2)); state.LastColumnIndex = columnId; } private static void ReadIndexColumnData(OracleDataReader reader, ref IndexColumnReaderState state) { // it's possible to have table and index in different schemas in oracle. // we silently ignore this, indexes are always belong to the same schema as its table. var columnIndex = ReadInt(reader, 6); if (columnIndex <= state.LastColumnIndex) { var schema = state.Catalog.Schemas[reader.GetString(0)]; state.Table = schema.Tables[reader.GetString(1)]; state.Index = state.Table.CreateIndex(reader.GetString(2)); state.Index.IsUnique = ReadBool(reader, 3); state.Index.IsBitmap = reader.GetString(4).EndsWith("BITMAP"); if (!reader.IsDBNull(5)) { var pctFree = ReadInt(reader, 5); state.Index.FillFactor = (byte) (100 - pctFree); } } var columnName = reader.IsDBNull(9) ? reader.GetString(7) : reader.GetOracleString(9).Value; columnName = columnName.Trim('"'); var column = state.Table.TableColumns[columnName]; var isAscending = reader.GetString(8) == "ASC"; _ = state.Index.CreateIndexColumn(column, isAscending); state.LastColumnIndex = columnIndex; } private static void ReadForeignKeyColumnData(DbDataReader reader, ref ForeignKeyReaderState state) { var lastColumnIndex = ReadInt(reader, 7); if (lastColumnIndex <= state.LastColumnIndex) { var referencingSchema = state.Catalog.Schemas[reader.GetString(0)]; state.ReferencingTable = referencingSchema.Tables[reader.GetString(1)]; state.ForeignKey = state.ReferencingTable.CreateForeignKey(reader.GetString(2)); ReadConstraintProperties(state.ForeignKey, reader, 3, 4); ReadCascadeAction(state.ForeignKey, reader, 5); var referencedSchema = state.Catalog.Schemas[reader.GetString(8)]; state.ReferencedTable = referencedSchema.Tables[reader.GetString(9)]; state.ForeignKey.ReferencedTable = state.ReferencedTable; } var referencingColumn = state.ReferencingTable.TableColumns[reader.GetString(6)]; var referencedColumn = state.ReferencedTable.TableColumns[reader.GetString(10)]; state.ForeignKey.Columns.Add(referencingColumn); state.ForeignKey.ReferencedColumns.Add(referencedColumn); state.LastColumnIndex = lastColumnIndex; } private static void ReadIndexBasedConstraintData(DbDataReader reader, ref IndexBasedConstraintReaderState state, bool readingCompleted) { if (readingCompleted) { if (state.Columns.Count > 0) { CreateIndexBasedConstraint(ref state); } } else { var columnIndex = ReadInt(reader, 5); if (columnIndex <= state.LastColumnIndex) { CreateIndexBasedConstraint(ref state); state.Columns.Clear(); } if (state.Columns.Count == 0) { var schema = state.Catalog.Schemas[reader.GetString(0)]; state.Table = schema.Tables[reader.GetString(1)]; state.ConstraintName = reader.GetString(2); state.ConstraintType = reader.GetString(3); } state.Columns.Add(state.Table.TableColumns[reader.GetString(4)]); state.LastColumnIndex = columnIndex; } } private static void ReadCheckConstraintData(DbDataReader reader, Catalog catalog) { var schema = catalog.Schemas[reader.GetString(0)]; var table = schema.Tables[reader.GetString(1)]; var name = reader.GetString(2); // It looks like ODP.NET sometimes fail to read a LONG column via GetString // It returns empty string instead of the actual value. var condition = string.IsNullOrEmpty(reader.GetString(3)) ? null : SqlDml.Native(reader.GetString(3)); var constraint = table.CreateCheckConstraint(name, condition); ReadConstraintProperties(constraint, reader, 4, 5); } private static void ReadSequenceData(DbDataReader reader, Catalog catalog) { var schema = catalog.Schemas[reader.GetString(0)]; var sequence = schema.CreateSequence(reader.GetString(1)); var descriptor = sequence.SequenceDescriptor; descriptor.MinValue = ReadLong(reader, 2); descriptor.MaxValue = ReadLong(reader, 3); descriptor.Increment = ReadLong(reader, 4); descriptor.IsCyclic = ReadBool(reader, 5); } private SqlValueType CreateValueType(IDataRecord row, int typeNameIndex, int precisionIndex, int scaleIndex, int charLengthIndex) { var typeName = row.GetString(typeNameIndex); if (typeName == "NUMBER") { var precision = row.IsDBNull(precisionIndex) ? DefaultPrecision : ReadInt(row, precisionIndex); var scale = row.IsDBNull(scaleIndex) ? DefaultScale : ReadInt(row, scaleIndex); return new SqlValueType(SqlType.Decimal, precision, scale); } if (typeName.StartsWith("INTERVAL DAY")) { // ignoring "day precision" and "second precision" // although they can be read as "scale" and "precision" return new SqlValueType(SqlType.Interval); } if (typeName.StartsWith("TIMESTAMP")) { // "timestamp precision" is saved as "scale", ignoring too if (typeName.Contains("WITH TIME ZONE")) { return new SqlValueType(SqlType.DateTimeOffset); } return new SqlValueType(SqlType.DateTime); } if (typeName == "NVARCHAR2" || typeName == "NCHAR") { var length = ReadInt(row, charLengthIndex); var sqlType = typeName.Length == 5 ? SqlType.Char : SqlType.VarChar; return new SqlValueType(sqlType, length); } var typeInfo = Driver.ServerInfo.DataTypes[typeName]; return typeInfo != null ? new SqlValueType(typeInfo.Type) : new SqlValueType(typeName); } private static void CreateIndexBasedConstraint(ref IndexBasedConstraintReaderState state) { switch (state.ConstraintType) { case "P": _ = state.Table.CreatePrimaryKey(state.ConstraintName, state.Columns.ToArray()); return; case "U": _ = state.Table.CreateUniqueConstraint(state.ConstraintName, state.Columns.ToArray()); return; default: throw new ArgumentOutOfRangeException(nameof(IndexBasedConstraintReaderState.ConstraintType)); } } private static bool ReadBool(IDataRecord row, int index) { var value = row.GetString(index); switch (value) { case "Y": case "YES": case "ENABLED": case "UNIQUE": return true; case "N": case "NO": case "DISABLED": case "NONUNIQUE": return false; default: throw new ArgumentOutOfRangeException(string.Format(Strings.ExInvalidBooleanStringX, value)); } } private static long ReadLong(IDataRecord row, int index) { var value = row.GetDecimal(index); if (value > long.MaxValue) { return long.MaxValue; } if (value < long.MinValue) { return long.MinValue; } return (long) value; } private static int ReadInt(IDataRecord row, int index) { var value = row.GetDecimal(index); if (value > int.MaxValue) { return int.MaxValue; } if (value < int.MinValue) { return int.MinValue; } return (int) value; } private static string ReadStringOrNull(IDataRecord row, int index) => row.IsDBNull(index) ? null : row.GetString(index); private static void ReadConstraintProperties(Constraint constraint, IDataRecord row, int isDeferrableIndex, int isInitiallyDeferredIndex) { constraint.IsDeferrable = row.GetString(isDeferrableIndex) == "DEFERRABLE"; constraint.IsInitiallyDeferred = row.GetString(isInitiallyDeferredIndex) == "DEFERRED"; } private static void ReadCascadeAction(ForeignKey foreignKey, IDataRecord row, int deleteRuleIndex) { var deleteRule = row.GetString(deleteRuleIndex); switch (deleteRule) { case "CASCADE": foreignKey.OnDelete = ReferentialAction.Cascade; return; case "SET NULL": foreignKey.OnDelete = ReferentialAction.SetNull; return; case "NO ACTION": foreignKey.OnDelete = ReferentialAction.NoAction; return; } } protected virtual void RegisterReplacements(Dictionary<string, string> replacements, IReadOnlyCollection<string> targetSchemes) { var schemaFilter = targetSchemes != null && targetSchemes.Count != 0 ? MakeSchemaFilter(targetSchemes) //? "= " + SqlHelper.QuoteString(targetSchema) : GetNonSystemSchemasFilter(); replacements[SchemaFilterPlaceholder] = schemaFilter; replacements[IndexesFilterPlaceholder] = "1 > 0"; replacements[TableFilterPlaceholder] = "IS NOT NULL"; } private static string MakeSchemaFilter(IReadOnlyCollection<string> targetSchemes) { var schemaStrings = targetSchemes.Select(SqlHelper.QuoteString); var schemaList = string.Join(",", schemaStrings); return $"IN ({schemaList})"; } protected override DbDataReader ExecuteReader(string commandText) { using var command = (OracleCommand) Connection.CreateCommand(commandText); // This option is required to access LONG columns command.InitialLONGFetchSize = -1; return command.ExecuteReader(); } protected override async Task<DbDataReader> ExecuteReaderAsync(string commandText, CancellationToken token = default) { var command = (OracleCommand) Connection.CreateCommand(commandText); await using (command.ConfigureAwait(false)) { // This option is required to access LONG columns command.InitialLONGFetchSize = -1; return await command.ExecuteReaderAsync(token).ConfigureAwait(false); } } protected override DbDataReader ExecuteReader(ISqlCompileUnit statement) { var commandText = Connection.Driver.Compile(statement).GetCommandText(); return ExecuteReader(commandText); } protected override Task<DbDataReader> ExecuteReaderAsync(ISqlCompileUnit statement, CancellationToken token = default) { var commandText = Connection.Driver.Compile(statement).GetCommandText(); return ExecuteReaderAsync(commandText, token); } private string GetNonSystemSchemasFilter() { if (nonSystemSchemasFilter == null) { lock (accessGuard) { if (nonSystemSchemasFilter == null) { var schemaStrings = GetSystemSchemas().Select(SqlHelper.QuoteString).ToArray(); var schemaList = string.Join(",", schemaStrings); nonSystemSchemasFilter = $"NOT IN ({schemaList})"; } } } return nonSystemSchemasFilter; } private static IEnumerable<string> GetSystemSchemas() => new[] { "ANONYMOUS", "APEX_PUBLIC_USER", "APEX_040000", "CTXSYS", "DBSNMP", "DIP", "EXFSYS", "FLOWS_%", "FLOWS_FILES", "LBACSYS", "MDDATA", "MDSYS", "MGMT_VIEW", "OLAPSYS", "ORACLE_OCM", "ORDDATA", "ORDPLUGINS", "ORDSYS", "OUTLN", "OWBSYS", "SI_INFORMTN_SCHEMA", "SPATIAL_CSW_ADMIN_USR", "SPATIAL_WFS_ADMIN_USR", "SYS", "SYSMAN", "SYSTEM", "WKPROXY", "WKSYS", "WK_TEST", "WMSYS", "XDB", "XS$NULL", }; private static void EnsureSchemasExist(Catalog catalog, string[] schemaNames) { foreach (var schemaName in schemaNames) { var realSchemaName = schemaName.ToUpperInvariant(); var schema = catalog.Schemas[realSchemaName]; if (schema==null) { catalog.CreateSchema(realSchemaName); } } } // Constructors public Extractor(SqlDriver driver) : base(driver) { } } }
35.967337
131
0.678764
[ "MIT" ]
NekrasovSt/dataobjects-net
Orm/Xtensive.Orm.Oracle/Sql.Drivers.Oracle/v09/Extractor.cs
28,630
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcApplication1 { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Administration", url: "Admin/{action}/{Id}", defaults: new { controller = "Administration", action = "PageList", Id = UrlParameter.Optional } ); routes.MapRoute( name: "Account", url: "Account/{action}/{Id}", defaults: new { controller = "Account", action = "UserList", Id = UrlParameter.Optional } ); routes.MapRoute( name: "level_1", url: "{PageName}", defaults: new { controller = "Home", action = "Index", PageName = UrlParameter.Optional } ); routes.MapRoute( name: "level_2", url: "{ParentName}/{PageName}", defaults: new { controller = "Home", action = "Index", ParentName = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{param}", defaults: new { controller = "Home", action = "Index", param = UrlParameter.Optional } ); } } }
30.46
111
0.5174
[ "Apache-2.0" ]
Andromeda6688/Anonymized_MvcApp
MvcApplication1/App_Start/RouteConfig.cs
1,525
C#
using Henooh.DeviceEmulator.Native; using SharpDX.XInput; namespace xinputTest { public class Binds { public string name; public GamepadButtonFlags button; public VirtualKeyCode key; public bool isdown = false; public Binds(string name, GamepadButtonFlags button, VirtualKeyCode key) { this.name = name; this.button = button; this.key = key; } } }
21.666667
80
0.602198
[ "MIT" ]
ZakKaioken/Windows-10-Explorer-Controller-Support
xinputTest/Binds.cs
457
C#
using System.Web.Http; namespace Northwind.Mvc { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); // Syncfusion Report Viewer config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }); } } }
27.333333
65
0.552846
[ "MIT" ]
EasyLOB/EasyLOB-Northwind-1
Northwind.Mvc.AJAX/App_Start/WebApiConfig.cs
494
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Network.Models { public partial class GetVpnSitesConfigurationRequest : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (VpnSites != null) { writer.WritePropertyName("vpnSites"); writer.WriteStartArray(); foreach (var item in VpnSites) { writer.WriteStringValue(item); } writer.WriteEndArray(); } writer.WritePropertyName("outputBlobSasUrl"); writer.WriteStringValue(OutputBlobSasUrl); writer.WriteEndObject(); } } }
27.352941
80
0.591398
[ "MIT" ]
AzureDataBox/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/Models/GetVpnSitesConfigurationRequest.Serialization.cs
930
C#
using System; using System.Threading.Tasks; using GraphQL; using GraphQL.DI; using Shouldly; using Xunit; namespace DIObjectGraphTypeTests { public class Services : DIObjectGraphTypeTestBase { [Fact] public void Service() { Configure<CService, object>(); _serviceProviderMock.Setup(x => x.GetService(typeof(string))).Returns("hello").Verifiable(); VerifyField("Field1", true, false, "hello"); Verify(false); } public class CService : DIObjectGraphBase { public static string Field1([FromServices] string arg) => arg; } [Fact] public void ServiceMissingThrows() { Configure<CService, object>(); _serviceProviderMock.Setup(x => x.GetService(typeof(string))).Returns((string)null!).Verifiable(); Should.Throw<InvalidOperationException>(() => VerifyField("Field1", true, false, "hello")); Verify(false); } [Fact] public async Task ScopedService() { Configure<CScopedService, object>(); _scopedServiceProviderMock.Setup(x => x.GetService(typeof(string))).Returns("hello").Verifiable(); await VerifyFieldAsync("Field1", true, true, "hello"); Verify(true); } public class CScopedService : DIObjectGraphBase { [Scoped] public static Task<string> Field1([FromServices] string arg) => Task.FromResult(arg); } } }
30.27451
110
0.591969
[ "MIT" ]
Shane32/GraphQL.MVC
src/Tests/DIObjectGraphTypeTests/Services.cs
1,544
C#
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. namespace Moq { /// <summary> /// Utility repository class to use to construct multiple /// mocks when consistent verification is /// desired for all of them. /// </summary> /// <remarks> /// If multiple mocks will be created during a test, passing /// the desired <see cref="MockBehavior"/> (if different than the /// <see cref="MockBehavior.Default"/> or the one /// passed to the repository constructor) and later verifying each /// mock can become repetitive and tedious. /// <para> /// This repository class helps in that scenario by providing a /// simplified creation of multiple mocks with a default /// <see cref="MockBehavior"/> (unless overridden by calling /// <see cref="MockFactory.Create{T}(MockBehavior)"/>) and posterior verification. /// </para> /// </remarks> /// <example group="repository"> /// The following is a straightforward example on how to /// create and automatically verify strict mocks using a <see cref="MockRepository"/>: /// <code> /// var repository = new MockRepository(MockBehavior.Strict); /// /// var foo = repository.Create&lt;IFoo&gt;(); /// var bar = repository.Create&lt;IBar&gt;(); /// /// // no need to call Verifiable() on the setup /// // as we'll be validating all of them anyway. /// foo.Setup(f => f.Do()); /// bar.Setup(b => b.Redo()); /// /// // exercise the mocks here /// /// repository.VerifyAll(); /// // At this point all setups are already checked /// // and an optional MockException might be thrown. /// // Note also that because the mocks are strict, any invocation /// // that doesn't have a matching setup will also throw a MockException. /// </code> /// The following examples shows how to setup the repository /// to create loose mocks and later verify only verifiable setups: /// <code> /// var repository = new MockRepository(MockBehavior.Loose); /// /// var foo = repository.Create&lt;IFoo&gt;(); /// var bar = repository.Create&lt;IBar&gt;(); /// /// // this setup will be verified when we verify the repository /// foo.Setup(f => f.Do()).Verifiable(); /// /// // this setup will NOT be verified /// foo.Setup(f => f.Calculate()); /// /// // this setup will be verified when we verify the repository /// bar.Setup(b => b.Redo()).Verifiable(); /// /// // exercise the mocks here /// // note that because the mocks are Loose, members /// // called in the interfaces for which no matching /// // setups exist will NOT throw exceptions, /// // and will rather return default values. /// /// repository.Verify(); /// // At this point verifiable setups are already checked /// // and an optional MockException might be thrown. /// </code> /// The following examples shows how to setup the repository with a /// default strict behavior, overriding that default for a /// specific mock: /// <code> /// var repository = new MockRepository(MockBehavior.Strict); /// /// // this particular one we want loose /// var foo = repository.Create&lt;IFoo&gt;(MockBehavior.Loose); /// var bar = repository.Create&lt;IBar&gt;(); /// /// // specify setups /// /// // exercise the mocks here /// /// repository.Verify(); /// </code> /// </example> /// <seealso cref="MockBehavior"/> #pragma warning disable 618 public partial class MockRepository : MockFactory { /// <summary> /// Initializes the repository with the given <paramref name="defaultBehavior"/> /// for newly created mocks from the repository. /// </summary> /// <param name="defaultBehavior">The behavior to use for mocks created /// using the <see cref="MockFactory.Create{T}()"/> repository method if not overridden /// by using the <see cref="MockFactory.Create{T}(MockBehavior)"/> overload.</param> public MockRepository(MockBehavior defaultBehavior) : base(defaultBehavior) { } #pragma warning restore 618 } }
37.564815
97
0.6702
[ "BSD-3-Clause" ]
304NotModified/moq4
src/Moq/MockRepository.cs
4,057
C#
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Catalog.API.Repositories; using Microsoft.Extensions.Logging; using Catalog.API.Entities; using System.Net; namespace Catalog.API.Controllers { // presentation Layer // Ist i convert the controller to Api controller [ApiController] [Route("api/v1/[controller]")]// it is going to get the controller , gemove the controller and get to name is controler. //inherit the controller base in order to use these API related object instead. public class CatalogController:ControllerBase { private readonly IProductRepository _repository; private readonly ILogger<CatalogController> _logger; public CatalogController(IProductRepository repository, ILogger<CatalogController> logger) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } // API method // Here I used HTTP method first [HttpGet] [ProducesResponseType(typeof(IEnumerable<Product>),(int)HttpStatusCode.OK)] public async Task<ActionResult<IEnumerable<Product>>>GetProducts() { var products =await _repository.GetProducts(); return Ok(products); } [HttpGet("{id:length(24)}", Name = "GetProduct")] [ProducesResponseType((int)HttpStatusCode.NotFound)] [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)] public async Task<ActionResult<Product>> GetProductsById(string id) { var product = await _repository.GetProduct(id); if(product==null) { _logger.LogError($"Product with id : {id}, not found!."); return NotFound(); } return Ok(product); } [Route("[action]/{category}",Name = "GetProductsByCategory")] [HttpGet] [ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)] public async Task<ActionResult<IEnumerable<Product>>>GetProductsByCategory(string category) { var products = await _repository.GetProductsByCategory(category); return Ok(products); } [HttpPost] [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)] public async Task<ActionResult<Product>> CreateProduct([FromBody] Product product) { await _repository.CreateProduct(product); return CreatedAtRoute("GetProduct", new { id = product.Id }, product); // Here I used rock n role theme for getting product // this is basically forwarding the calling the next APi method. //Get product with given product idea } [HttpPut] [ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)] public async Task<ActionResult<Product>> UpdateProduct([FromBody] Product product) { return Ok(await _repository.UpdateProduct(product)); } } }
37.952381
125
0.651819
[ "MIT" ]
jencyraj/AspnetMicroservices
src/Services/Catalog/Catalog.API/Controllers/CatalogController.cs
3,190
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("07.Aritmetics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07.Aritmetics")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("21a3beee-22e8-4bdd-94b6-0992dd815ef4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.783784
85
0.725436
[ "MIT" ]
bstaykov/Telerik-CSharp-Part-2
Using-Classes-and-Objects/07.Aritmetics/Properties/AssemblyInfo.cs
1,438
C#
using System.Text.Json.Serialization; namespace Flub.TelegramBot.Types { /// <summary> /// Represents an issue with the front side of a document. /// The error is considered resolved when the file with the front side of the document changes. /// </summary> public class PassportElementErrorFrontSide : PassportElementError { /// <summary> /// The section of the user's Telegram Passport which has the issue, /// one of <see cref="EncryptedPassportElementType.Passport"/>, <see cref="EncryptedPassportElementType.DriverLicense"/>, /// <see cref="EncryptedPassportElementType.IdentityCard"/>, <see cref="EncryptedPassportElementType.InternalPassport"/>. /// </summary> [JsonPropertyName("type")] public EncryptedPassportElementType? Type { get; set; } /// <summary> /// Base64-encoded hash of the file with the front side of the document. /// </summary> [JsonPropertyName("file_hash")] public string FileHash { get; set; } /// <summary> /// Initializes a new instance of the <see cref="PassportElementErrorFrontSide"/> class. /// </summary> public PassportElementErrorFrontSide() : base(PassportElementErrorType.FrontSide) { } public override string ToString() => $"{nameof(PassportElementErrorFrontSide)}[{Type}]"; } }
43.3125
129
0.663781
[ "MIT" ]
flubl/Flub.TelegramBot
Src/Flub.TelegramBot/Types/Passport/Errors/PassportElementErrorFrontSide.cs
1,388
C#
using Fenit.HelpTool.Core.Service; using Fenit.Toolbox.Core.Answers; namespace Fenit.HelpTool.Core.UserService { public class UserService : IUserService { public Response<bool> Login(string username, string password) { var res = new Response<bool>(); if (username == "admin" && password == "admin321") res.AddValue(true); return res; } public bool IsRootMode { get; set; } public bool IsLogged => true; } }
25.7
69
0.589494
[ "MIT" ]
glazier44/Fenit.HelpTool
Fenit.HelpTool.Core.UserService/UserService.cs
516
C#
namespace T02.GraphicEditor.Contracts { public interface IShape { } }
11.857143
38
0.662651
[ "MIT" ]
akdimitrov/CSharp-OOP
10.SOLID-Lab/T02.GraphicEditor/Contracts/IShape.cs
85
C#
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System.Runtime.CompilerServices; using System.Threading; namespace System { /// <summary> /// Represents a slice of managed memory. /// This object is not part of a MemoryLane and its lifetime does not affect other MemoryFragment instances. /// </summary> public class HeapSlot : MemoryFragment { /// <summary> /// Creates a MemoryFragment from a managed array. /// Be aware that the buffer could potentially be mutated concurrently or /// unexpectedly nulled from outside. Consider using the length constructor. /// </summary> /// <param name="slot">The buffer is shared!</param> /// <exception cref="ArgumentNullException"></exception> public HeapSlot(byte[] slot) { if (slot == null) throw new ArgumentNullException("slot"); useAccessChecks = false; this.slot = slot; this.length = slot.Length; } /// <summary> /// Creates a MemoryFragment from a managed array. /// Be aware that the buffer could potentially be mutated concurrently or /// unexpectedly nulled from outside. Consider using the length constructor. /// </summary> /// <param name="slot">The buffer</param> /// <param name="from">The start index</param> /// <param name="length">The number of bytes</param> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <exception cref="ArgumentNullException"></exception> public HeapSlot(byte[] slot, int from, int length) { if (slot == null) throw new ArgumentNullException("slot"); if (length < 1 || length > slot.Length) throw new ArgumentOutOfRangeException("length"); if (from < 0 || from > slot.Length) throw new ArgumentOutOfRangeException("from"); if (from + length > slot.Length) throw new ArgumentOutOfRangeException("from + length"); useAccessChecks = false; this.slot = slot.AsMemory(from, length); this.length = slot.Length; } /// <summary> /// Allocates a buffer on the managed heap. /// </summary> /// <param name="length">The buffer size in bytes</param> /// <exception cref="ArgumentOutOfRangeException"></exception> public HeapSlot(int length) { if (length < 1) throw new ArgumentOutOfRangeException("length", "Invalid length"); useAccessChecks = false; slot = new byte[length]; this.length = slot.Length; } /// <summary> /// Take a Span of the whole range. /// </summary> /// <param name="format">Zero the bytes</param> /// <returns>The Span</returns> public Span<byte> Span(bool format = false) { if (format) for (var i = 0; i < Length; i++) slot.Span[i] = 0; return slot.Span; } /// <summary> /// Writes the bytes in data (0-length) to the slot starting at <c>offset</c> position. /// </summary> /// <param name="data">The source array.</param> /// <param name="offset">The writing position in the heap slot.</param> /// <param name="length">How many bytes from the source to take.</param> /// <returns>The offset + length</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int Write(byte[] data, int offset, int length) { if (data == null) throw new ArgumentNullException("data"); if (length < 0 || length > data.Length) throw new ArgumentOutOfRangeException("length"); if (offset < 0 || offset + length > Length) throw new ArgumentOutOfRangeException("offset"); var src = new Span<byte>(data).Slice(0, length); var dst = Span().Slice(offset); src.CopyTo(dst); return offset + length; } /// <summary> /// Reads bytes from the slot starting at offset until <c>destination</c> is full or there is no more data. /// The writing in <c>destination</c> starts at destOffset. /// </summary> /// <param name="destination">The read data.</param> /// <param name="offset">The position in source to begin reading from.</param> /// <param name="destOffset">Index in destination where the copying will begin at. By default is 0.</param> /// <returns>The total bytes read, i.e. the new offset.</returns> /// <exception cref="System.ArgumentNullException">If destination is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">For offset and destOffset.</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int Read(byte[] destination, int offset, int destOffset = 0) { if (destination == null) throw new ArgumentNullException("destination"); if (offset < 0 || offset >= Length) throw new ArgumentOutOfRangeException("offset"); if (destOffset < 0 || destOffset >= destination.Length) throw new ArgumentOutOfRangeException("destOffset"); var destLength = destination.Length - destOffset; var readLength = (destLength + offset) > Length ? Length - offset : destLength; var src = Span().Slice(offset, readLength); var dst = new Span<byte>(destination).Slice(destOffset); src.CopyTo(dst); return offset + readLength; } /// <summary> /// Makes a span over the whole slot. /// </summary> /// <returns>The span structure.</returns> public override Span<byte> Span() => Span(false); public override StorageType Type => StorageType.ManagedHeapSlot; public override void Dispose() { if (Interlocked.CompareExchange(ref isDisposed, 1, 0) == 0) slot = null; } /// <summary> /// Gets the fragment Memory. /// </summary> /// <param name="ms">The slot.</param> public static implicit operator Memory<byte>(HeapSlot ms) => ms != null ? ms.slot : default; /// <summary> /// Casts the fragment as ReadOnlyMemory of bytes. /// </summary> /// <param name="ms">The slot.</param> public static implicit operator ReadOnlyMemory<byte>(HeapSlot ms) => ms != null ? ms.slot : default; /// <summary> /// The fragment length. /// </summary> public override int Length => length; readonly int length; Memory<byte> slot; } }
36.756098
111
0.68215
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
arsuq/MemoryLanes
MemoryLanes/src/Fragments/HeapSlot.cs
6,028
C#
using System; using UnityEngine; namespace Pathfinding { internal static class AstarSplines { public static global::UnityEngine.Vector3 CatmullRom(global::UnityEngine.Vector3 previous, global::UnityEngine.Vector3 start, global::UnityEngine.Vector3 end, global::UnityEngine.Vector3 next, float elapsedTime) { float num = elapsedTime * elapsedTime; float num2 = num * elapsedTime; return previous * (-0.5f * num2 + num - 0.5f * elapsedTime) + start * (1.5f * num2 + -2.5f * num + 1f) + end * (-1.5f * num2 + 2f * num + 0.5f * elapsedTime) + next * (0.5f * num2 - 0.5f * num); } [global::System.Obsolete("Use CatmullRom")] public static global::UnityEngine.Vector3 CatmullRomOLD(global::UnityEngine.Vector3 previous, global::UnityEngine.Vector3 start, global::UnityEngine.Vector3 end, global::UnityEngine.Vector3 next, float elapsedTime) { return global::Pathfinding.AstarSplines.CatmullRom(previous, start, end, next, elapsedTime); } public static global::UnityEngine.Vector3 CubicBezier(global::UnityEngine.Vector3 p0, global::UnityEngine.Vector3 p1, global::UnityEngine.Vector3 p2, global::UnityEngine.Vector3 p3, float t) { t = global::UnityEngine.Mathf.Clamp01(t); float num = 1f - t; return num * num * num * p0 + 3f * num * num * t * p1 + 3f * num * t * t * p2 + t * t * t * p3; } public static global::UnityEngine.Vector3 CubicBezierDerivative(global::UnityEngine.Vector3 p0, global::UnityEngine.Vector3 p1, global::UnityEngine.Vector3 p2, global::UnityEngine.Vector3 p3, float t) { t = global::UnityEngine.Mathf.Clamp01(t); float num = 1f - t; return 3f * num * num * (p1 - p0) + 6f * num * t * (p2 - p1) + 3f * t * t * (p3 - p2); } public static global::UnityEngine.Vector3 CubicBezierSecondDerivative(global::UnityEngine.Vector3 p0, global::UnityEngine.Vector3 p1, global::UnityEngine.Vector3 p2, global::UnityEngine.Vector3 p3, float t) { t = global::UnityEngine.Mathf.Clamp01(t); float num = 1f - t; return 6f * num * (p2 - 2f * p1 + p0) + 6f * t * (p3 - 2f * p2 + p1); } } }
48.046512
216
0.694095
[ "CC0-1.0" ]
FreyaFreed/mordheim
Assembly-CSharp/Pathfinding/AstarSplines.cs
2,068
C#
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; using GitHub.Discord.Bot.Cfg; using GitHub.Discord.Bot.Data.Context; using GitHub.Discord.Bot.Jobs; using GitHub.Discord.Bot.Services; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Quartz; using Quartz.Impl; using Serilog; #if !DEBUG using Serilog.Events; #endif using Serilog.Extensions.Logging; namespace GitHub.Discord.Bot { internal class Bot : IDisposable { private Bot() { _services = ConfigureServices(); _logger = _services.GetService<ILoggerFactory>().CreateLogger<Bot>(); } private readonly IServiceProvider _services; private readonly ILogger<Bot> _logger; private const string ConfigFile = "GitHub.Discord.Bot.Config.json"; internal static readonly BaseConfiguration BaseConfiguration = JsonConvert.DeserializeObject<BaseConfiguration>(File.ReadAllText(ConfigFile)); internal static void Main(string[] args) => new Bot().MainAsync().GetAwaiter().GetResult(); private async Task MainAsync() { _logger.LogInformation("Starting ..."); DiscordSocketClient client = _services.GetRequiredService<DiscordSocketClient>(); _logger.LogInformation("Created Discord client: {@DiscordSocketClient}", client); #if DEBUG _logger.LogInformation("Running application in DEBUG mode"); #endif _logger.LogInformation("Logging in ..."); await client.LoginAsync(TokenType.Bot, BaseConfiguration.DiscordToken); _logger.LogInformation("Starting client ..."); await client.StartAsync(); _logger.LogInformation("Loading commands ..."); await _services.GetRequiredService<ICommandHandlingService>().InitializeAsync(); _logger.LogInformation("Starting scheduler ..."); IScheduler scheduler = await _services.GetRequiredService<ISchedulerFactory>().GetScheduler(); await scheduler.Start(); _logger.LogInformation("Startup sequence complete. Awaiting user interaction ..."); await Task.Delay(Timeout.Infinite); await scheduler.Shutdown(); _logger.LogInformation("Shutting down ..."); } private static ServiceProvider ConfigureServices() { LoggerProviderCollection providers = new(); Log.Logger = new LoggerConfiguration() #if DEBUG .WriteTo.Debug() .WriteTo.Console() .WriteTo.File("GitHub.Discord.Bot.log") #else .WriteTo.Sentry(o => { o.Dsn = BaseConfiguration.SentryToken; o.MinimumBreadcrumbLevel = LogEventLevel.Information; o.MinimumEventLevel = LogEventLevel.Warning; }) .WriteTo.File("GitHub.Discord.Bot.log", LogEventLevel.Information) #endif .WriteTo.Providers(providers) .CreateLogger(); return new ServiceCollection() .AddSingleton<DiscordSocketClient>() .AddSingleton<CommandService>() .AddSingleton<ICommandHandlingService, CommandHandlingService>() .AddSingleton<ILoggingService, LoggingService>() .AddSingleton<IGitHubService, GitHubService>() .AddSingleton<IIssueUpdateService, IssueUpdateService>() .AddSingleton<ILoggerFactory>(sc => { LoggerProviderCollection providerCollection = sc.GetService<LoggerProviderCollection>(); SerilogLoggerFactory factory = new(null, true, providerCollection); foreach (ILoggerProvider provider in sc.GetServices<ILoggerProvider>()) { factory.AddProvider(provider); } return factory; }) .AddDbContext<BotContext>() .AddQuartz(q => { q.SchedulerId = "Scheduler-Core"; q.UseMicrosoftDependencyInjectionJobFactory(); q.UseSimpleTypeLoader(); q.UseInMemoryStore(); q.UseDefaultThreadPool(tp => { tp.MaxConcurrency = 10; }); q.ScheduleJob<GitHubSyncJob>(trigger => trigger .WithIdentity("GitHub Sync Trigger") .WithSimpleSchedule(x => x.WithIntervalInSeconds(Bot.BaseConfiguration.GitHubSyncInterval).RepeatForever()) ); }) .AddQuartzHostedService(options => { options.WaitForJobsToComplete = true; }) .BuildServiceProvider(); } public void Dispose() { if (_services is IDisposable disposable) { disposable.Dispose(); } } } }
39.18797
110
0.594781
[ "MIT" ]
gruenwaldlk/GitHub.Discord.Bot
GitHub.Discord.Bot/Bot.cs
5,214
C#
namespace DeriSock.Request { public class BuyParams { /// <summary> /// Instrument name /// </summary> public string InstrumentName { get; set; } /// <summary> /// It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is /// amount of corresponding cryptocurrency contracts, e.g., BTC or ETH /// </summary> public decimal Amount { get; set; } /// <summary> /// <para>The order type, default: "limit"</para> /// <para>Enum: <c>limit</c>, <c>stop_limit</c>, <c>market</c>, <c>stop_market</c></para> /// </summary> public string Type { get; set; } /// <summary> /// user defined label for the order (maximum 64 characters) /// </summary> public string Label { get; set; } /// <summary> /// <para>The order price in base currency (Only for limit and stop_limit orders)</para> /// <para>When adding order with advanced=usd, the field price should be the option price value in USD.</para> /// <para> /// When adding order with advanced=implv, the field price should be a value of implied volatility in percentages. /// For example, price=100, means implied volatility of 100% /// </para> /// </summary> public decimal? Price { get; set; } /// <summary> /// <para>Specifies how long the order remains in effect. Default <c>good_til_cancelled</c></para> /// <para><c>good_til_cancelled</c> - unfilled order remains in order book until cancelled</para> /// <para><c>fill_or_kill</c> - execute a transaction immediately and completely or not at all</para> /// <para> /// <c>immediate_or_cancel</c> - execute a transaction immediately, and any portion of the order that cannot be /// immediately filled is cancelled /// </para> /// </summary> public string TimeInForce { get; set; } /// <summary> /// Maximum amount within an order to be shown to other customers, 0 for invisible order /// </summary> public decimal? MaxShow { get; set; } /// <summary> /// <para> /// If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as /// taker), the price will be changed to be just below the spread. /// </para> /// <para>Only valid in combination with time_in_force="good_til_cancelled"</para> /// </summary> public bool? PostOnly { get; set; } /// <summary> /// <para> /// If order is considered post-only and this field is set to true than order is put to order book unmodified or /// request is rejected. /// </para> /// <para>Only valid in combination with "post_only" set to true</para> /// </summary> public bool? RejectPostOnly { get; set; } /// <summary> /// If true, the order is considered reduce-only which is intended to only reduce a current position /// </summary> public bool? ReduceOnly { get; set; } /// <summary> /// Stop price, required for stop limit orders (Only for stop orders) /// </summary> public decimal? StopPrice { get; set; } /// <summary> /// <para>Defines trigger type, required for "stop_limit" order type</para> /// <para>Enum: <c>index_price</c>, <c>mark_price</c>, <c>last_price</c></para> /// </summary> public string Trigger { get; set; } /// <summary> /// <para>Advanced option order type. (Only for options)</para> /// <para>Enum: <c>usd</c>, <c>implv</c></para> /// </summary> public string Advanced { get; set; } } }
38.914894
123
0.61181
[ "MIT" ]
gabfeldman/DeriSock
DeriSock/Request/BuyParams.cs
3,672
C#
/************************************************************************************* Toolkit for WPF Copyright (C) 2007-2019 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at https://github.com/xceedsoftware/wpftoolkit/blob/master/license.md For more features, controls, and fast professional support, pick up the Plus Edition at https://xceed.com/xceed-toolkit-plus-for-wpf/ Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ***********************************************************************************/ using System; using System.Linq; using System.Windows.Markup; using System.Xml.Serialization; using System.Windows; using System.Globalization; using System.Windows.Media; using System.ComponentModel; using Xceed.Wpf.AvalonDock.Controls; namespace Xceed.Wpf.AvalonDock.Layout { [ContentProperty( "Content" )] [Serializable] public abstract class LayoutContent : LayoutElement, IXmlSerializable, ILayoutElementForFloatingWindow, IComparable<LayoutContent>, ILayoutPreviousContainer { #region Constructors internal LayoutContent() { } #endregion #region Properties #region Title public static readonly DependencyProperty TitleProperty = DependencyProperty.Register( "Title", typeof( string ), typeof( LayoutContent ), new UIPropertyMetadata( null, OnTitlePropertyChanged, CoerceTitleValue ) ); public string Title { get { return ( string )GetValue( TitleProperty ); } set { SetValue( TitleProperty, value ); } } private static object CoerceTitleValue( DependencyObject obj, object value ) { var lc = ( LayoutContent )obj; if( ( ( string )value ) != lc.Title ) { lc.RaisePropertyChanging( LayoutContent.TitleProperty.Name ); } return value; } private static void OnTitlePropertyChanged( DependencyObject obj, DependencyPropertyChangedEventArgs args ) { ( ( LayoutContent )obj ).RaisePropertyChanged( LayoutContent.TitleProperty.Name ); } #endregion //Title #region Content [NonSerialized] private object _content = null; [XmlIgnore] public object Content { get { return _content; } set { if( _content != value ) { RaisePropertyChanging( "Content" ); _content = value; RaisePropertyChanged( "Content" ); if( this.ContentId == null ) { var contentAsControl = _content as FrameworkElement; if( contentAsControl != null && !string.IsNullOrWhiteSpace( contentAsControl.Name ) ) { this.SetCurrentValue( LayoutContent.ContentIdProperty, contentAsControl.Name ); } } } } } #endregion #region ContentId public static readonly DependencyProperty ContentIdProperty = DependencyProperty.Register( "ContentId", typeof( string ), typeof( LayoutContent ), new UIPropertyMetadata( null, OnContentIdPropertyChanged ) ); public string ContentId { get { return (string)GetValue( ContentIdProperty ); } set { SetValue( ContentIdProperty, value ); } } private static void OnContentIdPropertyChanged( DependencyObject obj, DependencyPropertyChangedEventArgs args ) { var layoutContent = obj as LayoutContent; if( layoutContent != null ) { layoutContent.OnContentIdPropertyChanged( (string)args.OldValue, (string)args.NewValue ); } } private void OnContentIdPropertyChanged( string oldValue, string newValue ) { if( oldValue != newValue ) { this.RaisePropertyChanged( "ContentId" ); } } #endregion //ContentId #region IsSelected private bool _isSelected = false; public bool IsSelected { get { return _isSelected; } set { if( _isSelected != value ) { bool oldValue = _isSelected; RaisePropertyChanging( "IsSelected" ); _isSelected = value; var parentSelector = ( Parent as ILayoutContentSelector ); if( parentSelector != null ) parentSelector.SelectedContentIndex = _isSelected ? parentSelector.IndexOf( this ) : -1; OnIsSelectedChanged( oldValue, value ); RaisePropertyChanged( "IsSelected" ); LayoutAnchorableTabItem.CancelMouseLeave(); } } } /// <summary> /// Provides derived classes an opportunity to handle changes to the IsSelected property. /// </summary> protected virtual void OnIsSelectedChanged( bool oldValue, bool newValue ) { if( IsSelectedChanged != null ) IsSelectedChanged( this, EventArgs.Empty ); } public event EventHandler IsSelectedChanged; #endregion #region IsActive [field: NonSerialized] private bool _isActive = false; [XmlIgnore] public bool IsActive { get { return _isActive; } set { if( _isActive != value ) { RaisePropertyChanging( "IsActive" ); bool oldValue = _isActive; _isActive = value; var root = Root; if( root != null && _isActive ) root.ActiveContent = this; if( _isActive ) IsSelected = true; OnIsActiveChanged( oldValue, value ); RaisePropertyChanged( "IsActive" ); } } } /// <summary> /// Provides derived classes an opportunity to handle changes to the IsActive property. /// </summary> protected virtual void OnIsActiveChanged( bool oldValue, bool newValue ) { if( newValue ) LastActivationTimeStamp = DateTime.Now; if( IsActiveChanged != null ) IsActiveChanged( this, EventArgs.Empty ); } public event EventHandler IsActiveChanged; #endregion #region IsLastFocusedDocument private bool _isLastFocusedDocument = false; public bool IsLastFocusedDocument { get { return _isLastFocusedDocument; } internal set { if( _isLastFocusedDocument != value ) { RaisePropertyChanging( "IsLastFocusedDocument" ); _isLastFocusedDocument = value; RaisePropertyChanged( "IsLastFocusedDocument" ); } } } #endregion #region PreviousContainer [field: NonSerialized] private ILayoutContainer _previousContainer = null; [XmlIgnore] ILayoutContainer ILayoutPreviousContainer.PreviousContainer { get { return _previousContainer; } set { if( _previousContainer != value ) { _previousContainer = value; RaisePropertyChanged( "PreviousContainer" ); var paneSerializable = _previousContainer as ILayoutPaneSerializable; if( paneSerializable != null && paneSerializable.Id == null ) paneSerializable.Id = Guid.NewGuid().ToString(); } } } protected ILayoutContainer PreviousContainer { get { return ( ( ILayoutPreviousContainer )this ).PreviousContainer; } set { ( ( ILayoutPreviousContainer )this ).PreviousContainer = value; } } [XmlIgnore] string ILayoutPreviousContainer.PreviousContainerId { get; set; } protected string PreviousContainerId { get { return ( ( ILayoutPreviousContainer )this ).PreviousContainerId; } set { ( ( ILayoutPreviousContainer )this ).PreviousContainerId = value; } } #endregion #region PreviousContainerIndex [field: NonSerialized] private int _previousContainerIndex = -1; [XmlIgnore] public int PreviousContainerIndex { get { return _previousContainerIndex; } set { if( _previousContainerIndex != value ) { _previousContainerIndex = value; RaisePropertyChanged( "PreviousContainerIndex" ); } } } #endregion #region LastActivationTimeStamp private DateTime? _lastActivationTimeStamp = null; public DateTime? LastActivationTimeStamp { get { return _lastActivationTimeStamp; } set { if( _lastActivationTimeStamp != value ) { _lastActivationTimeStamp = value; RaisePropertyChanged( "LastActivationTimeStamp" ); } } } #endregion #region FloatingWidth private double _floatingWidth = 0.0; public double FloatingWidth { get { return _floatingWidth; } set { if( _floatingWidth != value ) { RaisePropertyChanging( "FloatingWidth" ); _floatingWidth = value; RaisePropertyChanged( "FloatingWidth" ); } } } #endregion #region FloatingHeight private double _floatingHeight = 0.0; public double FloatingHeight { get { return _floatingHeight; } set { if( _floatingHeight != value ) { RaisePropertyChanging( "FloatingHeight" ); _floatingHeight = value; RaisePropertyChanged( "FloatingHeight" ); } } } #endregion #region FloatingLeft private double _floatingLeft = 0.0; public double FloatingLeft { get { return _floatingLeft; } set { if( _floatingLeft != value ) { RaisePropertyChanging( "FloatingLeft" ); _floatingLeft = value; RaisePropertyChanged( "FloatingLeft" ); } } } #endregion #region FloatingTop private double _floatingTop = 0.0; public double FloatingTop { get { return _floatingTop; } set { if( _floatingTop != value ) { RaisePropertyChanging( "FloatingTop" ); _floatingTop = value; RaisePropertyChanged( "FloatingTop" ); } } } #endregion #region IsMaximized private bool _isMaximized = false; public bool IsMaximized { get { return _isMaximized; } set { if( _isMaximized != value ) { RaisePropertyChanging( "IsMaximized" ); _isMaximized = value; RaisePropertyChanged( "IsMaximized" ); } } } #endregion #region ToolTip private object _toolTip = null; public object ToolTip { get { return _toolTip; } set { if( _toolTip != value ) { _toolTip = value; RaisePropertyChanged( "ToolTip" ); } } } #endregion #region IsFloating public bool IsFloating { get { return this.FindParent<LayoutFloatingWindow>() != null; } } #endregion #region IconSource private ImageSource _iconSource = null; public ImageSource IconSource { get { return _iconSource; } set { if( _iconSource != value ) { _iconSource = value; RaisePropertyChanged( "IconSource" ); } } } #endregion #region CanClose internal bool _canClose = true; public bool CanClose { get { return _canClose; } set { if( _canClose != value ) { _canClose = value; RaisePropertyChanged( "CanClose" ); } } } #endregion #region CanFloat private bool _canFloat = true; public bool CanFloat { get { return _canFloat; } set { if( _canFloat != value ) { _canFloat = value; RaisePropertyChanged( "CanFloat" ); } } } #endregion #region IsEnabled private bool _isEnabled = true; public bool IsEnabled { get { return _isEnabled; } set { if( _isEnabled != value ) { _isEnabled = value; RaisePropertyChanged( "IsEnabled" ); } } } #endregion #endregion #region Overrides protected override void OnParentChanging( ILayoutContainer oldValue, ILayoutContainer newValue ) { var root = Root; if( oldValue != null ) IsSelected = false; //if (root != null && _isActive && newValue == null) // root.ActiveContent = null; base.OnParentChanging( oldValue, newValue ); } protected override void OnParentChanged( ILayoutContainer oldValue, ILayoutContainer newValue ) { if( IsSelected && Parent != null && Parent is ILayoutContentSelector ) { var parentSelector = ( Parent as ILayoutContentSelector ); parentSelector.SelectedContentIndex = parentSelector.IndexOf( this ); } //var root = Root; //if (root != null && _isActive) // root.ActiveContent = this; base.OnParentChanged( oldValue, newValue ); } #endregion #region Public Methods /// <summary> /// Close the content /// </summary> /// <remarks>Please note that usually the anchorable is only hidden (not closed). By default when user click the X button it only hides the content.</remarks> public abstract void Close(); public System.Xml.Schema.XmlSchema GetSchema() { return null; } public virtual void ReadXml( System.Xml.XmlReader reader ) { if( reader.MoveToAttribute( "Title" ) ) Title = reader.Value; //if (reader.MoveToAttribute("IconSource")) // IconSource = new Uri(reader.Value, UriKind.RelativeOrAbsolute); if( reader.MoveToAttribute( "IsSelected" ) ) IsSelected = bool.Parse( reader.Value ); if( reader.MoveToAttribute( "ContentId" ) ) ContentId = reader.Value; if( reader.MoveToAttribute( "IsLastFocusedDocument" ) ) IsLastFocusedDocument = bool.Parse( reader.Value ); if( reader.MoveToAttribute( "PreviousContainerId" ) ) PreviousContainerId = reader.Value; if( reader.MoveToAttribute( "PreviousContainerIndex" ) ) PreviousContainerIndex = int.Parse( reader.Value ); if( reader.MoveToAttribute( "FloatingLeft" ) ) FloatingLeft = double.Parse( reader.Value, CultureInfo.InvariantCulture ); if( reader.MoveToAttribute( "FloatingTop" ) ) FloatingTop = double.Parse( reader.Value, CultureInfo.InvariantCulture ); if( reader.MoveToAttribute( "FloatingWidth" ) ) FloatingWidth = double.Parse( reader.Value, CultureInfo.InvariantCulture ); if( reader.MoveToAttribute( "FloatingHeight" ) ) FloatingHeight = double.Parse( reader.Value, CultureInfo.InvariantCulture ); if( reader.MoveToAttribute( "IsMaximized" ) ) IsMaximized = bool.Parse( reader.Value ); if( reader.MoveToAttribute( "CanClose" ) ) CanClose = bool.Parse( reader.Value ); if( reader.MoveToAttribute( "CanFloat" ) ) CanFloat = bool.Parse( reader.Value ); if( reader.MoveToAttribute( "LastActivationTimeStamp" ) ) LastActivationTimeStamp = DateTime.Parse( reader.Value, CultureInfo.InvariantCulture ); reader.Read(); } public virtual void WriteXml( System.Xml.XmlWriter writer ) { if( !string.IsNullOrWhiteSpace( Title ) ) writer.WriteAttributeString( "Title", Title ); //if (IconSource != null) // writer.WriteAttributeString("IconSource", IconSource.ToString()); if( IsSelected ) writer.WriteAttributeString( "IsSelected", IsSelected.ToString() ); if( IsLastFocusedDocument ) writer.WriteAttributeString( "IsLastFocusedDocument", IsLastFocusedDocument.ToString() ); if( !string.IsNullOrWhiteSpace( ContentId ) ) writer.WriteAttributeString( "ContentId", ContentId ); if( ToolTip != null && ToolTip is string ) if( !string.IsNullOrWhiteSpace( ( string )ToolTip ) ) writer.WriteAttributeString( "ToolTip", ( string )ToolTip ); if( FloatingLeft != 0.0 ) writer.WriteAttributeString( "FloatingLeft", FloatingLeft.ToString( CultureInfo.InvariantCulture ) ); if( FloatingTop != 0.0 ) writer.WriteAttributeString( "FloatingTop", FloatingTop.ToString( CultureInfo.InvariantCulture ) ); if( FloatingWidth != 0.0 ) writer.WriteAttributeString( "FloatingWidth", FloatingWidth.ToString( CultureInfo.InvariantCulture ) ); if( FloatingHeight != 0.0 ) writer.WriteAttributeString( "FloatingHeight", FloatingHeight.ToString( CultureInfo.InvariantCulture ) ); if( IsMaximized ) writer.WriteAttributeString( "IsMaximized", IsMaximized.ToString() ); if( !CanClose ) writer.WriteAttributeString( "CanClose", CanClose.ToString() ); if( !CanFloat ) writer.WriteAttributeString( "CanFloat", CanFloat.ToString() ); if( LastActivationTimeStamp != null ) writer.WriteAttributeString( "LastActivationTimeStamp", LastActivationTimeStamp.Value.ToString( CultureInfo.InvariantCulture ) ); if( _previousContainer != null ) { var paneSerializable = _previousContainer as ILayoutPaneSerializable; if( paneSerializable != null ) { writer.WriteAttributeString( "PreviousContainerId", paneSerializable.Id ); writer.WriteAttributeString( "PreviousContainerIndex", _previousContainerIndex.ToString() ); } } } public int CompareTo( LayoutContent other ) { var contentAsComparable = Content as IComparable; if( contentAsComparable != null ) { return contentAsComparable.CompareTo( other.Content ); } return string.Compare( Title, other.Title ); } /// <summary> /// Float the content in a popup window /// </summary> public void Float() { if( PreviousContainer != null && PreviousContainer.FindParent<LayoutFloatingWindow>() != null ) { var currentContainer = Parent as ILayoutPane; var currentContainerIndex = ( currentContainer as ILayoutGroup ).IndexOfChild( this ); var previousContainerAsLayoutGroup = PreviousContainer as ILayoutGroup; if( PreviousContainerIndex < previousContainerAsLayoutGroup.ChildrenCount ) previousContainerAsLayoutGroup.InsertChildAt( PreviousContainerIndex, this ); else previousContainerAsLayoutGroup.InsertChildAt( previousContainerAsLayoutGroup.ChildrenCount, this ); PreviousContainer = currentContainer; PreviousContainerIndex = currentContainerIndex; IsSelected = true; IsActive = true; Root.CollectGarbage(); } else { Root.Manager.StartDraggingFloatingWindowForContent( this, false ); IsSelected = true; IsActive = true; } } /// <summary> /// Dock the content as document /// </summary> public void DockAsDocument() { var root = Root as LayoutRoot; if( root == null ) throw new InvalidOperationException(); if( Parent is LayoutDocumentPane ) return; if( this is LayoutAnchorable ) { if( ( (LayoutAnchorable)this ).CanClose ) { ( (LayoutAnchorable)this ).SetCanCloseInternal( true ); } } if( PreviousContainer is LayoutDocumentPane ) { Dock(); return; } LayoutDocumentPane newParentPane; if( root.LastFocusedDocument != null ) { newParentPane = root.LastFocusedDocument.Parent as LayoutDocumentPane; } else { newParentPane = root.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault(); } if( newParentPane != null ) { newParentPane.Children.Add( this ); root.CollectGarbage(); } IsSelected = true; IsActive = true; } /// <summary> /// Re-dock the content to its previous container /// </summary> public void Dock() { if( PreviousContainer != null ) { var currentContainer = Parent as ILayoutContainer; var currentContainerIndex = ( currentContainer is ILayoutGroup ) ? ( currentContainer as ILayoutGroup ).IndexOfChild( this ) : -1; var previousContainerAsLayoutGroup = PreviousContainer as ILayoutGroup; if( PreviousContainerIndex < previousContainerAsLayoutGroup.ChildrenCount ) previousContainerAsLayoutGroup.InsertChildAt( PreviousContainerIndex, this ); else previousContainerAsLayoutGroup.InsertChildAt( previousContainerAsLayoutGroup.ChildrenCount, this ); if( currentContainerIndex > -1 ) { PreviousContainer = currentContainer; PreviousContainerIndex = currentContainerIndex; } else { PreviousContainer = null; PreviousContainerIndex = 0; } IsSelected = true; IsActive = true; } else { InternalDock(); } Root.CollectGarbage(); } #endregion #region Internal Methods /// <summary> /// Test if the content can be closed /// </summary> /// <returns></returns> internal bool TestCanClose() { CancelEventArgs args = new CancelEventArgs(); OnClosing( args ); if( args.Cancel ) return false; return true; } internal void CloseInternal() { var root = Root; var parentAsContainer = Parent as ILayoutContainer; parentAsContainer.RemoveChild( this ); if( root != null ) root.CollectGarbage(); OnClosed(); } protected virtual void OnClosed() { if( Closed != null ) Closed( this, EventArgs.Empty ); } protected virtual void OnClosing( CancelEventArgs args ) { if( Closing != null ) Closing( this, args ); } protected virtual void InternalDock() { } #endregion #region Events /// <summary> /// Event fired when the content is closed (i.e. removed definitely from the layout) /// </summary> public event EventHandler Closed; /// <summary> /// Event fired when the content is about to be closed (i.e. removed definitely from the layout) /// </summary> /// <remarks>Please note that LayoutAnchorable also can be hidden. Usually user hide anchorables when click the 'X' button. To completely close /// an anchorable the user should click the 'Close' menu item from the context menu. When an LayoutAnchorable is hidden its visibility changes to false and /// IsHidden property is set to true. /// Hanlde the Hiding event for the LayoutAnchorable to cancel the hide operation.</remarks> public event EventHandler<CancelEventArgs> Closing; #endregion } }
24.947594
219
0.607862
[ "MIT" ]
O-Debegnach/Supervisor-de-Comercio
wpftoolkit-master/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.AvalonDock/Layout/LayoutContent.cs
23,328
C#
// Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms. #region Using Statements using Valve.VR; #endregion namespace WaveEngine.OpenVR.Helpers { public class ButtonMask { public const ulong System = 1ul << (int)EVRButtonId.k_EButton_System; // reserved public const ulong ApplicationMenu = 1ul << (int)EVRButtonId.k_EButton_ApplicationMenu; public const ulong Grip = 1ul << (int)EVRButtonId.k_EButton_Grip; public const ulong Axis0 = 1ul << (int)EVRButtonId.k_EButton_Axis0; public const ulong Axis1 = 1ul << (int)EVRButtonId.k_EButton_Axis1; public const ulong Axis2 = 1ul << (int)EVRButtonId.k_EButton_Axis2; public const ulong Axis3 = 1ul << (int)EVRButtonId.k_EButton_Axis3; public const ulong Axis4 = 1ul << (int)EVRButtonId.k_EButton_Axis4; public const ulong Touchpad = 1ul << (int)EVRButtonId.k_EButton_SteamVR_Touchpad; public const ulong Trigger = 1ul << (int)EVRButtonId.k_EButton_SteamVR_Trigger; } }
45.391304
95
0.715517
[ "MIT" ]
WaveEngine/Extensions
WaveEngine.OpenVR/Shared/Helpers/ButtonMask.cs
1,047
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using NBCZ.Api.Model.Request; using NBCZ.BLL; using NBCZ.Model; namespace NBCZ.Api.Controllers { [Produces("application/json")] [Authorize] [Route("api/PubUser")] public class PubUserController : BaseController { private Pub_UserBLL bll = new Pub_UserBLL(); private V_PubUser_DeptBLL userDeptBLL = new V_PubUser_DeptBLL(); private Pub_UserRoleBLL userRoleBLL = new Pub_UserRoleBLL(); Pub_UserFunctionBLL userFunctionBLL = new Pub_UserFunctionBLL(); [HttpGet,Route("GetAccess")] public dynamic GetAccess() { // var userCode = User.Identity.Name; //var c = (a:1,b:2); //return ( // access: new List<string>() { "super_admin", "admin" }, // avatar: "https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png", // name: "super_admin", // user_id:"1" // ); var user = new NBCZUser(User); var userName = user.UserName; var userCode = user.UserCode; var access = user.Access; return new { access = access, avatar = "https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png", name = userName, user_id = userCode }; } /// <summary> /// 获取用户分页 /// </summary> /// <returns></returns> [Route("GetPage")] [HttpPost] public PageDateRes<V_PubUser_Dept> GetPage([FromBody]PageDataReq pageReq) { var whereStr = GetWhereStr(); if (whereStr=="-1") { return new PageDateRes<V_PubUser_Dept>() {code=ResCode.Error,msg="查询参数有误!",data=null }; } var users = userDeptBLL.GetPage(whereStr, (pageReq.field + " " + pageReq.order), pageReq.pageNum, pageReq.pageSize); // PageDateRes<V_PubUser_DeptExt> users = usersPage.MapTo<PageDateRes <V_PubUser_Dept>,PageDateRes <V_PubUser_DeptExt>>(); var userCodes = string.Join("','", users.data.Select(p => p.UserCode)); List<Pub_UserRole> userRoles = userRoleBLL.GetList($"userCode in ('{userCodes}')"); users.data.ForEach(p => { p.RoleCodes = userRoles.Where(c => c.UserCode == p.UserCode).Select(d => d.RoleCode); }); return users; } private string GetWhereStr() { StringBuilder sb = new StringBuilder(" 1=1 "); sb.Append(" and StopFlag=0 "); var query = this.HttpContext.GetWhereStr(); if (query=="-1") { return query; } sb.AppendFormat(" and {0} ", query); return sb.ToString(); } /// <summary> /// 添加用户 /// </summary> /// <returns></returns> [Route("Add")] [HttpPost] public DataRes<bool> Add([FromBody]V_PubUser_Dept model) { DataRes<bool> res = new DataRes<bool>() { code = ResCode.Success, data = true }; model.Crdt = model.Lmdt = DateTime.Now; var user = new NBCZUser(User); model.Crid = model.Lmid = $"{user.UserCode}-{user.UserName}"; var r = bll.Add(model); if (!r.Item1) { res.code = ResCode.Error; res.data = false; res.msg = r.Item2; } return res; } /// <summary> /// 编辑用户 /// </summary> /// <returns></returns> [Route("Edit")] [HttpPost] public DataRes<bool> Edit([FromBody]V_PubUser_Dept model) { DataRes<bool> res = new DataRes<bool>() { code = ResCode.Success, data = true }; model.Lmdt = DateTime.Now; var user = new NBCZUser(User); model.Lmid = $"{user.UserCode}-{user.UserName}"; var r = bll.Edit(model); if (!r.Item1) { res.code = ResCode.Error; res.data = false; res.msg = r.Item2; } return res; } /// <summary> /// 删除用户 /// </summary> /// <returns></returns> [Route("Delete/{id}")] [HttpPost] public DataRes<bool> Delete(long id) { DataRes<bool> res = new DataRes<bool>() { code = ResCode.Success, data = true }; var r = bll.ChangeSotpStatus($"id={id}", null); if (!r) { res.code = ResCode.Error; res.data = false; res.msg = "删除失败"; } return res; } /// <summary> /// 获取用户权限 /// </summary> /// <returns></returns> [Route("GetFunctions/{code}")] [HttpPost] public DataRes<IEnumerable<string>> GetFunctions(string code) { DataRes<IEnumerable<string>> res = new DataRes<IEnumerable<string>>() { code = ResCode.Success }; var list = userFunctionBLL.GetList($"userCode='{code}'"); res.data = list.Select(p=>p.FunctionCode); return res; } /// <summary> /// 保存用户权限 /// </summary> /// <returns></returns> [Route("SaveFunctions/{code}")] [HttpPost] public DataRes<bool> SaveFunctions(string code, [FromBody]List<string> functions) { DataRes<bool> res = new DataRes<bool>() { code = ResCode.Success, data = true }; List<Pub_UserFunction> list = new List<Pub_UserFunction>(); functions.ForEach(p => { list.Add(new Pub_UserFunction() { FunctionCode = p,UserCode = code }); }); var r = bll.SaveFunctions(code, list); if (!r.Item1) { res.code = ResCode.Error; res.data = false; res.msg = "保存失败"; } return res; } } }
31.450495
135
0.510467
[ "MIT" ]
chi8708/NBCZ_Admin_NetCore
NBCZ.Api/Controllers/PubUserController.cs
6,445
C#
/******************************************************************************* * Copyright © 2020 WaterCloud.Framework 版权所有 * Author: WaterCloud * Description: WaterCloud快速开发平台 * Website: *********************************************************************************/ using System; using SqlSugar; namespace WaterCloud.Domain.FlowManage { [SugarTable("oms_formtest")] public class FormTestEntity : IEntity<FormTestEntity>, ICreationAudited { [SugarColumn(ColumnName ="F_Id", IsPrimaryKey = true, ColumnDescription ="主键Id")] public string F_Id { get; set; } [SugarColumn(IsNullable = false, ColumnName = "F_UserName",ColumnDataType = "nvarchar(10)")] public string F_UserName { get; set; } [SugarColumn(IsNullable = false)] public string F_RequestType { get; set; } [SugarColumn(IsNullable = true)] public DateTime? F_StartTime { get; set; } [SugarColumn(IsNullable = true)] public DateTime? F_EndTime { get; set; } [SugarColumn(IsNullable = false, ColumnName = "F_RequestComment",ColumnDataType = "longtext")] public string F_RequestComment { get; set; } [SugarColumn(IsNullable = true, ColumnName = "F_Attachment", ColumnDataType = "longtext")] public string F_Attachment { get; set; } [SugarColumn(IsNullable = true, ColumnName = "F_FlowInstanceId", ColumnDataType = "nvarchar(50)")] public string F_FlowInstanceId { get; set; } [SugarColumn(IsNullable = true)] public DateTime? F_CreatorTime { get; set; } [SugarColumn(IsNullable = true, ColumnName = "F_CreatorUserId",ColumnDataType = "nvarchar(50)")] public string F_CreatorUserId { get; set; } [SugarColumn(IsNullable = true, ColumnName = "F_CreatorUserName",ColumnDataType = "nvarchar(50)")] public string F_CreatorUserName { get; set; } } }
47.725
107
0.612886
[ "MIT" ]
qian416322/WaterCloud
WaterCloud.Domain/Entity/FlowManage/FormTestEntity.cs
1,938
C#
using System.Windows.Controls; namespace CompanyName.ApplicationName.Views { /// <summary> /// Interaction logic for AnimationView.xaml /// </summary> public partial class AnimationView : UserControl { /// <summary> /// Initializes a new AnimationView object. /// </summary> public AnimationView() { InitializeComponent(); } } }
23
52
0.589372
[ "MIT" ]
PacktPublishing/Mastering-Windows-Presentation-Foundation-Second-Edition
CompanyName.ApplicationName.Views/AnimationView.xaml.cs
416
C#
using System; using System.IO; using NitroSharp.Graphics; using NitroSharp.Media; using NitroSharp.NsScript; using NitroSharp.NsScript.Primitives; namespace NitroSharp { internal partial class Builtins { public override void LoadAudio(in EntityPath entityPath, NsAudioKind kind, string fileName) { if (ResolvePath(entityPath, out ResolvedEntityPath path) && _ctx.Content.TryOpenStream(fileName) is Stream stream) { World.Add(new Sound(path, kind, stream, _ctx.AudioContext)); } } public override void PlayVideo( in EntityPath entityPath, int priority, NsCoordinate x, NsCoordinate y, bool loop, bool alpha, string source) { if (ResolvePath(entityPath, out ResolvedEntityPath resolvedPath) && _ctx.Content.TryOpenStream(source) is Stream fs) { Video video = World.Add(new Video( resolvedPath, priority, _renderCtx, _ctx.AudioContext, fs, alpha )).WithPosition(_renderCtx, x, y); video.Stream.ToggleLooping(loop); video.Stream.Start(); } } public override void SetLoopRegion(in EntityPath entityPath, TimeSpan loopStart, TimeSpan loopEnd) { if (Get(entityPath) is Sound sound) { sound.Stream.SetLoopRegion(new LoopRegion(loopStart, loopEnd)); sound.Stream.ToggleLooping(true); } } public override void ToggleLooping(EntityQuery query, bool enable) { foreach (Sound sound in Query<Sound>(query)) { sound.Stream.ToggleLooping(enable); } } public override void SetVolume(EntityQuery query, TimeSpan duration, NsRational volume) { duration = AdjustDuration(duration); foreach (Sound sound in Query<Sound>(query)) { sound.AnimateVolume(volume.Rebase(1.0f), duration); } } public override void WaitPlay(in EntityPath entityPath) { if (Get(entityPath) is object) { _ctx.Wait(CurrentThread, WaitCondition.EntityIdle, null, new EntityQuery(entityPath.Value) ); } } public override int GetSoundAmplitude(string characterName) { if (_ctx.GetVoice(characterName) is MediaStream voice) { ReadOnlySpan<short> samples = voice.AudioSource.GetCurrentBuffer(); if (samples.Length > 0) { int firstSample = samples[0]; int secondSample = samples[samples.Length / 4]; int thirdSample = samples[samples.Length / 4 + samples.Length / 2]; int fourthSample = samples[^2]; double amplitude = (Math.Abs(firstSample) + Math.Abs(secondSample) + Math.Abs(thirdSample) + Math.Abs(fourthSample)) / 4.0d; return (int)amplitude; } } return 0; } public override int GetMediaDuration(in EntityPath entityPath) => Get(entityPath) switch { Sound s => (int)s.Stream.Duration.TotalMilliseconds, Video v => (int)v.Stream.Duration.TotalMilliseconds, _ => 0 }; public override int GetTimeElapsed(in EntityPath entityPath) => Get(entityPath) switch { Sound s => (int)s.Stream.Elapsed.TotalMilliseconds, Video v => (int)v.Stream.Elapsed.TotalMilliseconds, _ => 0 }; public override int GetTimeRemaining(EntityQuery query) { int remaining = 0; foreach (Entity entity in Query(query)) { remaining = Math.Max(remaining, entity switch { Sound s => (int)(s.Stream.Duration - s.Stream.Elapsed).TotalMilliseconds, Video v => (int)(v.Stream.Duration - v.Stream.Elapsed).TotalMilliseconds, _ => 0 }); if (remaining > 0) { break; } } return remaining; } } }
34.476923
106
0.533467
[ "MIT" ]
Cred0utofnames/nitrosharp
src/NitroSharp/Builtins.Media.cs
4,482
C#
using System; using System.Linq; using System.Text; #if !NETSTANDARD2_0 using System.Web.UI; #endif namespace OfficeDevPnP.Core.Pages { #if !SP2013 && !SP2016 /// <summary> /// Represents a section on the canvas /// </summary> public class CanvasSection { #region variables private System.Collections.Generic.List<CanvasColumn> columns = new System.Collections.Generic.List<CanvasColumn>(3); private ClientSidePage page; private int zoneEmphasis; #endregion #region construction internal CanvasSection(ClientSidePage page) { if (page == null) { throw new ArgumentNullException("Passed page cannot be null"); } this.page = page; this.zoneEmphasis = 0; Order = 0; } /// <summary> /// Creates a new canvas section /// </summary> /// <param name="page"><see cref="ClientSidePage"/> instance that holds this section</param> /// <param name="canvasSectionTemplate">Type of section to create</param> /// <param name="order">Order of this section in the collection of sections on the page</param> public CanvasSection(ClientSidePage page, CanvasSectionTemplate canvasSectionTemplate, float order) { if (page == null) { throw new ArgumentNullException("Passed page cannot be null"); } this.page = page; this.zoneEmphasis = 0; Type = canvasSectionTemplate; Order = order; switch (canvasSectionTemplate) { case CanvasSectionTemplate.OneColumn: goto default; case CanvasSectionTemplate.OneColumnFullWidth: this.columns.Add(new CanvasColumn(this, 1, 0)); break; case CanvasSectionTemplate.TwoColumn: this.columns.Add(new CanvasColumn(this, 1, 6)); this.columns.Add(new CanvasColumn(this, 2, 6)); break; case CanvasSectionTemplate.ThreeColumn: this.columns.Add(new CanvasColumn(this, 1, 4)); this.columns.Add(new CanvasColumn(this, 2, 4)); this.columns.Add(new CanvasColumn(this, 3, 4)); break; case CanvasSectionTemplate.TwoColumnLeft: this.columns.Add(new CanvasColumn(this, 1, 8)); this.columns.Add(new CanvasColumn(this, 2, 4)); break; case CanvasSectionTemplate.TwoColumnRight: this.columns.Add(new CanvasColumn(this, 1, 4)); this.columns.Add(new CanvasColumn(this, 2, 8)); break; default: this.columns.Add(new CanvasColumn(this, 1, 12)); break; } } #endregion #region Properties /// <summary> /// Type of the section /// </summary> public CanvasSectionTemplate Type { get; set; } /// <summary> /// Order in which this section is presented on the page /// </summary> public float Order { get; set; } /// <summary> /// <see cref="CanvasColumn"/> instances that are part of this section /// </summary> public System.Collections.Generic.List<CanvasColumn> Columns { get { return this.columns; } } /// <summary> /// The <see cref="ClientSidePage"/> instance holding this section /// </summary> public ClientSidePage Page { get { return this.page; } } /// <summary> /// Controls hosted in this section /// </summary> public System.Collections.Generic.List<CanvasControl> Controls { get { return this.Page.Controls.Where(p => p.Section == this).ToList<CanvasControl>(); } } /// <summary> /// The default <see cref="CanvasColumn"/> of this section /// </summary> public CanvasColumn DefaultColumn { get { if (this.columns.Count == 0) { this.columns.Add(new CanvasColumn(this)); } return this.columns.First(); } } /// <summary> /// Color emphasis of the section /// </summary> public int ZoneEmphasis { get { return this.zoneEmphasis; } set { this.zoneEmphasis = value; } } #endregion #region public methods /// <summary> /// Renders this section as a HTML fragment /// </summary> /// <returns>HTML string representing this section</returns> public string ToHtml() { StringBuilder html = new StringBuilder(100); #if !NETSTANDARD2_0 using (var htmlWriter = new HtmlTextWriter(new System.IO.StringWriter(html), "")) { htmlWriter.NewLine = string.Empty; #endif foreach (var column in this.columns.OrderBy(z => z.Order)) { #if NETSTANDARD2_0 html.Append(column.ToHtml()); #else htmlWriter.Write(column.ToHtml()); #endif } #if !NETSTANDARD2_0 } #endif return html.ToString(); } #endregion #region internal and private methods internal void AddColumn(CanvasColumn column) { if (column == null) { throw new ArgumentNullException("Passed column cannot be null"); } this.columns.Add(column); } #endregion } #endif }
30.137931
125
0.508173
[ "MIT" ]
GLubomirov/PnP-Sites-Core
Core/OfficeDevPnP.Core/Pages/CanvasSection.cs
6,120
C#
namespace CSG { using CSG.Algorithms; using CSG.Attributes; using System; using System.ComponentModel; using System.Numerics; using System.Runtime.Serialization; [Serializable] public abstract class Shape : IEquatable<Shape>, ISerializable { [Category("Default")] public string Name { get; set; } /// <summary> /// Gets or sets the default color. /// </summary> [Category("Material")] [Color] public Vector4 Color { get => this.color; set { if (this.color != value) { this.color = value; Invalidate(); } } } /// <summary> /// Gets or sets the shape position. /// </summary> [Category("Transform")] public Vector3 Position { get => this.position; set { if (this.position != value) { this.position = value; Invalidate(); } } } /// <summary> /// Gets or sets the shape scale. /// </summary> [Category("Transform")] public Vector3 Scale { get => this.scale; set { if (this.scale != value) { this.scale = value; Invalidate(); } } } /// <summary> /// Gets the vertices from the <see cref="Shape"/>. /// </summary> public Vertex[] Vertices => Cache.Vertices; /// <summary> /// Gets the indices from the <see cref="Shape"/>. /// </summary> public uint[] Indices => Cache.Indices; /// <summary> /// Gets whether the shape is invalidated, and is required to be rebuilt. /// </summary> public bool IsInvalidated => this.cache == null; /// <summary> /// Gets the <see cref="ShapeCache"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public ShapeCache Cache => cache ?? (cache = BuildCache()).Value; private ShapeCache? cache = null; private Vector4 color = Vector4.One; private Vector3 position = Vector3.Zero; private Vector3 scale = Vector3.One; protected Shape() { } protected Shape(SerializationInfo info, StreamingContext context) { this.Name = info.GetString("name"); this.Position = (Vector3)info.GetValue("position", typeof(Vector3)); this.Scale = (Vector3)info.GetValue("scale", typeof(Vector3)); this.Color = (Vector4)info.GetValue("color", typeof(Vector4)); } /// <summary> /// Perform an operation with <paramref name="other"/> shape. /// </summary> /// <param name="operation"></param> /// <param name="other"></param> /// <returns></returns> public GeneratedShape Do(ShapeOperation operation, Shape other) => Do(operation, other, this); /// <summary> /// Perform a <see cref="ShapeOperation.Union"/> operation with <paramref name="other"/> shape. /// </summary> /// <param name="other"></param> /// <returns></returns> public GeneratedShape Union(Shape other) => Union(other, this); /// <summary> /// Perform a <see cref="ShapeOperation.Subtract"/> operation with <paramref name="other"/> shape. /// </summary> /// <param name="other"></param> /// <returns></returns> public GeneratedShape Subtract(Shape other) => Subtract(other, this); /// <summary> /// Perform a <see cref="ShapeOperation.Intersect"/> operation with <paramref name="other"/> shape. /// </summary> /// <param name="other"></param> /// <returns></returns> public GeneratedShape Intersect(Shape other) => Intersect(other, this); /// <summary> /// Create polygons of the <see cref="Shape"/>. /// </summary> public virtual Polygon[] CreatePolygons() => Cache.CreatePolygons(); /// <summary> /// Invalidates the cache. This will force it to rebuild next time it is accessed. /// </summary> public void Invalidate() { this.cache = null; } protected abstract void OnBuild(IShapeBuilder builder); private ShapeCache BuildCache() { var builder = ShapeBuilderPool.CurrentBuilder(); builder.DefaultColor = this.Color; builder.LocalPosition = this.Position; builder.LocalScale = this.Scale; // Make sure that it is clean. builder.Clear(); // Build the shape. OnBuild(builder); // Generate the shape cache. var tmpCache = builder.CreateCache(); // Clear the currently builder so we dont waste memory. builder.Clear(); return tmpCache; } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("name", this.Name); info.AddValue("position", this.Position); info.AddValue("scale", this.Scale); info.AddValue("color", this.color); } /// <inheritdoc /> public bool Equals(Shape other) { return this.Name == other.Name && this.Position == other.Position && this.Scale == other.Scale && this.Color == other.Color; } /// <summary> /// Perform an operation on the two shapes. /// </summary> /// <param name="operation"></param> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns></returns> public static GeneratedShape Do(ShapeOperation operation, Shape lhs, Shape rhs) { switch (operation) { default: case ShapeOperation.Intersect: return Intersect(lhs, rhs); case ShapeOperation.Subtract: return Subtract(lhs, rhs); case ShapeOperation.Union: return Union(lhs, rhs); } } /// <summary> /// Perform a <see cref="ShapeOperation.Union"/> operation on two shapes. /// </summary> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns></returns> public static GeneratedShape Union(Shape lhs, Shape rhs) { var a = new BSPNode(lhs.CreatePolygons()); var b = new BSPNode(rhs.CreatePolygons()); var polygons = BSPNode.Union(a, b).AllPolygons(); return new GeneratedShape(polygons); } /// <summary> /// Perform a <see cref="ShapeOperation.Subtract"/> operation on two shapes. /// </summary> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns></returns> public static GeneratedShape Subtract(Shape lhs, Shape rhs) { var a = new BSPNode(lhs.CreatePolygons()); var b = new BSPNode(rhs.CreatePolygons()); var polygons = BSPNode.Subtract(a, b).AllPolygons(); return new GeneratedShape(polygons); } /// <summary> /// Perform a <see cref="ShapeOperation.Intersect"/> operation on two shapes. /// </summary> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns></returns> public static GeneratedShape Intersect(Shape lhs, Shape rhs) { var a = new BSPNode(lhs.CreatePolygons()); var b = new BSPNode(rhs.CreatePolygons()); var polygons = BSPNode.Intersect(a, b).AllPolygons(); return new GeneratedShape(polygons); } } }
31.746154
107
0.511146
[ "MIT" ]
Kaydax/CSG
src/CSG/Shape.cs
8,256
C#
// // EventDeclaration.cs // // Author: // Mike Krüger <mkrueger@novell.com> // // Copyright (c) 2009 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.Collections.Generic; namespace ICSharpCode.NRefactory.CSharp { public class EventDeclaration : AttributedNode { public override NodeType NodeType { get { return NodeType.Member; } } public AstType ReturnType { get { return GetChildByRole (Roles.Type); } set { SetChildByRole(Roles.Type, value); } } public AstNodeCollection<VariableInitializer> Variables { get { return GetChildrenByRole (Roles.Variable); } } public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data) { return visitor.VisitEventDeclaration (this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { EventDeclaration o = other as EventDeclaration; return o != null && this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match) && this.Variables.DoMatch(o.Variables, match); } } public class CustomEventDeclaration : MemberDeclaration { public static readonly Role<Accessor> AddAccessorRole = new Role<Accessor>("AddAccessor", Accessor.Null); public static readonly Role<Accessor> RemoveAccessorRole = new Role<Accessor>("RemoveAccessor", Accessor.Null); public CSharpTokenNode LBraceToken { get { return GetChildByRole (Roles.LBrace); } } public Accessor AddAccessor { get { return GetChildByRole (AddAccessorRole); } set { SetChildByRole (AddAccessorRole, value); } } public Accessor RemoveAccessor { get { return GetChildByRole (RemoveAccessorRole); } set { SetChildByRole (RemoveAccessorRole, value); } } public CSharpTokenNode RBraceToken { get { return GetChildByRole (Roles.RBrace); } } public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data) { return visitor.VisitCustomEventDeclaration (this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { CustomEventDeclaration o = other as CustomEventDeclaration; return o != null && this.MatchMember(o, match) && this.AddAccessor.DoMatch(o.AddAccessor, match) && this.RemoveAccessor.DoMatch(o.RemoveAccessor, match); } } }
35.610526
113
0.736624
[ "MIT" ]
arturek/ILSpy
NRefactory/ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/EventDeclaration.cs
3,386
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 04:56:00 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using elliptic = go.crypto.elliptic_package; using hmac = go.crypto.hmac_package; using errors = go.errors_package; using hash = go.hash_package; using io = go.io_package; using big = go.math.big_package; using cryptobyte = go.golang.org.x.crypto.cryptobyte_package; using curve25519 = go.golang.org.x.crypto.curve25519_package; using hkdf = go.golang.org.x.crypto.hkdf_package; using go; #nullable enable namespace go { namespace crypto { public static partial class tls_package { [GeneratedCode("go2cs", "0.1.0.0")] private partial struct nistParameters { // Constructors public nistParameters(NilType _) { this.privateKey = default; this.x = default; this.y = default; this.curveID = default; } public nistParameters(slice<byte> privateKey = default, ref ptr<big.Int> x = default, ref ptr<big.Int> y = default, CurveID curveID = default) { this.privateKey = privateKey; this.x = x; this.y = y; this.curveID = curveID; } // Enable comparisons between nil and nistParameters struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(nistParameters value, NilType nil) => value.Equals(default(nistParameters)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(nistParameters value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, nistParameters value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, nistParameters value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator nistParameters(NilType nil) => default(nistParameters); } [GeneratedCode("go2cs", "0.1.0.0")] private static nistParameters nistParameters_cast(dynamic value) { return new nistParameters(value.privateKey, ref value.x, ref value.y, value.curveID); } } }}
36.987013
154
0.619382
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/crypto/tls/key_schedule_nistParametersStruct.cs
2,848
C#
/* INFINITY CODE 2013-2016 */ /* http://www.infinity-code.com */ #if !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6 && !UNITY_4_7 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2 #define UNITY_5_3P #endif using UnityEditor; using UnityEngine; #if UNITY_5_3P using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; #endif [CustomEditor(typeof (OnlineMapsGUITextureControl))] public class OnlineMapsGUITextureControlEditor : Editor { public override void OnInspectorGUI() { bool dirty = false; OnlineMapsControlBase control = target as OnlineMapsControlBase; OnlineMapsControlBaseEditor.CheckMultipleInstances(control, ref dirty); OnlineMaps api = OnlineMapsControlBaseEditor.GetOnlineMaps(control); OnlineMapsControlBaseEditor.CheckTarget(api, OnlineMapsTarget.texture, ref dirty); base.OnInspectorGUI(); if (dirty) { EditorUtility.SetDirty(api); EditorUtility.SetDirty(control); if (!Application.isPlaying) { #if UNITY_5_3P EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); #endif } else api.Redraw(); } } }
27.659091
98
0.673788
[ "CC0-1.0" ]
VisualSweden/Mixed
Assets/Infinity Code/Online maps/Scripts/Editor/Controls/OnlineMapsGUITextureControlEditor.cs
1,219
C#
namespace Simple.Owin.CorsMiddleware { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; internal class Builder { private readonly ParameterExpression _env = Expression.Parameter(typeof (IDictionary<string, object>)); private readonly ParameterExpression _next = Expression.Parameter(typeof (Func<IDictionary<string,object>, Task>)); private readonly ConstantExpression _hostKey = Expression.Constant("Host"); private readonly OriginMatcher[] _matchers; public Builder(IEnumerable<OriginMatcher> matchers) { _matchers = matchers.ToArray(); } public bool? AllowCredentials { get; set; } public string[] AllowMethods { get; set; } public string[] AllowHeaders { get; set; } public string[] ExposeHeaders { get; set; } public double? MaxAge { get; set; } public int StopStatus { get; set; } public Func<IDictionary<string, object>, Func<IDictionary<string, object>, Task>, Task> Build() { var isAllowed = BuildCheckBlock(); var block = BuildFinalBlock(isAllowed); var lambda = Expression.Lambda<Func<IDictionary<string, object>, Func<IDictionary<string, object>, Task>, Task>>(block, _env, _next); return lambda.Compile(); } private BlockExpression BuildCheckBlock() { if (_matchers.Length == 1 && _matchers[0] is OriginMatcher.WildcardMatcher) { return BuildWildcardBlock(); } return BuildOriginMatchingBlock(); } private BlockExpression BuildFinalBlock(Expression isAllowed) { var task = Expression.Variable(typeof (Task)); var stopStatus = Expression.Constant(StopStatus); var setHeadersBlock = BuildSetHeadersBlock(); Expression allowedBlock = Expression.Assign(task, Expression.Invoke(_next, _env)); if (setHeadersBlock.Count > 0) { setHeadersBlock.Add(allowedBlock); allowedBlock = Expression.Block(setHeadersBlock); } var ifThen = (Expression.IfThenElse(isAllowed, allowedBlock, Expression.Assign(task, Expression.Call(Methods.Stop, _env, stopStatus)))); var block = Expression.Block(new[] {task}, ifThen, task); return block; } private IList<Expression> BuildSetHeadersBlock() { var block = new List<Expression>(); if (AllowCredentials.GetValueOrDefault()) { block.Add(BuildSetHeaderCall(HeaderKeys.AccessControlAllowCredentials, "true")); } if (AllowMethods != null && AllowMethods.Length > 0) { if (AllowMethods.Length == 1 && AllowMethods[0] == "*") { block.Add(Expression.Call(Methods.MirrorRequestMethods, _env)); } else { block.Add(BuildSetHeaderCall(HeaderKeys.AccessControlAllowMethods, AllowMethods)); } } if (AllowHeaders != null && AllowHeaders.Length > 0) { if (AllowHeaders.Length == 1 && AllowHeaders[0] == "*") { block.Add(Expression.Call(Methods.MirrorRequestHeaders, _env)); } else { block.Add(BuildSetHeaderCall(HeaderKeys.AccessControlAllowHeaders, AllowHeaders)); } } if (ExposeHeaders != null && ExposeHeaders.Length > 0) { block.Add(BuildSetHeaderCall(HeaderKeys.AccessControlExposeHeaders, ExposeHeaders)); } if (MaxAge.HasValue) { block.Add(BuildSetHeaderCall(HeaderKeys.AccessControlMaxAge, MaxAge.Value.ToString(CultureInfo.InvariantCulture))); } return block; } private Expression BuildSetHeaderCall(string key, string[] values) { return BuildSetHeaderCall(key, string.Join(", ", values)); } private Expression BuildSetHeaderCall(string key, string value) { var keyConstant = Expression.Constant(key); var valueConstant = Expression.Constant(value); return Expression.Call(Methods.SetResponseHeaderValue, _env, keyConstant, valueConstant); } private BlockExpression BuildOriginMatchingBlock() { var blocks = new List<Expression>(); ParameterExpression allowed = Expression.Variable(typeof (bool)); var matchTests = new List<Expression>(); var host = Expression.Variable(typeof (string)); var assignHost = Expression.Assign(host, Expression.Call(Methods.GetRequestHeaderValue, _env, _hostKey)); blocks.Add(assignHost); var hostIsSet = Expression.Not(Expression.Call(Methods.StringIsNullOrWhitespace, host)); foreach (var expressionMatcher in _matchers) { var matcher = Expression.Constant(expressionMatcher); var isMatchMethod = expressionMatcher.GetType().GetMethod("IsMatch", new[] {typeof (string)}); matchTests.Add(Expression.Call(matcher, isMatchMethod, host)); } var isMatch = matchTests.Aggregate(Expression.Or); blocks.Add(Expression.Assign(allowed, Expression.And(hostIsSet, isMatch))); blocks.Add(Expression.IfThen(allowed, Expression.Call(Methods.SetResponseHeaderValue, _env, Expression.Constant(HeaderKeys.AccessControlAllowOrigin), host))); blocks.Add(allowed); return Expression.Block(new[] {host, allowed}, blocks); } private BlockExpression BuildWildcardBlock() { var blocks = new List<Expression> { Expression.Call(Methods.SetResponseHeaderValue, _env, Expression.Constant(HeaderKeys.AccessControlAllowOrigin), Expression.Constant("*")), Expression.Constant(true) }; return Expression.Block(blocks); } } }
38.894737
146
0.577808
[ "MIT" ]
simple-owin/Simple.Owin.Cors
src/Simple.Owin.Cors/Builder.cs
6,653
C#
using System; using System.Collections.Generic; using System.Text; namespace uplanit.Models { public enum MenuItemType { Browse, About } public class HomeMenuItem { public MenuItemType Id { get; set; } public string Title { get; set; } } }
15.736842
44
0.608696
[ "Apache-2.0" ]
dapperGeek/uPlanIt
uplanit/uplanit/Models/HomeMenuItem.cs
301
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v4/errors/time_zone_error.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.Ads.GoogleAds.V4.Errors { /// <summary>Holder for reflection information generated from google/ads/googleads/v4/errors/time_zone_error.proto</summary> public static partial class TimeZoneErrorReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v4/errors/time_zone_error.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TimeZoneErrorReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjRnb29nbGUvYWRzL2dvb2dsZWFkcy92NC9lcnJvcnMvdGltZV96b25lX2Vy", "cm9yLnByb3RvEh5nb29nbGUuYWRzLmdvb2dsZWFkcy52NC5lcnJvcnMaHGdv", "b2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8iWQoRVGltZVpvbmVFcnJvckVu", "dW0iRAoNVGltZVpvbmVFcnJvchIPCgtVTlNQRUNJRklFRBAAEgsKB1VOS05P", "V04QARIVChFJTlZBTElEX1RJTUVfWk9ORRAFQu0BCiJjb20uZ29vZ2xlLmFk", "cy5nb29nbGVhZHMudjQuZXJyb3JzQhJUaW1lWm9uZUVycm9yUHJvdG9QAVpE", "Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMvZ29v", "Z2xlYWRzL3Y0L2Vycm9ycztlcnJvcnOiAgNHQUGqAh5Hb29nbGUuQWRzLkdv", "b2dsZUFkcy5WNC5FcnJvcnPKAh5Hb29nbGVcQWRzXEdvb2dsZUFkc1xWNFxF", "cnJvcnPqAiJHb29nbGU6OkFkczo6R29vZ2xlQWRzOjpWNDo6RXJyb3JzYgZw", "cm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V4.Errors.TimeZoneErrorEnum), global::Google.Ads.GoogleAds.V4.Errors.TimeZoneErrorEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V4.Errors.TimeZoneErrorEnum.Types.TimeZoneError) }, null, null) })); } #endregion } #region Messages /// <summary> /// Container for enum describing possible time zone errors. /// </summary> public sealed partial class TimeZoneErrorEnum : pb::IMessage<TimeZoneErrorEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<TimeZoneErrorEnum> _parser = new pb::MessageParser<TimeZoneErrorEnum>(() => new TimeZoneErrorEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TimeZoneErrorEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V4.Errors.TimeZoneErrorReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeZoneErrorEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeZoneErrorEnum(TimeZoneErrorEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeZoneErrorEnum Clone() { return new TimeZoneErrorEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TimeZoneErrorEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TimeZoneErrorEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TimeZoneErrorEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] 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; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] 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; } } } #endif #region Nested types /// <summary>Container for nested types declared in the TimeZoneErrorEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Enum describing possible currency code errors. /// </summary> public enum TimeZoneError { /// <summary> /// Enum unspecified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// The received error code is not known in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// Time zone is not valid. /// </summary> [pbr::OriginalName("INVALID_TIME_ZONE")] InvalidTimeZone = 5, } } #endregion } #endregion } #endregion Designer generated code
35.852535
291
0.696144
[ "Apache-2.0" ]
GraphikaPS/google-ads-dotnet
src/V4/Types/TimeZoneError.cs
7,780
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SplinterTrip { class SplinterTrip { static void Main() { var distanceInMiles = double.Parse(Console.ReadLine()); var fuelCapacity = double.Parse(Console.ReadLine()); var spentInHeavyWinds = double.Parse(Console.ReadLine()); var nonWindsConsumptionLiters = (distanceInMiles - spentInHeavyWinds) * 25; var windsConsumptionLeters = spentInHeavyWinds * (25 * 1.5); var fuelConsumption = nonWindsConsumptionLiters + windsConsumptionLeters; var tolerance = fuelConsumption * 0.05; var totalFuel = fuelConsumption + tolerance; Console.WriteLine($"Fuel needed: {totalFuel:f2}L"); var remainingFuel = fuelCapacity - totalFuel; Console.WriteLine(remainingFuel >= 0 ? $"Enough with {remainingFuel:f2}L to spare!" : $"We need {Math.Abs(remainingFuel):f2}L more fuel."); } } }
36.5
87
0.631963
[ "MIT" ]
PavelRunchev/Programming-Fundamentals-2017
Programming Fundamentals - Sep-2017/33.Exam Programming Fundamentals/03.Exam 9-May2017/01.SplinterTrip/SplinterTrip.cs
1,097
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. */ namespace TencentCloud.Gaap.V20180529.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class GroupStatisticsInfo : AbstractModel { /// <summary> /// Connection group ID /// </summary> [JsonProperty("GroupId")] public string GroupId{ get; set; } /// <summary> /// Connection group name /// </summary> [JsonProperty("GroupName")] public string GroupName{ get; set; } /// <summary> /// List of connections of a connection group /// </summary> [JsonProperty("ProxySet")] public ProxySimpleInfo[] ProxySet{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "GroupId", this.GroupId); this.SetParamSimple(map, prefix + "GroupName", this.GroupName); this.SetParamArrayObj(map, prefix + "ProxySet.", this.ProxySet); } } }
31.051724
81
0.630761
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Gaap/V20180529/Models/GroupStatisticsInfo.cs
1,801
C#
/* * Copyright (c) Contributors, http://vision-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * For an explanation of the license of each contributor and the content it * covers please see the Licenses directory. * * 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 Vision-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using OpenMetaverse; using Vision.Framework.SceneInfo; namespace Vision.ScriptEngine.VisionScript.MiniModule { public class SOPObjectInventory : IObjectInventory { readonly TaskInventoryDictionary m_privateInventory; /// Vision's task inventory readonly Dictionary<UUID, IInventoryItem> m_publicInventory; /// MRM's inventory readonly IScene m_rootScene; public SOPObjectInventory(IScene rootScene, TaskInventoryDictionary taskInventory) { m_rootScene = rootScene; m_privateInventory = taskInventory; m_publicInventory = new Dictionary<UUID, IInventoryItem>(); } #region IObjectInventory Members //note: it looks to me this function is not doing anything, no return value, always throws exception public IInventoryItem this[string name] { get { foreach (TaskInventoryItem i in m_privateInventory.Values.Where(i => i.Name == name)) if (!m_publicInventory.ContainsKey(i.ItemID)) m_publicInventory.Add(i.ItemID, new InventoryItem(m_rootScene, i)); throw new KeyNotFoundException(); } } #endregion /// <summary> /// Fully populate the public dictionary with the contents of the private dictionary /// </summary> /// <description> /// This will only convert those items which hasn't already been converted. ensuring that /// no items are converted twice, and that any references already in use are maintained. /// </description> void SynchronizeDictionaries() { foreach ( TaskInventoryItem privateItem in m_privateInventory.Values.Where(privateItem => !m_publicInventory.ContainsKey(privateItem.ItemID))) m_publicInventory.Add(privateItem.ItemID, new InventoryItem(m_rootScene, privateItem)); } #region IDictionary<UUID, IInventoryItem> implementation public void Add(UUID key, IInventoryItem value) { m_publicInventory.Add(key, value); var invtValue = InventoryItem.FromInterface (value); // this could retuen null if unable to convert if (invtValue != null) m_privateInventory [key] = invtValue.ToTaskInventoryItem (); else m_privateInventory [key] = null; } public bool ContainsKey(UUID key) { return m_privateInventory.ContainsKey(key); } public bool Remove(UUID key) { m_publicInventory.Remove(key); return m_privateInventory.Remove(key); } public bool TryGetValue(UUID key, out IInventoryItem value) { value = null; bool result = false; if (!m_publicInventory.TryGetValue(key, out value)) { // wasn't found in the public inventory TaskInventoryItem privateItem; result = m_privateInventory.TryGetValue(key, out privateItem); if (result) { value = new InventoryItem(m_rootScene, privateItem); m_publicInventory.Add(key, value); // add item, so we don't convert again } } else return true; return result; } public ICollection<UUID> Keys { get { return m_privateInventory.Keys; } } public ICollection<IInventoryItem> Values { get { SynchronizeDictionaries(); return m_publicInventory.Values; } } #endregion #region IEnumerable<KeyValuePair<UUID, IInventoryItem>> implementation public IEnumerator<KeyValuePair<UUID, IInventoryItem>> GetEnumerator() { SynchronizeDictionaries(); return m_publicInventory.GetEnumerator(); } #endregion #region IEnumerable implementation IEnumerator IEnumerable.GetEnumerator() { SynchronizeDictionaries(); return m_publicInventory.GetEnumerator(); } #endregion #region ICollection<KeyValuePair<UUID, IInventoryItem>> implementation public void Add(KeyValuePair<UUID, IInventoryItem> item) { Add(item.Key, item.Value); } public void Clear() { m_publicInventory.Clear(); m_privateInventory.Clear(); } public bool Contains(KeyValuePair<UUID, IInventoryItem> item) { return m_privateInventory.ContainsKey(item.Key); } public bool Remove(KeyValuePair<UUID, IInventoryItem> item) { return Remove(item.Key); } public int Count { get { return m_privateInventory.Count; } } public bool IsReadOnly { get { return false; } } public void CopyTo(KeyValuePair<UUID, IInventoryItem>[] array, int arrayIndex) { throw new NotImplementedException(); } #endregion #region Explicit implementations IInventoryItem IDictionary<UUID, IInventoryItem>.this[UUID key] { get { IInventoryItem result; if (TryGetValue(key, out result)) return result; throw new KeyNotFoundException("[MRM] The requrested item ID could not be found"); } set { m_publicInventory[key] = value; var invtValue = InventoryItem.FromInterface (value); // this could retuen null if unable to convert if (invtValue != null) m_privateInventory [key] = invtValue.ToTaskInventoryItem (); else m_privateInventory [key] = null; } } void ICollection<KeyValuePair<UUID, IInventoryItem>>.CopyTo(KeyValuePair<UUID, IInventoryItem>[] array, int offset) { throw new NotImplementedException(); } #endregion } }
35.012346
120
0.590268
[ "MIT" ]
VisionSim/Vision-Sim
Vision/ScriptEngine/VisionScript/CompilerTools/Minimodule/SOPObjectInventory.cs
8,508
C#
using System; using System.Collections.Generic; using System.Text; namespace DataTransferObjects { public class Uloga { public string Id { get; set; } public string Naziv { get; set; } public bool IsGlavnaUloga { get; set; } public Glumac Glumac { get; set; } public Predstava Predstava { get; set; } } }
20.055556
48
0.623269
[ "MIT" ]
AdnanIT/eTeatar
eTeatar/DataTransferObjects/Uloga.cs
363
C#
/* * No license given, * taken from http://csharper.fairblog.ro/2010/05/compiling-c-projects-at-runtime-parsing-the-csproj-file */ namespace RunTimeCompiler { /// <summary> /// This is a reader for C# project files, or more precisely a /// wrapper to a reader of all .csproj. /// As the structure of the .csproj file appears to change with the version /// of Visual Studio, this class must use the appropriate .csproj reader. /// AllCsprojReader (the only class used currently to process .csproj files) /// support .csproj files created with Visual Studio 2005+. /// Visual Studio 2010 is the most recent version of Visual Studio, and the /// .csproj files it genererates are processed ok by AllCsprojReader. /// I do not know if .csproj files created with Visual Studio 2001-2003 can /// be processed successfully. /// </summary> public class CsprojReader : IProjectReader { #region IProjectReader Members /// <summary> /// Defined in IProjectReader. /// It is used to check if the specified file can be opened by this /// project-reader. /// </summary> /// <param name = "filename"></param> /// <returns></returns> public bool CanOpen(string filename) { //TODO: Add some logic here: check extension to be .csproj, //open the .csproj file and get Visual Studio version and see //if that version of .csproj can be open... return true; } /// <summary> /// Defined in IProjectReader. /// It is used to retriece all the data needed for UI and compilation. /// </summary> /// <param name = "filename">The name (and path) of the C# project file.</param> /// <returns></returns> public BasicProject ReadProject(string filename) { AllCsprojReader reader; if (!CanOpen(filename)) return null; reader = new AllCsprojReader(); return reader.ReadProject(filename); } #endregion } }
39.854545
107
0.590785
[ "BSD-3-Clause" ]
BillyWarrhol/Aurora-Sim
Aurora/Modules/Installer/CSProjCompiler/CsprojReader.cs
2,194
C#
#region Header // --------------------------------------------------------------------------------- // <copyright file="AbstractInfoLayout.cs" company="https://github.com/sant0ro/Yupi"> // Copyright (c) 2016 Claudio Santoro, TheDoctor // </copyright> // <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. // </license> // --------------------------------------------------------------------------------- #endregion Header namespace Yupi.Model.Domain { using System; public abstract class AbstractInfoLayout : DefaultImageLayout { #region Properties [Required] public virtual TString Description { get; set; } = string.Empty; [Ignore] public override TString[] Texts { get { return new TString[] { this.Description }; } } #endregion Properties } }
36.314815
85
0.624681
[ "MIT" ]
TheDoct0r11/Yupi
Yupi.Model/Domain/Catalog/Layout/AbstractInfoLayout.cs
1,961
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SagaImpl.InventoryService.Database; namespace SagaImpl.InventoryService.Migrations { [DbContext(typeof(InventoryDbContext))] partial class InventoryDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.11") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("SagaImpl.InventoryService.Entities.ProductEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<decimal>("Price") .HasColumnType("decimal(18,2)"); b.Property<int>("Quantity") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("Products", "ProductService"); }); #pragma warning restore 612, 618 } } }
37.196078
125
0.580917
[ "MIT" ]
IvanJevtic9/SagaPatternImpl
src/SagaImpl.InventoryService/Migrations/InventoryDbContextModelSnapshot.cs
1,899
C#
 using System; using System.Net.Http; using System.Web.Http; namespace Travo.Controllers { public class StatusController : TravoApiController { [Route("~/status"), HttpGet] public HttpResponseMessage GetStatus() { return TravoOk(); } } }
17.411765
54
0.614865
[ "MIT" ]
Tarpsvo/Travo
Travo.WebAPI/Controllers/StatusController.cs
298
C#
using Microsoft.IdentityModel.Tokens; using System; namespace Messages.App.Jwt { public class TokenProviderOptions { public string Path { get; set; } = "api/users/login"; public string Issuer { get; set; } public string Audience { get; set; } public TimeSpan Expitarion { get; set; } = TimeSpan.FromDays(15); public SigningCredentials SigningCredentials { get; set; } } }
22.631579
73
0.648837
[ "MIT" ]
DanielBankov/SoftUni
C# Web/ASP.NET Core MVC/Security & Identity/Messages/Messages.App/Jwt/TokenProviderOptions.cs
432
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EmpowerBusiness { using System; public partial class IW_Man_glOutOfBalanceJournals_Result { public Nullable<int> glJournalSysID { get; set; } public Nullable<decimal> glBalance { get; set; } } }
33.3
85
0.524024
[ "Apache-2.0" ]
HaloImageEngine/EmpowerClaim-hotfix-1.25.1
EmpowerBusiness/IW_Man_glOutOfBalanceJournals_Result.cs
666
C#
#region Copyright & License /* Copyright (c) 2022, Integrated Solutions, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Integrated Solutions, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ISI.Extensions.Extensions; namespace ISI.Extensions { public partial class Enum { public static object ParseKey(Type enumType, string value) { var @enum = GetEnumWrapperInstance(enumType); var methodInfo = @enum.GetType().GetMethod(nameof(Enum.IEnum.ParseKey), System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); return methodInfo?.Invoke(@enum, new object[] { value, Activator.CreateInstance(enumType) }); } } }
59.361111
754
0.797847
[ "BSD-3-Clause" ]
ISI-Extensions/ISI.Extensions
src/ISI.Extensions/Enum/Enum_ParseKey.cs
2,137
C#
using Newtonsoft.Json; namespace JdPay.Data.Request { public class JdWithdrawBaseReq { public JdWithdrawBaseReq(string customerNo) { this.CustomerNo = customerNo; } /// <summary> /// 提交者会员号 customer_no yes String(24) 提交者会员号或企业会员或个人会员 /// </summary> /// <returns></returns> [JsonProperty("customer_no")] public string CustomerNo { get; set; } } }
24.555556
62
0.58371
[ "MIT" ]
lousaibiao/JdPayWebApi
JdPay.Data/Request/JdWithdrawBaseReq.cs
486
C#
using System; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using petrus.Data; [assembly: HostingStartup(typeof(petrus.Areas.Identity.IdentityHostingStartup))] namespace petrus.Areas.Identity { public class IdentityHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { }); } } }
29.285714
80
0.749593
[ "MIT" ]
truongkimson/petrus
petrus/Areas/Identity/IdentityHostingStartup.cs
617
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; namespace System.Security.Cryptography { public partial class DSA : AsymmetricAlgorithm { public static new DSA Create() { return new DSAImplementation.DSACng(); } } internal static partial class DSAImplementation { public sealed partial class DSACng : DSA { private SafeNCryptKeyHandle _keyHandle; private int _lastKeySize; private SafeNCryptKeyHandle GetDuplicatedKeyHandle() { int keySize = KeySize; if (_lastKeySize != keySize) { if (_keyHandle != null) { _keyHandle.Dispose(); } const string BCRYPT_DSA_ALGORITHM = "DSA"; _keyHandle = CngKeyLite.GenerateNewExportableKey(BCRYPT_DSA_ALGORITHM, keySize); _lastKeySize = keySize; } return new DuplicateSafeNCryptKeyHandle(_keyHandle); } private byte[] ExportKeyBlob(bool includePrivateParameters) { // Use generic blob type for multiple version support string blobType = includePrivateParameters ? Interop.BCrypt.KeyBlobType.BCRYPT_PRIVATE_KEY_BLOB : Interop.BCrypt.KeyBlobType.BCRYPT_PUBLIC_KEY_BLOB; using (SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle()) { return CngKeyLite.ExportKeyBlob(keyHandle, blobType); } } private void ImportKeyBlob(byte[] rsaBlob, bool includePrivate) { // Use generic blob type for multiple version support string blobType = includePrivate ? Interop.BCrypt.KeyBlobType.BCRYPT_PRIVATE_KEY_BLOB : Interop.BCrypt.KeyBlobType.BCRYPT_PUBLIC_KEY_BLOB; SafeNCryptKeyHandle keyHandle = CngKeyLite.ImportKeyBlob(blobType, rsaBlob); Debug.Assert(!keyHandle.IsInvalid); _keyHandle = keyHandle; int newKeySize = CngKeyLite.GetKeyLength(keyHandle); // Our LegalKeySizes value stores the values that we encoded as being the correct // legal key size limitations for this algorithm, as documented on MSDN. // // But on a new OS version we might not question if our limit is accurate, or MSDN // could have been inaccurate to start with. // // Since the key is already loaded, we know that Windows thought it to be valid; // therefore we should set KeySizeValue directly to bypass the LegalKeySizes conformance // check. ForceSetKeySize(newKeySize); _lastKeySize = newKeySize; } } } }
36.738636
104
0.579029
[ "MIT" ]
Acidburn0zzz/corefx
src/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSACng.cs
3,233
C#
using FoxTool.Fox.Types.Values; namespace FoxTool.Tpp.Classes { public class ChCharacterInstance : Data { // Static properties public FoxEntityPtr Factory { get; set; } public FoxEntityPtr Params { get; set; } public FoxUInt32 Size { get; set; } } }
23.615385
50
0.612378
[ "MIT" ]
Atvaark/FoxTool
FoxTool/Tpp/Classes/ChCharacterInstance.cs
307
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace LetterGame { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } }
22.217391
65
0.612524
[ "BSD-2-Clause" ]
erenright/LetterGame
LetterGame/Program.cs
513
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using FatturaElettronica.FatturaElettronicaBody.DatiGenerali; using FatturaElettronica.Tabelle; namespace Tests { [TestClass] public class DatiRitenutaValidator: BaseClass<DatiRitenuta, FatturaElettronica.Validators.DatiRitenutaValidator> { [TestMethod] public void TipoRitenutaIsRequired() { AssertRequired(x => x.TipoRitenuta); } [TestMethod] public void TipoRitenutaOnlyAcceptsTableValues() { AssertOnlyAcceptsTableValues<TipoRitenuta>(x => x.TipoRitenuta); } [TestMethod] public void ImportoRitenutaIsRequired() { AssertRequired(x => x.ImportoRitenuta); } [TestMethod] public void AliquotaRitenutaIsRequired() { AssertRequired(x => x.AliquotaRitenuta); } [TestMethod] public void CausalePagamentoIsRequired() { AssertRequired(x => x.CausalePagamento); } [TestMethod] public void CausalePagamentoOnlyAcceptsTableValues() { AssertOnlyAcceptsTableValues<CausalePagamento>(x => x.CausalePagamento); } } }
29.5
116
0.635997
[ "BSD-3-Clause" ]
MassimoLinossi/FatturaElettronica.NET
Test/DatiRitenutaValidator.cs
1,241
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace google.maps { [Imported] public partial class GroundOverlay : MVCObject { /// <summary> /// Creates a ground overlay from the provided image URL and its LatLngBounds. The image is scaled to fit the current bounds, and projected using the current map projection. /// </summary> public GroundOverlay(string url, LatLngBounds bounds) { throw new NotImplementedException(); } /// <summary> /// Creates a ground overlay from the provided image URL and its LatLngBounds. The image is scaled to fit the current bounds, and projected using the current map projection. /// </summary> public GroundOverlay(string url, LatLngBounds bounds, GroundOverlayOptions opts) { throw new NotImplementedException(); } /// <summary> /// Gets the LatLngBounds of this overlay. /// </summary> public LatLngBounds GetBounds() { throw new NotImplementedException(); } /// <summary> /// Returns the map on which this ground overlay is displayed. /// </summary> public Map GetMap() { throw new NotImplementedException(); } /// <summary> /// Gets the url of the projected image. /// </summary> public string GetUrl() { throw new NotImplementedException(); } /// <summary> /// Renders the ground overlay on the specified map. If map is set to null, the overlay is removed. /// </summary> public void SetMap(Map map) { throw new NotImplementedException(); } } }
32.189655
182
0.573648
[ "MIT" ]
BTDevelop/Serenity
Serenity.Script.Imports/GoogleMaps/Overlays/GroundOverlay.cs
1,869
C#
namespace Examples.InheritanceAndPolymorphism { public class BaseCar { private readonly int maxSpeed; private int currSpeed; public BaseCar(int max) { maxSpeed = max; } protected BaseCar() { maxSpeed = 55; } public int Speed { get { return currSpeed; } set { currSpeed = value <= maxSpeed ? value : maxSpeed; } } } }
19.458333
69
0.496788
[ "MIT" ]
luigiberrettini/c-sharp-basics
InheritanceAndPolymorphism/BaseCar.cs
467
C#
using System.ComponentModel; using AViews = Android.Views; using Xamarin.Forms; using Xamarin.Forms.ControlGallery.Android; using Xamarin.Forms.Controls.Issues; using Xamarin.Forms.Platform.Android; using AndroidX.Core.View; using AndroidX.Core.View.Accessibility; [assembly: ExportEffect(typeof(ContentDescriptionEffectRenderer), ContentDescriptionEffect.EffectName)] namespace Xamarin.Forms.ControlGallery.Android { public class ContentDescriptionEffectRenderer : PlatformEffect { protected override void OnAttached() { } protected override void OnDetached() { } protected override void OnElementPropertyChanged(PropertyChangedEventArgs args) { System.Diagnostics.Debug.WriteLine("OnElementPropertyChanged" + args.PropertyName); var viewGroup = Control as AViews.ViewGroup; var nativeView = Control as AViews.View; if (nativeView != null && viewGroup != null && viewGroup.ChildCount > 0) { nativeView = viewGroup.GetChildAt(0); } if (nativeView == null) { return; } var info = AccessibilityNodeInfoCompat.Obtain(nativeView); ViewCompat.OnInitializeAccessibilityNodeInfo(nativeView, info); System.Diagnostics.Debug.WriteLine(info.ContentDescription); System.Diagnostics.Debug.WriteLine(nativeView.ContentDescription); Element.SetValue( ContentDescriptionEffectProperties.NameAndHelpTextProperty, info.ContentDescription); Element.SetValue( ContentDescriptionEffectProperties.ContentDescriptionProperty, nativeView.ContentDescription); } } }
27.087719
103
0.779145
[ "MIT" ]
AlleSchonWeg/Xamarin.Forms
Xamarin.Forms.ControlGallery.Android/ContentDescriptionEffectRenderer.cs
1,546
C#
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; namespace ASP.NET_Core_CRUD_Web_App.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), RoleId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), UserId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(maxLength: 128, nullable: false), ProviderKey = table.Column<string>(maxLength: 128, nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(maxLength: 128, nullable: false), Name = table.Column<string>(maxLength: 128, nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true, filter: "[NormalizedName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true, filter: "[NormalizedUserName] IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
43.149321
122
0.499161
[ "MIT" ]
yousifgarabet/ASP.NET-Core-CRUD-Web-App
Data/Migrations/00000000000000_CreateIdentitySchema.cs
9,538
C#
using OpenQA.Selenium; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Blog.UI.Tests.Pages.HomePage { public partial class HomePage { public IWebElement Logo { get { return this.Wait.Until(w => w.FindElement(By.XPath("/html/body/div[1]/div/div[1]/a"))); } } public IWebElement Login { get { return this.Wait.Until(w => w.FindElement(By.Id("loginLink"))); } } public IWebElement Logoff { get { return this.Wait.Until(w => w.FindElement(By.CssSelector("#logoutForm > ul > li:nth-child(3) > a"))); } } public IWebElement Register { get { return this.Wait.Until(w => w.FindElement(By.Id("registerLink"))); } } public IWebElement GreatingLink { get { return this.Driver.FindElement(By.XPath("//*[@id=\"logoutForm\"]/ul/li[2]/a")); } } } }
22.163636
117
0.47662
[ "MIT" ]
ilian790112/My-Blog-with-automated-tests
TestCommit/Blog.UI.Tests/Pages/HomePage/HomePageMap.cs
1,221
C#
using System; using Vts.Common; namespace Vts.FemModeling.MGRTE._2D.SourceInputs { /// <summary> /// External line source /// </summary> public class ExtLineSourceInput : IExtFemSourceInput { /// <summary> /// General constructor for external line source /// </summary> /// <param name="start">starting point (x,z)</param> /// <param name="end">end point (x,z)</param> /// <param name="thetaRange">Theta Range</param> public ExtLineSourceInput( DoubleRange start, DoubleRange end, DoubleRange thetaRange) { SourceType = FemSourceType.ExtPointSource; Start = start; End = end; ThetaRange = thetaRange; } /// <summary> /// Default constructor for external line source /// </summary> public ExtLineSourceInput() : this( new DoubleRange(0.0, 0.0), new DoubleRange(0.0, 0.0), new DoubleRange(0, 2 * Math.PI)) { } /// <summary> /// Ext source type /// </summary> public FemSourceType SourceType { get; set; } /// <summary> /// Starting cooordinates (x,z) /// </summary> public DoubleRange Start { get; set; } /// <summary> /// Ending cooordinates (x,z) /// </summary> public DoubleRange End { get; set; } /// <summary> /// Theta angle range /// </summary> public DoubleRange ThetaRange { get; set; } } }
29.928571
61
0.495227
[ "MIT" ]
acs3235/VTS
src/Vts/FemModeling/MGRTE/2D/DataStructures/SourceInputs/ExternalSourceInputs/ExtLineSourceInput.cs
1,678
C#
using System; using System.Collections.Generic; using System.Text; using Discord; using Discord.WebSocket; namespace Lomztein.Moduthulhu.Core.Extensions { /// <summary> /// Contains a bunch of utility extension methods for various Discord objects. /// </summary> public static class DiscordExtensions { public static string GetPath (this IChannel channel) { if (channel == null) return "null"; if (channel is SocketGuildChannel guildChannel) { return $"{guildChannel.Guild.Name} / {guildChannel.Name}"; } if (channel is SocketDMChannel dmChannel) return $"{dmChannel.Recipient.Username}"; return ""; } public static string GetPath (this IMessage message) { if (message is SocketUserMessage userMessage) return userMessage.Channel.GetPath () + " / " + userMessage.Author.Username; if (message is SocketSystemMessage systemMessage) return systemMessage.Source.ToString (); return ""; } public static string GetPath (this SocketGuildUser guildUser) { if (guildUser == null) return "null"; return guildUser.Guild.Name + " / " + (string.IsNullOrEmpty (guildUser.Nickname) ? guildUser.Username : guildUser.Nickname); } public static string GetPath (this IRole role) { if (role == null) return "null"; return role.Guild + " / " + role.Name; } public static ulong ZeroIfNull (this IEntity<ulong> entity) { if (entity == null) return 0; return entity.Id; } public static string ToStringOrNull (this object obj) { return obj == null ? "null" : obj.ToString(); } } }
29.461538
136
0.570757
[ "MIT" ]
drcd/Moduthulhu
Core/Extensions/DiscordExtensions.cs
1,917
C#
#region Header /** * JsonData.cs * Generic type to hold JSON data (objects, arrays, and so on). This is * the default type returned by JsonMapper.ToObject(). * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; namespace LitJson { public class JsonData : IJsonWrapper, IEquatable<JsonData> { #region Fields private IList<JsonData> inst_array; private bool inst_boolean; private double inst_double; private int inst_int; private long inst_long; private IDictionary<string, JsonData> inst_object; private string inst_string; private string json; private JsonType type; // Used to implement the IOrderedDictionary interface private IList<KeyValuePair<string, JsonData>> object_list; #endregion #region Properties public int Count { get { return EnsureCollection().Count; } } public bool IsArray { get { return type == JsonType.Array; } } public bool IsBoolean { get { return type == JsonType.Boolean; } } public bool IsDouble { get { return type == JsonType.Double; } } public bool IsInt { get { return type == JsonType.Int; } } public bool IsLong { get { return type == JsonType.Long; } } public bool IsObject { get { return type == JsonType.Object; } } public bool IsString { get { return type == JsonType.String; } } public ICollection<string> Keys { get { EnsureDictionary(); return inst_object.Keys; } } #endregion #region ICollection Properties int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return EnsureCollection().IsSynchronized; } } object ICollection.SyncRoot { get { return EnsureCollection().SyncRoot; } } #endregion #region IDictionary Properties bool IDictionary.IsFixedSize { get { return EnsureDictionary().IsFixedSize; } } bool IDictionary.IsReadOnly { get { return EnsureDictionary().IsReadOnly; } } ICollection IDictionary.Keys { get { EnsureDictionary(); IList<string> keys = new List<string>(); foreach (KeyValuePair<string, JsonData> entry in object_list) { keys.Add(entry.Key); } return (ICollection)keys; } } ICollection IDictionary.Values { get { EnsureDictionary(); IList<JsonData> values = new List<JsonData>(); foreach (KeyValuePair<string, JsonData> entry in object_list) { values.Add(entry.Value); } return (ICollection)values; } } #endregion #region IJsonWrapper Properties bool IJsonWrapper.IsArray { get { return IsArray; } } bool IJsonWrapper.IsBoolean { get { return IsBoolean; } } bool IJsonWrapper.IsDouble { get { return IsDouble; } } bool IJsonWrapper.IsInt { get { return IsInt; } } bool IJsonWrapper.IsLong { get { return IsLong; } } bool IJsonWrapper.IsObject { get { return IsObject; } } bool IJsonWrapper.IsString { get { return IsString; } } #endregion #region IList Properties bool IList.IsFixedSize { get { return EnsureList().IsFixedSize; } } bool IList.IsReadOnly { get { return EnsureList().IsReadOnly; } } #endregion #region IDictionary Indexer object IDictionary.this[object key] { get { return EnsureDictionary()[key]; } set { if (!(key is String)) throw new ArgumentException( "The key has to be a string"); JsonData data = ToJsonData(value); this[(string)key] = data; } } #endregion #region IOrderedDictionary Indexer object IOrderedDictionary.this[int idx] { get { EnsureDictionary(); return object_list[idx].Value; } set { EnsureDictionary(); JsonData data = ToJsonData(value); KeyValuePair<string, JsonData> old_entry = object_list[idx]; inst_object[old_entry.Key] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData>(old_entry.Key, data); object_list[idx] = entry; } } #endregion #region IList Indexer object IList.this[int index] { get { return EnsureList()[index]; } set { EnsureList(); JsonData data = ToJsonData(value); this[index] = data; } } #endregion #region Public Indexers public JsonData this[string prop_name] { get { EnsureDictionary(); return inst_object[prop_name]; } set { EnsureDictionary(); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData>(prop_name, value); if (inst_object.ContainsKey(prop_name)) { for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == prop_name) { object_list[i] = entry; break; } } } else object_list.Add(entry); inst_object[prop_name] = value; json = null; } } public JsonData this[int index] { get { EnsureCollection(); if (type == JsonType.Array) return inst_array[index]; return object_list[index].Value; } set { EnsureCollection(); if (type == JsonType.Array) inst_array[index] = value; else { KeyValuePair<string, JsonData> entry = object_list[index]; KeyValuePair<string, JsonData> new_entry = new KeyValuePair<string, JsonData>(entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; } json = null; } } #endregion #region Constructors public JsonData() { } public JsonData(bool boolean) { type = JsonType.Boolean; inst_boolean = boolean; } public JsonData(double number) { type = JsonType.Double; inst_double = number; } public JsonData(int number) { type = JsonType.Int; inst_int = number; } public JsonData(long number) { type = JsonType.Long; inst_long = number; } public JsonData(object obj) { if (obj is Boolean) { type = JsonType.Boolean; inst_boolean = (bool)obj; return; } if (obj is Double) { type = JsonType.Double; inst_double = (double)obj; return; } if (obj is Int32) { type = JsonType.Int; inst_int = (int)obj; return; } if (obj is Int64) { type = JsonType.Long; inst_long = (long)obj; return; } if (obj is String) { type = JsonType.String; inst_string = (string)obj; return; } throw new ArgumentException( "Unable to wrap the given object with JsonData"); } public JsonData(string str) { type = JsonType.String; inst_string = str; } #endregion #region Implicit Conversions public static implicit operator JsonData(Boolean data) { return new JsonData(data); } public static implicit operator JsonData(Double data) { return new JsonData(data); } public static implicit operator JsonData(Int32 data) { return new JsonData(data); } public static implicit operator JsonData(Int64 data) { return new JsonData(data); } public static implicit operator JsonData(String data) { return new JsonData(data); } #endregion #region Explicit Conversions public static explicit operator Boolean(JsonData data) { if (data.type != JsonType.Boolean) throw new InvalidCastException( "Instance of JsonData doesn't hold a double"); return data.inst_boolean; } public static explicit operator Double(JsonData data) { if (data.type != JsonType.Double) throw new InvalidCastException( "Instance of JsonData doesn't hold a double"); return data.inst_double; } public static explicit operator Int32(JsonData data) { if (data.type != JsonType.Int) throw new InvalidCastException( "Instance of JsonData doesn't hold an int"); return data.inst_int; } public static explicit operator Int64(JsonData data) { if (data.type != JsonType.Long) throw new InvalidCastException( "Instance of JsonData doesn't hold an int"); return data.inst_long; } public static explicit operator String(JsonData data) { if (data.type != JsonType.String) throw new InvalidCastException( "Instance of JsonData doesn't hold a string"); return data.inst_string; } #endregion #region ICollection Methods void ICollection.CopyTo(Array array, int index) { EnsureCollection().CopyTo(array, index); } #endregion #region IDictionary Methods void IDictionary.Add(object key, object value) { JsonData data = ToJsonData(value); EnsureDictionary().Add(key, data); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData>((string)key, data); object_list.Add(entry); json = null; } void IDictionary.Clear() { EnsureDictionary().Clear(); object_list.Clear(); json = null; } bool IDictionary.Contains(object key) { return EnsureDictionary().Contains(key); } IDictionaryEnumerator IDictionary.GetEnumerator() { return ((IOrderedDictionary)this).GetEnumerator(); } void IDictionary.Remove(object key) { EnsureDictionary().Remove(key); for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == (string)key) { object_list.RemoveAt(i); break; } } json = null; } #endregion #region IEnumerable Methods IEnumerator IEnumerable.GetEnumerator() { return EnsureCollection().GetEnumerator(); } #endregion #region IJsonWrapper Methods bool IJsonWrapper.GetBoolean() { if (type != JsonType.Boolean) throw new InvalidOperationException( "JsonData instance doesn't hold a boolean"); return inst_boolean; } double IJsonWrapper.GetDouble() { if (type != JsonType.Double) throw new InvalidOperationException( "JsonData instance doesn't hold a double"); return inst_double; } int IJsonWrapper.GetInt() { if (type != JsonType.Int) throw new InvalidOperationException( "JsonData instance doesn't hold an int"); return inst_int; } long IJsonWrapper.GetLong() { if (type != JsonType.Long) throw new InvalidOperationException( "JsonData instance doesn't hold a long"); return inst_long; } string IJsonWrapper.GetString() { if (type != JsonType.String) throw new InvalidOperationException( "JsonData instance doesn't hold a string"); return inst_string; } void IJsonWrapper.SetBoolean(bool val) { type = JsonType.Boolean; inst_boolean = val; json = null; } void IJsonWrapper.SetDouble(double val) { type = JsonType.Double; inst_double = val; json = null; } void IJsonWrapper.SetInt(int val) { type = JsonType.Int; inst_int = val; json = null; } void IJsonWrapper.SetLong(long val) { type = JsonType.Long; inst_long = val; json = null; } void IJsonWrapper.SetString(string val) { type = JsonType.String; inst_string = val; json = null; } string IJsonWrapper.ToJson() { return ToJson(); } void IJsonWrapper.ToJson(JsonWriter writer) { ToJson(writer); } #endregion #region IList Methods int IList.Add(object value) { return Add(value); } void IList.Clear() { EnsureList().Clear(); json = null; } bool IList.Contains(object value) { return EnsureList().Contains(value); } int IList.IndexOf(object value) { return EnsureList().IndexOf(value); } void IList.Insert(int index, object value) { EnsureList().Insert(index, value); json = null; } void IList.Remove(object value) { EnsureList().Remove(value); json = null; } void IList.RemoveAt(int index) { EnsureList().RemoveAt(index); json = null; } #endregion #region IOrderedDictionary Methods IDictionaryEnumerator IOrderedDictionary.GetEnumerator() { EnsureDictionary(); return new OrderedDictionaryEnumerator( object_list.GetEnumerator()); } void IOrderedDictionary.Insert(int idx, object key, object value) { string property = (string)key; JsonData data = ToJsonData(value); this[property] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData>(property, data); object_list.Insert(idx, entry); } void IOrderedDictionary.RemoveAt(int idx) { EnsureDictionary(); inst_object.Remove(object_list[idx].Key); object_list.RemoveAt(idx); } #endregion #region Private Methods private ICollection EnsureCollection() { if (type == JsonType.Array) return (ICollection)inst_array; if (type == JsonType.Object) return (ICollection)inst_object; throw new InvalidOperationException( "The JsonData instance has to be initialized first"); } private IDictionary EnsureDictionary() { if (type == JsonType.Object) return (IDictionary)inst_object; if (type != JsonType.None) throw new InvalidOperationException( "Instance of JsonData is not a dictionary"); type = JsonType.Object; inst_object = new Dictionary<string, JsonData>(); object_list = new List<KeyValuePair<string, JsonData>>(); return (IDictionary)inst_object; } private IList EnsureList() { if (type == JsonType.Array) return (IList)inst_array; if (type != JsonType.None) throw new InvalidOperationException( "Instance of JsonData is not a list"); type = JsonType.Array; inst_array = new List<JsonData>(); return (IList)inst_array; } private JsonData ToJsonData(object obj) { if (obj == null) return null; if (obj is JsonData) return (JsonData)obj; return new JsonData(obj); } private static void WriteJson(IJsonWrapper obj, JsonWriter writer) { if (obj == null) { writer.Write(null); return; } if (obj.IsString) { writer.Write(obj.GetString()); return; } if (obj.IsBoolean) { writer.Write(obj.GetBoolean()); return; } if (obj.IsDouble) { writer.Write(obj.GetDouble()); return; } if (obj.IsInt) { writer.Write(obj.GetInt()); return; } if (obj.IsLong) { writer.Write(obj.GetLong()); return; } if (obj.IsArray) { writer.WriteArrayStart(); foreach (object elem in (IList)obj) WriteJson((JsonData)elem, writer); writer.WriteArrayEnd(); return; } if (obj.IsObject) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in ((IDictionary)obj)) { writer.WritePropertyName((string)entry.Key); WriteJson((JsonData)entry.Value, writer); } writer.WriteObjectEnd(); return; } } #endregion public int Add(object value) { JsonData data = ToJsonData(value); json = null; return EnsureList().Add(data); } public void Clear() { if (IsObject) { ((IDictionary)this).Clear(); return; } if (IsArray) { ((IList)this).Clear(); return; } } public bool Equals(JsonData x) { if (x == null) return false; if (x.type != this.type) return false; switch (this.type) { case JsonType.None: return true; case JsonType.Object: return this.inst_object.Equals(x.inst_object); case JsonType.Array: return this.inst_array.Equals(x.inst_array); case JsonType.String: return this.inst_string.Equals(x.inst_string); case JsonType.Int: return this.inst_int.Equals(x.inst_int); case JsonType.Long: return this.inst_long.Equals(x.inst_long); case JsonType.Double: return this.inst_double.Equals(x.inst_double); case JsonType.Boolean: return this.inst_boolean.Equals(x.inst_boolean); } return false; } public JsonType GetJsonType() { return type; } public void SetJsonType(JsonType type) { if (this.type == type) return; switch (type) { case JsonType.None: break; case JsonType.Object: inst_object = new Dictionary<string, JsonData>(); object_list = new List<KeyValuePair<string, JsonData>>(); break; case JsonType.Array: inst_array = new List<JsonData>(); break; case JsonType.String: inst_string = default(String); break; case JsonType.Int: inst_int = default(Int32); break; case JsonType.Long: inst_long = default(Int64); break; case JsonType.Double: inst_double = default(Double); break; case JsonType.Boolean: inst_boolean = default(Boolean); break; } this.type = type; } public string ToJson() { if (json != null) return json; StringWriter sw = new StringWriter(); JsonWriter writer = new JsonWriter(sw); writer.Validate = false; WriteJson(this, writer); json = sw.ToString(); return json; } public void ToJson(JsonWriter writer) { bool old_validate = writer.Validate; writer.Validate = false; WriteJson(this, writer); writer.Validate = old_validate; } public override string ToString() { switch (type) { case JsonType.Array: return "JsonData array"; case JsonType.Boolean: return inst_boolean.ToString(); case JsonType.Double: return inst_double.ToString(); case JsonType.Int: return inst_int.ToString(); case JsonType.Long: return inst_long.ToString(); case JsonType.Object: return "JsonData object"; case JsonType.String: return inst_string; } return "Uninitialized JsonData"; } } internal class OrderedDictionaryEnumerator : IDictionaryEnumerator { IEnumerator<KeyValuePair<string, JsonData>> list_enumerator; public object Current { get { return Entry; } } public DictionaryEntry Entry { get { KeyValuePair<string, JsonData> curr = list_enumerator.Current; return new DictionaryEntry(curr.Key, curr.Value); } } public object Key { get { return list_enumerator.Current.Key; } } public object Value { get { return list_enumerator.Current.Value; } } public OrderedDictionaryEnumerator( IEnumerator<KeyValuePair<string, JsonData>> enumerator) { list_enumerator = enumerator; } public bool MoveNext() { return list_enumerator.MoveNext(); } public void Reset() { list_enumerator.Reset(); } } }
26.171642
78
0.490977
[ "Unlicense" ]
EleBrain/-CS-ZWJsonEditor
0other/LitJson/JsonData.cs
24,549
C#
using System; using System.Collections.Generic; namespace ETPKLDivLibrary{ class TPDict{ private Dictionary<int, PatternCounts> _q_counts; private Dictionary<int, PatternList> _patterns; private Dictionary<int, BorderPatternList> _border_patterns; public TPDict(List<int[,]> input_samples, List<int> sizes, WarpOptions warp=null, BorderOptions borders=null){ Tuple<Dictionary<int, PatternCounts>, Dictionary<int, PatternList>, Dictionary<int, BorderPatternList>> temp = Helper.CalculateTilePatternProbabilities(input_samples, sizes, warp, borders); this._q_counts = temp.Item1; this._patterns = temp.Item2; this._border_patterns = temp.Item3; } public PatternList GetTPArray(int size){ return this._patterns[size]; } public PatternList GetTPBorderArray(int size, string dir){ return this._border_patterns[size][dir]; } public PatternCounts GetQCount(int size){ return this._q_counts[size]; } } }
32.225806
116
0.724725
[ "MIT" ]
amidos2006/ETPKLDiv
C#/code/TPDict.cs
999
C#
namespace YAMP { /// <summary> /// This is the class representing the *= operator. /// </summary> class MultiplyAssignmentOperator : AssignmentPrefixOperator { public MultiplyAssignmentOperator() : base(new MultiplyOperator()) { } public override Operator Create() { return new MultiplyAssignmentOperator(); } } }
21.684211
63
0.575243
[ "BSD-3-Clause" ]
FlorianRappl/YAMP
YAMP.Core/Operators/AssigmentOperators/MultiplyAssignmentOperator.cs
414
C#
// Copyright (c) Microsoft Corporation, Inc. All rights reserved. // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.AspNet.Identity { /// <summary> /// Return result for IPasswordHasher /// </summary> public enum PasswordVerificationResult { /// <summary> /// Password verification failed /// </summary> Failed = 0, /// <summary> /// Success /// </summary> Success = 1, /// <summary> /// Success but should update and rehash the password /// </summary> SuccessRehashNeeded = 2 } }
27.846154
109
0.551105
[ "MIT" ]
Sinoprise/ASP.NET-Identity
src/Microsoft.AspNet.Identity.Core/PasswordVerificationResult.cs
726
C#
using System; using System.Collections.Generic; namespace PoolManager.Domains.Pools { public class GetVacantInstancesResult { public GetVacantInstancesResult(IEnumerable<Guid> vacantInstances) { VacantInstances = vacantInstances; } public IEnumerable<Guid> VacantInstances { get; } } }
21.5625
74
0.684058
[ "MIT" ]
charleszipp/service-fabric-dotnet-pool-manager
src/PoolManager.Domains.Pools/GetVacantInstances/GetVacantInstancesResult.cs
347
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace FluentTester.Models { public class ExternalLoginConfirmationViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class ExternalLoginListViewModel { public string ReturnUrl { get; set; } } public class SendCodeViewModel { public string SelectedProvider { get; set; } public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; } public string ReturnUrl { get; set; } public bool RememberMe { get; set; } } public class VerifyCodeViewModel { [Required] public string Provider { get; set; } [Required] [Display(Name = "Code")] public string Code { get; set; } public string ReturnUrl { get; set; } [Display(Name = "Remember this browser?")] public bool RememberBrowser { get; set; } public bool RememberMe { get; set; } } public class ForgotViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class LoginViewModel { [Required] [Display(Name = "Email")] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class ResetPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public class ForgotPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } } }
27.530973
110
0.588557
[ "MIT" ]
vince1023/FluentTester
FluentTester/FluentTester/Models/AccountViewModels.cs
3,113
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Drawing; using DocumentFormat.OpenXml.Framework; using DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation.Schema; using System; using System.Collections.Generic; using System.IO.Packaging; namespace DocumentFormat.OpenXml.Drawing.ChartDrawing { /// <summary> /// <para>Relative Anchor Shape Size.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:relSizeAnchor.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>FromAnchor &lt;cdr:from></description></item> /// <item><description>ToAnchor &lt;cdr:to></description></item> /// <item><description>Shape &lt;cdr:sp></description></item> /// <item><description>GroupShape &lt;cdr:grpSp></description></item> /// <item><description>GraphicFrame &lt;cdr:graphicFrame></description></item> /// <item><description>ConnectionShape &lt;cdr:cxnSp></description></item> /// <item><description>Picture &lt;cdr:pic></description></item> /// <item><description>DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing.ContentPart &lt;cdr14:contentPart></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(FromAnchor))] [ChildElementInfo(typeof(ToAnchor))] [ChildElementInfo(typeof(Shape))] [ChildElementInfo(typeof(GroupShape))] [ChildElementInfo(typeof(GraphicFrame))] [ChildElementInfo(typeof(ConnectionShape))] [ChildElementInfo(typeof(Picture))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing.ContentPart), FileFormatVersions.Office2010)] [SchemaAttr(12, "relSizeAnchor")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class RelativeAnchorSize : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the RelativeAnchorSize class. /// </summary> public RelativeAnchorSize() : base() { } /// <summary> /// Initializes a new instance of the RelativeAnchorSize class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public RelativeAnchorSize(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the RelativeAnchorSize class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public RelativeAnchorSize(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the RelativeAnchorSize class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public RelativeAnchorSize(string outerXml) : base(outerXml) { } /// <summary> /// <para>Starting Anchor Point.</para> /// <para>Represents the following element tag in the schema: cdr:from.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public FromAnchor FromAnchor { get => GetElement<FromAnchor>(); set => SetElement(value); } /// <summary> /// <para>Ending Anchor Point.</para> /// <para>Represents the following element tag in the schema: cdr:to.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public ToAnchor ToAnchor { get => GetElement<ToAnchor>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.FromAnchor), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.ToAnchor), 1, 1), new CompositeParticle(ParticleType.Group, 1, 1) { new CompositeParticle(ParticleType.Sequence, 1, 1) { new CompositeParticle(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Shape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.GroupShape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.GraphicFrame), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.ConnectionShape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Picture), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing.ContentPart), 1, 1, version: FileFormatVersions.Office2010) } } } }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<RelativeAnchorSize>(deep); } /// <summary> /// <para>Absolute Anchor Shape Size.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:absSizeAnchor.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>FromAnchor &lt;cdr:from></description></item> /// <item><description>Extent &lt;cdr:ext></description></item> /// <item><description>Shape &lt;cdr:sp></description></item> /// <item><description>GroupShape &lt;cdr:grpSp></description></item> /// <item><description>GraphicFrame &lt;cdr:graphicFrame></description></item> /// <item><description>ConnectionShape &lt;cdr:cxnSp></description></item> /// <item><description>Picture &lt;cdr:pic></description></item> /// <item><description>DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing.ContentPart &lt;cdr14:contentPart></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(FromAnchor))] [ChildElementInfo(typeof(Extent))] [ChildElementInfo(typeof(Shape))] [ChildElementInfo(typeof(GroupShape))] [ChildElementInfo(typeof(GraphicFrame))] [ChildElementInfo(typeof(ConnectionShape))] [ChildElementInfo(typeof(Picture))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing.ContentPart), FileFormatVersions.Office2010)] [SchemaAttr(12, "absSizeAnchor")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class AbsoluteAnchorSize : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the AbsoluteAnchorSize class. /// </summary> public AbsoluteAnchorSize() : base() { } /// <summary> /// Initializes a new instance of the AbsoluteAnchorSize class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AbsoluteAnchorSize(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AbsoluteAnchorSize class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AbsoluteAnchorSize(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AbsoluteAnchorSize class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public AbsoluteAnchorSize(string outerXml) : base(outerXml) { } /// <summary> /// <para>FromAnchor.</para> /// <para>Represents the following element tag in the schema: cdr:from.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public FromAnchor FromAnchor { get => GetElement<FromAnchor>(); set => SetElement(value); } /// <summary> /// <para>Shape Extent.</para> /// <para>Represents the following element tag in the schema: cdr:ext.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public Extent Extent { get => GetElement<Extent>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.FromAnchor), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Extent), 1, 1), new CompositeParticle(ParticleType.Group, 1, 1) { new CompositeParticle(ParticleType.Sequence, 1, 1) { new CompositeParticle(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Shape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.GroupShape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.GraphicFrame), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.ConnectionShape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Picture), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing.ContentPart), 1, 1, version: FileFormatVersions.Office2010) } } } }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AbsoluteAnchorSize>(deep); } /// <summary> /// <para>Shape Definition.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:sp.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualShapeProperties &lt;cdr:nvSpPr></description></item> /// <item><description>ShapeProperties &lt;cdr:spPr></description></item> /// <item><description>Style &lt;cdr:style></description></item> /// <item><description>TextBody &lt;cdr:txBody></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualShapeProperties))] [ChildElementInfo(typeof(ShapeProperties))] [ChildElementInfo(typeof(Style))] [ChildElementInfo(typeof(TextBody))] [SchemaAttr(12, "sp")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Shape : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Shape class. /// </summary> public Shape() : base() { } /// <summary> /// Initializes a new instance of the Shape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Shape(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Shape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Shape(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Shape class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Shape(string outerXml) : base(outerXml) { } /// <summary> /// <para>Reference to Custom Function</para> /// <para>Represents the following attribute in the schema: macro</para> /// </summary> [SchemaAttr(0, "macro")] [Index(0)] public StringValue Macro { get; set; } /// <summary> /// <para>Text Link</para> /// <para>Represents the following attribute in the schema: textlink</para> /// </summary> [SchemaAttr(0, "textlink")] [Index(1)] public StringValue TextLink { get; set; } /// <summary> /// <para>Lock Text</para> /// <para>Represents the following attribute in the schema: fLocksText</para> /// </summary> [SchemaAttr(0, "fLocksText")] [Index(2)] public BooleanValue LockText { get; set; } /// <summary> /// <para>Publish to Server</para> /// <para>Represents the following attribute in the schema: fPublished</para> /// </summary> [SchemaAttr(0, "fPublished")] [Index(3)] public BooleanValue Published { get; set; } /// <summary> /// <para>Non-Visual Shape Properties.</para> /// <para>Represents the following element tag in the schema: cdr:nvSpPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualShapeProperties NonVisualShapeProperties { get => GetElement<NonVisualShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>Shape Properties.</para> /// <para>Represents the following element tag in the schema: cdr:spPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public ShapeProperties ShapeProperties { get => GetElement<ShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>Shape Style.</para> /// <para>Represents the following element tag in the schema: cdr:style.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public Style Style { get => GetElement<Style>(); set => SetElement(value); } /// <summary> /// <para>Shape Text Body.</para> /// <para>Represents the following element tag in the schema: cdr:txBody.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public TextBody TextBody { get => GetElement<TextBody>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualShapeProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.ShapeProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Style), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.TextBody), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Shape>(deep); } /// <summary> /// <para>Group Shape.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:grpSp.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualGroupShapeProperties &lt;cdr:nvGrpSpPr></description></item> /// <item><description>GroupShapeProperties &lt;cdr:grpSpPr></description></item> /// <item><description>Shape &lt;cdr:sp></description></item> /// <item><description>GroupShape &lt;cdr:grpSp></description></item> /// <item><description>GraphicFrame &lt;cdr:graphicFrame></description></item> /// <item><description>ConnectionShape &lt;cdr:cxnSp></description></item> /// <item><description>Picture &lt;cdr:pic></description></item> /// <item><description>DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing.ContentPart &lt;cdr14:contentPart></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualGroupShapeProperties))] [ChildElementInfo(typeof(GroupShapeProperties))] [ChildElementInfo(typeof(Shape))] [ChildElementInfo(typeof(GroupShape))] [ChildElementInfo(typeof(GraphicFrame))] [ChildElementInfo(typeof(ConnectionShape))] [ChildElementInfo(typeof(Picture))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing.ContentPart), FileFormatVersions.Office2010)] [SchemaAttr(12, "grpSp")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class GroupShape : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the GroupShape class. /// </summary> public GroupShape() : base() { } /// <summary> /// Initializes a new instance of the GroupShape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShape(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShape(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShape class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public GroupShape(string outerXml) : base(outerXml) { } /// <summary> /// <para>Non-Visual Group Shape Properties.</para> /// <para>Represents the following element tag in the schema: cdr:nvGrpSpPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualGroupShapeProperties NonVisualGroupShapeProperties { get => GetElement<NonVisualGroupShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>Group Shape Properties.</para> /// <para>Represents the following element tag in the schema: cdr:grpSpPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public GroupShapeProperties GroupShapeProperties { get => GetElement<GroupShapeProperties>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualGroupShapeProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.GroupShapeProperties), 1, 1), new CompositeParticle(ParticleType.Choice, 0, 0) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Shape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.GroupShape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.GraphicFrame), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.ConnectionShape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Picture), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office2010.Drawing.ChartDrawing.ContentPart), 1, 1, version: FileFormatVersions.Office2010) } }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<GroupShape>(deep); } /// <summary> /// <para>Graphic Frame.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:graphicFrame.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualGraphicFrameProperties &lt;cdr:nvGraphicFramePr></description></item> /// <item><description>Transform &lt;cdr:xfrm></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Graphic &lt;a:graphic></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualGraphicFrameProperties))] [ChildElementInfo(typeof(Transform))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Graphic))] [SchemaAttr(12, "graphicFrame")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class GraphicFrame : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the GraphicFrame class. /// </summary> public GraphicFrame() : base() { } /// <summary> /// Initializes a new instance of the GraphicFrame class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GraphicFrame(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GraphicFrame class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GraphicFrame(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GraphicFrame class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public GraphicFrame(string outerXml) : base(outerXml) { } /// <summary> /// <para>Reference to Custom Function</para> /// <para>Represents the following attribute in the schema: macro</para> /// </summary> [SchemaAttr(0, "macro")] [Index(0)] public StringValue Macro { get; set; } /// <summary> /// <para>Publish To Server</para> /// <para>Represents the following attribute in the schema: fPublished</para> /// </summary> [SchemaAttr(0, "fPublished")] [Index(1)] public BooleanValue Published { get; set; } /// <summary> /// <para>Non-Visual Graphic Frame Properties.</para> /// <para>Represents the following element tag in the schema: cdr:nvGraphicFramePr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualGraphicFrameProperties NonVisualGraphicFrameProperties { get => GetElement<NonVisualGraphicFrameProperties>(); set => SetElement(value); } /// <summary> /// <para>Graphic Frame Transform.</para> /// <para>Represents the following element tag in the schema: cdr:xfrm.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public Transform Transform { get => GetElement<Transform>(); set => SetElement(value); } /// <summary> /// <para>Graphical Object.</para> /// <para>Represents the following element tag in the schema: a:graphic.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.Graphic Graphic { get => GetElement<DocumentFormat.OpenXml.Drawing.Graphic>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualGraphicFrameProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Transform), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Graphic), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<GraphicFrame>(deep); } /// <summary> /// <para>Connection Shape.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:cxnSp.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualConnectorShapeDrawingProperties &lt;cdr:nvCxnSpPr></description></item> /// <item><description>ShapeProperties &lt;cdr:spPr></description></item> /// <item><description>Style &lt;cdr:style></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualConnectorShapeDrawingProperties))] [ChildElementInfo(typeof(ShapeProperties))] [ChildElementInfo(typeof(Style))] [SchemaAttr(12, "cxnSp")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ConnectionShape : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the ConnectionShape class. /// </summary> public ConnectionShape() : base() { } /// <summary> /// Initializes a new instance of the ConnectionShape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ConnectionShape(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ConnectionShape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ConnectionShape(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ConnectionShape class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ConnectionShape(string outerXml) : base(outerXml) { } /// <summary> /// <para>Reference to Custom Function</para> /// <para>Represents the following attribute in the schema: macro</para> /// </summary> [SchemaAttr(0, "macro")] [Index(0)] public StringValue Macro { get; set; } /// <summary> /// <para>Publish to Server</para> /// <para>Represents the following attribute in the schema: fPublished</para> /// </summary> [SchemaAttr(0, "fPublished")] [Index(1)] public BooleanValue Published { get; set; } /// <summary> /// <para>Connector Non Visual Properties.</para> /// <para>Represents the following element tag in the schema: cdr:nvCxnSpPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualConnectorShapeDrawingProperties NonVisualConnectorShapeDrawingProperties { get => GetElement<NonVisualConnectorShapeDrawingProperties>(); set => SetElement(value); } /// <summary> /// <para>Shape Properties.</para> /// <para>Represents the following element tag in the schema: cdr:spPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public ShapeProperties ShapeProperties { get => GetElement<ShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>Connection Shape Style.</para> /// <para>Represents the following element tag in the schema: cdr:style.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public Style Style { get => GetElement<Style>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualConnectorShapeDrawingProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.ShapeProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Style), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ConnectionShape>(deep); } /// <summary> /// <para>Defines the Picture Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:pic.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualPictureProperties &lt;cdr:nvPicPr></description></item> /// <item><description>BlipFill &lt;cdr:blipFill></description></item> /// <item><description>ShapeProperties &lt;cdr:spPr></description></item> /// <item><description>Style &lt;cdr:style></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualPictureProperties))] [ChildElementInfo(typeof(BlipFill))] [ChildElementInfo(typeof(ShapeProperties))] [ChildElementInfo(typeof(Style))] [SchemaAttr(12, "pic")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Picture : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Picture class. /// </summary> public Picture() : base() { } /// <summary> /// Initializes a new instance of the Picture class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Picture(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Picture class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Picture(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Picture class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Picture(string outerXml) : base(outerXml) { } /// <summary> /// <para>Reference to Custom Function</para> /// <para>Represents the following attribute in the schema: macro</para> /// </summary> [SchemaAttr(0, "macro")] [Index(0)] public StringValue Macro { get; set; } /// <summary> /// <para>Publish to Server</para> /// <para>Represents the following attribute in the schema: fPublished</para> /// </summary> [SchemaAttr(0, "fPublished")] [Index(1)] public BooleanValue Published { get; set; } /// <summary> /// <para>Non-Visual Picture Properties.</para> /// <para>Represents the following element tag in the schema: cdr:nvPicPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualPictureProperties NonVisualPictureProperties { get => GetElement<NonVisualPictureProperties>(); set => SetElement(value); } /// <summary> /// <para>Picture Fill.</para> /// <para>Represents the following element tag in the schema: cdr:blipFill.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public BlipFill BlipFill { get => GetElement<BlipFill>(); set => SetElement(value); } /// <summary> /// <para>ShapeProperties.</para> /// <para>Represents the following element tag in the schema: cdr:spPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public ShapeProperties ShapeProperties { get => GetElement<ShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>Style.</para> /// <para>Represents the following element tag in the schema: cdr:style.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public Style Style { get => GetElement<Style>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualPictureProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.BlipFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.ShapeProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.Style), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Picture>(deep); } /// <summary> /// <para>Chart Non Visual Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:cNvPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.HyperlinkOnClick &lt;a:hlinkClick></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.HyperlinkOnHover &lt;a:hlinkHover></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.HyperlinkOnClick))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.HyperlinkOnHover))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList))] [SchemaAttr(12, "cNvPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualDrawingProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualDrawingProperties class. /// </summary> public NonVisualDrawingProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualDrawingProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualDrawingProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualDrawingProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualDrawingProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>id</para> /// <para>Represents the following attribute in the schema: id</para> /// </summary> [RequiredValidator()] [SchemaAttr(0, "id")] [Index(0)] public UInt32Value Id { get; set; } /// <summary> /// <para>name</para> /// <para>Represents the following attribute in the schema: name</para> /// </summary> [RequiredValidator()] [SchemaAttr(0, "name")] [Index(1)] public StringValue Name { get; set; } /// <summary> /// <para>descr</para> /// <para>Represents the following attribute in the schema: descr</para> /// </summary> [SchemaAttr(0, "descr")] [Index(2)] public StringValue Description { get; set; } /// <summary> /// <para>hidden</para> /// <para>Represents the following attribute in the schema: hidden</para> /// </summary> [SchemaAttr(0, "hidden")] [Index(3)] public BooleanValue Hidden { get; set; } /// <summary> /// <para>title</para> /// <para>Represents the following attribute in the schema: title</para> /// </summary> [SchemaAttr(0, "title")] [Index(4)] public StringValue Title { get; set; } /// <summary> /// <para>HyperlinkOnClick.</para> /// <para>Represents the following element tag in the schema: a:hlinkClick.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.HyperlinkOnClick HyperlinkOnClick { get => GetElement<DocumentFormat.OpenXml.Drawing.HyperlinkOnClick>(); set => SetElement(value); } /// <summary> /// <para>HyperlinkOnHover.</para> /// <para>Represents the following element tag in the schema: a:hlinkHover.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.HyperlinkOnHover HyperlinkOnHover { get => GetElement<DocumentFormat.OpenXml.Drawing.HyperlinkOnHover>(); set => SetElement(value); } /// <summary> /// <para>NonVisualDrawingPropertiesExtensionList.</para> /// <para>Represents the following element tag in the schema: a:extLst.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList NonVisualDrawingPropertiesExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.HyperlinkOnClick), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.HyperlinkOnHover), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualDrawingProperties>(deep); } /// <summary> /// <para>Non-Visual Shape Drawing Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:cNvSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.ShapeLocks &lt;a:spLocks></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.ShapeLocks))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList))] [SchemaAttr(12, "cNvSpPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualShapeDrawingProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualShapeDrawingProperties class. /// </summary> public NonVisualShapeDrawingProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualShapeDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualShapeDrawingProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualShapeDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualShapeDrawingProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualShapeDrawingProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualShapeDrawingProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Text Box</para> /// <para>Represents the following attribute in the schema: txBox</para> /// </summary> [SchemaAttr(0, "txBox")] [Index(0)] public BooleanValue TextBox { get; set; } /// <summary> /// <para>Shape Locks.</para> /// <para>Represents the following element tag in the schema: a:spLocks.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.ShapeLocks ShapeLocks { get => GetElement<DocumentFormat.OpenXml.Drawing.ShapeLocks>(); set => SetElement(value); } /// <summary> /// <para>ExtensionList.</para> /// <para>Represents the following element tag in the schema: a:extLst.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.ExtensionList ExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.ExtensionList>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ShapeLocks), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualShapeDrawingProperties>(deep); } /// <summary> /// <para>Non-Visual Shape Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:nvSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualDrawingProperties &lt;cdr:cNvPr></description></item> /// <item><description>NonVisualShapeDrawingProperties &lt;cdr:cNvSpPr></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualDrawingProperties))] [ChildElementInfo(typeof(NonVisualShapeDrawingProperties))] [SchemaAttr(12, "nvSpPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualShapeProperties class. /// </summary> public NonVisualShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualShapeProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Chart Non Visual Properties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualDrawingProperties NonVisualDrawingProperties { get => GetElement<NonVisualDrawingProperties>(); set => SetElement(value); } /// <summary> /// <para>Non-Visual Shape Drawing Properties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvSpPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualShapeDrawingProperties NonVisualShapeDrawingProperties { get => GetElement<NonVisualShapeDrawingProperties>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualDrawingProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualShapeDrawingProperties), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualShapeProperties>(deep); } /// <summary> /// <para>Shape Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:spPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.Transform2D &lt;a:xfrm></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.CustomGeometry &lt;a:custGeom></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.PresetGeometry &lt;a:prstGeom></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.NoFill &lt;a:noFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.SolidFill &lt;a:solidFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.GradientFill &lt;a:gradFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.BlipFill &lt;a:blipFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.PatternFill &lt;a:pattFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.GroupFill &lt;a:grpFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Outline &lt;a:ln></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectList &lt;a:effectLst></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectDag &lt;a:effectDag></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Scene3DType &lt;a:scene3d></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Shape3DType &lt;a:sp3d></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ShapePropertiesExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Transform2D))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.CustomGeometry))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.PresetGeometry))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.NoFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.SolidFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.GradientFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.BlipFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.PatternFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.GroupFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Outline))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.EffectList))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.EffectDag))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Scene3DType))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Shape3DType))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.ShapePropertiesExtensionList))] [SchemaAttr(12, "spPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the ShapeProperties class. /// </summary> public ShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the ShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ShapeProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Black and White Mode</para> /// <para>Represents the following attribute in the schema: bwMode</para> /// </summary> [StringValidator(IsToken = true)] [SchemaAttr(0, "bwMode")] [Index(0)] public EnumValue<DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues> BlackWhiteMode { get; set; } /// <summary> /// <para>2D Transform for Individual Objects.</para> /// <para>Represents the following element tag in the schema: a:xfrm.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.Transform2D Transform2D { get => GetElement<DocumentFormat.OpenXml.Drawing.Transform2D>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Transform2D), 0, 1), new CompositeParticle(ParticleType.Group, 0, 1) { new CompositeParticle(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.CustomGeometry), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.PresetGeometry), 1, 1) } }, new CompositeParticle(ParticleType.Group, 0, 1) { new CompositeParticle(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NoFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.SolidFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GradientFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.BlipFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.PatternFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GroupFill), 1, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Outline), 0, 1), new CompositeParticle(ParticleType.Group, 0, 1) { new CompositeParticle(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectList), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectDag), 1, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Scene3DType), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Shape3DType), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ShapePropertiesExtensionList), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ShapeProperties>(deep); } /// <summary> /// <para>Shape Style.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:style.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.LineReference &lt;a:lnRef></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.FillReference &lt;a:fillRef></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectReference &lt;a:effectRef></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.FontReference &lt;a:fontRef></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.LineReference))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.FillReference))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.EffectReference))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.FontReference))] [SchemaAttr(12, "style")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Style : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Style class. /// </summary> public Style() : base() { } /// <summary> /// Initializes a new instance of the Style class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Style(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Style class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Style(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Style class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Style(string outerXml) : base(outerXml) { } /// <summary> /// <para>LineReference.</para> /// <para>Represents the following element tag in the schema: a:lnRef.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.LineReference LineReference { get => GetElement<DocumentFormat.OpenXml.Drawing.LineReference>(); set => SetElement(value); } /// <summary> /// <para>FillReference.</para> /// <para>Represents the following element tag in the schema: a:fillRef.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.FillReference FillReference { get => GetElement<DocumentFormat.OpenXml.Drawing.FillReference>(); set => SetElement(value); } /// <summary> /// <para>EffectReference.</para> /// <para>Represents the following element tag in the schema: a:effectRef.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.EffectReference EffectReference { get => GetElement<DocumentFormat.OpenXml.Drawing.EffectReference>(); set => SetElement(value); } /// <summary> /// <para>Font Reference.</para> /// <para>Represents the following element tag in the schema: a:fontRef.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.FontReference FontReference { get => GetElement<DocumentFormat.OpenXml.Drawing.FontReference>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.LineReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.FillReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.FontReference), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Style>(deep); } /// <summary> /// <para>Shape Text Body.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:txBody.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.BodyProperties &lt;a:bodyPr></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ListStyle &lt;a:lstStyle></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Paragraph &lt;a:p></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.BodyProperties))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.ListStyle))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Paragraph))] [SchemaAttr(12, "txBody")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class TextBody : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the TextBody class. /// </summary> public TextBody() : base() { } /// <summary> /// Initializes a new instance of the TextBody class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TextBody(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TextBody class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TextBody(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TextBody class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public TextBody(string outerXml) : base(outerXml) { } /// <summary> /// <para>Body Properties.</para> /// <para>Represents the following element tag in the schema: a:bodyPr.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.BodyProperties BodyProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.BodyProperties>(); set => SetElement(value); } /// <summary> /// <para>Text List Styles.</para> /// <para>Represents the following element tag in the schema: a:lstStyle.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.ListStyle ListStyle { get => GetElement<DocumentFormat.OpenXml.Drawing.ListStyle>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.BodyProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ListStyle), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Paragraph), 1, 0) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<TextBody>(deep); } /// <summary> /// <para>Non-Visual Connection Shape Drawing Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:cNvCxnSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.ConnectionShapeLocks &lt;a:cxnSpLocks></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.StartConnection &lt;a:stCxn></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EndConnection &lt;a:endCxn></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.ConnectionShapeLocks))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.StartConnection))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.EndConnection))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList))] [SchemaAttr(12, "cNvCxnSpPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualConnectionShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualConnectionShapeProperties class. /// </summary> public NonVisualConnectionShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualConnectionShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualConnectionShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualConnectionShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualConnectionShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualConnectionShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualConnectionShapeProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Connection Shape Locks.</para> /// <para>Represents the following element tag in the schema: a:cxnSpLocks.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.ConnectionShapeLocks ConnectionShapeLocks { get => GetElement<DocumentFormat.OpenXml.Drawing.ConnectionShapeLocks>(); set => SetElement(value); } /// <summary> /// <para>Connection Start.</para> /// <para>Represents the following element tag in the schema: a:stCxn.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.StartConnection StartConnection { get => GetElement<DocumentFormat.OpenXml.Drawing.StartConnection>(); set => SetElement(value); } /// <summary> /// <para>Connection End.</para> /// <para>Represents the following element tag in the schema: a:endCxn.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.EndConnection EndConnection { get => GetElement<DocumentFormat.OpenXml.Drawing.EndConnection>(); set => SetElement(value); } /// <summary> /// <para>ExtensionList.</para> /// <para>Represents the following element tag in the schema: a:extLst.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.ExtensionList ExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.ExtensionList>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ConnectionShapeLocks), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.StartConnection), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EndConnection), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualConnectionShapeProperties>(deep); } /// <summary> /// <para>Connector Non Visual Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:nvCxnSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualDrawingProperties &lt;cdr:cNvPr></description></item> /// <item><description>NonVisualConnectionShapeProperties &lt;cdr:cNvCxnSpPr></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualDrawingProperties))] [ChildElementInfo(typeof(NonVisualConnectionShapeProperties))] [SchemaAttr(12, "nvCxnSpPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualConnectorShapeDrawingProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualConnectorShapeDrawingProperties class. /// </summary> public NonVisualConnectorShapeDrawingProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualConnectorShapeDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualConnectorShapeDrawingProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualConnectorShapeDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualConnectorShapeDrawingProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualConnectorShapeDrawingProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualConnectorShapeDrawingProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Chart Non Visual Properties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualDrawingProperties NonVisualDrawingProperties { get => GetElement<NonVisualDrawingProperties>(); set => SetElement(value); } /// <summary> /// <para>Non-Visual Connection Shape Drawing Properties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvCxnSpPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualConnectionShapeProperties NonVisualConnectionShapeProperties { get => GetElement<NonVisualConnectionShapeProperties>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualDrawingProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualConnectionShapeProperties), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualConnectorShapeDrawingProperties>(deep); } /// <summary> /// <para>Non-Visual Picture Drawing Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:cNvPicPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.PictureLocks &lt;a:picLocks></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.NonVisualPicturePropertiesExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.PictureLocks))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.NonVisualPicturePropertiesExtensionList))] [SchemaAttr(12, "cNvPicPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualPictureDrawingProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualPictureDrawingProperties class. /// </summary> public NonVisualPictureDrawingProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualPictureDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualPictureDrawingProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualPictureDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualPictureDrawingProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualPictureDrawingProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualPictureDrawingProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>preferRelativeResize</para> /// <para>Represents the following attribute in the schema: preferRelativeResize</para> /// </summary> [SchemaAttr(0, "preferRelativeResize")] [Index(0)] public BooleanValue PreferRelativeResize { get; set; } /// <summary> /// <para>PictureLocks.</para> /// <para>Represents the following element tag in the schema: a:picLocks.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.PictureLocks PictureLocks { get => GetElement<DocumentFormat.OpenXml.Drawing.PictureLocks>(); set => SetElement(value); } /// <summary> /// <para>NonVisualPicturePropertiesExtensionList.</para> /// <para>Represents the following element tag in the schema: a:extLst.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.NonVisualPicturePropertiesExtensionList NonVisualPicturePropertiesExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.NonVisualPicturePropertiesExtensionList>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.PictureLocks), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NonVisualPicturePropertiesExtensionList), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualPictureDrawingProperties>(deep); } /// <summary> /// <para>Non-Visual Picture Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:nvPicPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualDrawingProperties &lt;cdr:cNvPr></description></item> /// <item><description>NonVisualPictureDrawingProperties &lt;cdr:cNvPicPr></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualDrawingProperties))] [ChildElementInfo(typeof(NonVisualPictureDrawingProperties))] [SchemaAttr(12, "nvPicPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualPictureProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualPictureProperties class. /// </summary> public NonVisualPictureProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualPictureProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualPictureProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualPictureProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualPictureProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualPictureProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualPictureProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>NonVisualDrawingProperties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualDrawingProperties NonVisualDrawingProperties { get => GetElement<NonVisualDrawingProperties>(); set => SetElement(value); } /// <summary> /// <para>Non-Visual Picture Drawing Properties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvPicPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualPictureDrawingProperties NonVisualPictureDrawingProperties { get => GetElement<NonVisualPictureDrawingProperties>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualDrawingProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualPictureDrawingProperties), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualPictureProperties>(deep); } /// <summary> /// <para>Picture Fill.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:blipFill.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.Blip &lt;a:blip></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.SourceRectangle &lt;a:srcRect></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Tile &lt;a:tile></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Stretch &lt;a:stretch></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Blip))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.SourceRectangle))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Tile))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Stretch))] [SchemaAttr(12, "blipFill")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class BlipFill : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the BlipFill class. /// </summary> public BlipFill() : base() { } /// <summary> /// Initializes a new instance of the BlipFill class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BlipFill(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BlipFill class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BlipFill(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BlipFill class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public BlipFill(string outerXml) : base(outerXml) { } /// <summary> /// <para>DPI Setting</para> /// <para>Represents the following attribute in the schema: dpi</para> /// </summary> [SchemaAttr(0, "dpi")] [Index(0)] public UInt32Value Dpi { get; set; } /// <summary> /// <para>Rotate With Shape</para> /// <para>Represents the following attribute in the schema: rotWithShape</para> /// </summary> [SchemaAttr(0, "rotWithShape")] [Index(1)] public BooleanValue RotateWithShape { get; set; } /// <summary> /// <para>Blip.</para> /// <para>Represents the following element tag in the schema: a:blip.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.Blip Blip { get => GetElement<DocumentFormat.OpenXml.Drawing.Blip>(); set => SetElement(value); } /// <summary> /// <para>Source Rectangle.</para> /// <para>Represents the following element tag in the schema: a:srcRect.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.SourceRectangle SourceRectangle { get => GetElement<DocumentFormat.OpenXml.Drawing.SourceRectangle>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Blip), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.SourceRectangle), 0, 1), new CompositeParticle(ParticleType.Group, 0, 1) { new CompositeParticle(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Tile), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Stretch), 1, 1) } } }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<BlipFill>(deep); } /// <summary> /// <para>Non-Visual Graphic Frame Drawing Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:cNvGraphicFramePr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.GraphicFrameLocks &lt;a:graphicFrameLocks></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.GraphicFrameLocks))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList))] [SchemaAttr(12, "cNvGraphicFramePr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualGraphicFrameDrawingProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualGraphicFrameDrawingProperties class. /// </summary> public NonVisualGraphicFrameDrawingProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualGraphicFrameDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGraphicFrameDrawingProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGraphicFrameDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGraphicFrameDrawingProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGraphicFrameDrawingProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualGraphicFrameDrawingProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Graphic Frame Locks.</para> /// <para>Represents the following element tag in the schema: a:graphicFrameLocks.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.GraphicFrameLocks GraphicFrameLocks { get => GetElement<DocumentFormat.OpenXml.Drawing.GraphicFrameLocks>(); set => SetElement(value); } /// <summary> /// <para>ExtensionList.</para> /// <para>Represents the following element tag in the schema: a:extLst.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.ExtensionList ExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.ExtensionList>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GraphicFrameLocks), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualGraphicFrameDrawingProperties>(deep); } /// <summary> /// <para>Non-Visual Graphic Frame Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:nvGraphicFramePr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualDrawingProperties &lt;cdr:cNvPr></description></item> /// <item><description>NonVisualGraphicFrameDrawingProperties &lt;cdr:cNvGraphicFramePr></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualDrawingProperties))] [ChildElementInfo(typeof(NonVisualGraphicFrameDrawingProperties))] [SchemaAttr(12, "nvGraphicFramePr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualGraphicFrameProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualGraphicFrameProperties class. /// </summary> public NonVisualGraphicFrameProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualGraphicFrameProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGraphicFrameProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGraphicFrameProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGraphicFrameProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGraphicFrameProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualGraphicFrameProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Non-Visual Drawing Properties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualDrawingProperties NonVisualDrawingProperties { get => GetElement<NonVisualDrawingProperties>(); set => SetElement(value); } /// <summary> /// <para>Non-Visual Graphic Frame Drawing Properties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvGraphicFramePr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualGraphicFrameDrawingProperties NonVisualGraphicFrameDrawingProperties { get => GetElement<NonVisualGraphicFrameDrawingProperties>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualDrawingProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualGraphicFrameDrawingProperties), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualGraphicFrameProperties>(deep); } /// <summary> /// <para>Graphic Frame Transform.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:xfrm.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.Offset &lt;a:off></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Extents &lt;a:ext></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Offset))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Extents))] [SchemaAttr(12, "xfrm")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Transform : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Transform class. /// </summary> public Transform() : base() { } /// <summary> /// Initializes a new instance of the Transform class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Transform(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Transform class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Transform(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Transform class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Transform(string outerXml) : base(outerXml) { } /// <summary> /// <para>Rotation</para> /// <para>Represents the following attribute in the schema: rot</para> /// </summary> [SchemaAttr(0, "rot")] [Index(0)] public Int32Value Rotation { get; set; } /// <summary> /// <para>Horizontal Flip</para> /// <para>Represents the following attribute in the schema: flipH</para> /// </summary> [SchemaAttr(0, "flipH")] [Index(1)] public BooleanValue HorizontalFlip { get; set; } /// <summary> /// <para>Vertical Flip</para> /// <para>Represents the following attribute in the schema: flipV</para> /// </summary> [SchemaAttr(0, "flipV")] [Index(2)] public BooleanValue VerticalFlip { get; set; } /// <summary> /// <para>Offset.</para> /// <para>Represents the following element tag in the schema: a:off.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.Offset Offset { get => GetElement<DocumentFormat.OpenXml.Drawing.Offset>(); set => SetElement(value); } /// <summary> /// <para>Extents.</para> /// <para>Represents the following element tag in the schema: a:ext.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.Extents Extents { get => GetElement<DocumentFormat.OpenXml.Drawing.Extents>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Offset), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Extents), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Transform>(deep); } /// <summary> /// <para>Non-Visual Group Shape Drawing Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:cNvGrpSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.GroupShapeLocks &lt;a:grpSpLocks></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.GroupShapeLocks))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList))] [SchemaAttr(12, "cNvGrpSpPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualGroupShapeDrawingProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualGroupShapeDrawingProperties class. /// </summary> public NonVisualGroupShapeDrawingProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualGroupShapeDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGroupShapeDrawingProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGroupShapeDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGroupShapeDrawingProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGroupShapeDrawingProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualGroupShapeDrawingProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>GroupShapeLocks.</para> /// <para>Represents the following element tag in the schema: a:grpSpLocks.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.GroupShapeLocks GroupShapeLocks { get => GetElement<DocumentFormat.OpenXml.Drawing.GroupShapeLocks>(); set => SetElement(value); } /// <summary> /// <para>NonVisualGroupDrawingShapePropsExtensionList.</para> /// <para>Represents the following element tag in the schema: a:extLst.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList NonVisualGroupDrawingShapePropsExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GroupShapeLocks), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualGroupShapeDrawingProperties>(deep); } /// <summary> /// <para>Relative X Coordinate.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:x.</para> /// </summary> [NumberValidator(MinInclusive = 0L, MaxInclusive = 1L, SimpleType = typeof(DoubleValue))] [SchemaAttr(12, "x")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class XPosition : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the XPosition class. /// </summary> public XPosition() : base() { } /// <summary> /// Initializes a new instance of the XPosition class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public XPosition(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new DoubleValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<XPosition>(deep); } /// <summary> /// <para>Relative Y Coordinate.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:y.</para> /// </summary> [NumberValidator(MinInclusive = 0L, MaxInclusive = 1L, SimpleType = typeof(DoubleValue))] [SchemaAttr(12, "y")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class YPosition : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the YPosition class. /// </summary> public YPosition() : base() { } /// <summary> /// Initializes a new instance of the YPosition class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public YPosition(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new DoubleValue { InnerText = text }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<YPosition>(deep); } /// <summary> /// <para>Starting Anchor Point.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:from.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>XPosition &lt;cdr:x></description></item> /// <item><description>YPosition &lt;cdr:y></description></item> /// </list> /// </remark> [SchemaAttr(12, "from")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class FromAnchor : MarkerType { /// <summary> /// Initializes a new instance of the FromAnchor class. /// </summary> public FromAnchor() : base() { } /// <summary> /// Initializes a new instance of the FromAnchor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FromAnchor(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FromAnchor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public FromAnchor(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the FromAnchor class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public FromAnchor(string outerXml) : base(outerXml) { } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.XPosition), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.YPosition), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<FromAnchor>(deep); } /// <summary> /// <para>Ending Anchor Point.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:to.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>XPosition &lt;cdr:x></description></item> /// <item><description>YPosition &lt;cdr:y></description></item> /// </list> /// </remark> [SchemaAttr(12, "to")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class ToAnchor : MarkerType { /// <summary> /// Initializes a new instance of the ToAnchor class. /// </summary> public ToAnchor() : base() { } /// <summary> /// Initializes a new instance of the ToAnchor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ToAnchor(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ToAnchor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ToAnchor(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ToAnchor class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ToAnchor(string outerXml) : base(outerXml) { } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.XPosition), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.YPosition), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ToAnchor>(deep); } /// <summary> /// <para>Defines the MarkerType Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is :.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>XPosition &lt;cdr:x></description></item> /// <item><description>YPosition &lt;cdr:y></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(XPosition))] [ChildElementInfo(typeof(YPosition))] public abstract partial class MarkerType : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the MarkerType class. /// </summary> protected MarkerType() : base() { } /// <summary> /// Initializes a new instance of the MarkerType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected MarkerType(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the MarkerType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected MarkerType(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the MarkerType class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> protected MarkerType(string outerXml) : base(outerXml) { } /// <summary> /// <para>Relative X Coordinate.</para> /// <para>Represents the following element tag in the schema: cdr:x.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public XPosition XPosition { get => GetElement<XPosition>(); set => SetElement(value); } /// <summary> /// <para>Relative Y Coordinate.</para> /// <para>Represents the following element tag in the schema: cdr:y.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public YPosition YPosition { get => GetElement<YPosition>(); set => SetElement(value); } } /// <summary> /// <para>Shape Extent.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:ext.</para> /// </summary> [SchemaAttr(12, "ext")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class Extent : OpenXmlLeafElement { /// <summary> /// Initializes a new instance of the Extent class. /// </summary> public Extent() : base() { } /// <summary> /// <para>Extent Length</para> /// <para>Represents the following attribute in the schema: cx</para> /// </summary> [RequiredValidator()] [NumberValidator(MinInclusive = 0L, MaxInclusive = 2147483647L)] [SchemaAttr(0, "cx")] [Index(0)] public Int64Value Cx { get; set; } /// <summary> /// <para>Extent Width</para> /// <para>Represents the following attribute in the schema: cy</para> /// </summary> [RequiredValidator()] [NumberValidator(MinInclusive = 0L, MaxInclusive = 2147483647L)] [SchemaAttr(0, "cy")] [Index(1)] public Int64Value Cy { get; set; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Extent>(deep); } /// <summary> /// <para>Non-Visual Group Shape Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:nvGrpSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualDrawingProperties &lt;cdr:cNvPr></description></item> /// <item><description>NonVisualGroupShapeDrawingProperties &lt;cdr:cNvGrpSpPr></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(NonVisualDrawingProperties))] [ChildElementInfo(typeof(NonVisualGroupShapeDrawingProperties))] [SchemaAttr(12, "nvGrpSpPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class NonVisualGroupShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualGroupShapeProperties class. /// </summary> public NonVisualGroupShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualGroupShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGroupShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGroupShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGroupShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGroupShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualGroupShapeProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Chart Non Visual Properties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualDrawingProperties NonVisualDrawingProperties { get => GetElement<NonVisualDrawingProperties>(); set => SetElement(value); } /// <summary> /// <para>Non-Visual Group Shape Drawing Properties.</para> /// <para>Represents the following element tag in the schema: cdr:cNvGrpSpPr.</para> /// </summary> /// <remark> /// xmlns:cdr = http://schemas.openxmlformats.org/drawingml/2006/chartDrawing /// </remark> public NonVisualGroupShapeDrawingProperties NonVisualGroupShapeDrawingProperties { get => GetElement<NonVisualGroupShapeDrawingProperties>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualDrawingProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ChartDrawing.NonVisualGroupShapeDrawingProperties), 1, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualGroupShapeProperties>(deep); } /// <summary> /// <para>Group Shape Properties.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is cdr:grpSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.TransformGroup &lt;a:xfrm></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.NoFill &lt;a:noFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.SolidFill &lt;a:solidFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.GradientFill &lt;a:gradFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.BlipFill &lt;a:blipFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.PatternFill &lt;a:pattFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.GroupFill &lt;a:grpFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectList &lt;a:effectLst></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectDag &lt;a:effectDag></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Scene3DType &lt;a:scene3d></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.TransformGroup))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.NoFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.SolidFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.GradientFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.BlipFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.PatternFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.GroupFill))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.EffectList))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.EffectDag))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.Scene3DType))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList))] [SchemaAttr(12, "grpSpPr")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class GroupShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the GroupShapeProperties class. /// </summary> public GroupShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the GroupShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public GroupShapeProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Black and White Mode</para> /// <para>Represents the following attribute in the schema: bwMode</para> /// </summary> [StringValidator(IsToken = true)] [SchemaAttr(0, "bwMode")] [Index(0)] public EnumValue<DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues> BlackWhiteMode { get; set; } /// <summary> /// <para>2D Transform for Grouped Objects.</para> /// <para>Represents the following element tag in the schema: a:xfrm.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.TransformGroup TransformGroup { get => GetElement<DocumentFormat.OpenXml.Drawing.TransformGroup>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.TransformGroup), 0, 1), new CompositeParticle(ParticleType.Group, 0, 1) { new CompositeParticle(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NoFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.SolidFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GradientFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.BlipFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.PatternFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GroupFill), 1, 1) } }, new CompositeParticle(ParticleType.Group, 0, 1) { new CompositeParticle(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectList), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectDag), 1, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Scene3DType), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<GroupShapeProperties>(deep); } }
43.606133
165
0.634103
[ "MIT" ]
yangzhinong/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas_openxmlformats_org_drawingml_2006_chartDrawing.g.cs
127,986
C#
using System; using Administrator.Common; using Administrator.Database; using Administrator.Services; using Discord; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using Qmmands; namespace Administrator.Commands { public sealed class AdminCommandContext : CommandContext, IDisposable { private readonly LocalizationService _localization; public AdminCommandContext(SocketUserMessage message, string prefix, LocalizedLanguage language, IServiceProvider provider) : base(provider) { _localization = provider.GetRequiredService<LocalizationService>(); Client = provider.GetRequiredService<DiscordSocketClient>(); Message = message; Prefix = prefix; Database = new AdminDatabaseContext(provider); Language = language; } public DiscordSocketClient Client { get; } public SocketUser User => Message.Author; public SocketGuild Guild => (Message.Channel as SocketGuildChannel)?.Guild; public SocketUserMessage Message { get; } public ISocketMessageChannel Channel => Message.Channel; public bool IsPrivate => Message.Channel is IPrivateChannel; public string Prefix { get; } public AdminDatabaseContext Database { get; } public LocalizedLanguage Language { get; } public string Localize(string key, params object[] args) => _localization.Localize(Language, key, args); public void Dispose() { Database.Dispose(); } } }
30.471698
131
0.674303
[ "MIT" ]
Quahu/Administrator
Administrator/Commands/AdminCommandContext.cs
1,615
C#
using BEPUphysics.Entities; using BEPUphysics.Entities.Prefabs; using BEPUutilities; namespace BEPUphysicsDemos.Demos.Extras { /// <summary> /// Demo showing a tower of blocks being smashed by a sphere. /// </summary> public class IncomingDemo : StandardDemo { /// <summary> /// Constructs a new demo. /// </summary> /// <param name="game">Game owning this demo.</param> public IncomingDemo(DemosGame game) : base(game) { Entity toAdd; //Build the stack... for (int k = 1; k <= 12; k++) { if (k % 2 == 1) { toAdd = new Box(new Vector3(-3, k, 0), 1, 1, 7, 10); Space.Add(toAdd); toAdd = new Box(new Vector3(3, k, 0), 1, 1, 7, 10); Space.Add(toAdd); } else { toAdd = new Box(new Vector3(0, k, -3), 7, 1, 1, 10); Space.Add(toAdd); toAdd = new Box(new Vector3(0, k, 3), 7, 1, 1, 10); Space.Add(toAdd); } } //And then smash it! toAdd = new Sphere(new Vector3(0, 150, 0), 3, 100); Space.Add(toAdd); Space.Add(new Box(new Vector3(0, 0, 0), 10, 1m, 10)); game.Camera.Position = new Vector3(0, 6, 30); } /// <summary> /// Gets the name of the simulation. /// </summary> public override string Name { get { return "Incoming!"; } } } }
31.648148
73
0.42715
[ "MIT" ]
RossNordby/bepuphysics1int
BEPUphysicsDemos/Demos/Extras/IncomingDemo.cs
1,711
C#
using LinkedData.Helpers; using Sitecore.Data.Items; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VDS.RDF; namespace LinkedData { public class SitecoreNode { private readonly INode _node; private Item _sitecoreItem; public SitecoreNode(INode node) { _node = node; } public Item Item { get { if (_sitecoreItem == null) { _sitecoreItem = SitecoreTripleHelper.UriToItem(_node.ToString()); } return _sitecoreItem; } } } }
20.2
85
0.547383
[ "MIT" ]
Adamsimsy/Sitecore.CloudBlobStorageProvider
LinkedData/SitecoreNode.cs
709
C#
using Newbe.Mahua; using System.Collections.Generic; namespace Newbe.Mahua.Plugins.telegra { public class MyMenuProvider : IMahuaMenuProvider { public IEnumerable<MahuaMenu> GetMenus() { return new[] { new MahuaMenu { Id = "menu1", Text = "测试菜单1" }, new MahuaMenu { Id = "menu2", Text = "测试菜单2" }, }; } } }
21.423077
52
0.393178
[ "MIT" ]
FirmianaMarsili/QQBot-Pixiv
telegra/Newbe.Mahua.Plugins.telegra/MyMenuProvider.cs
575
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.OSS.Models { public class DeleteBucketLoggingRequest : TeaModel { /// <summary> /// BucketName /// </summary> [NameInMap("BucketName")] [Validation(Required=true, Pattern="[a-zA-Z0-9-_]+")] public string BucketName { get; set; } } }
20.363636
61
0.629464
[ "Apache-2.0" ]
18730298725/alibabacloud-oss-sdk
csharp/core/Models/DeleteBucketLoggingRequest.cs
448
C#
using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using Dapper; public class ProductRepository { private string connectionString; public ProductRepository() { connectionString = @"Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;"; } public IDbConnection Connection { get { return new SqlConnection(connectionString); } } public void Add(Product prod) { using (IDbConnection dbConnection = Connection) { string sQuery = "INSERT INTO Products (Name, Quantity, Price, netPrice, expiryDate, code, providerId, categoryId )" + " VALUES(@Name, @Quantity, @Price, @netPrice, @expiryDate, @code, @providerId, @categoryId)"; dbConnection.Open(); dbConnection.Execute(sQuery, prod); } } public IEnumerable<Product> GetAll() { using (IDbConnection dbConnection = Connection) { dbConnection.Open(); return dbConnection.Query<Product>("SELECT * FROM Products"); } } public Product GetByID(int id) { using (IDbConnection dbConnection = Connection) { string sQuery = "SELECT * FROM Products" + " WHERE ProductId = @Id"; dbConnection.Open(); return dbConnection.Query<Product>(sQuery, new { Id = id }).FirstOrDefault(); } } public void Delete(int id) { using (IDbConnection dbConnection = Connection) { string sQuery = "DELETE FROM Products" + " WHERE ProductId = @Id"; dbConnection.Open(); dbConnection.Execute(sQuery, new { Id = id }); } } public void Update(Product prod) { using (IDbConnection dbConnection = Connection) { string sQuery = "UPDATE Products SET Name = @Name," + " Quantity = @Quantity, Price= @Price," + " netPrice = @netPrice, expiryDate=@expiryDate, code= @code, providerId= @providerId, categoryId =@categoryId " + " WHERE ProductId = @ProductId"; dbConnection.Open(); dbConnection.Query(sQuery, prod); } } }
29.7
140
0.56271
[ "MIT" ]
phamhuyhoang95/online-store-dotnetcore
Database/RespositoryImpl/ProductRespository.cs
2,376
C#
using System; namespace BPNetwork { public static class IMath { private static readonly Random RANDOM = new Random(); public static double GaussianRandomDistributed { get { var u1 = RANDOM.NextDouble(); var u2 = RANDOM.NextDouble(); var randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2); return randStdNormal / 12.5663706144 + 0.5; } } public static float GaussianRandom(float min, float max) { return min + (max - min) * (float)GaussianRandomDistributed; } } }
25.464286
72
0.502104
[ "Apache-2.0" ]
WNJXYK/Tank_AI
Assets/Control/NeuralNetwork/IMath.cs
715
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Accord.MachineLearning; namespace ML.TypingClassifier.Models { public class Classification { public KMeansClusterCollection Clusters { get; internal set; } } }
21.846154
71
0.71831
[ "MIT" ]
joshuadeleon/typingclassifier
ML.TypingClassifier/Models/Classification.cs
286
C#
using System.Collections.Generic; namespace Amethyst.Subscription.Abstractions { public interface IStreamEvent { object Event { get; } DeserializationStatus Status { get; } IReadOnlyCollection<KeyValuePair<string, object>> Metadata { get; } } }
21.769231
75
0.689046
[ "Apache-2.0" ]
amethyst-pro/subscription
Amethyst.Subscription/src/Amethyst.Subscription.Abstractions/IStreamEvent.cs
283
C#
// 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 Silk.NET.Core.Attributes; #pragma warning disable 1591 namespace Silk.NET.OpenCL.Extensions.INTEL { [NativeName("Name", "cl_va_api_device_set_intel")] public enum VaApiDeviceSet : int { [NativeName("Name", "CL_PREFERRED_DEVICES_FOR_VA_API_INTEL")] PreferredDevicesForVAApi = 0x4095, [NativeName("Name", "CL_ALL_DEVICES_FOR_VA_API_INTEL")] AllDevicesForVAApi = 0x4096, } }
27.666667
71
0.722892
[ "MIT" ]
Ar37-rs/Silk.NET
src/OpenCL/Extensions/Silk.NET.OpenCL.Extensions.INTEL/Enums/VaApiDeviceSet.gen.cs
581
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SampleCsCefSharpVue.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SampleCsCefSharpVue.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> internal static System.Drawing.Icon icon { get { object obj = ResourceManager.GetObject("icon", resourceCulture); return ((System.Drawing.Icon)(obj)); } } } }
42.891892
185
0.603655
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
fraguada/SampleCsCefSharpVue
SampleCsCefSharpVuePlugin/Properties/Resources.Designer.cs
3,176
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary>Just an interface to call the relevant game session methods</summary> public class Overlay : MonoBehaviour { // Cached references GameSession session; [Tooltip("Button press sound")] [SerializeField] AudioClip buttonPress = null; void Start() { session = GameObject.Find("Game Session").GetComponent<GameSession>(); // Set main camera as canvas' camera GetComponent<Canvas>().worldCamera = Camera.main; } public void Restart() { session.PlaySound(buttonPress); session.Restart(); } public void LoadMenu() { session.PlaySound(buttonPress); session.LoadMenu(); } public void QuitGame() { session.PlaySound(buttonPress); session.QuitGame(); } }
22.589744
82
0.641317
[ "MIT" ]
LucRosset/Match-3
Assets/Scripts/Overlay.cs
883
C#
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the medialive-2017-10-14.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.MediaLive.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaLive.Model.Internal.MarshallTransformations { /// <summary> /// OutputLocationRef Marshaller /// </summary> public class OutputLocationRefMarshaller : IRequestMarshaller<OutputLocationRef, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(OutputLocationRef requestObject, JsonMarshallerContext context) { if(requestObject.IsSetDestinationRefId()) { context.Writer.WritePropertyName("destinationRefId"); context.Writer.Write(requestObject.DestinationRefId); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static OutputLocationRefMarshaller Instance = new OutputLocationRefMarshaller(); } }
34.451613
109
0.67088
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/MediaLive/Generated/Model/Internal/MarshallTransformations/OutputLocationRefMarshaller.cs
2,136
C#
using CommandLine; using System; namespace GVFS.CommandLine { [Verb(UpgradeVerbName, HelpText = "Checks for new GVFS release, downloads and installs it when available.")] public class UpgradeVerb : GVFSVerb.ForNoEnlistment { private const string UpgradeVerbName = "upgrade"; public UpgradeVerb() { this.Output = Console.Out; } [Option( "confirm", Default = false, Required = false, HelpText = "Pass in this flag to actually install the newest release")] public bool Confirmed { get; set; } [Option( "dry-run", Default = false, Required = false, HelpText = "Display progress and errors, but don't install GVFS")] public bool DryRun { get; set; } [Option( "no-verify", Default = false, Required = false, HelpText = "Do not verify NuGet packages after downloading them. Some platforms do not support NuGet verification.")] public bool NoVerify { get; set; } protected override string VerbName { get { return UpgradeVerbName; } } public override void Execute() { Console.Error.WriteLine("'gvfs upgrade' is no longer supported. Visit https://github.com/microsoft/vfsforgit for the latest install/upgrade instructions."); } } }
31.25
169
0.565333
[ "MIT" ]
Andrea-MariaDB-2/VFSForGit
GVFS/GVFS/CommandLine/UpgradeVerb.cs
1,500
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Duality.Editor.Plugins.UndoHistoryView.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Duality.Editor.Plugins.UndoHistoryView.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap arrow_redo { get { object obj = ResourceManager.GetObject("arrow_redo", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap arrow_undo { get { object obj = ResourceManager.GetObject("arrow_undo", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
42.654762
204
0.599498
[ "MIT" ]
padesso/duality
Source/Plugins/EditorModules/UndoHistoryView/Properties/Resources.Designer.cs
3,585
C#
using FavoDeMel.Domain.Dto; using FavoDeMel.Domain.Querys.Base; using System; namespace FavoDeMel.Domain.Querys.Comanda.Consultas { public class ObterComandaQuery : ObterPorIdQuery<ComandaDto> { public ObterComandaQuery(Guid id) : base(id) { } } }
20.428571
64
0.692308
[ "MIT" ]
fernandovictorTI/processo-seletivo-ewave-arquiteto-fev-2021
api/src/FavoDeMel.Domain/Querys/Comanda/Consultas/ObterComandaQuery.cs
288
C#
// 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.Buffers; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using Newtonsoft.Json; using Xunit; namespace System.Text.Json.Tests { public static partial class Utf8JsonReaderTests { [Fact] public static void TestingNumbers_TryGetMethods() { byte[] dataUtf8 = JsonNumberTestData.JsonData; List<byte> bytes = JsonNumberTestData.Bytes; List<sbyte> sbytes = JsonNumberTestData.SBytes; List<short> shorts = JsonNumberTestData.Shorts; List<int> ints = JsonNumberTestData.Ints; List<long> longs = JsonNumberTestData.Longs; List<ushort> ushorts = JsonNumberTestData.UShorts; List<uint> uints = JsonNumberTestData.UInts; List<ulong> ulongs = JsonNumberTestData.ULongs; List<float> floats = JsonNumberTestData.Floats; List<double> doubles = JsonNumberTestData.Doubles; List<decimal> decimals = JsonNumberTestData.Decimals; var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); string key = ""; int count = 0; while (json.Read()) { if (json.TokenType == JsonTokenType.PropertyName) { key = json.GetString(); } if (json.TokenType == JsonTokenType.Number) { if (key.StartsWith("byte")) { Assert.True(json.TryGetByte(out byte numberByte)); if (count >= bytes.Count) count = 0; Assert.Equal(bytes[count], numberByte); count++; } else if (key.StartsWith("sbyte")) { Assert.True(json.TryGetSByte(out sbyte numberSByte)); if (count >= sbytes.Count) count = 0; Assert.Equal(sbytes[count], numberSByte); count++; } else if (key.StartsWith("short")) { Assert.True(json.TryGetInt16(out short numberShort)); if (count >= shorts.Count) count = 0; Assert.Equal(shorts[count], numberShort); count++; } else if (key.StartsWith("int")) { Assert.True(json.TryGetInt32(out int numberInt)); if (count >= ints.Count) count = 0; Assert.Equal(ints[count], numberInt); count++; } else if (key.StartsWith("long")) { Assert.True(json.TryGetInt64(out long numberLong)); if (count >= longs.Count) count = 0; Assert.Equal(longs[count], numberLong); count++; } else if (key.StartsWith("ushort")) { Assert.True(json.TryGetUInt16(out ushort numberUShort)); if (count >= ushorts.Count) count = 0; Assert.Equal(ushorts[count], numberUShort); count++; } else if (key.StartsWith("uint")) { Assert.True(json.TryGetUInt32(out uint numberUInt)); if (count >= ints.Count) count = 0; Assert.Equal(uints[count], numberUInt); count++; } else if (key.StartsWith("ulong")) { Assert.True(json.TryGetUInt64(out ulong numberULong)); if (count >= ints.Count) count = 0; Assert.Equal(ulongs[count], numberULong); count++; } else if (key.StartsWith("float")) { Assert.True(json.TryGetSingle(out float numberFloat)); if (count >= floats.Count) count = 0; string roundTripActual = numberFloat.ToString(JsonTestHelper.SingleFormatString, CultureInfo.InvariantCulture); float actual = float.Parse(roundTripActual, CultureInfo.InvariantCulture); string roundTripExpected = floats[count].ToString(JsonTestHelper.SingleFormatString, CultureInfo.InvariantCulture); float expected = float.Parse(roundTripExpected, CultureInfo.InvariantCulture); Assert.Equal(expected, actual); count++; } else if (key.StartsWith("double")) { Assert.True(json.TryGetDouble(out double numberDouble)); if (count >= doubles.Count) count = 0; string roundTripActual = numberDouble.ToString(JsonTestHelper.DoubleFormatString, CultureInfo.InvariantCulture); double actual = double.Parse(roundTripActual, CultureInfo.InvariantCulture); string roundTripExpected = doubles[count].ToString(JsonTestHelper.DoubleFormatString, CultureInfo.InvariantCulture); double expected = double.Parse(roundTripExpected, CultureInfo.InvariantCulture); Assert.Equal(expected, actual); count++; } else if (key.StartsWith("decimal")) { Assert.True(json.TryGetDecimal(out decimal numberDecimal)); if (count >= decimals.Count) count = 0; var str = string.Format(CultureInfo.InvariantCulture, "{0}", decimals[count]); decimal expected = decimal.Parse(str, CultureInfo.InvariantCulture); Assert.Equal(expected, numberDecimal); count++; } } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Fact] public static void TestingNumbers_GetMethods() { byte[] dataUtf8 = JsonNumberTestData.JsonData; List<byte> bytes = JsonNumberTestData.Bytes; List<sbyte> sbytes = JsonNumberTestData.SBytes; List<short> shorts = JsonNumberTestData.Shorts; List<int> ints = JsonNumberTestData.Ints; List<long> longs = JsonNumberTestData.Longs; List<ushort> ushorts = JsonNumberTestData.UShorts; List<uint> uints = JsonNumberTestData.UInts; List<ulong> ulongs = JsonNumberTestData.ULongs; List<float> floats = JsonNumberTestData.Floats; List<double> doubles = JsonNumberTestData.Doubles; List<decimal> decimals = JsonNumberTestData.Decimals; var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); string key = ""; int count = 0; while (json.Read()) { if (json.TokenType == JsonTokenType.PropertyName) { key = json.GetString(); } if (json.TokenType == JsonTokenType.Number) { if (key.StartsWith("byte")) { if (count >= bytes.Count) count = 0; Assert.Equal(bytes[count], json.GetByte()); count++; } else if (key.StartsWith("sbyte")) { if (count >= sbytes.Count) count = 0; Assert.Equal(sbytes[count], json.GetSByte()); count++; } else if (key.StartsWith("short")) { if (count >= shorts.Count) count = 0; Assert.Equal(shorts[count], json.GetInt16()); count++; } else if (key.StartsWith("int")) { if (count >= ints.Count) count = 0; Assert.Equal(ints[count], json.GetInt32()); count++; } else if (key.StartsWith("long")) { if (count >= longs.Count) count = 0; Assert.Equal(longs[count], json.GetInt64()); count++; } else if (key.StartsWith("ushort")) { if (count >= ushorts.Count) count = 0; Assert.Equal(ushorts[count], json.GetUInt16()); count++; } else if (key.StartsWith("uint")) { if (count >= uints.Count) count = 0; Assert.Equal(uints[count], json.GetUInt32()); count++; } else if (key.StartsWith("ulong")) { if (count >= ulongs.Count) count = 0; Assert.Equal(ulongs[count], json.GetUInt64()); count++; } else if (key.StartsWith("float")) { if (count >= floats.Count) count = 0; string roundTripActual = json.GetSingle().ToString(JsonTestHelper.SingleFormatString, CultureInfo.InvariantCulture); float actual = float.Parse(roundTripActual, CultureInfo.InvariantCulture); string roundTripExpected = floats[count].ToString(JsonTestHelper.SingleFormatString, CultureInfo.InvariantCulture); float expected = float.Parse(roundTripExpected, CultureInfo.InvariantCulture); Assert.Equal(expected, actual); count++; } else if (key.StartsWith("double")) { if (count >= doubles.Count) count = 0; string roundTripActual = json.GetDouble().ToString(JsonTestHelper.DoubleFormatString, CultureInfo.InvariantCulture); double actual = double.Parse(roundTripActual, CultureInfo.InvariantCulture); string roundTripExpected = doubles[count].ToString(JsonTestHelper.DoubleFormatString, CultureInfo.InvariantCulture); double expected = double.Parse(roundTripExpected, CultureInfo.InvariantCulture); Assert.Equal(expected, actual); count++; } else if (key.StartsWith("decimal")) { try { if (count >= decimals.Count) count = 0; var str = string.Format(CultureInfo.InvariantCulture, "{0}", decimals[count]); decimal expected = decimal.Parse(str, CultureInfo.InvariantCulture); Assert.Equal(expected, json.GetDecimal()); count++; } catch (Exception except) { Assert.True(false, string.Format("Unexpected exception: {0}. Message: {1}", except.Source, except.Message)); } } } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("0.000", 0)] [InlineData("1e1", 10)] [InlineData("1.1e2", 110)] [InlineData("220.1", 220.1)] [InlineData("12345678901", 12345678901)] [InlineData("123456789012345678901", 123456789012345678901d)] [InlineData("-1", -1)] // byte.MinValue - 1 public static void TestingNumbersInvalidConversionToByte(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { Assert.False(json.TryGetByte(out byte value)); Assert.Equal(default, value); Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expected, doubleValue); try { json.GetByte(); Assert.True(false, "Expected GetByte to throw FormatException."); } catch (FormatException) { /* Expected exception */ } doubleValue = json.GetDouble(); Assert.Equal(expected, doubleValue); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("0.000", 0)] [InlineData("1e1", 10)] [InlineData("1.1e2", 110)] [InlineData("120.1", 120.1)] [InlineData("12345678901", 12345678901)] [InlineData("123456789012345678901", 123456789012345678901d)] [InlineData("-129", -129)] // sbyte.MinValue - 1 public static void TestingNumbersInvalidConversionToSByte(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { Assert.False(json.TryGetSByte(out sbyte value)); Assert.Equal(default, value); Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expected, doubleValue); try { json.GetSByte(); Assert.True(false, "Expected GetSByte to throw FormatException."); } catch (FormatException) { /* Expected exception */ } doubleValue = json.GetDouble(); Assert.Equal(expected, doubleValue); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("0.000", 0)] [InlineData("1e1", 10)] [InlineData("1.1e2", 110)] [InlineData("12345.1", 12345.1)] [InlineData("12345678901", 12345678901)] [InlineData("123456789012345678901", 123456789012345678901d)] [InlineData("-32769", -32769)] // short.MinValue - 1 public static void TestingNumbersInvalidConversionToInt16(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { Assert.False(json.TryGetInt16(out short value)); Assert.Equal(default, value); Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expected, doubleValue); try { json.GetInt16(); Assert.True(false, "Expected GetInt16 to throw FormatException."); } catch (FormatException) { /* Expected exception */ } doubleValue = json.GetDouble(); Assert.Equal(expected, doubleValue); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("0.000", 0)] [InlineData("1e1", 10)] [InlineData("1.1e2", 110)] [InlineData("12345.1", 12345.1)] [InlineData("12345678901", 12345678901)] [InlineData("123456789012345678901", 123456789012345678901d)] [InlineData("-2147483649", -2147483649)] // int.MinValue - 1 public static void TestingNumbersInvalidConversionToInt32(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { Assert.False(json.TryGetInt32(out int value)); Assert.Equal(default, value); Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expected, doubleValue); try { json.GetInt32(); Assert.True(false, "Expected GetInt32 to throw FormatException."); } catch (FormatException) { /* Expected exception */ } doubleValue = json.GetDouble(); Assert.Equal(expected, doubleValue); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("0.000", 0)] [InlineData("1e1", 10)] [InlineData("1.1e2", 110)] [InlineData("12345.1", 12345.1)] [InlineData("123456789012345678901", 123456789012345678901d)] [InlineData("-9223372036854775809", -9223372036854775809d)] // long.MinValue - 1 public static void TestingNumbersInvalidConversionToInt64(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { Assert.False(json.TryGetInt64(out long value)); Assert.Equal(default, value); Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expected, doubleValue); try { json.GetInt64(); Assert.True(false, "Expected GetInt64 to throw FormatException."); } catch (FormatException) { /* Expected exception */ } doubleValue = json.GetDouble(); Assert.Equal(expected, doubleValue); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("0.000", 0)] [InlineData("1e1", 10)] [InlineData("1.1e2", 110)] [InlineData("12345.1", 12345.1)] [InlineData("12345678901", 12345678901)] [InlineData("123456789012345678901", 123456789012345678901d)] [InlineData("-1", -1)] // ushort.MinValue - 1 public static void TestingNumbersInvalidConversionToUInt16(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { Assert.False(json.TryGetUInt16(out ushort value)); Assert.Equal(default, value); Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expected, doubleValue); try { json.GetUInt16(); Assert.True(false, "Expected GetUInt16 to throw FormatException."); } catch (FormatException) { /* Expected exception */ } doubleValue = json.GetDouble(); Assert.Equal(expected, doubleValue); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("0.000", 0)] [InlineData("1e1", 10)] [InlineData("1.1e2", 110)] [InlineData("12345.1", 12345.1)] [InlineData("12345678901", 12345678901)] [InlineData("123456789012345678901", 123456789012345678901d)] [InlineData("-1", -1)] // uint.MinValue - 1 public static void TestingNumbersInvalidConversionToUInt32(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { Assert.False(json.TryGetUInt32(out uint value)); Assert.Equal(default, value); Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expected, doubleValue); try { json.GetUInt32(); Assert.True(false, "Expected GetUInt32 to throw FormatException."); } catch (FormatException) { /* Expected exception */ } doubleValue = json.GetDouble(); Assert.Equal(expected, doubleValue); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("0.000", 0)] [InlineData("1e1", 10)] [InlineData("1.1e2", 110)] [InlineData("12345.1", 12345.1)] [InlineData("123456789012345678901", 123456789012345678901d)] [InlineData("-1", -1)] // ulong.MinValue - 1 public static void TestingNumbersInvalidConversionToUInt64(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { Assert.False(json.TryGetUInt64(out ulong value)); Assert.Equal(default, value); Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expected, doubleValue); try { json.GetUInt64(); Assert.True(false, "Expected GetInt64 to throw FormatException."); } catch (FormatException) { /* Expected exception */ } doubleValue = json.GetDouble(); Assert.Equal(expected, doubleValue); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("-4.402823E+38", float.NegativeInfinity, -4.402823E+38)] // float.MinValue - 1 [InlineData("4.402823E+38", float.PositiveInfinity, 4.402823E+38)] // float.MaxValue + 1 public static void TestingTooLargeSingleConversionToInfinity(string jsonString, float expectedFloat, double expectedDouble) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { if (PlatformDetection.IsNetFramework) { // .NET Framework throws for overflow rather than returning Infinity // This was fixed for .NET Core 3.0 in order to be IEEE 754 compliant Assert.False(json.TryGetSingle(out float _)); try { json.GetSingle(); Assert.True(false, $"Expected {nameof(FormatException)}."); } catch (FormatException) { /* Expected exception */ } } else { Assert.True(json.TryGetSingle(out float floatValue)); Assert.Equal(expectedFloat, floatValue); Assert.Equal(expectedFloat, json.GetSingle()); } Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expectedDouble, doubleValue); Assert.Equal(expectedDouble, json.GetDouble()); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("-2.79769313486232E+308", double.NegativeInfinity)] // double.MinValue - 1 [InlineData("2.79769313486232E+308", double.PositiveInfinity)] // double.MaxValue + 1 public static void TestingTooLargeDoubleConversionToInfinity(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { if (PlatformDetection.IsNetFramework) { // .NET Framework throws for overflow rather than returning Infinity // This was fixed for .NET Core 3.0 in order to be IEEE 754 compliant Assert.False(json.TryGetDouble(out double _)); try { json.GetDouble(); Assert.True(false, $"Expected {nameof(FormatException)}."); } catch (FormatException) { /* Expected exception */ } } else { Assert.True(json.TryGetDouble(out double actual)); Assert.Equal(expected, actual); Assert.Equal(expected, json.GetDouble()); } } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("-79228162514264337593543950336", -79228162514264337593543950336d)] // decimal.MinValue - 1 [InlineData("79228162514264337593543950336", 79228162514264337593543950336d)] // decimal.MaxValue + 1 public static void TestingNumbersInvalidConversionToDecimal(string jsonString, double expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); while (json.Read()) { if (json.TokenType == JsonTokenType.Number) { Assert.False(json.TryGetDecimal(out decimal value)); Assert.Equal(default, value); Assert.True(json.TryGetDouble(out double doubleValue)); Assert.Equal(expected, doubleValue); try { json.GetDecimal(); Assert.True(false, "Expected GetDecimal to throw FormatException."); } catch (FormatException) { /* Expected exception */ } doubleValue = json.GetDouble(); Assert.Equal(expected, doubleValue); } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Fact] public static void InvalidConversion() { string jsonString = "[\"stringValue\", true, /* Comment within */ 1234, null] // Comment outside"; byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var state = new JsonReaderState(options: new JsonReaderOptions { CommentHandling = JsonCommentHandling.Allow }); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state); while (json.Read()) { if (json.TokenType != JsonTokenType.String) { if (json.TokenType == JsonTokenType.Null) { Assert.Null(json.GetString()); } else { JsonTestHelper.AssertThrows<InvalidOperationException>(json, (jsonReader) => jsonReader.GetString()); } try { byte[] value = json.GetBytesFromBase64(); Assert.True(false, "Expected GetBytesFromBase64 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetBytesFromBase64(out byte[] value); Assert.True(false, "Expected TryGetBytesFromBase64 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { DateTime value = json.GetDateTime(); Assert.True(false, "Expected GetDateTime to throw InvalidOperationException due to mismatched token type."); } catch (InvalidOperationException) { } try { json.TryGetDateTime(out DateTime value); Assert.True(false, "Expected TryGetDateTime to throw InvalidOperationException due to mismatched token type."); } catch (InvalidOperationException) { } try { DateTimeOffset value = json.GetDateTimeOffset(); Assert.True(false, "Expected GetDateTimeOffset to throw InvalidOperationException due to mismatched token type."); } catch (InvalidOperationException) { } try { json.TryGetDateTimeOffset(out DateTimeOffset value); Assert.True(false, "Expected TryGetDateTimeOffset to throw InvalidOperationException due to mismatched token type."); } catch (InvalidOperationException) { } JsonTestHelper.AssertThrows<InvalidOperationException>(json, (jsonReader) => jsonReader.GetGuid()); JsonTestHelper.AssertThrows<InvalidOperationException>(json, (jsonReader) => jsonReader.TryGetGuid(out _)); } if (json.TokenType != JsonTokenType.Comment) { try { string value = json.GetComment(); Assert.True(false, "Expected GetComment to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } } if (json.TokenType != JsonTokenType.True && json.TokenType != JsonTokenType.False) { try { bool value = json.GetBoolean(); Assert.True(false, "Expected GetBoolean to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } } if (json.TokenType != JsonTokenType.Number) { try { json.TryGetByte(out byte value); Assert.True(false, "Expected TryGetByte to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetByte(); Assert.True(false, "Expected GetByte to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetSByte(out sbyte value); Assert.True(false, "Expected TryGetSByte to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetSByte(); Assert.True(false, "Expected GetSByte to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetInt16(out short value); Assert.True(false, "Expected TryGetInt16 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetInt16(); Assert.True(false, "Expected GetInt16 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetInt32(out int value); Assert.True(false, "Expected TryGetInt32 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetInt32(); Assert.True(false, "Expected GetInt32 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetInt64(out long value); Assert.True(false, "Expected TryGetInt64 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetInt64(); Assert.True(false, "Expected GetInt64 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetUInt16(out ushort value); Assert.True(false, "Expected TryGetUInt16 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetUInt16(); Assert.True(false, "Expected GetUInt16 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetUInt32(out uint value); Assert.True(false, "Expected TryGetUInt32 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetUInt32(); Assert.True(false, "Expected GetUInt32 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetUInt64(out ulong value); Assert.True(false, "Expected TryGetUInt64 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetUInt64(); Assert.True(false, "Expected GetUInt64 to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetSingle(out float value); Assert.True(false, "Expected TryGetSingle to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetSingle(); Assert.True(false, "Expected GetSingle to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetDouble(out double value); Assert.True(false, "Expected TryGetDouble to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetDouble(); Assert.True(false, "Expected GetDouble to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.TryGetDecimal(out decimal value); Assert.True(false, "Expected TryGetDecimal to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } try { json.GetDecimal(); Assert.True(false, "Expected GetDecimal to throw InvalidOperationException due to mismatch token type."); } catch (InvalidOperationException) { } } } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("{\"message\":\"Hello, I am \\\"Ahson!\\\"\"}")] [InlineData("{\"nam\\\"e\":\"ah\\\"son\"}")] [InlineData("{\"Here is a string: \\\"\\\"\":\"Here is a\",\"Here is a back slash\\\\\":[\"Multiline\\r\\n String\\r\\n\",\"\\tMul\\r\\ntiline String\",\"\\\"somequote\\\"\\tMu\\\"\\\"l\\r\\ntiline\\\"another\\\" String\\\\\"],\"str\":\"\\\"\\\"\"}")] [InlineData("[\"\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\", \"\\u0000\\u002B\", \"a\\u005C\\u0072b\", \"a\\\\u005C\\u0072b\", \"a\\u008E\\u008Fb\", \"a\\uD803\\uDE6Db\", \"a\\uD834\\uDD1Eb\", \"a\\\\uD834\\\\uDD1Eb\"]")] [InlineData("{\"message\":\"Hello /a/b/c \\/ \\r\\b\\n\\f\\t\\/\"}")] [InlineData(null)] // Large randomly generated string public static void TestingGetString(string jsonString) { if (jsonString == null) { var random = new Random(42); var charArray = new char[500]; charArray[0] = '"'; for (int i = 1; i < charArray.Length; i++) { charArray[i] = (char)random.Next('?', '\\'); // ASCII values (between 63 and 91) that don't need to be escaped. } charArray[256] = '\\'; charArray[257] = '"'; charArray[charArray.Length - 1] = '"'; jsonString = new string(charArray); } var expectedPropertyNames = new List<string>(); var expectedValues = new List<string>(); var jsonNewtonsoft = new JsonTextReader(new StringReader(jsonString)); while (jsonNewtonsoft.Read()) { if (jsonNewtonsoft.TokenType == JsonToken.String) { expectedValues.Add(jsonNewtonsoft.Value.ToString()); } else if (jsonNewtonsoft.TokenType == JsonToken.PropertyName) { expectedPropertyNames.Add(jsonNewtonsoft.Value.ToString()); } } byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var actualPropertyNames = new List<string>(); var actualValues = new List<string>(); var json = new Utf8JsonReader(dataUtf8, true, default); while (json.Read()) { if (json.TokenType == JsonTokenType.String) { actualValues.Add(json.GetString()); } else if (json.TokenType == JsonTokenType.PropertyName) { actualPropertyNames.Add(json.GetString()); } } Assert.Equal(expectedPropertyNames.Count, actualPropertyNames.Count); for (int i = 0; i < expectedPropertyNames.Count; i++) { Assert.Equal(expectedPropertyNames[i], actualPropertyNames[i]); } Assert.Equal(expectedValues.Count, actualValues.Count); for (int i = 0; i < expectedValues.Count; i++) { Assert.Equal(expectedValues[i], actualValues[i]); } Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [InlineData("\"a\\uDD1E\"")] [InlineData("\"a\\uDD1Eb\"")] [InlineData("\"a\\uD834\"")] [InlineData("\"a\\uD834\\u0030\"")] [InlineData("\"a\\uD834\\uD834\"")] [InlineData("\"a\\uD834b\"")] [InlineData("\"a\\uDD1E\\uD834b\"")] [InlineData("\"a\\\\uD834\\uDD1Eb\"")] [InlineData("\"a\\uDD1E\\\\uD834b\"")] public static void TestingGetStringInvalidUTF16(string jsonString) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); foreach (JsonCommentHandling commentHandling in Enum.GetValues(typeof(JsonCommentHandling))) { var state = new JsonReaderState(options: new JsonReaderOptions { CommentHandling = commentHandling }); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state); Assert.True(json.Read()); Assert.Equal(JsonTokenType.String, json.TokenType); try { string val = json.GetString(); Assert.True(false, "Expected InvalidOperationException when trying to get string value for invalid UTF-16 JSON text."); } catch (InvalidOperationException) { } } } [Theory] [MemberData(nameof(InvalidUTF8Strings))] public static void TestingGetStringInvalidUTF8(byte[] dataUtf8) { foreach (JsonCommentHandling commentHandling in Enum.GetValues(typeof(JsonCommentHandling))) { var state = new JsonReaderState(options: new JsonReaderOptions { CommentHandling = commentHandling }); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state); // It is expected that the Utf8JsonReader won't throw an exception here Assert.True(json.Read()); Assert.Equal(JsonTokenType.String, json.TokenType); while (json.Read()) ; json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state); while (json.Read()) { if (json.TokenType == JsonTokenType.String) { try { string val = json.GetString(); Assert.True(false, "Expected InvalidOperationException when trying to get string value for invalid UTF-8 JSON text."); } catch (InvalidOperationException ex) { Assert.Equal(typeof(DecoderFallbackException), ex.InnerException.GetType()); } } } } } [Fact] public static void GetBase64Unescapes() { string jsonString = "\"\\u0031234\""; // equivalent to "\"1234\"" byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); Assert.True(json.Read()); byte[] expected = Convert.FromBase64String("1234"); // new byte[3] { 215, 109, 248 } byte[] value = json.GetBytesFromBase64(); Assert.Equal(expected, value); Assert.True(json.TryGetBytesFromBase64(out value)); Assert.Equal(expected, value); } [Theory] [MemberData(nameof(JsonBase64TestData.ValidBase64Tests), MemberType = typeof(JsonBase64TestData))] public static void ValidBase64(string jsonString) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); Assert.True(json.Read()); byte[] expected = Convert.FromBase64String(jsonString.AsSpan(1, jsonString.Length - 2).ToString()); byte[] value = json.GetBytesFromBase64(); Assert.Equal(expected, value); Assert.True(json.TryGetBytesFromBase64(out value)); Assert.Equal(expected, value); } [Theory] [MemberData(nameof(JsonBase64TestData.InvalidBase64Tests), MemberType = typeof(JsonBase64TestData))] public static void InvalidBase64(string jsonString) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); Assert.True(json.Read()); Assert.False(json.TryGetBytesFromBase64(out byte[] value)); Assert.Null(value); try { byte[] val = json.GetBytesFromBase64(); Assert.True(false, "Expected InvalidOperationException when trying to decode base 64 string for invalid UTF-16 JSON text."); } catch (FormatException) { } } [Theory] [InlineData("\"a\\uDD1E\"")] [InlineData("\"a\\uDD1Eb\"")] [InlineData("\"a\\uD834\"")] [InlineData("\"a\\uD834\\u0030\"")] [InlineData("\"a\\uD834\\uD834\"")] [InlineData("\"a\\uD834b\"")] [InlineData("\"a\\uDD1E\\uD834b\"")] [InlineData("\"a\\\\uD834\\uDD1Eb\"")] [InlineData("\"a\\uDD1E\\\\uD834b\"")] public static void TestingGetBase64InvalidUTF16(string jsonString) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); foreach (JsonCommentHandling commentHandling in Enum.GetValues(typeof(JsonCommentHandling))) { var state = new JsonReaderState(options: new JsonReaderOptions { CommentHandling = commentHandling }); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state); Assert.True(json.Read()); Assert.Equal(JsonTokenType.String, json.TokenType); try { byte[] val = json.GetBytesFromBase64(); Assert.True(false, "Expected InvalidOperationException when trying to decode base 64 string for invalid UTF-16 JSON text."); } catch (InvalidOperationException) { } try { json.TryGetBytesFromBase64(out byte[] val); Assert.True(false, "Expected InvalidOperationException when trying to decode base 64 string for invalid UTF-16 JSON text."); } catch (InvalidOperationException) { } } } [Theory] [MemberData(nameof(InvalidUTF8Strings))] public static void TestingGetBase64InvalidUTF8(byte[] dataUtf8) { foreach (JsonCommentHandling commentHandling in Enum.GetValues(typeof(JsonCommentHandling))) { var state = new JsonReaderState(options: new JsonReaderOptions { CommentHandling = commentHandling }); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state); // It is expected that the Utf8JsonReader won't throw an exception here Assert.True(json.Read()); Assert.Equal(JsonTokenType.String, json.TokenType); while (json.Read()) ; json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state); while (json.Read()) { if (json.TokenType == JsonTokenType.String) { try { byte[] val = json.GetBytesFromBase64(); Assert.True(false, "Expected InvalidOperationException when trying to decode base 64 string for invalid UTF-8 JSON text."); } catch (FormatException) { } Assert.False(json.TryGetBytesFromBase64(out byte[] value)); Assert.Null(value); } } } } [Theory] [MemberData(nameof(GetCommentTestData))] public static void TestingGetComment(string jsonData, string expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonData); var state = new JsonReaderState(options: new JsonReaderOptions { CommentHandling = JsonCommentHandling.Allow }); var reader = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state); Assert.True(reader.Read()); Assert.Equal(JsonTokenType.StartObject, reader.TokenType); Assert.True(reader.Read()); Assert.Equal(JsonTokenType.Comment, reader.TokenType); Assert.Equal(expected, reader.GetComment()); Assert.True(reader.Read()); Assert.Equal(JsonTokenType.EndObject, reader.TokenType); Assert.False(reader.Read()); } [Theory] [MemberData(nameof(GetCommentUnescapeData))] public static void TestGetCommentUnescape(string jsonData, string expected) { byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonData); var state = new JsonReaderState(options: new JsonReaderOptions { CommentHandling = JsonCommentHandling.Allow }); var reader = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state); bool commentFound = false; while (reader.Read()) { switch (reader.TokenType) { case JsonTokenType.Comment: commentFound = true; string comment = reader.GetComment(); Assert.Equal(expected, comment); Assert.NotEqual(Regex.Unescape(expected), comment); break; default: Assert.True(false); break; } } Assert.True(commentFound); } [Theory] [MemberData(nameof(JsonGuidTestData.ValidGuidTests), MemberType = typeof(JsonGuidTestData))] [MemberData(nameof(JsonGuidTestData.ValidHexGuidTests), MemberType = typeof(JsonGuidTestData))] public static void TestingStringsConversionToGuid(string testString, string expectedString) { byte[] dataUtf8 = Encoding.UTF8.GetBytes($"\"{testString}\""); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); Guid expected = new Guid(expectedString); Assert.True(json.Read(), "Read string value"); Assert.Equal(JsonTokenType.String, json.TokenType); Assert.True(json.TryGetGuid(out Guid actual)); Assert.Equal(expected, actual); Assert.Equal(expected, json.GetGuid()); Assert.Equal(dataUtf8.Length, json.BytesConsumed); } [Theory] [MemberData(nameof(JsonGuidTestData.ValidGuidTests), MemberType = typeof(JsonGuidTestData))] public static void TryGetGuid_HasValueSequence_RetrievesGuid(string testString, string expectedString) { TryGetGuid_HasValueSequence_RetrievesGuid(testString, expectedString, isFinalBlock: true); TryGetGuid_HasValueSequence_RetrievesGuid(testString, expectedString, isFinalBlock: false); } private static void TryGetGuid_HasValueSequence_RetrievesGuid(string testString, string expectedString, bool isFinalBlock) { byte[] dataUtf8 = Encoding.UTF8.GetBytes($"\"{testString}\""); ReadOnlySequence<byte> sequence = JsonTestHelper.GetSequence(dataUtf8, 1); var json = new Utf8JsonReader(sequence, isFinalBlock: isFinalBlock, state: default); Guid expected = new Guid(expectedString); Assert.True(json.Read(), "json.Read()"); Assert.Equal(JsonTokenType.String, json.TokenType); Assert.True(json.HasValueSequence, "json.HasValueSequence"); Assert.False(json.ValueSequence.IsEmpty, "json.ValueSequence.IsEmpty"); Assert.True(json.ValueSpan.IsEmpty, "json.ValueSpan.IsEmpty"); Assert.True(json.TryGetGuid(out Guid actual), "TryGetGuid"); Assert.Equal(expected, actual); Assert.Equal(expected, json.GetGuid()); } [Theory] [MemberData(nameof(JsonGuidTestData.InvalidGuidTests), MemberType = typeof(JsonGuidTestData))] public static void TestingStringsInvalidConversionToGuid(string testString) { byte[] dataUtf8 = Encoding.UTF8.GetBytes($"\"{testString}\""); var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default); Assert.True(json.Read(), "Read string value"); Assert.Equal(JsonTokenType.String, json.TokenType); Assert.False(json.TryGetGuid(out Guid actual)); Assert.Equal(default, actual); JsonTestHelper.AssertThrows<FormatException>(json, (jsonReader) => jsonReader.GetGuid()); } [Theory] [MemberData(nameof(JsonGuidTestData.InvalidGuidTests), MemberType = typeof(JsonGuidTestData))] public static void TryGetGuid_HasValueSequence_False(string testString) { TryGetGuid_HasValueSequence_False(testString, isFinalBlock: true); TryGetGuid_HasValueSequence_False(testString, isFinalBlock: false); } private static void TryGetGuid_HasValueSequence_False(string testString, bool isFinalBlock) { byte[] dataUtf8 = Encoding.UTF8.GetBytes($"\"{testString}\""); ReadOnlySequence<byte> sequence = JsonTestHelper.GetSequence(dataUtf8, 1); var json = new Utf8JsonReader(sequence, isFinalBlock: isFinalBlock, state: default); Assert.True(json.Read(), "json.Read()"); Assert.Equal(JsonTokenType.String, json.TokenType); Assert.True(json.HasValueSequence, "json.HasValueSequence"); // If the string is empty, the ValueSequence is empty, because it contains all 0 bytes between the two characters Assert.Equal(string.IsNullOrEmpty(testString), json.ValueSequence.IsEmpty); Assert.False(json.TryGetGuid(out Guid actual), "json.TryGetGuid(out Guid actual)"); Assert.Equal(Guid.Empty, actual); JsonTestHelper.AssertThrows<FormatException>(json, (jsonReader) => jsonReader.GetGuid()); } } }
42.505698
259
0.497738
[ "MIT" ]
1shekhar/runtime
src/libraries/System.Text.Json/tests/Utf8JsonReaderTests.TryGet.cs
59,678
C#
// <copyright file="Devices.cs" company="3M"> // Copyright (c) 3M. All rights reserved. // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.Devices; using Microsoft.Azure.Devices.Shared; using Mmm.Iot.Common.Services.Config; using Mmm.Iot.Common.Services.Exceptions; using Mmm.Iot.Common.Services.External.AsaManager; using Mmm.Iot.Common.Services.Models; using Mmm.Iot.IoTHubManager.Services.Extensions; using Mmm.Iot.IoTHubManager.Services.Helpers; using Mmm.Iot.IoTHubManager.Services.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using AuthenticationType = Mmm.Iot.IoTHubManager.Services.Models.AuthenticationType; namespace Mmm.Iot.IoTHubManager.Services { public delegate Task<DevicePropertyServiceModel> DevicePropertyDelegate(DevicePropertyServiceModel model); public class Devices : IDevices { private const int MaximumGetList = 1000; private const string QueryPrefix = "SELECT * FROM devices"; private const string ModuleQueryPrefix = "SELECT * FROM devices.modules"; private const string DevicesConnectedQuery = "connectionState = 'Connected'"; private readonly ITenantConnectionHelper tenantConnectionHelper; private readonly IAsaManagerClient asaManager; public Devices(AppConfig config, ITenantConnectionHelper tenantConnectionHelper, IAsaManagerClient asaManagerClient) { if (config == null) { throw new ArgumentNullException("config"); } this.tenantConnectionHelper = tenantConnectionHelper; this.asaManager = asaManagerClient; } public Devices(ITenantConnectionHelper tenantConnectionHelper, string ioTHubHostName, IAsaManagerClient asaManagerClient) { this.tenantConnectionHelper = tenantConnectionHelper ?? throw new ArgumentNullException("tenantConnectionHelper " + ioTHubHostName); this.asaManager = asaManagerClient; } // Ping the registry to see if the connection is healthy public async Task<StatusResultServiceModel> StatusAsync() { var result = new StatusResultServiceModel(false, string.Empty); try { await this.tenantConnectionHelper.GetRegistry().GetDeviceAsync("healthcheck"); result.IsHealthy = true; result.Message = "Alive and Well!"; } catch (Exception e) { result.Message = e.Message; } return result; } public async Task<DeviceServiceListModel> GetListAsync(string query, string continuationToken) { if (!string.IsNullOrWhiteSpace(query)) { // Try to translate clauses to query query = QueryConditionTranslator.ToQueryString(query); } var twins = await this.GetTwinByQueryAsync( QueryPrefix, query, continuationToken, MaximumGetList); var connectedEdgeDevices = await this.GetConnectedEdgeDevices(twins.Result); var resultModel = new DeviceServiceListModel( twins.Result.Select(azureTwin => new DeviceServiceModel( azureTwin, this.tenantConnectionHelper.GetIotHubName(), connectedEdgeDevices.ContainsKey(azureTwin.DeviceId))), twins.ContinuationToken); return resultModel; } public async Task<DeviceTwinName> GetDeviceTwinNamesAsync() { var content = await this.GetListAsync(string.Empty, string.Empty); return content.GetDeviceTwinNames(); } public async Task<DeviceServiceModel> GetAsync(string id) { var device = this.tenantConnectionHelper.GetRegistry().GetDeviceAsync(id); var twin = this.tenantConnectionHelper.GetRegistry().GetTwinAsync(id); await Task.WhenAll(device, twin); if (device.Result == null) { throw new ResourceNotFoundException("The device doesn't exist."); } var isEdgeConnectedDevice = await this.DoesDeviceHaveConnectedModules(device.Result.Id); return new DeviceServiceModel(device.Result, twin.Result, this.tenantConnectionHelper.GetIotHubName(), isEdgeConnectedDevice); } public async Task<DeviceServiceModel> CreateAsync(DeviceServiceModel device) { if (device.IsEdgeDevice && device.Authentication != null && !device.Authentication.AuthenticationType.Equals(AuthenticationType.Sas)) { throw new InvalidInputException("Edge devices only support symmetric key authentication."); } // auto generate DeviceId, if missing if (string.IsNullOrEmpty(device.Id)) { device.Id = Guid.NewGuid().ToString(); } var azureDevice = await this.tenantConnectionHelper.GetRegistry().AddDeviceAsync(device.ToAzureModel()); Twin azureTwin; if (device.Twin == null) { azureTwin = await this.tenantConnectionHelper.GetRegistry().GetTwinAsync(device.Id); } else { azureTwin = await this.tenantConnectionHelper.GetRegistry().UpdateTwinAsync(device.Id, device.Twin.ToAzureModel(), "*"); } await this.asaManager.BeginDeviceGroupsConversionAsync(); return new DeviceServiceModel(azureDevice, azureTwin, this.tenantConnectionHelper.GetIotHubName()); } public async Task<DeviceServiceModel> UpdateAsync(DeviceServiceModel device, DevicePropertyDelegate devicePropertyDelegate) { // validate device module var azureDevice = await this.tenantConnectionHelper.GetRegistry().GetDeviceAsync(device.Id); if (azureDevice == null) { throw new ResourceNotFoundException($"Device {device.Id} could not be found on this tenant's IoT Hub. You must create the device first before calling the update method."); } Twin azureTwin; if (device.Twin == null) { azureTwin = await this.tenantConnectionHelper.GetRegistry().GetTwinAsync(device.Id); } else { azureTwin = await this.tenantConnectionHelper.GetRegistry().UpdateTwinAsync(device.Id, device.Twin.ToAzureModel(), device.Twin.ETag); // Update the deviceGroupFilter cache, no need to wait var model = new DevicePropertyServiceModel(); if (JsonConvert.DeserializeObject(JsonConvert.SerializeObject(device.Twin.Tags)) is JToken tagRoot) { model.Tags = new HashSet<string>(tagRoot.GetAllLeavesPath()); } if (JsonConvert.DeserializeObject(JsonConvert.SerializeObject(device.Twin.ReportedProperties)) is JToken reportedRoot) { model.Reported = new HashSet<string>(reportedRoot.GetAllLeavesPath()); } _ = devicePropertyDelegate(model); } await this.asaManager.BeginDeviceGroupsConversionAsync(); return new DeviceServiceModel(azureDevice, azureTwin, this.tenantConnectionHelper.GetIotHubName()); } public async Task DeleteAsync(string id) { await this.tenantConnectionHelper.GetRegistry().RemoveDeviceAsync(id); } public async Task<TwinServiceModel> GetModuleTwinAsync(string deviceId, string moduleId) { if (string.IsNullOrWhiteSpace(deviceId)) { throw new InvalidInputException("A valid deviceId must be provided."); } if (string.IsNullOrWhiteSpace(moduleId)) { throw new InvalidInputException("A valid moduleId must be provided."); } var twin = await this.tenantConnectionHelper.GetRegistry().GetTwinAsync(deviceId, moduleId); return new TwinServiceModel(twin); } public async Task<TwinServiceListModel> GetModuleTwinsByQueryAsync( string query, string continuationToken) { var twins = await this.GetTwinByQueryAsync( ModuleQueryPrefix, query, continuationToken, MaximumGetList); var result = twins.Result.Select(twin => new TwinServiceModel(twin)).ToList(); return new TwinServiceListModel(result, twins.ContinuationToken); } private async Task<ResultWithContinuationToken<List<Twin>>> GetTwinByQueryAsync( string queryPrefix, string query, string continuationToken, int numberOfResult) { query = string.IsNullOrEmpty(query) ? queryPrefix : $"{queryPrefix} where {query}"; var twins = new List<Twin>(); var twinQuery = this.tenantConnectionHelper.GetRegistry().CreateQuery(query); QueryOptions options = new QueryOptions(); options.ContinuationToken = continuationToken; while (twinQuery.HasMoreResults && twins.Count < numberOfResult) { var response = await twinQuery.GetNextAsTwinAsync(options); options.ContinuationToken = response.ContinuationToken; twins.AddRange(response); } return new ResultWithContinuationToken<List<Twin>>(twins, options.ContinuationToken); } private async Task<Dictionary<string, Twin>> GetConnectedEdgeDevices(List<Twin> twins) { var devicesWithConnectedModules = await this.GetDevicesWithConnectedModules(); var edgeTwins = twins .Where(twin => twin.Capabilities?.IotEdge ?? twin.Capabilities?.IotEdge ?? false) .Where(edgeDvc => devicesWithConnectedModules.Contains(edgeDvc.DeviceId)) .ToDictionary(edgeDevice => edgeDevice.DeviceId, edgeDevice => edgeDevice); return edgeTwins; } private async Task<HashSet<string>> GetDevicesWithConnectedModules() { var connectedEdgeDevices = new HashSet<string>(); var edgeModules = await this.GetModuleTwinsByQueryAsync(DevicesConnectedQuery, string.Empty); foreach (var model in edgeModules.Items) { connectedEdgeDevices.Add(model.DeviceId); } return connectedEdgeDevices; } private async Task<bool> DoesDeviceHaveConnectedModules(string deviceId) { var query = $"deviceId='{deviceId}' AND {DevicesConnectedQuery}"; var edgeModules = await this.GetModuleTwinsByQueryAsync(query, string.Empty); return edgeModules.Items.Any(); } private class ResultWithContinuationToken<T> { public ResultWithContinuationToken(T queryResult, string continuationToken) { this.Result = queryResult; this.ContinuationToken = continuationToken; } public T Result { get; private set; } public string ContinuationToken { get; private set; } } } }
39.726027
187
0.628707
[ "MIT" ]
JonathanAsbury-ACS/azure-iot-platform-dotnet-1
src/services/iothub-manager/Services/Devices.cs
11,600
C#
using System; #if NET452 using System.Data.SqlClient; #else using Microsoft.Data.SqlClient; #endif using Xunit; using Serilog.Sinks.MSSqlServer.Tests.TestUtils; using Serilog.Sinks.MSSqlServer.Platform.SqlClient; namespace Serilog.Sinks.MSSqlServer.Tests.Platform.SqlClient { [Trait(TestCategory.TraitName, TestCategory.Unit)] public class SqlCommandWrapperTests { [Fact] public void InitializeThrowsIfSqlCommandIsNull() { Assert.Throws<ArgumentNullException>(() => new SqlCommandWrapper(null)); } [Fact] public void AddParameterDoesNotThrow() { // Arrange using (var sqlCommand = new SqlCommand()) { using (var sut = new SqlCommandWrapper(sqlCommand)) { // Act (should not throw) sut.AddParameter("Parameter", "Value"); } } } } }
26
84
0.595634
[ "Apache-2.0" ]
serilog-mssql/serilog-sinks-mssqlserver
test/Serilog.Sinks.MSSqlServer.Tests/Sinks/MSSqlServer/Platform/SqlClient/SqlCommandWrapperTests.cs
964
C#
// 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.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.ChangeSignature; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task RemoveParameters1() { var markup = @" static class Ext { /// <summary> /// This is a summary of <see cref=""M(object, int, string, bool, int, string, int[])""/> /// </summary> /// <param name=""o""></param> /// <param name=""a""></param> /// <param name=""b""></param> /// <param name=""c""></param> /// <param name=""x""></param> /// <param name=""y""></param> /// <param name=""p""></param> static void $$M(this object o, int a, string b, bool c, int x = 0, string y = ""Zero"", params int[] p) { object t = new object(); M(t, 1, ""two"", true, 3, ""four"", new[] { 5, 6 }); M(t, 1, ""two"", true, 3, ""four"", 5, 6); t.M(1, ""two"", true, 3, ""four"", new[] { 5, 6 }); t.M(1, ""two"", true, 3, ""four"", 5, 6); M(t, 1, ""two"", true, 3, ""four""); M(t, 1, ""two"", true, 3); M(t, 1, ""two"", true); M(t, 1, ""two"", c: true); M(t, 1, ""two"", true, 3, y: ""four""); M(t, 1, ""two"", true, 3, p: new[] { 5 }); M(t, 1, ""two"", true, p: new[] { 5 }); M(t, 1, ""two"", true, y: ""four""); M(t, 1, ""two"", true, x: 3); M(t, 1, ""two"", true, y: ""four"", x: 3); M(t, 1, y: ""four"", x: 3, b: ""two"", c: true); M(t, y: ""four"", x: 3, c: true, b: ""two"", a: 1); M(t, p: new[] { 5 }, y: ""four"", x: 3, c: true, b: ""two"", a: 1); M(p: new[] { 5 }, y: ""four"", x: 3, c: true, b: ""two"", a: 1, o: t); } }"; var updatedSignature = new[] { 0, 2, 5 }; var updatedCode = @" static class Ext { /// <summary> /// This is a summary of <see cref=""M(object, string, string)""/> /// </summary> /// <param name=""o""></param> /// <param name=""b""></param> /// <param name=""y""></param> /// /// /// /// static void M(this object o, string b, string y = ""Zero"") { object t = new object(); M(t, ""two"", ""four""); M(t, ""two"", ""four""); t.M(""two"", ""four""); t.M(""two"", ""four""); M(t, ""two"", ""four""); M(t, ""two""); M(t, ""two""); M(t, ""two""); M(t, ""two"", y: ""four""); M(t, ""two""); M(t, ""two""); M(t, ""two"", y: ""four""); M(t, ""two""); M(t, ""two"", y: ""four""); M(t, y: ""four"", b: ""two""); M(t, y: ""four"", b: ""two""); M(t, y: ""four"", b: ""two""); M(y: ""four"", b: ""two"", o: t); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task RemoveParameters_GenericParameterType() { var markup = @" class DA { void M(params int[] i) { } void B() { DP20<int>.D d = new DP20<int>.D(M); /*DA19*/$$d(0); d(); d(0, 1); } } public class DP20<T> { public delegate void /*DP20*/D(params T[] t); public event D E1; public event D E2; public void M1(params T[] t) { } public void M2(params T[] t) { } public void M3(params T[] t) { } void B() { D d = new D(M1); E1 += new D(M2); E2 -= new D(M3); } }"; var updatedSignature = Array.Empty<int>(); var updatedCode = @" class DA { void M() { } void B() { DP20<int>.D d = new DP20<int>.D(M); /*DA19*/d(); d(); d(); } } public class DP20<T> { public delegate void /*DP20*/D(); public event D E1; public event D E2; public void M1() { } public void M2() { } public void M3() { } void B() { D d = new D(M1); E1 += new D(M2); E2 -= new D(M3); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] [WorkItem(1102830)] [WorkItem(784, "https://github.com/dotnet/roslyn/issues/784")] public async Task RemoveParameters_ExtensionMethodInAnotherFile() { var workspaceXml = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSharpAssembly"" CommonReferences=""true"">"; for (int i = 0; i <= 4; i++) { workspaceXml += $@" <Document FilePath = ""C{i}.cs""> class C{i} {{ void M() {{ C5 c = new C5(); c.Ext(1, ""two""); }} }} </Document>"; } workspaceXml += @" <Document FilePath = ""C5.cs""> public class C5 { } public static class C5Ext { public void $$Ext(this C5 c, int i, string s) { } } </Document>"; for (int i = 6; i <= 9; i++) { workspaceXml += $@" <Document FilePath = ""C{i}.cs""> class C{i} {{ void M() {{ C5 c = new C5(); c.Ext(1, ""two""); }} }} </Document>"; } workspaceXml += @" </Project> </Workspace>"; // Ext(this F f, int i, string s) --> Ext(this F f, string s) // If a reference does not bind correctly, it will believe Ext is not an extension // method and remove the string argument instead of the int argument. var updatedSignature = new[] { 0, 2 }; using (var testState = await ChangeSignatureTestState.CreateAsync(XElement.Parse(workspaceXml))) { testState.TestChangeSignatureOptionsService.IsCancelled = false; testState.TestChangeSignatureOptionsService.UpdatedSignature = updatedSignature; var result = testState.ChangeSignature(); Assert.True(result.Succeeded); Assert.Null(testState.ErrorMessage); foreach (var updatedDocument in testState.Workspace.Documents.Select(d => result.UpdatedSolution.GetDocument(d.Id))) { if (updatedDocument.Name == "C5.cs") { Assert.Contains("void Ext(this C5 c, string s)", (await updatedDocument.GetTextAsync(CancellationToken.None)).ToString()); } else { Assert.Contains(@"c.Ext(""two"");", (await updatedDocument.GetTextAsync(CancellationToken.None)).ToString()); } } } } [WpfFact] [Trait(Traits.Feature, Traits.Features.ChangeSignature)] [Trait(Traits.Feature, Traits.Features.Interactive)] public async Task ChangeSignatureCommandDisabledInSubmission() { var exportProvider = MinimalTestExportProvider.CreateExportProvider( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveDocumentSupportsFeatureService))); using (var workspace = await TestWorkspace.CreateAsync(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { void M$$(int x) { } } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, exportProvider: exportProvider)) { // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = new ChangeSignatureCommandHandler(); var delegatedToNext = false; Func<CommandState> nextHandler = () => { delegatedToNext = true; return CommandState.Unavailable; }; var state = handler.GetCommandState(new Commands.RemoveParametersCommandArgs(textView, textView.TextBuffer), nextHandler); Assert.True(delegatedToNext); Assert.False(state.IsAvailable); delegatedToNext = false; state = handler.GetCommandState(new Commands.ReorderParametersCommandArgs(textView, textView.TextBuffer), nextHandler); Assert.True(delegatedToNext); Assert.False(state.IsAvailable); } } } }
30.884984
171
0.517637
[ "Apache-2.0" ]
TronsGuitar/roslyn
src/EditorFeatures/CSharpTest/ChangeSignature/RemoveParametersTests.cs
9,669
C#
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace BTCPayServer.Migrations { public partial class PaymentAccounted : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<bool>( name: "Accounted", table: "Payments", nullable: false, defaultValue: false); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Accounted", table: "Payments"); } } }
26.307692
71
0.593567
[ "MIT" ]
2pac1/btcpayserver
BTCPayServer/Migrations/20171105235734_PaymentAccounted.cs
686
C#
using System; namespace TaxCalculator.Services.InputOutput.Implementation { public class ConsoleReader : IReader { public string ReadLine() => Console.ReadLine(); } }
18.272727
59
0.656716
[ "MIT" ]
LuGeorgiev/CSharpSelfLearning
SimpleTaxCalculator/TaxCalculator.Services/InputOutput/Implementation/ConsoleReader.cs
203
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Security.AccessControl; using System.Text; namespace Microsoft.Win32 { /// <summary>Registry encapsulation. To get an instance of a RegistryKey use the Registry class's static members then call OpenSubKey.</summary> public sealed partial class RegistryKey : MarshalByRefObject, IDisposable { private static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); private static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); private static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); private static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004)); private static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); /// <summary>Names of keys. This array must be in the same order as the HKEY values listed above.</summary> private static readonly string[] s_hkeyNames = new string[] { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_PERFORMANCE_DATA", "HKEY_CURRENT_CONFIG" }; // MSDN defines the following limits for registry key names & values: // Key Name: 255 characters // Value name: 16,383 Unicode characters // Value: either 1 MB or current available memory, depending on registry format. private const int MaxKeyLength = 255; private const int MaxValueLength = 16383; private volatile SafeRegistryHandle _hkey; private volatile string _keyName; private readonly bool _remoteKey; private volatile StateFlags _state; private volatile RegistryKeyPermissionCheck _checkMode; private readonly RegistryView _regView = RegistryView.Default; /// <summary> /// Creates a RegistryKey. This key is bound to hkey, if writable is <b>false</b> then no write operations will be allowed. /// </summary> private RegistryKey(SafeRegistryHandle hkey, bool writable, RegistryView view) : this(hkey, writable, false, false, false, view) { } /// <summary> /// Creates a RegistryKey. /// This key is bound to hkey, if writable is <b>false</b> then no write operations /// will be allowed. If systemkey is set then the hkey won't be released /// when the object is GC'ed. /// The remoteKey flag when set to true indicates that we are dealing with registry entries /// on a remote machine and requires the program making these calls to have full trust. /// </summary> private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) { ValidateKeyView(view); _hkey = hkey; _keyName = ""; _remoteKey = remoteKey; _regView = view; if (systemkey) { _state |= StateFlags.SystemKey; } if (writable) { _state |= StateFlags.WriteAccess; } if (isPerfData) { _state |= StateFlags.PerfData; } } public void Flush() { FlushCore(); } public void Close() { Dispose(); } public void Dispose() { if (_hkey != null) { if (!IsSystemKey()) { try { _hkey.Dispose(); } catch (IOException) { // we don't really care if the handle is invalid at this point } finally { _hkey = null!; } } else if (IsPerfDataKey()) { ClosePerfDataKey(); } } } /// <summary>Creates a new subkey, or opens an existing one.</summary> /// <param name="subkey">Name or path to subkey to create or open.</param> /// <returns>The subkey, or <b>null</b> if the operation failed.</returns> public RegistryKey CreateSubKey(string subkey) { return CreateSubKey(subkey, _checkMode); } public RegistryKey CreateSubKey(string subkey, bool writable) { return CreateSubKey(subkey, writable ? RegistryKeyPermissionCheck.ReadWriteSubTree : RegistryKeyPermissionCheck.ReadSubTree, RegistryOptions.None); } public RegistryKey CreateSubKey(string subkey, bool writable, RegistryOptions options) { return CreateSubKey(subkey, writable ? RegistryKeyPermissionCheck.ReadWriteSubTree : RegistryKeyPermissionCheck.ReadSubTree, options); } public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck) { return CreateSubKey(subkey, permissionCheck, RegistryOptions.None); } public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions, RegistrySecurity? registrySecurity) { return CreateSubKey(subkey, permissionCheck, registryOptions); } public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity? registrySecurity) { return CreateSubKey(subkey, permissionCheck, RegistryOptions.None); } public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions) { ValidateKeyOptions(registryOptions); ValidateKeyName(subkey); ValidateKeyMode(permissionCheck); EnsureWriteable(); subkey = FixupName(subkey); // Fixup multiple slashes to a single slash // only keys opened under read mode is not writable if (!_remoteKey) { RegistryKey? key = InternalOpenSubKeyWithoutSecurityChecks(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree)); if (key != null) { // Key already exits key._checkMode = permissionCheck; return key; } } return CreateSubKeyInternalCore(subkey, permissionCheck, registryOptions); } /// <summary> /// Deletes the specified subkey. Will throw an exception if the subkey has /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree. /// </summary> /// <param name="subkey">SubKey to delete.</param> /// <exception cref="InvalidOperationException">Thrown if the subkey has child subkeys.</exception> public void DeleteSubKey(string subkey) { DeleteSubKey(subkey, true); } public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) { ValidateKeyName(subkey); EnsureWriteable(); subkey = FixupName(subkey); // Fixup multiple slashes to a single slash // Open the key we are deleting and check for children. Be sure to // explicitly call close to avoid keeping an extra HKEY open. // RegistryKey? key = InternalOpenSubKeyWithoutSecurityChecks(subkey, false); if (key != null) { using (key) { if (key.SubKeyCount > 0) { throw new InvalidOperationException(SR.InvalidOperation_RegRemoveSubKey); } } DeleteSubKeyCore(subkey, throwOnMissingSubKey); } else // there is no key which also means there is no subkey { if (throwOnMissingSubKey) { throw new ArgumentException(SR.Arg_RegSubKeyAbsent); } } } /// <summary>Recursively deletes a subkey and any child subkeys.</summary> /// <param name="subkey">SubKey to delete.</param> public void DeleteSubKeyTree(string subkey) { DeleteSubKeyTree(subkey, throwOnMissingSubKey: true); } public void DeleteSubKeyTree(string subkey, bool throwOnMissingSubKey) { ValidateKeyName(subkey); // Security concern: Deleting a hive's "" subkey would delete all // of that hive's contents. Don't allow "". if (subkey.Length == 0 && IsSystemKey()) { throw new ArgumentException(SR.Arg_RegKeyDelHive); } EnsureWriteable(); subkey = FixupName(subkey); // Fixup multiple slashes to a single slash RegistryKey? key = InternalOpenSubKeyWithoutSecurityChecks(subkey, true); if (key != null) { using (key) { if (key.SubKeyCount > 0) { string[] keys = key.GetSubKeyNames(); for (int i = 0; i < keys.Length; i++) { key.DeleteSubKeyTreeInternal(keys[i]); } } } DeleteSubKeyTreeCore(subkey); } else if (throwOnMissingSubKey) { throw new ArgumentException(SR.Arg_RegSubKeyAbsent); } } /// <summary> /// An internal version which does no security checks or argument checking. Skipping the /// security checks should give us a slight perf gain on large trees. /// </summary> private void DeleteSubKeyTreeInternal(string subkey) { RegistryKey? key = InternalOpenSubKeyWithoutSecurityChecks(subkey, true); if (key != null) { using (key) { if (key.SubKeyCount > 0) { string[] keys = key.GetSubKeyNames(); for (int i = 0; i < keys.Length; i++) { key.DeleteSubKeyTreeInternal(keys[i]); } } } DeleteSubKeyTreeCore(subkey); } else { throw new ArgumentException(SR.Arg_RegSubKeyAbsent); } } /// <summary>Deletes the specified value from this key.</summary> /// <param name="name">Name of value to delete.</param> public void DeleteValue(string name) { DeleteValue(name, true); } public void DeleteValue(string name, bool throwOnMissingValue) { EnsureWriteable(); DeleteValueCore(name, throwOnMissingValue); } public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) { ValidateKeyView(view); return OpenBaseKeyCore(hKey, view); } /// <summary>Retrieves a new RegistryKey that represents the requested key on a foreign machine.</summary> /// <param name="hKey">hKey HKEY_* to open.</param> /// <param name="machineName">Name the machine to connect to.</param> /// <returns>The RegistryKey requested.</returns> public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName) { return OpenRemoteBaseKey(hKey, machineName, RegistryView.Default); } public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName!!, RegistryView view) { ValidateKeyView(view); return OpenRemoteBaseKeyCore(hKey, machineName, view); } /// <summary>Returns a subkey with read only permissions.</summary> /// <param name="name">Name or path of subkey to open.</param> /// <returns>The Subkey requested, or <b>null</b> if the operation failed.</returns> public RegistryKey? OpenSubKey(string name) { return OpenSubKey(name, false); } /// <summary> /// Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with /// read-only access. /// </summary> /// <param name="name">Name or the path of subkey to open.</param> /// <param name="writable">Set to <b>true</b> if you only need readonly access.</param> /// <returns>the Subkey requested, or <b>null</b> if the operation failed.</returns> public RegistryKey? OpenSubKey(string name, bool writable) { ValidateKeyName(name); EnsureNotDisposed(); name = FixupName(name); return InternalOpenSubKeyCore(name, writable); } public RegistryKey? OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck) { ValidateKeyMode(permissionCheck); return OpenSubKey(name, permissionCheck, (RegistryRights)GetRegistryKeyAccess(permissionCheck)); } public RegistryKey? OpenSubKey(string name, RegistryRights rights) { return OpenSubKey(name, this._checkMode, rights); } public RegistryKey? OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights) { ValidateKeyName(name); ValidateKeyMode(permissionCheck); ValidateKeyRights(rights); EnsureNotDisposed(); name = FixupName(name); // Fixup multiple slashes to a single slash return InternalOpenSubKeyCore(name, permissionCheck, (int)rights); } internal RegistryKey? InternalOpenSubKeyWithoutSecurityChecks(string name, bool writable) { ValidateKeyName(name); EnsureNotDisposed(); return InternalOpenSubKeyWithoutSecurityChecksCore(name, writable); } public RegistrySecurity GetAccessControl() { return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } public RegistrySecurity GetAccessControl(AccessControlSections includeSections) { EnsureNotDisposed(); return new RegistrySecurity(Handle, Name, includeSections); } public void SetAccessControl(RegistrySecurity registrySecurity) { EnsureWriteable(); ArgumentNullException.ThrowIfNull(registrySecurity); registrySecurity.Persist(Handle, Name); } /// <summary>Retrieves the count of subkeys.</summary> /// <returns>A count of subkeys.</returns> public int SubKeyCount { get { EnsureNotDisposed(); return InternalSubKeyCountCore(); } } public RegistryView View { get { EnsureNotDisposed(); return _regView; } } public SafeRegistryHandle Handle { get { EnsureNotDisposed(); return IsSystemKey() ? SystemKeyHandle : _hkey; } } public static RegistryKey FromHandle(SafeRegistryHandle handle) { return FromHandle(handle, RegistryView.Default); } public static RegistryKey FromHandle(SafeRegistryHandle handle!!, RegistryView view) { ValidateKeyView(view); return new RegistryKey(handle, writable: true, view: view); } /// <summary>Retrieves an array of strings containing all the subkey names.</summary> /// <returns>All subkey names.</returns> public string[] GetSubKeyNames() { EnsureNotDisposed(); int subkeys = SubKeyCount; return subkeys > 0 ? InternalGetSubKeyNamesCore(subkeys) : Array.Empty<string>(); } /// <summary>Retrieves the count of values.</summary> /// <returns>A count of values.</returns> public int ValueCount { get { EnsureNotDisposed(); return InternalValueCountCore(); } } /// <summary>Retrieves an array of strings containing all the value names.</summary> /// <returns>All value names.</returns> public string[] GetValueNames() { EnsureNotDisposed(); int values = ValueCount; return values > 0 ? GetValueNamesCore(values) : Array.Empty<string>(); } /// <summary>Retrieves the specified value. <b>null</b> is returned if the value doesn't exist</summary> /// <remarks> /// Note that <var>name</var> can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. /// </remarks> /// <param name="name">Name of value to retrieve.</param> /// <returns>The data associated with the value.</returns> public object? GetValue(string? name) { return InternalGetValue(name, null, false); } /// <summary>Retrieves the specified value. <i>defaultValue</i> is returned if the value doesn't exist.</summary> /// <remarks> /// Note that <var>name</var> can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. /// The default values for RegistryKeys are OS-dependent. NT doesn't /// have them by default, but they can exist and be of any type. On /// Win95, the default value is always an empty key of type REG_SZ. /// Win98 supports default values of any type, but defaults to REG_SZ. /// </remarks> /// <param name="name">Name of value to retrieve.</param> /// <param name="defaultValue">Value to return if <i>name</i> doesn't exist.</param> /// <returns>The data associated with the value.</returns> public object? GetValue(string? name, object? defaultValue) { return InternalGetValue(name, defaultValue, false); } public object? GetValue(string? name, object? defaultValue, RegistryValueOptions options) { if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options)); } bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames); return InternalGetValue(name, defaultValue, doNotExpand); } private object? InternalGetValue(string? name, object? defaultValue, bool doNotExpand) { EnsureNotDisposed(); return InternalGetValueCore(name, defaultValue, doNotExpand); } public RegistryValueKind GetValueKind(string? name) { EnsureNotDisposed(); return GetValueKindCore(name); } public string Name { get { EnsureNotDisposed(); return _keyName; } } /// <summary>Sets the specified value.</summary> /// <param name="name">Name of value to store data in.</param> /// <param name="value">Data to store.</param> public void SetValue(string? name, object value) { SetValue(name, value, RegistryValueKind.Unknown); } public void SetValue(string? name, object value!!, RegistryValueKind valueKind) { if (name != null && name.Length > MaxValueLength) { throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name)); } if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind)) { throw new ArgumentException(SR.Arg_RegBadKeyKind, nameof(valueKind)); } EnsureWriteable(); if (valueKind == RegistryValueKind.Unknown) { // this is to maintain compatibility with the old way of autodetecting the type. // SetValue(string, object) will come through this codepath. valueKind = CalculateValueKind(value); } SetValueCore(name, value, valueKind); } private RegistryValueKind CalculateValueKind(object value) { // This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days. // Even though we could add detection for an int64 in here, we want to maintain compatibility with the // old behavior. if (value is int) { return RegistryValueKind.DWord; } else if (value is Array) { if (value is byte[]) { return RegistryValueKind.Binary; } else if (value is string[]) { return RegistryValueKind.MultiString; } else { throw new ArgumentException(SR.Format(SR.Arg_RegSetBadArrType, value.GetType().Name)); } } else { return RegistryValueKind.String; } } /// <summary>Retrieves a string representation of this key.</summary> /// <returns>A string representing the key.</returns> public override string ToString() { EnsureNotDisposed(); return _keyName; } private static string FixupName(string name) { Debug.Assert(name != null, "[FixupName]name!=null"); if (!name.Contains('\\')) { return name; } StringBuilder sb = new StringBuilder(name); FixupPath(sb); int temp = sb.Length - 1; if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash { sb.Length = temp; } return sb.ToString(); } private static void FixupPath(StringBuilder path) { Debug.Assert(path != null); int length = path.Length; bool fixup = false; char markerChar = (char)0xFFFF; int i = 1; while (i < length - 1) { if (path[i] == '\\') { i++; while (i < length && path[i] == '\\') { path[i] = markerChar; i++; fixup = true; } } i++; } if (fixup) { i = 0; int j = 0; while (i < length) { if (path[i] == markerChar) { i++; continue; } path[j] = path[i]; i++; j++; } path.Length += j - i; } } private void EnsureNotDisposed() { if (_hkey == null) { throw new ObjectDisposedException(_keyName, SR.ObjectDisposed_RegKeyClosed); } } private void EnsureWriteable() { EnsureNotDisposed(); if (!IsWritable()) { throw new UnauthorizedAccessException(SR.UnauthorizedAccess_RegistryNoWrite); } } private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable) { if (_checkMode == RegistryKeyPermissionCheck.Default) { return _checkMode; } if (subkeyWritable) { return RegistryKeyPermissionCheck.ReadWriteSubTree; } else { return RegistryKeyPermissionCheck.ReadSubTree; } } private static void ValidateKeyName(string name!!) { int nextSlash = name.IndexOf('\\'); int current = 0; while (nextSlash >= 0) { if ((nextSlash - current) > MaxKeyLength) { throw new ArgumentException(SR.Arg_RegKeyStrLenBug, nameof(name)); } current = nextSlash + 1; nextSlash = name.IndexOf('\\', current); } if ((name.Length - current) > MaxKeyLength) { throw new ArgumentException(SR.Arg_RegKeyStrLenBug, nameof(name)); } } private static void ValidateKeyMode(RegistryKeyPermissionCheck mode) { if (mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree) { throw new ArgumentException(SR.Argument_InvalidRegistryKeyPermissionCheck, nameof(mode)); } } private static void ValidateKeyOptions(RegistryOptions options) { if (options < RegistryOptions.None || options > RegistryOptions.Volatile) { throw new ArgumentException(SR.Argument_InvalidRegistryOptionsCheck, nameof(options)); } } private static void ValidateKeyView(RegistryView view) { if (view != RegistryView.Default && view != RegistryView.Registry32 && view != RegistryView.Registry64) { throw new ArgumentException(SR.Argument_InvalidRegistryViewCheck, nameof(view)); } } private static void ValidateKeyRights(RegistryRights rights) { if (0 != (rights & ~RegistryRights.FullControl)) { // We need to throw SecurityException here for compatiblity reason, // although UnauthorizedAccessException will make more sense. throw new SecurityException(SR.Security_RegistryPermission); } } /// <summary>Retrieves the current state of the dirty property.</summary> /// <remarks>A key is marked as dirty if any operation has occurred that modifies the contents of the key.</remarks> /// <returns><b>true</b> if the key has been modified.</returns> private bool IsDirty() => (_state & StateFlags.Dirty) != 0; private bool IsSystemKey() => (_state & StateFlags.SystemKey) != 0; private bool IsWritable() => (_state & StateFlags.WriteAccess) != 0; private bool IsPerfDataKey() => (_state & StateFlags.PerfData) != 0; private void SetDirty() => _state |= StateFlags.Dirty; [Flags] private enum StateFlags { /// <summary>Dirty indicates that we have munged data that should be potentially written to disk.</summary> Dirty = 0x0001, /// <summary>SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened" or "closed".</summary> SystemKey = 0x0002, /// <summary>Access</summary> WriteAccess = 0x0004, /// <summary>Indicates if this key is for HKEY_PERFORMANCE_DATA</summary> PerfData = 0x0008 } } }
36.098485
167
0.554739
[ "MIT" ]
AUTOMATE-2001/runtime
src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs
28,590
C#
using System; using Perpetuum.Deployers; using Perpetuum.EntityFramework; using Perpetuum.ExportedTypes; using Perpetuum.Players; using Perpetuum.Units; namespace Perpetuum.Zones.Teleporting { public class MobileTeleportDeployer : ItemDeployer { private readonly TeleportWorldTargetHelper _worldTargetHelper; public MobileTeleportDeployer(IEntityServices entityServices,TeleportWorldTargetHelper worldTargetHelper) : base(entityServices) { _worldTargetHelper = worldTargetHelper; } public TeleportWorldTargetHelper WorldTargetHelper => _worldTargetHelper; protected override Unit CreateDeployableItem(IZone zone, Position spawnPosition, Player player) { var mobileTeleport = (MobileTeleport)base.CreateDeployableItem(zone, spawnPosition, player); mobileTeleport.CheckDeploymentAndThrow(zone,spawnPosition); mobileTeleport.SetDespawnTime(MobileTeleportDespawnTime); mobileTeleport.SetCooldownInterval(MobileTeleportCooldown); return mobileTeleport; } private TimeSpan MobileTeleportCooldown { get { var m = GetPropertyModifier(AggregateField.mobile_teleport_cooldown); return TimeSpan.FromMilliseconds(m.Value); } } private TimeSpan MobileTeleportDespawnTime { get { var m = GetPropertyModifier(AggregateField.despawn_time); return TimeSpan.FromMilliseconds((int)m.Value); } } public int WorkingRange { get { var targetDefinition = DeployableItemEntityDefault; var dc = targetDefinition.Config; if (dc.item_work_range == null) { return (int) DistanceConstants.MOBILE_WORLD_TELEPORT_RANGE; } return (int) dc.item_work_range; } } } }
30.597015
136
0.631707
[ "MIT" ]
LoyalServant/PerpetuumServerCore
Perpetuum/Zones/Teleporting/MobileTeleportDeployer.cs
2,050
C#