context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** * an implementation of the AES (Rijndael)), from FIPS-197. * <p> * For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a> * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor), they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations), 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each), for a total of 2Kbytes), * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first * * The slowest version uses no static tables at all and computes the values in each round * </p> * <p> * This file contains the fast version with 8Kbytes of static tables for round precomputation * </p> */ public class AesFastEngine : IBlockCipher { // The S box private static readonly byte[] _s = { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22 }; // The inverse S-box private static readonly byte[] _si = { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125 }; // vector used in calculating key schedule (powers of x in GF(256)) private static readonly byte[] _rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static readonly uint[] _t0 = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c }; private static readonly uint[] _t1 = { 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a }; private static readonly uint[] _t2 = { 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16 }; private static readonly uint[] _t3 = { 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616 }; private static readonly uint[] _tinv0 = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0 }; private static readonly uint[] _tinv1 = { 0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, 0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, 0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042 }; private static readonly uint[] _tinv2 = { 0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c, 0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257 }; private static readonly uint[] _tinv3 = { 0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a, 0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19, 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000, 0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8 }; private static uint Shift(uint r, int shift) { return (r >> shift) | (r << (32 - shift)); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private const uint M1 = 0x80808080; private const uint M2 = 0x7f7f7f7f; private const uint M3 = 0x0000001b; private static uint FFmulX(uint x) { return ((x & M2) << 1) ^ (((x & M1) >> 7) * M3); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private static uint InvMcol(uint x) { var f2 = FFmulX(x); var f4 = FFmulX(f2); var f8 = FFmulX(f4); var f9 = x ^ f8; return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24); } private static uint SubWord(uint x) { return _s[x & 255] | (((uint)_s[(x >> 8) & 255]) << 8) | (((uint)_s[(x >> 16) & 255]) << 16) | (((uint)_s[(x >> 24) & 255]) << 24); } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private uint[,] GenerateWorkingKey(byte[] key, bool forEncryption) { var kc = key.Length / 4; // key length in words if (((kc != 4) && (kc != 6) && (kc != 8)) || ((kc * 4) != key.Length)) throw new ArgumentException("Key length not 128/192/256 bits."); _rounds = kc + 6; // This is not always true for the generalized Rijndael that allows larger block sizes var w = new uint[_rounds + 1, 4]; // 4 words in a block // // copy the key into the round key array // var t = 0; for (var i = 0; i < key.Length; t++) { w[t >> 2, t & 3] = Pack.LE_To_UInt32(key, i); i += 4; } // // while not enough round key material calculated // calculate new values // var k = (_rounds + 1) << 2; for (var i = kc; (i < k); i++) { var temp = w[(i - 1) >> 2, (i - 1) & 3]; if ((i % kc) == 0) { temp = SubWord(Shift(temp, 8)) ^ _rcon[(i / kc) - 1]; } else if ((kc > 6) && ((i % kc) == 4)) { temp = SubWord(temp); } w[i >> 2, i & 3] = w[(i - kc) >> 2, (i - kc) & 3] ^ temp; } if (!forEncryption) { for (var j = 1; j < _rounds; j++) { for (var i = 0; i < 4; i++) { w[j, i] = InvMcol(w[j, i]); } } } return w; } private int _rounds; private uint[,] _workingKey; private uint _c0, _c1, _c2, _c3; private bool _forEncryption; private const int BlockSize = 16; /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init(bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType()); _workingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey(), forEncryption); _forEncryption = forEncryption; } public string AlgorithmName { get { return "AES"; } } public bool IsPartialBlockOkay { get { return false; } } public int GetBlockSize() { return BlockSize; } public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (_workingKey == null) { throw new InvalidOperationException("AES engine not initialised"); } if ((inOff + (32 / 2)) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (32 / 2)) > output.Length) { throw new DataLengthException("output buffer too short"); } UnPackBlock(input, inOff); if (_forEncryption) { EncryptBlock(_workingKey); } else { DecryptBlock(_workingKey); } PackBlock(output, outOff); return BlockSize; } public void Reset() { } private void UnPackBlock(byte[] bytes, int off) { _c0 = Pack.LE_To_UInt32(bytes, off); _c1 = Pack.LE_To_UInt32(bytes, off + 4); _c2 = Pack.LE_To_UInt32(bytes, off + 8); _c3 = Pack.LE_To_UInt32(bytes, off + 12); } private void PackBlock(byte[] bytes, int off) { Pack.UInt32_To_LE(_c0, bytes, off); Pack.UInt32_To_LE(_c1, bytes, off + 4); Pack.UInt32_To_LE(_c2, bytes, off + 8); Pack.UInt32_To_LE(_c3, bytes, off + 12); } private void EncryptBlock(uint[,] kw) { int r; uint r0, r1, r2, r3; _c0 ^= kw[0, 0]; _c1 ^= kw[0, 1]; _c2 ^= kw[0, 2]; _c3 ^= kw[0, 3]; for (r = 1; r < _rounds - 1; ) { r0 = _t0[_c0 & 255] ^ _t1[(_c1 >> 8) & 255] ^ _t2[(_c2 >> 16) & 255] ^ _t3[_c3 >> 24] ^ kw[r, 0]; r1 = _t0[_c1 & 255] ^ _t1[(_c2 >> 8) & 255] ^ _t2[(_c3 >> 16) & 255] ^ _t3[_c0 >> 24] ^ kw[r, 1]; r2 = _t0[_c2 & 255] ^ _t1[(_c3 >> 8) & 255] ^ _t2[(_c0 >> 16) & 255] ^ _t3[_c1 >> 24] ^ kw[r, 2]; r3 = _t0[_c3 & 255] ^ _t1[(_c0 >> 8) & 255] ^ _t2[(_c1 >> 16) & 255] ^ _t3[_c2 >> 24] ^ kw[r++, 3]; _c0 = _t0[r0 & 255] ^ _t1[(r1 >> 8) & 255] ^ _t2[(r2 >> 16) & 255] ^ _t3[r3 >> 24] ^ kw[r, 0]; _c1 = _t0[r1 & 255] ^ _t1[(r2 >> 8) & 255] ^ _t2[(r3 >> 16) & 255] ^ _t3[r0 >> 24] ^ kw[r, 1]; _c2 = _t0[r2 & 255] ^ _t1[(r3 >> 8) & 255] ^ _t2[(r0 >> 16) & 255] ^ _t3[r1 >> 24] ^ kw[r, 2]; _c3 = _t0[r3 & 255] ^ _t1[(r0 >> 8) & 255] ^ _t2[(r1 >> 16) & 255] ^ _t3[r2 >> 24] ^ kw[r++, 3]; } r0 = _t0[_c0 & 255] ^ _t1[(_c1 >> 8) & 255] ^ _t2[(_c2 >> 16) & 255] ^ _t3[_c3 >> 24] ^ kw[r, 0]; r1 = _t0[_c1 & 255] ^ _t1[(_c2 >> 8) & 255] ^ _t2[(_c3 >> 16) & 255] ^ _t3[_c0 >> 24] ^ kw[r, 1]; r2 = _t0[_c2 & 255] ^ _t1[(_c3 >> 8) & 255] ^ _t2[(_c0 >> 16) & 255] ^ _t3[_c1 >> 24] ^ kw[r, 2]; r3 = _t0[_c3 & 255] ^ _t1[(_c0 >> 8) & 255] ^ _t2[(_c1 >> 16) & 255] ^ _t3[_c2 >> 24] ^ kw[r++, 3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it _c0 = _s[r0 & 255] ^ (((uint)_s[(r1 >> 8) & 255]) << 8) ^ (((uint)_s[(r2 >> 16) & 255]) << 16) ^ (((uint)_s[r3 >> 24]) << 24) ^ kw[r, 0]; _c1 = _s[r1 & 255] ^ (((uint)_s[(r2 >> 8) & 255]) << 8) ^ (((uint)_s[(r3 >> 16) & 255]) << 16) ^ (((uint)_s[r0 >> 24]) << 24) ^ kw[r, 1]; _c2 = _s[r2 & 255] ^ (((uint)_s[(r3 >> 8) & 255]) << 8) ^ (((uint)_s[(r0 >> 16) & 255]) << 16) ^ (((uint)_s[r1 >> 24]) << 24) ^ kw[r, 2]; _c3 = _s[r3 & 255] ^ (((uint)_s[(r0 >> 8) & 255]) << 8) ^ (((uint)_s[(r1 >> 16) & 255]) << 16) ^ (((uint)_s[r2 >> 24]) << 24) ^ kw[r, 3]; } private void DecryptBlock(uint[,] kw) { int r; uint r0, r1, r2, r3; _c0 ^= kw[_rounds, 0]; _c1 ^= kw[_rounds, 1]; _c2 ^= kw[_rounds, 2]; _c3 ^= kw[_rounds, 3]; for (r = _rounds - 1; r > 1; ) { r0 = _tinv0[_c0 & 255] ^ _tinv1[(_c3 >> 8) & 255] ^ _tinv2[(_c2 >> 16) & 255] ^ _tinv3[_c1 >> 24] ^ kw[r, 0]; r1 = _tinv0[_c1 & 255] ^ _tinv1[(_c0 >> 8) & 255] ^ _tinv2[(_c3 >> 16) & 255] ^ _tinv3[_c2 >> 24] ^ kw[r, 1]; r2 = _tinv0[_c2 & 255] ^ _tinv1[(_c1 >> 8) & 255] ^ _tinv2[(_c0 >> 16) & 255] ^ _tinv3[_c3 >> 24] ^ kw[r, 2]; r3 = _tinv0[_c3 & 255] ^ _tinv1[(_c2 >> 8) & 255] ^ _tinv2[(_c1 >> 16) & 255] ^ _tinv3[_c0 >> 24] ^ kw[r--, 3]; _c0 = _tinv0[r0 & 255] ^ _tinv1[(r3 >> 8) & 255] ^ _tinv2[(r2 >> 16) & 255] ^ _tinv3[r1 >> 24] ^ kw[r, 0]; _c1 = _tinv0[r1 & 255] ^ _tinv1[(r0 >> 8) & 255] ^ _tinv2[(r3 >> 16) & 255] ^ _tinv3[r2 >> 24] ^ kw[r, 1]; _c2 = _tinv0[r2 & 255] ^ _tinv1[(r1 >> 8) & 255] ^ _tinv2[(r0 >> 16) & 255] ^ _tinv3[r3 >> 24] ^ kw[r, 2]; _c3 = _tinv0[r3 & 255] ^ _tinv1[(r2 >> 8) & 255] ^ _tinv2[(r1 >> 16) & 255] ^ _tinv3[r0 >> 24] ^ kw[r--, 3]; } r0 = _tinv0[_c0 & 255] ^ _tinv1[(_c3 >> 8) & 255] ^ _tinv2[(_c2 >> 16) & 255] ^ _tinv3[_c1 >> 24] ^ kw[r, 0]; r1 = _tinv0[_c1 & 255] ^ _tinv1[(_c0 >> 8) & 255] ^ _tinv2[(_c3 >> 16) & 255] ^ _tinv3[_c2 >> 24] ^ kw[r, 1]; r2 = _tinv0[_c2 & 255] ^ _tinv1[(_c1 >> 8) & 255] ^ _tinv2[(_c0 >> 16) & 255] ^ _tinv3[_c3 >> 24] ^ kw[r, 2]; r3 = _tinv0[_c3 & 255] ^ _tinv1[(_c2 >> 8) & 255] ^ _tinv2[(_c1 >> 16) & 255] ^ _tinv3[_c0 >> 24] ^ kw[r, 3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it _c0 = _si[r0 & 255] ^ (((uint)_si[(r3 >> 8) & 255]) << 8) ^ (((uint)_si[(r2 >> 16) & 255]) << 16) ^ (((uint)_si[r1 >> 24]) << 24) ^ kw[0, 0]; _c1 = _si[r1 & 255] ^ (((uint)_si[(r0 >> 8) & 255]) << 8) ^ (((uint)_si[(r3 >> 16) & 255]) << 16) ^ (((uint)_si[r2 >> 24]) << 24) ^ kw[0, 1]; _c2 = _si[r2 & 255] ^ (((uint)_si[(r1 >> 8) & 255]) << 8) ^ (((uint)_si[(r0 >> 16) & 255]) << 16) ^ (((uint)_si[r3 >> 24]) << 24) ^ kw[0, 2]; _c3 = _si[r3 & 255] ^ (((uint)_si[(r2 >> 8) & 255]) << 8) ^ (((uint)_si[(r1 >> 16) & 255]) << 16) ^ (((uint)_si[r0 >> 24]) << 24) ^ kw[0, 3]; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Trollbridge.WebApi.Areas.HelpPage.ModelDescriptions; using Trollbridge.WebApi.Areas.HelpPage.Models; namespace Trollbridge.WebApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TraceManagerConfigTests.cs"> // Copyright (c) 2011-2016 https://github.com/logjam2. // </copyright> // Licensed under the <a href="https://github.com/logjam2/logjam/blob/master/LICENSE.txt">Apache License, Version 2.0</a>; // you may not use this file except in compliance with the License. // -------------------------------------------------------------------------------------------------------------------- namespace LogJam.UnitTests.Trace.Config { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; using LogJam.Config; using LogJam.Config.Json; using LogJam.Internal.UnitTests.Examples; using LogJam.Trace; using LogJam.Trace.Config; using LogJam.Trace.Format; using LogJam.Trace.Switches; using LogJam.Writer; using Json = Newtonsoft.Json; using Xunit; using Xunit.Abstractions; using LogJam.Shared.Internal; /// <summary> /// Exercises use cases for <see cref="TraceManager.Config" /> modification. /// </summary> public sealed class TraceManagerConfigTests { private readonly ITestOutputHelper _testOutputHelper; public TraceManagerConfigTests(ITestOutputHelper testOutputHelper) { Arg.NotNull(testOutputHelper, nameof(testOutputHelper)); _testOutputHelper = testOutputHelper; } [Theory] [InlineData(ConfigForm.ObjectGraph)] [InlineData(ConfigForm.Fluent)] public void TraceToString(ConfigForm configForm) { var stringWriter = new StringWriter(); TraceManager traceManager; if (configForm == ConfigForm.ObjectGraph) { var config = new TextWriterLogWriterConfig(stringWriter).Format(new DefaultTraceFormatter() { IncludeDate = true, IncludeTimestamp = true }); traceManager = new TraceManager(config); } else if (configForm == ConfigForm.Fluent) { traceManager = new TraceManager(); traceManager.Config.TraceTo(stringWriter, traceFormatter: new DefaultTraceFormatter() { IncludeDate = true, IncludeTimestamp = true }); } else { throw new NotImplementedException(); } using (traceManager) { var tracer = traceManager.TracerFor(this); Assert.True(traceManager.IsStarted()); Assert.True(traceManager.LogManager.IsStarted()); Assert.True(tracer.IsInfoEnabled()); Assert.False(tracer.IsVerboseEnabled()); Assert.True(traceManager.IsHealthy); //Assert.Single(tracer.Writers); //Assert.IsType<DebuggerLogWriter>(tracer.Writers[0].innerEntryWriter); tracer.Info("Info message"); tracer.Debug("Debug message not written"); } Assert.Matches(@"Info\s+LJ\.UT\.T\.Config\.TraceManagerConfigTests\s+Info message\r\n", stringWriter.ToString()); _testOutputHelper.WriteEntries(traceManager.SetupLog); Assert.False(traceManager.IsStarted()); Assert.False(traceManager.LogManager.IsStarted()); Assert.True(traceManager.State == StartableState.Disposed); Assert.True(traceManager.LogManager.State == StartableState.Disposed); Assert.True(traceManager.IsHealthy); } /// <summary> /// Ensures that everything works as expected when no TraceWriterConfig elements are configured. /// </summary> [Fact] public void NoTraceWritersConfiguredWorks() { var traceManagerConfig = new TraceManagerConfig(); Assert.Empty(traceManagerConfig.Writers); using (var traceManager = new TraceManager(traceManagerConfig)) { traceManager.Start(); var tracer = traceManager.TracerFor(this); Assert.False(tracer.IsInfoEnabled()); tracer.Info("Info"); } } //[Fact] //public void RootThresholdCanBeSetOnInitialization() //{ // var listTraceLog = new ListLogWriter<TraceEntry>(); // // Trace output has threshold == Error // using (var traceManager = new TraceManager(listTraceLog, new ThresholdTraceSwitch(TraceLevel.Error))) // { // var tracer = traceManager.TracerFor(this); // Assert.False(tracer.IsInfoEnabled()); // Assert.False(tracer.IsWarnEnabled()); // Assert.True(tracer.IsErrorEnabled()); // Assert.True(tracer.IsSevereEnabled()); // } //} [Fact] public void RootThresholdCanBeModifiedAfterTracing() { var setupTracerFactory = new SetupLog(); var listLogWriter = new ListLogWriter<TraceEntry>(setupTracerFactory); // Start with threshold == Info var traceSwitch = new ThresholdTraceSwitch(TraceLevel.Info); using (var traceManager = new TraceManager(listLogWriter, traceSwitch)) { traceManager.Start(); var tracer = traceManager.TracerFor(this); // Log stuff tracer.Info("Info"); // Should log tracer.Verbose("Verbose"); // Shouldn't log Assert.Single(listLogWriter); // Change threshold traceSwitch.Threshold = TraceLevel.Verbose; // Log tracer.Info("Info"); tracer.Verbose("Verbose"); // Should log tracer.Debug("Debug"); // Shouldn't log Assert.Equal(3, listLogWriter.Count()); } } //[Fact] //public void RootLogWriterCanBeReplacedAfterTracing() //{ // // First log entry is written here // var initialList = new ListLogWriter<TraceEntry>(); // var secondList = new ListLogWriter<TraceEntry>(); // var rootTracerConfig = new TracerConfig(Tracer.RootTracerName, new ThresholdTraceSwitch(TraceLevel.Info), initialList); // using (var traceManager = new TraceManager(rootTracerConfig)) // { // var tracer = traceManager.TracerFor(this); // tracer.Info("Info"); // tracer.Verbose("Verbose"); // Shouldn't log // Assert.Equal(1, initialList.Count); // // Change LogWriter // rootTracerConfig.Replace(null, secondList); // // Log // tracer.Info("Info"); // tracer.Verbose("Verbose"); // Shouldn't log // Assert.Equal(1, secondList.Count); // } //} //[Fact] //public void RootLogWriterCanBeAddedAfterTracing() //{ // var initialList = new ListLogWriter<TraceEntry>(); // var secondList = new ListLogWriter<TraceEntry>(); // var rootTracerConfig = new TracerConfig(Tracer.RootTracerName, new ThresholdTraceSwitch(TraceLevel.Info), initialList); // using (var traceManager = new TraceManager(rootTracerConfig)) // { // var tracer = traceManager.TracerFor(this); // tracer.Info("Info"); // tracer.Verbose("Verbose"); // Shouldn't log // Assert.Equal(1, initialList.Count); // // Add a LogWriter // rootTracerConfig.Add(new OnOffTraceSwitch(true), secondList); // // Log // tracer.Info("Info"); // tracer.Verbose("Verbose"); // Shouldn't log to first // Assert.Equal(2, initialList.Count); // Assert.Equal(2, secondList.Count); // Assert.DoesNotContain("Verbose", initialList.Select(entry => entry.Message)); // Assert.Contains("Verbose", secondList.Select(entry => entry.Message)); // } //} [Fact(Skip = "Not yet implemented")] public void RootLogWriterCanBeAddedThenRemoved() {} [Fact(Skip = "Not yet implemented")] public void NonRootThresholdCanBeModified() {} [Fact(Skip = "Not yet implemented")] public void NonRootLogWriterCanBeReplaced() {} [Fact(Skip = "Not yet implemented")] public void NonRootLogWriterCanBeAdded() {} [Fact(Skip = "Not yet implemented")] public void NonRootLogWriterCanBeAddedThenRemoved() {} [Fact(Skip = "Not yet implemented")] public void CanReadTraceManagerConfigFromFile() {} [Fact] public void MultipleTraceLogWritersForSameNamePrefixWithDifferentSwitchThresholds() { var setupTracerFactory = new SetupLog(); var allListLogWriter = new ListLogWriter<TraceEntry>(setupTracerFactory); var errorListLogWriter = new ListLogWriter<TraceEntry>(setupTracerFactory); var traceWriterConfigAll = new TraceWriterConfig(allListLogWriter) { Switches = { { "LogJam.UnitTests", new OnOffTraceSwitch(true) } } }; var traceWriterConfigErrors = new TraceWriterConfig(errorListLogWriter) { Switches = { { "LogJam.UnitTests", new ThresholdTraceSwitch(TraceLevel.Error) } } }; using (var traceManager = new TraceManager(new TraceManagerConfig(traceWriterConfigAll, traceWriterConfigErrors), setupTracerFactory)) { var tracer = traceManager.TracerFor(this); var fooTracer = traceManager.GetTracer("foo"); tracer.Info("Info"); tracer.Verbose("Verbose"); tracer.Error("Error"); tracer.Severe("Severe"); // fooTracer shouldn't log to either of these lists fooTracer.Severe("foo Severe"); Assert.Equal(2, errorListLogWriter.Count); Assert.Equal(4, allListLogWriter.Count); } } public static IEnumerable<object[]> TestTraceManagerConfigs { get { // test TraceManagerConfig #1 var config = new TraceManagerConfig( new TraceWriterConfig() { LogWriterConfig = new ListLogWriterConfig<TraceEntry>(), Switches = { { Tracer.All, new ThresholdTraceSwitch(TraceLevel.Info) }, { "Microsoft.WebApi.", new ThresholdTraceSwitch(TraceLevel.Warn) } } }, new TraceWriterConfig() { LogWriterConfig = new DebuggerLogWriterConfig(), Switches = { { Tracer.All, new ThresholdTraceSwitch(TraceLevel.Info) }, } }); yield return new object[] { config }; } } [Theory(Skip = "Not yet implemented")] [MemberData(nameof(TestTraceManagerConfigs))] public void CanRoundTripTraceManagerConfigToJson(TraceManagerConfig traceManagerConfig) { var jsonSettings = new Json.JsonSerializerSettings(); jsonSettings.ContractResolver = new JsonConfigContractResolver(jsonSettings.ContractResolver); string json = Json.JsonConvert.SerializeObject(traceManagerConfig, Json.Formatting.Indented, jsonSettings); _testOutputHelper.WriteLine(json); // TODO: Deserialize back to TraceManagerConfig, then validate that the config is equal. } [Theory(Skip = "Not yet implemented")] [MemberData(nameof(TestTraceManagerConfigs))] public void CanRoundTripTraceManagerConfigToXml(TraceManagerConfig traceManagerConfig) { // Serialize to xml XmlSerializer xmlSerializer = new XmlSerializer(typeof(TraceManagerConfig)); var sw = new StringWriter(); xmlSerializer.Serialize(sw, traceManagerConfig); string xml = sw.ToString(); _testOutputHelper.WriteLine(xml); // Deserialize back to TraceManagerConfig TraceManagerConfig deserializedConfig = (TraceManagerConfig) xmlSerializer.Deserialize(new StringReader(xml)); Assert.Equal(traceManagerConfig, deserializedConfig); } [Fact] public void ConfigCanBeChangedAfterStarting() { var setupTracerFactory = new SetupLog(); var logWriter = new ListLogWriter<TraceEntry>(setupTracerFactory); var config = new TraceManagerConfig(); // TODO: Rename to tracerConfig? var traceWriterConfig = config.UseLogWriter(logWriter, "A"); // Only logs for tracer A TraceManager traceManager; using (traceManager = new TraceManager(config, setupTracerFactory)) { var tracerA = traceManager.GetTracer("A"); var tracerB = traceManager.GetTracer("B"); Assert.True(traceManager.IsStarted()); Assert.True(traceManager.LogManager.IsStarted()); Assert.True(tracerA.IsInfoEnabled()); Assert.False(tracerB.IsInfoEnabled()); // Option 1: Change the config traceWriterConfig.Switches.Add("B", new OnOffTraceSwitch(true)); traceManager.Start(); // Explicit restart required Assert.True(tracerB.IsInfoEnabled()); Assert.True(tracerB.IsDebugEnabled()); // For option 2, see the next test: AddNewTracerConfigToSameWriterAfterStarting } } [Fact] public void AddNewTracerConfigToSameWriterAfterStarting() { var setupTracerFactory = new SetupLog(); var logWriter = new ListLogWriter<TraceEntry>(setupTracerFactory); var config = new TraceManagerConfig(); config.UseLogWriter(logWriter, "A"); // Only logs for tracer A TraceManager traceManager; using (traceManager = new TraceManager(config, setupTracerFactory)) { var tracerA = traceManager.GetTracer("A"); var tracerB = traceManager.GetTracer("B"); Assert.True(traceManager.IsStarted()); Assert.True(tracerA.IsInfoEnabled()); Assert.False(tracerB.IsInfoEnabled()); // For option 1, see the previous test: ConfigCanBeChangedAfterStarting // Option 2: Add a new TraceWriterConfig, and restart, to enable B config.UseLogWriter(logWriter, "B", new OnOffTraceSwitch(true)); Assert.False(tracerB.IsInfoEnabled()); // before the restart, tracerB is disabled traceManager.Start(); Assert.True(tracerB.IsInfoEnabled()); Assert.True(tracerB.IsDebugEnabled()); } } [Fact] public void AddingTraceWriterConfigUpdatesLogManagerConfig() { var textWriterLogWriterConfig = new TextWriterLogWriterConfig(new StringWriter()); var logWriterConfigs = new ILogWriterConfig[] { new ListLogWriterConfig<TraceEntry>(), textWriterLogWriterConfig }; using (var traceManager = new TraceManager()) { foreach (var logWriterConfig in logWriterConfigs) { traceManager.Config.Writers.Add(new TraceWriterConfig(logWriterConfig, TraceManagerConfig.CreateDefaultSwitchSet())); Assert.Contains(traceManager.LogManager.Config.Writers, lwc => lwc == logWriterConfig); } } } [Fact] public void RemovingTraceWriterConfigDoesNotRemoveLogWriterConfigs() { var textWriterLogWriterConfig = new TextWriterLogWriterConfig(new StringWriter()); var logWriterConfigs = new ILogWriterConfig[] { new ListLogWriterConfig<TraceEntry>(), textWriterLogWriterConfig }; var traceWriterConfigs = new List<TraceWriterConfig>(); using (var traceManager = new TraceManager()) { foreach (var logWriterConfig in logWriterConfigs) { traceWriterConfigs.Add(new TraceWriterConfig(logWriterConfig, TraceManagerConfig.CreateDefaultSwitchSet())); } traceManager.Config.Writers.UnionWith(traceWriterConfigs); // Test removing each for (int i = 0; i < logWriterConfigs.Length; ++i) { var logWriterConfig = logWriterConfigs[i]; var traceWriterConfig = traceWriterConfigs[i]; // Each logWriterConfig should exist in the LogManagerConfig before it is removed from the TraceManagerConfig Assert.Contains(traceManager.LogManager.Config.Writers, lwc => lwc == logWriterConfig); traceManager.Config.Writers.Remove(traceWriterConfig); Assert.DoesNotContain(traceManager.Config.Writers, twc => twc == traceWriterConfig); // LogWriters are left in place, because they may be used for other purposes Assert.Contains(traceManager.LogManager.Config.Writers, lwc => lwc == logWriterConfig); } } } [Fact] public void RemovingTraceWriterConfigLeavesWritersFormattedForOtherEntryTypes() { var textWriterLogWriterConfig = new TextWriterLogWriterConfig(new StringWriter()); textWriterLogWriterConfig.Format<MessageEntry>(); using (var traceManager = new TraceManager()) { // Add tracing to the textWriter var traceWriterConfig = traceManager.Config.TraceTo(textWriterLogWriterConfig); // The textWriterLogWriter should now include formatters for 2 entry types Assert.True(textWriterLogWriterConfig.HasFormatterFor<TraceEntry>()); Assert.True(textWriterLogWriterConfig.HasFormatterFor<MessageEntry>()); // Remove the LogWriter from LogManager.Config traceManager.LogManager.Config.Writers.Remove(textWriterLogWriterConfig); // Now it should not exist either in the TraceManagerConfig or the LogManagerConfig Assert.DoesNotContain(traceManager.LogManager.Config.Writers, lwc => lwc == textWriterLogWriterConfig); Assert.DoesNotContain(traceManager.Config.Writers, twc => twc == traceWriterConfig); // Add tracing to the textWriter (again) traceWriterConfig = traceManager.Config.TraceTo(textWriterLogWriterConfig); // Now it should exist in both the TraceManagerConfig and the LogManagerConfig Assert.Contains(traceManager.LogManager.Config.Writers, lwc => lwc == textWriterLogWriterConfig); Assert.Contains(traceManager.Config.Writers, twc => twc == traceWriterConfig); // Remove tracing to the textWriter Assert.True(traceManager.Config.Writers.Remove(traceWriterConfig)); // Now it should exist only in the LogManagerConfig Assert.Contains(traceManager.LogManager.Config.Writers, lwc => lwc == textWriterLogWriterConfig); Assert.DoesNotContain(traceManager.Config.Writers, twc => twc == traceWriterConfig); } } } }
// 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.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; namespace System.Diagnostics { /// <summary> /// Performance Counter component. /// This class provides support for NT Performance counters. /// It handles both the existing counters (accessible by Perf Registry Interface) /// and user defined (extensible) counters. /// This class is a part of a larger framework, that includes the perf dll object and /// perf service. /// </summary> public sealed class PerformanceCounter : Component, ISupportInitialize { private string _machineName; private string _categoryName; private string _counterName; private string _instanceName; private PerformanceCounterInstanceLifetime _instanceLifetime = PerformanceCounterInstanceLifetime.Global; private bool _isReadOnly; private bool _initialized = false; private string _helpMsg = null; private int _counterType = -1; // Cached old sample private CounterSample _oldSample = CounterSample.Empty; // Cached IP Shared Performanco counter private SharedPerformanceCounter _sharedCounter; [ObsoleteAttribute("This field has been deprecated and is not used. Use machine.config or an application configuration file to set the size of the PerformanceCounter file mapping.")] public static int DefaultFileMappingSize = 524288; private object _instanceLockObject; private object InstanceLockObject { get { if (_instanceLockObject == null) { object o = new object(); Interlocked.CompareExchange(ref _instanceLockObject, o, null); } return _instanceLockObject; } } /// <summary> /// The defaut constructor. Creates the perf counter object /// </summary> public PerformanceCounter() { _machineName = "."; _categoryName = string.Empty; _counterName = string.Empty; _instanceName = string.Empty; _isReadOnly = true; GC.SuppressFinalize(this); } /// <summary> /// Creates the Performance Counter Object /// </summary> public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName) { MachineName = machineName; CategoryName = categoryName; CounterName = counterName; InstanceName = instanceName; _isReadOnly = true; Initialize(); GC.SuppressFinalize(this); } internal PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName, bool skipInit) { MachineName = machineName; CategoryName = categoryName; CounterName = counterName; InstanceName = instanceName; _isReadOnly = true; _initialized = true; GC.SuppressFinalize(this); } /// <summary> /// Creates the Performance Counter Object on local machine. /// </summary> public PerformanceCounter(string categoryName, string counterName, string instanceName) : this(categoryName, counterName, instanceName, true) { } /// <summary> /// Creates the Performance Counter Object on local machine. /// </summary> public PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly) { if (!readOnly) { VerifyWriteableCounterAllowed(); } MachineName = "."; CategoryName = categoryName; CounterName = counterName; InstanceName = instanceName; _isReadOnly = readOnly; Initialize(); GC.SuppressFinalize(this); } /// <summary> /// Creates the Performance Counter Object, assumes that it's a single instance /// </summary> public PerformanceCounter(string categoryName, string counterName) : this(categoryName, counterName, true) { } /// <summary> /// Creates the Performance Counter Object, assumes that it's a single instance /// </summary> public PerformanceCounter(string categoryName, string counterName, bool readOnly) : this(categoryName, counterName, "", readOnly) { } /// <summary> /// Returns the performance category name for this performance counter /// </summary> public string CategoryName { get { return _categoryName; } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (_categoryName == null || !string.Equals(_categoryName, value, StringComparison.OrdinalIgnoreCase)) { _categoryName = value; Close(); } } } /// <summary> /// Returns the description message for this performance counter /// </summary> public string CounterHelp { get { string currentCategoryName = _categoryName; string currentMachineName = _machineName; Initialize(); if (_helpMsg == null) _helpMsg = PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, _counterName); return _helpMsg; } } /// <summary> /// Sets/returns the performance counter name for this performance counter /// </summary> public string CounterName { get { return _counterName; } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (_counterName == null || !string.Equals(_counterName, value, StringComparison.OrdinalIgnoreCase)) { _counterName = value; Close(); } } } /// <summary> /// Sets/Returns the counter type for this performance counter /// </summary> public PerformanceCounterType CounterType { get { if (_counterType == -1) { string currentCategoryName = _categoryName; string currentMachineName = _machineName; // This is the same thing that NextSample does, except that it doesn't try to get the actual counter // value. If we wanted the counter value, we would need to have an instance name. Initialize(); CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName); CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName); _counterType = counterSample._counterType; } return (PerformanceCounterType)_counterType; } } public PerformanceCounterInstanceLifetime InstanceLifetime { get { return _instanceLifetime; } set { if (value > PerformanceCounterInstanceLifetime.Process || value < PerformanceCounterInstanceLifetime.Global) throw new ArgumentOutOfRangeException(nameof(value)); if (_initialized) throw new InvalidOperationException(SR.Format(SR.CantSetLifetimeAfterInitialized)); _instanceLifetime = value; } } /// <summary> /// Sets/returns an instance name for this performance counter /// </summary> public string InstanceName { get { return _instanceName; } set { if (value == null && _instanceName == null) return; if ((value == null && _instanceName != null) || (value != null && _instanceName == null) || !string.Equals(_instanceName, value, StringComparison.OrdinalIgnoreCase)) { _instanceName = value; Close(); } } } /// <summary> /// Returns true if counter is read only (system counter, foreign extensible counter or remote counter) /// </summary> public bool ReadOnly { get { return _isReadOnly; } set { if (value != _isReadOnly) { if (value == false) { VerifyWriteableCounterAllowed(); } _isReadOnly = value; Close(); } } } /// <summary> /// Set/returns the machine name for this performance counter /// </summary> public string MachineName { get { return _machineName; } set { if (!SyntaxCheck.CheckMachineName(value)) throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(MachineName), value), nameof(value)); if (_machineName != value) { _machineName = value; Close(); } } } /// <summary> /// Directly accesses the raw value of this counter. If counter type is of a 32-bit size, it will truncate /// the value given to 32 bits. This can be significantly more performant for scenarios where /// the raw value is sufficient. Note that this only works for custom counters created using /// this component, non-custom counters will throw an exception if this property is accessed. /// </summary> public long RawValue { get { if (ReadOnly) { //No need to initialize or Demand, since NextSample already does. return NextSample().RawValue; } else { Initialize(); return _sharedCounter.Value; } } set { if (ReadOnly) ThrowReadOnly(); Initialize(); _sharedCounter.Value = value; } } /// <summary> /// </summary> public void BeginInit() { Close(); } /// <summary> /// Frees all the resources allocated by this counter /// </summary> public void Close() { _helpMsg = null; _oldSample = CounterSample.Empty; _sharedCounter = null; _initialized = false; _counterType = -1; } /// <summary> /// Frees all the resources allocated for all performance /// counters, frees File Mapping used by extensible counters, /// unloads dll's used to read counters. /// </summary> public static void CloseSharedResources() { PerformanceCounterLib.CloseAllLibraries(); } /// <internalonly/> /// <summary> /// </summary> protected override void Dispose(bool disposing) { // safe to call while finalizing or disposing if (disposing) { //Dispose managed and unmanaged resources Close(); } base.Dispose(disposing); } /// <summary> /// Decrements counter by one using an efficient atomic operation. /// </summary> public long Decrement() { if (ReadOnly) ThrowReadOnly(); Initialize(); return _sharedCounter.Decrement(); } /// <summary> /// </summary> public void EndInit() { Initialize(); } /// <summary> /// Increments the value of this counter. If counter type is of a 32-bit size, it'll truncate /// the value given to 32 bits. This method uses a mutex to guarantee correctness of /// the operation in case of multiple writers. This method should be used with caution because of the negative /// impact on performance due to creation of the mutex. /// </summary> public long IncrementBy(long value) { if (_isReadOnly) ThrowReadOnly(); Initialize(); return _sharedCounter.IncrementBy(value); } /// <summary> /// Increments counter by one using an efficient atomic operation. /// </summary> public long Increment() { if (_isReadOnly) ThrowReadOnly(); Initialize(); return _sharedCounter.Increment(); } private void ThrowReadOnly() { throw new InvalidOperationException(SR.Format(SR.ReadOnlyCounter)); } private static void VerifyWriteableCounterAllowed() { if (EnvironmentHelpers.IsAppContainerProcess) { throw new NotSupportedException(SR.Format(SR.PCNotSupportedUnderAppContainer)); } } private void Initialize() { // Keep this method small so the JIT will inline it. if (!_initialized && !DesignMode) { InitializeImpl(); } } /// <summary> /// Intializes required resources /// </summary> private void InitializeImpl() { bool tookLock = false; try { Monitor.Enter(InstanceLockObject, ref tookLock); if (!_initialized) { string currentCategoryName = _categoryName; string currentMachineName = _machineName; if (currentCategoryName == string.Empty) throw new InvalidOperationException(SR.Format(SR.CategoryNameMissing)); if (_counterName == string.Empty) throw new InvalidOperationException(SR.Format(SR.CounterNameMissing)); if (ReadOnly) { if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, _counterName)) throw new InvalidOperationException(SR.Format(SR.CounterExists, currentCategoryName, _counterName)); PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName); if (categoryType == PerformanceCounterCategoryType.MultiInstance) { if (string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName)); } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) { if (!string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName)); } if (_instanceLifetime != PerformanceCounterInstanceLifetime.Global) throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessonReadOnly)); _initialized = true; } else { if (currentMachineName != "." && !string.Equals(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException(SR.Format(SR.RemoteWriting)); if (!PerformanceCounterLib.IsCustomCategory(currentMachineName, currentCategoryName)) throw new InvalidOperationException(SR.Format(SR.NotCustomCounter)); // check category type PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName); if (categoryType == PerformanceCounterCategoryType.MultiInstance) { if (string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName)); } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) { if (!string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName)); } if (string.IsNullOrEmpty(_instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process) throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessforSingleInstance)); _sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), _counterName.ToLower(CultureInfo.InvariantCulture), _instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime); _initialized = true; } } } finally { if (tookLock) Monitor.Exit(InstanceLockObject); } } // Will cause an update, raw value /// <summary> /// Obtains a counter sample and returns the raw value for it. /// </summary> public CounterSample NextSample() { string currentCategoryName = _categoryName; string currentMachineName = _machineName; Initialize(); CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName); CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName); _counterType = counterSample._counterType; if (!categorySample._isMultiInstance) { if (_instanceName != null && _instanceName.Length != 0) throw new InvalidOperationException(SR.Format(SR.InstanceNameProhibited, _instanceName)); return counterSample.GetSingleValue(); } else { if (_instanceName == null || _instanceName.Length == 0) throw new InvalidOperationException(SR.Format(SR.InstanceNameRequired)); return counterSample.GetInstanceValue(_instanceName); } } /// <summary> /// Obtains a counter sample and returns the calculated value for it. /// NOTE: For counters whose calculated value depend upon 2 counter reads, /// the very first read will return 0.0. /// </summary> public float NextValue() { //No need to initialize or Demand, since NextSample already does. CounterSample newSample = NextSample(); float retVal = 0.0f; retVal = CounterSample.Calculate(_oldSample, newSample); _oldSample = newSample; return retVal; } /// <summary> /// Removes this counter instance from the shared memory /// </summary> public void RemoveInstance() { if (_isReadOnly) throw new InvalidOperationException(SR.Format(SR.ReadOnlyRemoveInstance)); Initialize(); _sharedCounter.RemoveInstance(_instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime); } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Data; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.News; using Nop.Core.Domain.Stores; using Nop.Services.Events; namespace Nop.Services.News { /// <summary> /// News service /// </summary> public partial class NewsService : INewsService { #region Fields private readonly IRepository<NewsItem> _newsItemRepository; private readonly IRepository<NewsComment> _newsCommentRepository; private readonly IRepository<StoreMapping> _storeMappingRepository; private readonly CatalogSettings _catalogSettings; private readonly IEventPublisher _eventPublisher; #endregion #region Ctor public NewsService(IRepository<NewsItem> newsItemRepository, IRepository<NewsComment> newsCommentRepository, IRepository<StoreMapping> storeMappingRepository, CatalogSettings catalogSettings, IEventPublisher eventPublisher) { this._newsItemRepository = newsItemRepository; this._newsCommentRepository = newsCommentRepository; this._storeMappingRepository = storeMappingRepository; this._catalogSettings = catalogSettings; this._eventPublisher = eventPublisher; } #endregion #region Methods #region News /// <summary> /// Deletes a news /// </summary> /// <param name="newsItem">News item</param> public virtual void DeleteNews(NewsItem newsItem) { if (newsItem == null) throw new ArgumentNullException("newsItem"); _newsItemRepository.Delete(newsItem); //event notification _eventPublisher.EntityDeleted(newsItem); } /// <summary> /// Gets a news /// </summary> /// <param name="newsId">The news identifier</param> /// <returns>News</returns> public virtual NewsItem GetNewsById(int newsId) { if (newsId == 0) return null; return _newsItemRepository.GetById(newsId); } /// <summary> /// Gets news /// </summary> /// <param name="newsIds">The news identifiers</param> /// <returns>News</returns> public virtual IList<NewsItem> GetNewsByIds(int[] newsIds) { var query = _newsItemRepository.Table; return query.Where(p => newsIds.Contains(p.Id)).ToList(); } /// <summary> /// Gets all news /// </summary> /// <param name="languageId">Language identifier; 0 if you want to get all records</param> /// <param name="storeId">Store identifier; 0 if you want to get all records</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>News items</returns> public virtual IPagedList<NewsItem> GetAllNews(int languageId = 0, int storeId = 0, int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false) { var query = _newsItemRepository.Table; if (languageId > 0) query = query.Where(n => languageId == n.LanguageId); if (!showHidden) { var utcNow = DateTime.UtcNow; query = query.Where(n => n.Published); query = query.Where(n => !n.StartDateUtc.HasValue || n.StartDateUtc <= utcNow); query = query.Where(n => !n.EndDateUtc.HasValue || n.EndDateUtc >= utcNow); } query = query.OrderByDescending(n => n.StartDateUtc ?? n.CreatedOnUtc); //Store mapping if (storeId > 0 && !_catalogSettings.IgnoreStoreLimitations) { query = from n in query join sm in _storeMappingRepository.Table on new { c1 = n.Id, c2 = "NewsItem" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into n_sm from sm in n_sm.DefaultIfEmpty() where !n.LimitedToStores || storeId == sm.StoreId select n; //only distinct items (group by ID) query = from n in query group n by n.Id into nGroup orderby nGroup.Key select nGroup.FirstOrDefault(); query = query.OrderByDescending(n => n.StartDateUtc ?? n.CreatedOnUtc); } var news = new PagedList<NewsItem>(query, pageIndex, pageSize); return news; } /// <summary> /// Inserts a news item /// </summary> /// <param name="news">News item</param> public virtual void InsertNews(NewsItem news) { if (news == null) throw new ArgumentNullException("news"); _newsItemRepository.Insert(news); //event notification _eventPublisher.EntityInserted(news); } /// <summary> /// Updates the news item /// </summary> /// <param name="news">News item</param> public virtual void UpdateNews(NewsItem news) { if (news == null) throw new ArgumentNullException("news"); _newsItemRepository.Update(news); //event notification _eventPublisher.EntityUpdated(news); } #endregion #region News comments /// <summary> /// Gets all comments /// </summary> /// <param name="customerId">Customer identifier; 0 to load all records</param> /// <param name="storeId">Store identifier; pass 0 to load all records</param> /// <param name="newsItemId">News item ID; 0 or null to load all records</param> /// <param name="approved">A value indicating whether to content is approved; null to load all records</param> /// <param name="fromUtc">Item creation from; null to load all records</param> /// <param name="toUtc">Item creation to; null to load all records</param> /// <param name="commentText">Search comment text; null to load all records</param> /// <returns>Comments</returns> public virtual IList<NewsComment> GetAllComments(int customerId = 0, int storeId = 0, int? newsItemId = null, bool? approved = null, DateTime? fromUtc = null, DateTime? toUtc = null, string commentText = null) { var query = _newsCommentRepository.Table; if (approved.HasValue) query = query.Where(comment => comment.IsApproved == approved); if (newsItemId > 0) query = query.Where(comment => comment.NewsItemId == newsItemId); if (customerId > 0) query = query.Where(comment => comment.CustomerId == customerId); if (storeId > 0) query = query.Where(comment => comment.StoreId == storeId); if (fromUtc.HasValue) query = query.Where(comment => fromUtc.Value <= comment.CreatedOnUtc); if (toUtc.HasValue) query = query.Where(comment => toUtc.Value >= comment.CreatedOnUtc); if (!string.IsNullOrEmpty(commentText)) query = query.Where(c => c.CommentText.Contains(commentText) || c.CommentTitle.Contains(commentText)); query = query.OrderBy(nc => nc.CreatedOnUtc); return query.ToList(); } /// <summary> /// Gets a news comment /// </summary> /// <param name="newsCommentId">News comment identifier</param> /// <returns>News comment</returns> public virtual NewsComment GetNewsCommentById(int newsCommentId) { if (newsCommentId == 0) return null; return _newsCommentRepository.GetById(newsCommentId); } /// <summary> /// Get news comments by identifiers /// </summary> /// <param name="commentIds">News comment identifiers</param> /// <returns>News comments</returns> public virtual IList<NewsComment> GetNewsCommentsByIds(int[] commentIds) { if (commentIds == null || commentIds.Length == 0) return new List<NewsComment>(); var query = from nc in _newsCommentRepository.Table where commentIds.Contains(nc.Id) select nc; var comments = query.ToList(); //sort by passed identifiers var sortedComments = new List<NewsComment>(); foreach (int id in commentIds) { var comment = comments.Find(x => x.Id == id); if (comment != null) sortedComments.Add(comment); } return sortedComments; } /// <summary> /// Get the count of news comments /// </summary> /// <param name="newsItem">News item</param> /// <param name="storeId">Store identifier; pass 0 to load all records</param> /// <param name="isApproved">A value indicating whether to count only approved or not approved comments; pass null to get number of all comments</param> /// <returns>Number of news comments</returns> public virtual int GetNewsCommentsCount(NewsItem newsItem, int storeId = 0, bool? isApproved = null) { var query = _newsCommentRepository.Table.Where(comment => comment.NewsItemId == newsItem.Id); if (storeId > 0) query = query.Where(comment => comment.StoreId == storeId); if (isApproved.HasValue) query = query.Where(comment => comment.IsApproved == isApproved.Value); return query.Count(); } /// <summary> /// Deletes a news comment /// </summary> /// <param name="newsComment">News comment</param> public virtual void DeleteNewsComment(NewsComment newsComment) { if (newsComment == null) throw new ArgumentNullException("newsComment"); _newsCommentRepository.Delete(newsComment); //event notification _eventPublisher.EntityDeleted(newsComment); } /// <summary> /// Deletes a news comments /// </summary> /// <param name="newsComments">News comments</param> public virtual void DeleteNewsComments(IList<NewsComment> newsComments) { if (newsComments == null) throw new ArgumentNullException("newsComments"); foreach (var newsComment in newsComments) { DeleteNewsComment(newsComment); } } #endregion #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // //((a+b)+c) //permutations for ((a+b)+c) //((a+b)+c) //(c+(a+b)) //(a+b) //(b+a) //a //b //(b+a) //(a+b) //c //(a+(b+c)) //(b+(a+c)) //(b+c) //(c+b) //b //c //(c+b) //(b+c) //(a+c) //(c+a) //a //c //(c+a) //(a+c) //(c+(a+b)) //((a+b)+c) namespace CseTest { using System; public class Test_Main { static int Main() { int ret = 100; int b = return_int(false, 6); int c = return_int(false, -40); int a = return_int(false, -27); int v; #if LOOP for (int j = 0; j < 6; j++) { for (int i = 0; i < 5; i++) { #endif v = ((a + b) + c); if (v != -61) { Console.WriteLine("test0: for ((a+b)+c) failed actual value {0} ", v); ret = ret + 1; } v = (c + (a + b)); if (v != -61) { Console.WriteLine("test1: for (c+(a+b)) failed actual value {0} ", v); ret = ret + 1; } v = (a + b); if (v != -21) { Console.WriteLine("test2: for (a+b) failed actual value {0} ", v); ret = ret + 1; } v = (b + a); if (v != -21) { Console.WriteLine("test3: for (b+a) failed actual value {0} ", v); ret = ret + 1; } #if LOOP #if KILL1 c = return_int(false, -40); #endif } #if KILL2 a = return_int(false, -27); #endif } #endif #if TRY try { #endif v = (b + a); if (v != -21) { Console.WriteLine("test4: for (b+a) failed actual value {0} ", v); ret = ret + 1; } v = (a + b); if (v != -21) { Console.WriteLine("test5: for (a+b) failed actual value {0} ", v); ret = ret + 1; } v = (a + (b + c)); if (v != -61) { Console.WriteLine("test6: for (a+(b+c)) failed actual value {0} ", v); ret = ret + 1; } v = (b + (a + c)); if (v != -61) { Console.WriteLine("test7: for (b+(a+c)) failed actual value {0} ", v); ret = ret + 1; } v = (b + c); if (v != -34) { Console.WriteLine("test8: for (b+c) failed actual value {0} ", v); ret = ret + 1; } v = (c + b); if (v != -34) { Console.WriteLine("test9: for (c+b) failed actual value {0} ", v); ret = ret + 1; } v = (c + b); if (v != -34) { Console.WriteLine("test10: for (c+b) failed actual value {0} ", v); ret = ret + 1; } v = (b + c); if (v != -34) { Console.WriteLine("test11: for (b+c) failed actual value {0} ", v); ret = ret + 1; } v = (a + c); if (v != -67) { Console.WriteLine("test12: for (a+c) failed actual value {0} ", v); ret = ret + 1; } v = (c + a); if (v != -67) { Console.WriteLine("test13: for (c+a) failed actual value {0} ", v); ret = ret + 1; } v = (c + a); if (v != -67) { Console.WriteLine("test14: for (c+a) failed actual value {0} ", v); ret = ret + 1; } c = return_int(false, -71); #if LOOP for (int i = 0; i < 4; i++) { #endif v = (a + c); if (v != -98) { Console.WriteLine("test15: for (a+c) failed actual value {0} ", v); ret = ret + 1; } #if LOOP } #endif #if TRY } finally { #endif v = (c + (a + b)); if (v != -92) { Console.WriteLine("test16: for (c+(a+b)) failed actual value {0} ", v); ret = ret + 1; } v = ((a + b) + c); if (v != -92) { Console.WriteLine("test17: for ((a+b)+c) failed actual value {0} ", v); ret = ret + 1; } #if TRY } #endif Console.WriteLine(ret); return ret; } private static int return_int(bool verbose, int input) { int ans; try { ans = input; } finally { if (verbose) { Console.WriteLine("returning : ans"); } } return ans; } } }
using System.Security; using System; public class DisposableClass : IDisposable { public void Dispose() { } } /// <summary> /// IsAlive /// </summary> [SecuritySafeCritical] public class WeakReferenceIsAlive { #region Private Fields private const int c_MIN_STRING_LENGTH = 8; private const int c_MAX_STRING_LENGTH = 1024; private WeakReference[] m_References; #endregion #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: IsAlive should return true before GC collecting memory for short weak references"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); GenerateUnusedData1(); for (int i = 0; i < m_References.Length; ++i) { if (!m_References[i].IsAlive) { TestLibrary.TestFramework.LogError("001.1", "IsAlive return false before GC collecting memory"); if (m_References[i].Target != null) { TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = " + m_References[i].Target.ToString()); } else { TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = null"); } retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: IsAlive should return false before GC collecting memory for weak references reference null"); try { WeakReference reference = new WeakReference(null, false); if (reference.IsAlive) { TestLibrary.TestFramework.LogError("002.1", "IsAlive returns true before GC collecting memory"); retVal = false; } reference = new WeakReference(null, true); if (reference.IsAlive) { TestLibrary.TestFramework.LogError("002.2", "IsAlive returns true before GC collecting memory"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: IsAlive should return false after GC collecting memory for short weak references"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); GenerateUnusedData1(); // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < m_References.Length; ++i) { if (m_References[i].IsAlive) { TestLibrary.TestFramework.LogError("003.1", "IsAlive returns true after GC collecting memory"); if (m_References[i].Target != null) { TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = " + m_References[i].Target.ToString()); } else { TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = null"); } retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: IsAlive should return true before GC collecting memory for long weak references"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); GenerateUnusedData2(); for (int i = 0; i < m_References.Length; ++i) { if (!m_References[i].IsAlive) { TestLibrary.TestFramework.LogError("004.1", "IsAlive return false before GC collecting memory"); if (m_References[i].Target != null) { TestLibrary.TestFramework.LogInformation("WARNING: m_References[" + i.ToString() + "] = " + m_References[i].Target.ToString()); } else { TestLibrary.TestFramework.LogInformation("WARNING: m_References[" + i.ToString() + "] = null"); } retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: IsAlive should return true after GC collecting memory for long weak references"); try { // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); GenerateUnusedData2(); // Reclaim memories GC.Collect(); GC.WaitForPendingFinalizers(); for (int i = 0; i < m_References.Length; ++i) { if (m_References[i].IsAlive) { TestLibrary.TestFramework.LogError("005.1", "IsAlive returns true before GC collecting memory"); if (m_References[i].Target != null) { TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = " + m_References[i].Target.ToString()); } else { TestLibrary.TestFramework.LogInformation("WARNING: m_References[i] = null"); } retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } finally { m_References = null; } return retVal; } #endregion #endregion public static int Main() { WeakReferenceIsAlive test = new WeakReferenceIsAlive(); TestLibrary.TestFramework.BeginTestCase("WeakReferenceIsAlive"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private void GenerateUnusedData1() { int intRandValue = TestLibrary.Generator.GetInt32(-55); long longRandValue = TestLibrary.Generator.GetInt64(-55); double doubleRandValue = TestLibrary.Generator.GetDouble(-55); object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); WeakReferenceIsAlive thisClass = new WeakReferenceIsAlive(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); m_References = new WeakReference[] { new WeakReference(obj, false), new WeakReference(str, false), new WeakReference(randBytes, false), new WeakReference(thisClass, false), new WeakReference(ptr, false), new WeakReference(IntPtr.Zero, false), new WeakReference(dc, false) }; } private void GenerateUnusedData2() { object obj = new object(); string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); Byte[] randBytes = new Byte[c_MAX_STRING_LENGTH]; TestLibrary.Generator.GetBytes(-55, randBytes); WeakReferenceIsAlive thisClass = new WeakReferenceIsAlive(); DisposableClass dc = new DisposableClass(); IntPtr ptr = new IntPtr(TestLibrary.Generator.GetInt32(-55)); m_References = new WeakReference[] { new WeakReference(obj, true), new WeakReference(str, true), new WeakReference(randBytes, true), new WeakReference(thisClass, true), new WeakReference(ptr, true), new WeakReference(IntPtr.Zero, true), new WeakReference(dc, true) }; } #endregion }
using System; using Csla; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERLevel; namespace ParentLoad.Business.ERLevel { /// <summary> /// A03_Continent_Child (editable child object).<br/> /// This is a generated base class of <see cref="A03_Continent_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="A02_Continent"/> collection. /// </remarks> [Serializable] public partial class A03_Continent_Child : BusinessBase<A03_Continent_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "Continent Child Name"); /// <summary> /// Gets or sets the Continent Child Name. /// </summary> /// <value>The Continent Child Name.</value> public string Continent_Child_Name { get { return GetProperty(Continent_Child_NameProperty); } set { SetProperty(Continent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A03_Continent_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="A03_Continent_Child"/> object.</returns> internal static A03_Continent_Child NewA03_Continent_Child() { return DataPortal.CreateChild<A03_Continent_Child>(); } /// <summary> /// Factory method. Loads a <see cref="A03_Continent_Child"/> object from the given A03_Continent_ChildDto. /// </summary> /// <param name="data">The <see cref="A03_Continent_ChildDto"/>.</param> /// <returns>A reference to the fetched <see cref="A03_Continent_Child"/> object.</returns> internal static A03_Continent_Child GetA03_Continent_Child(A03_Continent_ChildDto data) { A03_Continent_Child obj = new A03_Continent_Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A03_Continent_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public A03_Continent_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A03_Continent_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A03_Continent_Child"/> object from the given <see cref="A03_Continent_ChildDto"/>. /// </summary> /// <param name="data">The A03_Continent_ChildDto to use.</param> private void Fetch(A03_Continent_ChildDto data) { // Value properties LoadProperty(Continent_Child_NameProperty, data.Continent_Child_Name); var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="A03_Continent_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A02_Continent parent) { var dto = new A03_Continent_ChildDto(); dto.Parent_Continent_ID = parent.Continent_ID; dto.Continent_Child_Name = Continent_Child_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IA03_Continent_ChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="A03_Continent_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(A02_Continent parent) { if (!IsDirty) return; var dto = new A03_Continent_ChildDto(); dto.Parent_Continent_ID = parent.Continent_ID; dto.Continent_Child_Name = Continent_Child_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IA03_Continent_ChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="A03_Continent_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(A02_Continent parent) { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IA03_Continent_ChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Continent_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading; using System.Windows.Forms; using Common; using Common.Controls; using Common.Queries; using DTA; using Fairweather.Service; using Fairweather.Service.Syntax; using Standardization; namespace Common.Dialogs { public partial class Search_Form { const string STR_BARCODE = "BARCODE"; /* Searching */ void Apply() { Message_Box mbox = null; Clause clause; Action act; int total_records = 0; string current_record = ""; Action<IRead<string, object>> action, every; bool is_stock = record_type == Record_Type.Stock; every = rd => current_record = rd[is_stock ? "STOCK_CODE" : "ACCOUNT_REF"].str(); action = rd => { int row_ind = dgv_results.Rows.Add(1); var row = dgv_results.Rows[row_ind]; var cells = row.Cells; if (is_stock) { var record = rd["STOCK_CODE"].str(); cells[RESULT_AC].Value = record; cells[RESULT_NAME].Value = rd["DESCRIPTION"]; decimal ratio = new Tax_Code((short)rd["TAX_CODE"]).VAT_Ratio; cells[RESULT_PHONE].Value = rd["SALES_PRICE"].ToDecimal() * (1.0m + ratio); cells[RESULT_BALANCE].Value = rd["QTY_IN_STOCK"]; } else { var record = rd["ACCOUNT_REF"].str(); cells[RESULT_AC].Value = record; cells[RESULT_NAME].Value = rd["NAME"]; cells[RESULT_PHONE].Value = rd["TELEPHONE"]; cells[RESULT_BALANCE].Value = rd["BALANCE"]; } }; IToken[] tokens; Dictionary<string, string> strings; if (Try_Predefined_Fields(out strings)) { // Premature optimization!!! act = () => m_sgr.Run_Contains_Query( record_type, strings, every, action, m_caseless_contains, out total_records); } else { if (!Try_Predefined_Fields(out tokens)) { var barcode_data = tb_predefined_2.Text.Trim(); if (is_stock && !barcode_data.IsNullOrEmpty()) { } if (!dgv_1.Get_Tokens(out tokens)) { Standard.Show(Message_Type.Warning, "Please fill all required fields in the grid."); return; } } if (tokens.Is_Empty()) { Standard.Show(Message_Type.Warning, "Please enter information for the query."); return; } clause = Query.Create_Structured_Query(tokens); act = () => m_sgr.Run_Record_Query(record_type, clause, every, action, out total_records); } dgv_results.Rows.Clear(); dgv_results.SuspendLayout(); lab_results.Text = ""; bool ok; int stop = 0; var thr = new Thread(() => { using (mbox = new Message_Box()) { mbox.Size = new Size(202, 100); mbox.Text = "Please wait..."; var label = mbox.label5; label.Visible = true; // "Searching for matching records"; // mbox.Label5.move(-38, 0); /* stock codes can be much longer than account refs */ mbox.Label5.move(is_stock ? -54 : -32, 3); mbox.TopMost = true; mbox.StartPosition = FormStartPosition.Manual; mbox.Location = this.Bounds.Center().Translate(-101, -50); mbox.Show(); mbox.Refresh(); while (stop == 0) { label.Text = "Current record: " + current_record; mbox.Refresh(); Thread.Sleep(100); } mbox.Hide(); } }); ok = Sage_Access.Sage_Guard(act); if (ok) { thr.Start(); Interlocked.Exchange(ref stop, 1); thr.Join(); } dgv_results.ResumeLayout(); // result count dialog removed in revision 780 // Set_Result_Label(); if (!ok) { dgv_results.Rows.Clear(); lab_results.Text = "Query Failed"; Prepare_For_Work(); return; } int results = dgv_results.RowCount; lab_results.Text = "{0} of {1} Records Matched".spf(results, total_records); dgv_results.Select_Focus(); } Triple<string> Get_Predefined_Fields(IRead<Ini_Field, string> company_proxy) { if (record_type == Record_Type.Stock) return Triple.Make("STOCK_CODE", STR_BARCODE, "DESCRIPTION"); Triple<string> ret; var fields = new Dictionary<Ini_Field, string> { {DTA_Fields.POS_search_address,ADDRESS}, {DTA_Fields.POS_search_phone, TELEPHONE}, {DTA_Fields.POS_search_email, "E_MAIL"}, {DTA_Fields.POS_search_contact,"CONTACT_NAME"}, {DTA_Fields.POS_search_name, "NAME"}, //{DTA_Fields.POS_search_country,SRFields.COUNTRY_CODE}, }; var list = new List<string>(3); int ii = 0; foreach (var kvp in fields) { if (company_proxy[kvp.Key] == Ini_Main.YES) { list.Add(kvp.Value); ++ii; } if (ii == 3) { break; } } list = list.Take(3).Pad_Left(3, null).lst(); ret = new Triple<string>(list[0], list[1], list[2]); return ret; } bool Try_Predefined_Fields(out Dictionary<string, string> strings) { bool ret = false; strings = new Dictionary<string, string>(); foreach (var kvp in rd_predefined_tbxs) { var text = kvp.Key.Text.Trim(); if (text.IsNullOrEmpty()) continue; ret = true; var pair = kvp.Value; // pair.First is the sage field var sage_field = pair.First; if (sage_field == STR_BARCODE) return false; strings[sage_field] = text; } return ret; } bool Try_Predefined_Fields(out IToken[] tokens) { bool ret = false; var tokens_lst = new List<IToken>(); Operation op = m_caseless_contains ? Operation.Contains : Operation.Contains_Caseless; bool first = false; foreach (var pair1 in rd_predefined_tbxs.Mark_Last()) { var tbx = pair1.First.Key; var text = tbx.Text.Trim(); if (text.IsNullOrEmpty()) continue; if (H.Set(ref first, true)) tokens_lst.Add(new Binary_Token(2, Operation.And)); ret = true; var sage_field = pair1.First.Value.First; var fields = (sage_field == STR_BARCODE) ? m_sgr.Used_Barcode_Fields : new[] { sage_field }; foreach (var pair2 in fields.Mark_Last()) { var field = pair2.First; Clause clause = new Clause(new Argument(Argument_Type.Entity, field), new Argument(Argument_Type.String, text), op); tokens_lst.Add(new Argument_Token(clause)); if (!pair2.Second) tokens_lst.Add(new Binary_Token(10, Operation.Or)); } } tokens = tokens_lst.arr(); return ret; } Clause Get_Predefined_Clause(string field, string value) { var op = m_caseless_contains ? Operation.Contains_Caseless : Operation.Contains; if (field == ADDRESS) { var list = from _field in new string[]{"ADDRESS_1", "ADDRESS_2", "ADDRESS_3", "ADDRESS_4", "ADDRESS_5"} select new Pair<object>(_field, value); var clause = Query.Make_Chained_Clause(Argument_Type.Entity, Argument_Type.String, op, false, list.ToList()); return clause; } else if (field == TELEPHONE) { //we'll only search the first field //* var arg1 = new Argument(Argument_Type.Entity, "TELEPHONE"); var arg2 = new Argument(Argument_Type.String, value); var main_clause = new Clause(arg1, arg2, op); /*/ Clause clause1, clause2, main_clause; { var arg1 = new Argument(Argument_Type.Entity, "TELEPHONE"); var arg2 = new Argument(Argument_Type.String, value); clause1 = new Clause(arg1, arg2, Operation.Contains); } { var arg1 = new Argument(Argument_Type.Entity, "TELEPHONE_2"); var arg2 = new Argument(Argument_Type.String, value); clause2 = new Clause(arg1, arg2, Operation.Contains); } { var arg1 = new Argument(Argument_Type.Clause, clause1); var arg2 = new Argument(Argument_Type.Clause, clause2); main_clause = new Clause(arg1, arg2, Operation.Or); } //*/ return main_clause; } else { var arg1 = new Argument(Argument_Type.Entity, field); var arg2 = new Argument(Argument_Type.String, value); var temp_clause = new Clause(arg1, arg2, op); return temp_clause; } } void tb_predefined_TextChanged(object sender, EventArgs e) { var txt = tb_predefined_1.Text + tb_predefined_2.Text + tb_predefined_3.Text; bool empty = txt.IsNullOrEmpty(); bool enabled = dgv_1.Enabled; if (empty != enabled) { dgv_1.BackgroundColor = empty ? Color.White : Color.LightGray; foreach (DataGridViewRow row in dgv_1.Rows) row.Visible = empty; } dgv_1.Enabled = empty; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPricingGroup { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPricingGroup() : base() { FormClosed += frmPricingGroup_FormClosed; KeyPress += frmPricingGroup_KeyPress; Resize += frmPricingGroup_Resize; Load += frmPricingGroup_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.CheckBox chkPricing; public System.Windows.Forms.TextBox _txtFields_28; public System.Windows.Forms.TextBox _txtInteger_0; public System.Windows.Forms.TextBox _txtFloat_1; public System.Windows.Forms.TextBox _txtInteger_2; public System.Windows.Forms.TextBox _txtFloatNegative_0; public System.Windows.Forms.TextBox _txtFloatNegative_1; public System.Windows.Forms.TextBox _txtFloatNegative_2; public System.Windows.Forms.TextBox _txtFloatNegative_3; public System.Windows.Forms.TextBox _txtFloatNegative_4; public System.Windows.Forms.TextBox _txtFloatNegative_5; public System.Windows.Forms.TextBox _txtFloatNegative_6; public System.Windows.Forms.TextBox _txtFloatNegative_7; public System.Windows.Forms.TextBox _txtFloatNegative_8; public System.Windows.Forms.TextBox _txtFloatNegative_9; public System.Windows.Forms.TextBox _txtFloatNegative_10; public System.Windows.Forms.TextBox _txtFloatNegative_11; public System.Windows.Forms.TextBox _txtFloatNegative_12; public System.Windows.Forms.TextBox _txtFloatNegative_13; public System.Windows.Forms.TextBox _txtFloatNegative_14; public System.Windows.Forms.TextBox _txtFloatNegative_15; private System.Windows.Forms.Button withEventsField_cmdMatrix; public System.Windows.Forms.Button cmdMatrix { get { return withEventsField_cmdMatrix; } set { if (withEventsField_cmdMatrix != null) { withEventsField_cmdMatrix.Click -= cmdMatrix_Click; } withEventsField_cmdMatrix = value; if (withEventsField_cmdMatrix != null) { withEventsField_cmdMatrix.Click += cmdMatrix_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPrint; public System.Windows.Forms.Button cmdPrint { get { return withEventsField_cmdPrint; } set { if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click -= cmdPrint_Click; } withEventsField_cmdPrint = value; if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click += cmdPrint_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_3; public System.Windows.Forms.Label Label1; public System.Windows.Forms.Label _lbl_10; public System.Windows.Forms.Label _lbl_18; public System.Windows.Forms.Label _lbl_2; public System.Windows.Forms.Label _lbl_3; public System.Windows.Forms.Label _lbl_4; public System.Windows.Forms.Label _lblLabels_38; public System.Windows.Forms.Label _lblLabels_34; public System.Windows.Forms.Label _lblLabels_33; public System.Windows.Forms.Label _lblCG_0; public System.Windows.Forms.Label _lblCG_1; public System.Windows.Forms.Label _lblCG_2; public System.Windows.Forms.Label _lblCG_3; public System.Windows.Forms.Label _lblCG_4; public System.Windows.Forms.Label _lblCG_5; public System.Windows.Forms.Label _lblCG_6; public System.Windows.Forms.Label _lblCG_7; public System.Windows.Forms.Label _lbl_1; public System.Windows.Forms.Label _lbl_0; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_1; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; public System.Windows.Forms.Label _lbl_5; //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray // Public WithEvents lblCG As Microsoft.VisualBasic.Compatibility.VB6.LabelArray' //Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray //Public WithEvents txtFloat As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray //Public WithEvents txtFloatNegative As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray //Public WithEvents txtInteger As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPricingGroup)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.chkPricing = new System.Windows.Forms.CheckBox(); this._txtFields_28 = new System.Windows.Forms.TextBox(); this._txtInteger_0 = new System.Windows.Forms.TextBox(); this._txtFloat_1 = new System.Windows.Forms.TextBox(); this._txtInteger_2 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_0 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_1 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_2 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_3 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_4 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_5 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_6 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_7 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_8 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_9 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_10 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_11 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_12 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_13 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_14 = new System.Windows.Forms.TextBox(); this._txtFloatNegative_15 = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdMatrix = new System.Windows.Forms.Button(); this.cmdPrint = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this._Shape1_3 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this.Label1 = new System.Windows.Forms.Label(); this._lbl_10 = new System.Windows.Forms.Label(); this._lbl_18 = new System.Windows.Forms.Label(); this._lbl_2 = new System.Windows.Forms.Label(); this._lbl_3 = new System.Windows.Forms.Label(); this._lbl_4 = new System.Windows.Forms.Label(); this._lblLabels_38 = new System.Windows.Forms.Label(); this._lblLabels_34 = new System.Windows.Forms.Label(); this._lblLabels_33 = new System.Windows.Forms.Label(); this._lblCG_0 = new System.Windows.Forms.Label(); this._lblCG_1 = new System.Windows.Forms.Label(); this._lblCG_2 = new System.Windows.Forms.Label(); this._lblCG_3 = new System.Windows.Forms.Label(); this._lblCG_4 = new System.Windows.Forms.Label(); this._lblCG_5 = new System.Windows.Forms.Label(); this._lblCG_6 = new System.Windows.Forms.Label(); this._lblCG_7 = new System.Windows.Forms.Label(); this._lbl_1 = new System.Windows.Forms.Label(); this._lbl_0 = new System.Windows.Forms.Label(); this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._Shape1_1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._lbl_5 = new System.Windows.Forms.Label(); //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lblCG = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.txtFields = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components) //Me.txtFloat = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components) //M''e.txtFloatNegative = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components) //Me.txtInteger = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components) this.Shape1 = new RectangleShapeArray(components); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lblCG, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.txtFields, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.txtFloat, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.txtFloatNegative, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.txtInteger, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Edit Pricing Group Details"; this.ClientSize = new System.Drawing.Size(527, 351); this.Location = new System.Drawing.Point(73, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPricingGroup"; this.chkPricing.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.chkPricing.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkPricing.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.chkPricing.Text = "Disable This Pricing Group"; this.chkPricing.ForeColor = System.Drawing.SystemColors.WindowText; this.chkPricing.Size = new System.Drawing.Size(157, 19); this.chkPricing.Location = new System.Drawing.Point(352, 312); this.chkPricing.TabIndex = 44; this.chkPricing.CausesValidation = true; this.chkPricing.Enabled = true; this.chkPricing.Cursor = System.Windows.Forms.Cursors.Default; this.chkPricing.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkPricing.Appearance = System.Windows.Forms.Appearance.Normal; this.chkPricing.TabStop = true; this.chkPricing.CheckState = System.Windows.Forms.CheckState.Unchecked; this.chkPricing.Visible = true; this.chkPricing.Name = "chkPricing"; this._txtFields_28.AutoSize = false; this._txtFields_28.Size = new System.Drawing.Size(375, 19); this._txtFields_28.Location = new System.Drawing.Point(126, 66); this._txtFields_28.TabIndex = 5; this._txtFields_28.AcceptsReturn = true; this._txtFields_28.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_28.BackColor = System.Drawing.SystemColors.Window; this._txtFields_28.CausesValidation = true; this._txtFields_28.Enabled = true; this._txtFields_28.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_28.HideSelection = true; this._txtFields_28.ReadOnly = false; this._txtFields_28.MaxLength = 0; this._txtFields_28.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_28.Multiline = false; this._txtFields_28.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_28.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_28.TabStop = true; this._txtFields_28.Visible = true; this._txtFields_28.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_28.Name = "_txtFields_28"; this._txtInteger_0.AutoSize = false; this._txtInteger_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtInteger_0.Size = new System.Drawing.Size(52, 19); this._txtInteger_0.Location = new System.Drawing.Point(144, 159); this._txtInteger_0.TabIndex = 13; this._txtInteger_0.AcceptsReturn = true; this._txtInteger_0.BackColor = System.Drawing.SystemColors.Window; this._txtInteger_0.CausesValidation = true; this._txtInteger_0.Enabled = true; this._txtInteger_0.ForeColor = System.Drawing.SystemColors.WindowText; this._txtInteger_0.HideSelection = true; this._txtInteger_0.ReadOnly = false; this._txtInteger_0.MaxLength = 0; this._txtInteger_0.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtInteger_0.Multiline = false; this._txtInteger_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtInteger_0.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtInteger_0.TabStop = true; this._txtInteger_0.Visible = true; this._txtInteger_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtInteger_0.Name = "_txtInteger_0"; this._txtFloat_1.AutoSize = false; this._txtFloat_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloat_1.Size = new System.Drawing.Size(52, 19); this._txtFloat_1.Location = new System.Drawing.Point(207, 123); this._txtFloat_1.TabIndex = 8; this._txtFloat_1.AcceptsReturn = true; this._txtFloat_1.BackColor = System.Drawing.SystemColors.Window; this._txtFloat_1.CausesValidation = true; this._txtFloat_1.Enabled = true; this._txtFloat_1.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloat_1.HideSelection = true; this._txtFloat_1.ReadOnly = false; this._txtFloat_1.MaxLength = 0; this._txtFloat_1.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloat_1.Multiline = false; this._txtFloat_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloat_1.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloat_1.TabStop = true; this._txtFloat_1.Visible = true; this._txtFloat_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloat_1.Name = "_txtFloat_1"; this._txtInteger_2.AutoSize = false; this._txtInteger_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtInteger_2.Size = new System.Drawing.Size(52, 19); this._txtInteger_2.Location = new System.Drawing.Point(378, 123); this._txtInteger_2.TabIndex = 10; this._txtInteger_2.AcceptsReturn = true; this._txtInteger_2.BackColor = System.Drawing.SystemColors.Window; this._txtInteger_2.CausesValidation = true; this._txtInteger_2.Enabled = true; this._txtInteger_2.ForeColor = System.Drawing.SystemColors.WindowText; this._txtInteger_2.HideSelection = true; this._txtInteger_2.ReadOnly = false; this._txtInteger_2.MaxLength = 0; this._txtInteger_2.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtInteger_2.Multiline = false; this._txtInteger_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtInteger_2.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtInteger_2.TabStop = true; this._txtInteger_2.Visible = true; this._txtInteger_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtInteger_2.Name = "_txtInteger_2"; this._txtFloatNegative_0.AutoSize = false; this._txtFloatNegative_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_0.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_0.Location = new System.Drawing.Point(93, 234); this._txtFloatNegative_0.TabIndex = 19; this._txtFloatNegative_0.Text = "999.99"; this._txtFloatNegative_0.AcceptsReturn = true; this._txtFloatNegative_0.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_0.CausesValidation = true; this._txtFloatNegative_0.Enabled = true; this._txtFloatNegative_0.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_0.HideSelection = true; this._txtFloatNegative_0.ReadOnly = false; this._txtFloatNegative_0.MaxLength = 0; this._txtFloatNegative_0.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_0.Multiline = false; this._txtFloatNegative_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_0.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_0.TabStop = true; this._txtFloatNegative_0.Visible = true; this._txtFloatNegative_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_0.Name = "_txtFloatNegative_0"; this._txtFloatNegative_1.AutoSize = false; this._txtFloatNegative_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_1.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_1.Location = new System.Drawing.Point(93, 252); this._txtFloatNegative_1.TabIndex = 20; this._txtFloatNegative_1.AcceptsReturn = true; this._txtFloatNegative_1.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_1.CausesValidation = true; this._txtFloatNegative_1.Enabled = true; this._txtFloatNegative_1.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_1.HideSelection = true; this._txtFloatNegative_1.ReadOnly = false; this._txtFloatNegative_1.MaxLength = 0; this._txtFloatNegative_1.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_1.Multiline = false; this._txtFloatNegative_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_1.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_1.TabStop = true; this._txtFloatNegative_1.Visible = true; this._txtFloatNegative_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_1.Name = "_txtFloatNegative_1"; this._txtFloatNegative_2.AutoSize = false; this._txtFloatNegative_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_2.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_2.Location = new System.Drawing.Point(144, 234); this._txtFloatNegative_2.TabIndex = 22; this._txtFloatNegative_2.AcceptsReturn = true; this._txtFloatNegative_2.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_2.CausesValidation = true; this._txtFloatNegative_2.Enabled = true; this._txtFloatNegative_2.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_2.HideSelection = true; this._txtFloatNegative_2.ReadOnly = false; this._txtFloatNegative_2.MaxLength = 0; this._txtFloatNegative_2.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_2.Multiline = false; this._txtFloatNegative_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_2.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_2.TabStop = true; this._txtFloatNegative_2.Visible = true; this._txtFloatNegative_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_2.Name = "_txtFloatNegative_2"; this._txtFloatNegative_3.AutoSize = false; this._txtFloatNegative_3.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_3.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_3.Location = new System.Drawing.Point(144, 252); this._txtFloatNegative_3.TabIndex = 23; this._txtFloatNegative_3.AcceptsReturn = true; this._txtFloatNegative_3.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_3.CausesValidation = true; this._txtFloatNegative_3.Enabled = true; this._txtFloatNegative_3.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_3.HideSelection = true; this._txtFloatNegative_3.ReadOnly = false; this._txtFloatNegative_3.MaxLength = 0; this._txtFloatNegative_3.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_3.Multiline = false; this._txtFloatNegative_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_3.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_3.TabStop = true; this._txtFloatNegative_3.Visible = true; this._txtFloatNegative_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_3.Name = "_txtFloatNegative_3"; this._txtFloatNegative_4.AutoSize = false; this._txtFloatNegative_4.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_4.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_4.Location = new System.Drawing.Point(195, 234); this._txtFloatNegative_4.TabIndex = 25; this._txtFloatNegative_4.AcceptsReturn = true; this._txtFloatNegative_4.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_4.CausesValidation = true; this._txtFloatNegative_4.Enabled = true; this._txtFloatNegative_4.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_4.HideSelection = true; this._txtFloatNegative_4.ReadOnly = false; this._txtFloatNegative_4.MaxLength = 0; this._txtFloatNegative_4.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_4.Multiline = false; this._txtFloatNegative_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_4.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_4.TabStop = true; this._txtFloatNegative_4.Visible = true; this._txtFloatNegative_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_4.Name = "_txtFloatNegative_4"; this._txtFloatNegative_5.AutoSize = false; this._txtFloatNegative_5.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_5.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_5.Location = new System.Drawing.Point(195, 252); this._txtFloatNegative_5.TabIndex = 26; this._txtFloatNegative_5.AcceptsReturn = true; this._txtFloatNegative_5.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_5.CausesValidation = true; this._txtFloatNegative_5.Enabled = true; this._txtFloatNegative_5.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_5.HideSelection = true; this._txtFloatNegative_5.ReadOnly = false; this._txtFloatNegative_5.MaxLength = 0; this._txtFloatNegative_5.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_5.Multiline = false; this._txtFloatNegative_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_5.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_5.TabStop = true; this._txtFloatNegative_5.Visible = true; this._txtFloatNegative_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_5.Name = "_txtFloatNegative_5"; this._txtFloatNegative_6.AutoSize = false; this._txtFloatNegative_6.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_6.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_6.Location = new System.Drawing.Point(246, 234); this._txtFloatNegative_6.TabIndex = 28; this._txtFloatNegative_6.AcceptsReturn = true; this._txtFloatNegative_6.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_6.CausesValidation = true; this._txtFloatNegative_6.Enabled = true; this._txtFloatNegative_6.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_6.HideSelection = true; this._txtFloatNegative_6.ReadOnly = false; this._txtFloatNegative_6.MaxLength = 0; this._txtFloatNegative_6.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_6.Multiline = false; this._txtFloatNegative_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_6.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_6.TabStop = true; this._txtFloatNegative_6.Visible = true; this._txtFloatNegative_6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_6.Name = "_txtFloatNegative_6"; this._txtFloatNegative_7.AutoSize = false; this._txtFloatNegative_7.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_7.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_7.Location = new System.Drawing.Point(246, 252); this._txtFloatNegative_7.TabIndex = 29; this._txtFloatNegative_7.AcceptsReturn = true; this._txtFloatNegative_7.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_7.CausesValidation = true; this._txtFloatNegative_7.Enabled = true; this._txtFloatNegative_7.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_7.HideSelection = true; this._txtFloatNegative_7.ReadOnly = false; this._txtFloatNegative_7.MaxLength = 0; this._txtFloatNegative_7.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_7.Multiline = false; this._txtFloatNegative_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_7.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_7.TabStop = true; this._txtFloatNegative_7.Visible = true; this._txtFloatNegative_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_7.Name = "_txtFloatNegative_7"; this._txtFloatNegative_8.AutoSize = false; this._txtFloatNegative_8.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_8.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_8.Location = new System.Drawing.Point(297, 234); this._txtFloatNegative_8.TabIndex = 31; this._txtFloatNegative_8.AcceptsReturn = true; this._txtFloatNegative_8.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_8.CausesValidation = true; this._txtFloatNegative_8.Enabled = true; this._txtFloatNegative_8.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_8.HideSelection = true; this._txtFloatNegative_8.ReadOnly = false; this._txtFloatNegative_8.MaxLength = 0; this._txtFloatNegative_8.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_8.Multiline = false; this._txtFloatNegative_8.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_8.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_8.TabStop = true; this._txtFloatNegative_8.Visible = true; this._txtFloatNegative_8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_8.Name = "_txtFloatNegative_8"; this._txtFloatNegative_9.AutoSize = false; this._txtFloatNegative_9.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_9.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_9.Location = new System.Drawing.Point(297, 252); this._txtFloatNegative_9.TabIndex = 32; this._txtFloatNegative_9.AcceptsReturn = true; this._txtFloatNegative_9.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_9.CausesValidation = true; this._txtFloatNegative_9.Enabled = true; this._txtFloatNegative_9.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_9.HideSelection = true; this._txtFloatNegative_9.ReadOnly = false; this._txtFloatNegative_9.MaxLength = 0; this._txtFloatNegative_9.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_9.Multiline = false; this._txtFloatNegative_9.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_9.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_9.TabStop = true; this._txtFloatNegative_9.Visible = true; this._txtFloatNegative_9.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_9.Name = "_txtFloatNegative_9"; this._txtFloatNegative_10.AutoSize = false; this._txtFloatNegative_10.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_10.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_10.Location = new System.Drawing.Point(348, 234); this._txtFloatNegative_10.TabIndex = 34; this._txtFloatNegative_10.AcceptsReturn = true; this._txtFloatNegative_10.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_10.CausesValidation = true; this._txtFloatNegative_10.Enabled = true; this._txtFloatNegative_10.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_10.HideSelection = true; this._txtFloatNegative_10.ReadOnly = false; this._txtFloatNegative_10.MaxLength = 0; this._txtFloatNegative_10.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_10.Multiline = false; this._txtFloatNegative_10.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_10.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_10.TabStop = true; this._txtFloatNegative_10.Visible = true; this._txtFloatNegative_10.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_10.Name = "_txtFloatNegative_10"; this._txtFloatNegative_11.AutoSize = false; this._txtFloatNegative_11.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_11.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_11.Location = new System.Drawing.Point(348, 252); this._txtFloatNegative_11.TabIndex = 35; this._txtFloatNegative_11.AcceptsReturn = true; this._txtFloatNegative_11.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_11.CausesValidation = true; this._txtFloatNegative_11.Enabled = true; this._txtFloatNegative_11.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_11.HideSelection = true; this._txtFloatNegative_11.ReadOnly = false; this._txtFloatNegative_11.MaxLength = 0; this._txtFloatNegative_11.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_11.Multiline = false; this._txtFloatNegative_11.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_11.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_11.TabStop = true; this._txtFloatNegative_11.Visible = true; this._txtFloatNegative_11.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_11.Name = "_txtFloatNegative_11"; this._txtFloatNegative_12.AutoSize = false; this._txtFloatNegative_12.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_12.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_12.Location = new System.Drawing.Point(399, 234); this._txtFloatNegative_12.TabIndex = 37; this._txtFloatNegative_12.AcceptsReturn = true; this._txtFloatNegative_12.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_12.CausesValidation = true; this._txtFloatNegative_12.Enabled = true; this._txtFloatNegative_12.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_12.HideSelection = true; this._txtFloatNegative_12.ReadOnly = false; this._txtFloatNegative_12.MaxLength = 0; this._txtFloatNegative_12.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_12.Multiline = false; this._txtFloatNegative_12.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_12.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_12.TabStop = true; this._txtFloatNegative_12.Visible = true; this._txtFloatNegative_12.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_12.Name = "_txtFloatNegative_12"; this._txtFloatNegative_13.AutoSize = false; this._txtFloatNegative_13.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_13.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_13.Location = new System.Drawing.Point(399, 252); this._txtFloatNegative_13.TabIndex = 38; this._txtFloatNegative_13.AcceptsReturn = true; this._txtFloatNegative_13.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_13.CausesValidation = true; this._txtFloatNegative_13.Enabled = true; this._txtFloatNegative_13.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_13.HideSelection = true; this._txtFloatNegative_13.ReadOnly = false; this._txtFloatNegative_13.MaxLength = 0; this._txtFloatNegative_13.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_13.Multiline = false; this._txtFloatNegative_13.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_13.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_13.TabStop = true; this._txtFloatNegative_13.Visible = true; this._txtFloatNegative_13.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_13.Name = "_txtFloatNegative_13"; this._txtFloatNegative_14.AutoSize = false; this._txtFloatNegative_14.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_14.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_14.Location = new System.Drawing.Point(450, 234); this._txtFloatNegative_14.TabIndex = 40; this._txtFloatNegative_14.AcceptsReturn = true; this._txtFloatNegative_14.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_14.CausesValidation = true; this._txtFloatNegative_14.Enabled = true; this._txtFloatNegative_14.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_14.HideSelection = true; this._txtFloatNegative_14.ReadOnly = false; this._txtFloatNegative_14.MaxLength = 0; this._txtFloatNegative_14.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_14.Multiline = false; this._txtFloatNegative_14.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_14.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_14.TabStop = true; this._txtFloatNegative_14.Visible = true; this._txtFloatNegative_14.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_14.Name = "_txtFloatNegative_14"; this._txtFloatNegative_15.AutoSize = false; this._txtFloatNegative_15.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtFloatNegative_15.Size = new System.Drawing.Size(49, 19); this._txtFloatNegative_15.Location = new System.Drawing.Point(450, 252); this._txtFloatNegative_15.TabIndex = 41; this._txtFloatNegative_15.AcceptsReturn = true; this._txtFloatNegative_15.BackColor = System.Drawing.SystemColors.Window; this._txtFloatNegative_15.CausesValidation = true; this._txtFloatNegative_15.Enabled = true; this._txtFloatNegative_15.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloatNegative_15.HideSelection = true; this._txtFloatNegative_15.ReadOnly = false; this._txtFloatNegative_15.MaxLength = 0; this._txtFloatNegative_15.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloatNegative_15.Multiline = false; this._txtFloatNegative_15.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloatNegative_15.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFloatNegative_15.TabStop = true; this._txtFloatNegative_15.Visible = true; this._txtFloatNegative_15.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloatNegative_15.Name = "_txtFloatNegative_15"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(527, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 2; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdMatrix.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdMatrix.Text = "Pricing Matrix"; this.cmdMatrix.Size = new System.Drawing.Size(81, 29); this.cmdMatrix.Location = new System.Drawing.Point(104, 3); this.cmdMatrix.TabIndex = 45; this.cmdMatrix.BackColor = System.Drawing.SystemColors.Control; this.cmdMatrix.CausesValidation = true; this.cmdMatrix.Enabled = true; this.cmdMatrix.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdMatrix.Cursor = System.Windows.Forms.Cursors.Default; this.cmdMatrix.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdMatrix.TabStop = true; this.cmdMatrix.Name = "cmdMatrix"; this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPrint.Text = "&Print"; this.cmdPrint.Size = new System.Drawing.Size(73, 29); this.cmdPrint.Location = new System.Drawing.Point(345, 3); this.cmdPrint.TabIndex = 42; this.cmdPrint.TabStop = false; this.cmdPrint.BackColor = System.Drawing.SystemColors.Control; this.cmdPrint.CausesValidation = true; this.cmdPrint.Enabled = true; this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrint.Name = "cmdPrint"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCancel.Text = "&Undo"; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.Location = new System.Drawing.Point(5, 3); this.cmdCancel.TabIndex = 1; this.cmdCancel.TabStop = false; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Name = "cmdCancel"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "E&xit"; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.Location = new System.Drawing.Point(441, 3); this.cmdClose.TabIndex = 0; this.cmdClose.TabStop = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this._Shape1_3.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_3.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_3.Size = new System.Drawing.Size(502, 35); this._Shape1_3.Location = new System.Drawing.Point(14, 304); this._Shape1_3.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_3.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_3.BorderWidth = 1; this._Shape1_3.FillColor = System.Drawing.Color.Black; this._Shape1_3.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_3.Visible = true; this._Shape1_3.Name = "_Shape1_3"; this.Label1.Text = "&4 Disabled Pricing Group"; this.Label1.Size = new System.Drawing.Size(193, 17); this.Label1.Location = new System.Drawing.Point(16, 288); this.Label1.TabIndex = 43; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label1.BackColor = System.Drawing.Color.Transparent; this.Label1.Enabled = true; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = false; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this._lbl_10.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_10.Text = "When a Stock Item value is over"; this._lbl_10.Size = new System.Drawing.Size(157, 13); this._lbl_10.Location = new System.Drawing.Point(48, 126); this._lbl_10.TabIndex = 7; this._lbl_10.BackColor = System.Drawing.Color.Transparent; this._lbl_10.Enabled = true; this._lbl_10.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_10.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_10.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_10.UseMnemonic = true; this._lbl_10.Visible = true; this._lbl_10.AutoSize = true; this._lbl_10.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_10.Name = "_lbl_10"; this._lbl_18.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_18.Text = "round all amounts below"; this._lbl_18.Size = new System.Drawing.Size(115, 13); this._lbl_18.Location = new System.Drawing.Point(258, 126); this._lbl_18.TabIndex = 9; this._lbl_18.BackColor = System.Drawing.Color.Transparent; this._lbl_18.Enabled = true; this._lbl_18.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_18.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_18.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_18.UseMnemonic = true; this._lbl_18.Visible = true; this._lbl_18.AutoSize = true; this._lbl_18.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_18.Name = "_lbl_18"; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_2.Text = " value, then remove "; this._lbl_2.Size = new System.Drawing.Size(97, 13); this._lbl_2.Location = new System.Drawing.Point(45, 162); this._lbl_2.TabIndex = 12; this._lbl_2.BackColor = System.Drawing.Color.Transparent; this._lbl_2.Enabled = true; this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_2.UseMnemonic = true; this._lbl_2.Visible = true; this._lbl_2.AutoSize = true; this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_2.Name = "_lbl_2"; this._lbl_3.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_3.Text = "cents to the lower Rand value, else the amount is rounded to the next highest Rand"; this._lbl_3.Size = new System.Drawing.Size(394, 13); this._lbl_3.Location = new System.Drawing.Point(48, 144); this._lbl_3.TabIndex = 11; this._lbl_3.BackColor = System.Drawing.Color.Transparent; this._lbl_3.Enabled = true; this._lbl_3.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_3.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_3.UseMnemonic = true; this._lbl_3.Visible = true; this._lbl_3.AutoSize = true; this._lbl_3.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_3.Name = "_lbl_3"; this._lbl_4.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_4.Text = "cents from the rounded stock item Rand value."; this._lbl_4.Size = new System.Drawing.Size(223, 13); this._lbl_4.Location = new System.Drawing.Point(195, 162); this._lbl_4.TabIndex = 14; this._lbl_4.BackColor = System.Drawing.Color.Transparent; this._lbl_4.Enabled = true; this._lbl_4.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_4.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_4.UseMnemonic = true; this._lbl_4.Visible = true; this._lbl_4.AutoSize = true; this._lbl_4.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_4.Name = "_lbl_4"; this._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_38.Text = "Pricing Group Name:"; this._lblLabels_38.Size = new System.Drawing.Size(98, 13); this._lblLabels_38.Location = new System.Drawing.Point(23, 69); this._lblLabels_38.TabIndex = 4; this._lblLabels_38.BackColor = System.Drawing.Color.Transparent; this._lblLabels_38.Enabled = true; this._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_38.UseMnemonic = true; this._lblLabels_38.Visible = true; this._lblLabels_38.AutoSize = true; this._lblLabels_38.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_38.Name = "_lblLabels_38"; this._lblLabels_34.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_34.Text = "Unit:"; this._lblLabels_34.Size = new System.Drawing.Size(22, 13); this._lblLabels_34.Location = new System.Drawing.Point(66, 235); this._lblLabels_34.TabIndex = 16; this._lblLabels_34.BackColor = System.Drawing.Color.Transparent; this._lblLabels_34.Enabled = true; this._lblLabels_34.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_34.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_34.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_34.UseMnemonic = true; this._lblLabels_34.Visible = true; this._lblLabels_34.AutoSize = true; this._lblLabels_34.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_34.Name = "_lblLabels_34"; this._lblLabels_33.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_33.Text = "Case/Carton:"; this._lblLabels_33.Size = new System.Drawing.Size(63, 13); this._lblLabels_33.Location = new System.Drawing.Point(25, 254); this._lblLabels_33.TabIndex = 17; this._lblLabels_33.BackColor = System.Drawing.Color.Transparent; this._lblLabels_33.Enabled = true; this._lblLabels_33.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_33.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_33.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_33.UseMnemonic = true; this._lblLabels_33.Visible = true; this._lblLabels_33.AutoSize = true; this._lblLabels_33.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_33.Name = "_lblLabels_33"; this._lblCG_0.TextAlign = System.Drawing.ContentAlignment.TopCenter; this._lblCG_0.Text = "PricingGroup_Unit3:"; this._lblCG_0.Size = new System.Drawing.Size(49, 13); this._lblCG_0.Location = new System.Drawing.Point(93, 222); this._lblCG_0.TabIndex = 18; this._lblCG_0.BackColor = System.Drawing.Color.Transparent; this._lblCG_0.Enabled = true; this._lblCG_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lblCG_0.Cursor = System.Windows.Forms.Cursors.Default; this._lblCG_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblCG_0.UseMnemonic = true; this._lblCG_0.Visible = true; this._lblCG_0.AutoSize = false; this._lblCG_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblCG_0.Name = "_lblCG_0"; this._lblCG_1.TextAlign = System.Drawing.ContentAlignment.TopCenter; this._lblCG_1.Text = "PricingGroup_Case3:"; this._lblCG_1.Size = new System.Drawing.Size(49, 13); this._lblCG_1.Location = new System.Drawing.Point(144, 222); this._lblCG_1.TabIndex = 21; this._lblCG_1.BackColor = System.Drawing.Color.Transparent; this._lblCG_1.Enabled = true; this._lblCG_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lblCG_1.Cursor = System.Windows.Forms.Cursors.Default; this._lblCG_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblCG_1.UseMnemonic = true; this._lblCG_1.Visible = true; this._lblCG_1.AutoSize = false; this._lblCG_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblCG_1.Name = "_lblCG_1"; this._lblCG_2.TextAlign = System.Drawing.ContentAlignment.TopCenter; this._lblCG_2.Text = "PricingGroup_Unit4:"; this._lblCG_2.Size = new System.Drawing.Size(49, 13); this._lblCG_2.Location = new System.Drawing.Point(195, 222); this._lblCG_2.TabIndex = 24; this._lblCG_2.BackColor = System.Drawing.Color.Transparent; this._lblCG_2.Enabled = true; this._lblCG_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lblCG_2.Cursor = System.Windows.Forms.Cursors.Default; this._lblCG_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblCG_2.UseMnemonic = true; this._lblCG_2.Visible = true; this._lblCG_2.AutoSize = false; this._lblCG_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblCG_2.Name = "_lblCG_2"; this._lblCG_3.TextAlign = System.Drawing.ContentAlignment.TopCenter; this._lblCG_3.Text = "PricingGroup_Case4:"; this._lblCG_3.Size = new System.Drawing.Size(49, 13); this._lblCG_3.Location = new System.Drawing.Point(246, 222); this._lblCG_3.TabIndex = 27; this._lblCG_3.BackColor = System.Drawing.Color.Transparent; this._lblCG_3.Enabled = true; this._lblCG_3.ForeColor = System.Drawing.SystemColors.ControlText; this._lblCG_3.Cursor = System.Windows.Forms.Cursors.Default; this._lblCG_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblCG_3.UseMnemonic = true; this._lblCG_3.Visible = true; this._lblCG_3.AutoSize = false; this._lblCG_3.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblCG_3.Name = "_lblCG_3"; this._lblCG_4.TextAlign = System.Drawing.ContentAlignment.TopCenter; this._lblCG_4.Text = "PricingGroup_Unit5:"; this._lblCG_4.Size = new System.Drawing.Size(49, 13); this._lblCG_4.Location = new System.Drawing.Point(297, 222); this._lblCG_4.TabIndex = 30; this._lblCG_4.BackColor = System.Drawing.Color.Transparent; this._lblCG_4.Enabled = true; this._lblCG_4.ForeColor = System.Drawing.SystemColors.ControlText; this._lblCG_4.Cursor = System.Windows.Forms.Cursors.Default; this._lblCG_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblCG_4.UseMnemonic = true; this._lblCG_4.Visible = true; this._lblCG_4.AutoSize = false; this._lblCG_4.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblCG_4.Name = "_lblCG_4"; this._lblCG_5.TextAlign = System.Drawing.ContentAlignment.TopCenter; this._lblCG_5.Text = "PricingGroup_Case5:"; this._lblCG_5.Size = new System.Drawing.Size(49, 13); this._lblCG_5.Location = new System.Drawing.Point(348, 222); this._lblCG_5.TabIndex = 33; this._lblCG_5.BackColor = System.Drawing.Color.Transparent; this._lblCG_5.Enabled = true; this._lblCG_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lblCG_5.Cursor = System.Windows.Forms.Cursors.Default; this._lblCG_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblCG_5.UseMnemonic = true; this._lblCG_5.Visible = true; this._lblCG_5.AutoSize = false; this._lblCG_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblCG_5.Name = "_lblCG_5"; this._lblCG_6.TextAlign = System.Drawing.ContentAlignment.TopCenter; this._lblCG_6.Text = "PricingGroup_Unit6:"; this._lblCG_6.Size = new System.Drawing.Size(49, 13); this._lblCG_6.Location = new System.Drawing.Point(399, 222); this._lblCG_6.TabIndex = 36; this._lblCG_6.BackColor = System.Drawing.Color.Transparent; this._lblCG_6.Enabled = true; this._lblCG_6.ForeColor = System.Drawing.SystemColors.ControlText; this._lblCG_6.Cursor = System.Windows.Forms.Cursors.Default; this._lblCG_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblCG_6.UseMnemonic = true; this._lblCG_6.Visible = true; this._lblCG_6.AutoSize = false; this._lblCG_6.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblCG_6.Name = "_lblCG_6"; this._lblCG_7.TextAlign = System.Drawing.ContentAlignment.TopCenter; this._lblCG_7.Text = "PricingGroup_Case6:"; this._lblCG_7.Size = new System.Drawing.Size(49, 13); this._lblCG_7.Location = new System.Drawing.Point(450, 222); this._lblCG_7.TabIndex = 39; this._lblCG_7.BackColor = System.Drawing.Color.Transparent; this._lblCG_7.Enabled = true; this._lblCG_7.ForeColor = System.Drawing.SystemColors.ControlText; this._lblCG_7.Cursor = System.Windows.Forms.Cursors.Default; this._lblCG_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblCG_7.UseMnemonic = true; this._lblCG_7.Visible = true; this._lblCG_7.AutoSize = false; this._lblCG_7.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblCG_7.Name = "_lblCG_7"; this._lbl_1.BackColor = System.Drawing.Color.Transparent; this._lbl_1.Text = "&3. Default Pricing Markup Percentage"; this._lbl_1.Size = new System.Drawing.Size(215, 13); this._lbl_1.Location = new System.Drawing.Point(15, 201); this._lbl_1.TabIndex = 15; this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_1.Enabled = true; this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_1.UseMnemonic = true; this._lbl_1.Visible = true; this._lbl_1.AutoSize = true; this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_1.Name = "_lbl_1"; this._lbl_0.BackColor = System.Drawing.Color.Transparent; this._lbl_0.Text = "&2. Pricing Rules"; this._lbl_0.Size = new System.Drawing.Size(283, 13); this._lbl_0.Location = new System.Drawing.Point(15, 102); this._lbl_0.TabIndex = 6; this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_0.Enabled = true; this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_0.UseMnemonic = true; this._lbl_0.Visible = true; this._lbl_0.AutoSize = true; this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_0.Name = "_lbl_0"; this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_0.Size = new System.Drawing.Size(502, 70); this._Shape1_0.Location = new System.Drawing.Point(15, 117); this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_0.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_0.BorderWidth = 1; this._Shape1_0.FillColor = System.Drawing.Color.Black; this._Shape1_0.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_0.Visible = true; this._Shape1_0.Name = "_Shape1_0"; this._Shape1_1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_1.Size = new System.Drawing.Size(502, 67); this._Shape1_1.Location = new System.Drawing.Point(15, 216); this._Shape1_1.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_1.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_1.BorderWidth = 1; this._Shape1_1.FillColor = System.Drawing.Color.Black; this._Shape1_1.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_1.Visible = true; this._Shape1_1.Name = "_Shape1_1"; this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.Size = new System.Drawing.Size(502, 31); this._Shape1_2.Location = new System.Drawing.Point(15, 60); this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_2.BorderWidth = 1; this._Shape1_2.FillColor = System.Drawing.Color.Black; this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_2.Visible = true; this._Shape1_2.Name = "_Shape1_2"; this._lbl_5.BackColor = System.Drawing.Color.Transparent; this._lbl_5.Text = "&1. General"; this._lbl_5.Size = new System.Drawing.Size(60, 13); this._lbl_5.Location = new System.Drawing.Point(15, 45); this._lbl_5.TabIndex = 3; this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_5.Enabled = true; this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_5.UseMnemonic = true; this._lbl_5.Visible = true; this._lbl_5.AutoSize = true; this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_5.Name = "_lbl_5"; this.Controls.Add(chkPricing); this.Controls.Add(_txtFields_28); this.Controls.Add(_txtInteger_0); this.Controls.Add(_txtFloat_1); this.Controls.Add(_txtInteger_2); this.Controls.Add(_txtFloatNegative_0); this.Controls.Add(_txtFloatNegative_1); this.Controls.Add(_txtFloatNegative_2); this.Controls.Add(_txtFloatNegative_3); this.Controls.Add(_txtFloatNegative_4); this.Controls.Add(_txtFloatNegative_5); this.Controls.Add(_txtFloatNegative_6); this.Controls.Add(_txtFloatNegative_7); this.Controls.Add(_txtFloatNegative_8); this.Controls.Add(_txtFloatNegative_9); this.Controls.Add(_txtFloatNegative_10); this.Controls.Add(_txtFloatNegative_11); this.Controls.Add(_txtFloatNegative_12); this.Controls.Add(_txtFloatNegative_13); this.Controls.Add(_txtFloatNegative_14); this.Controls.Add(_txtFloatNegative_15); this.Controls.Add(picButtons); this.ShapeContainer1.Shapes.Add(_Shape1_3); this.Controls.Add(Label1); this.Controls.Add(_lbl_10); this.Controls.Add(_lbl_18); this.Controls.Add(_lbl_2); this.Controls.Add(_lbl_3); this.Controls.Add(_lbl_4); this.Controls.Add(_lblLabels_38); this.Controls.Add(_lblLabels_34); this.Controls.Add(_lblLabels_33); this.Controls.Add(_lblCG_0); this.Controls.Add(_lblCG_1); this.Controls.Add(_lblCG_2); this.Controls.Add(_lblCG_3); this.Controls.Add(_lblCG_4); this.Controls.Add(_lblCG_5); this.Controls.Add(_lblCG_6); this.Controls.Add(_lblCG_7); this.Controls.Add(_lbl_1); this.Controls.Add(_lbl_0); this.ShapeContainer1.Shapes.Add(_Shape1_0); this.ShapeContainer1.Shapes.Add(_Shape1_1); this.ShapeContainer1.Shapes.Add(_Shape1_2); this.Controls.Add(_lbl_5); this.Controls.Add(ShapeContainer1); this.picButtons.Controls.Add(cmdMatrix); this.picButtons.Controls.Add(cmdPrint); this.picButtons.Controls.Add(cmdCancel); this.picButtons.Controls.Add(cmdClose); //Me.lbl.SetIndex(_lbl_10, CType(10, Short)) //Me.lbl.SetIndex(_lbl_18, CType(18, Short)) //Me.lbl.SetIndex(_lbl_2, CType(2, Short)) //Me.lbl.SetIndex(_lbl_3, CType(3, Short)) //Me.lbl.SetIndex(_lbl_4, CType(4, Short)) //Me.lbl.SetIndex(_lbl_1, CType(1, Short)) //Me.lbl.SetIndex(_lbl_0, CType(0, Short)) //Me.lbl.SetIndex(_lbl_5, CType(5, Short)) //Me.lblCG.SetIndex(_lblCG_0, CType(0, Short)) //Me.lblCG.SetIndex(_lblCG_1, CType(1, Short)) //Me.lblCG.SetIndex(_lblCG_2, CType(2, Short)) //Me.lblCG.SetIndex(_lblCG_3, CType(3, Short)) //Me.lblCG.SetIndex(_lblCG_4, CType(4, Short)) //Me.lblCG.SetIndex(_lblCG_5, CType(5, Short)) //Me.lblCG.SetIndex(_lblCG_6, CType(6, Short)) //Me.lblCG.SetIndex(_lblCG_7, CType(7, Short)) //Me.lblLabels.SetIndex(_lblLabels_38, CType(38, Short)) //Me.lblLabels.SetIndex(_lblLabels_34, CType(34, Short)) //Me.lblLabels.SetIndex(_lblLabels_33, CType(33, Short)) //Me.txtFields.SetIndex(_txtFields_28, CType(28, Short)) //Me.txtFloat.SetIndex(_txtFloat_1, CType(1, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_0, CType(0, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_1, CType(1, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_2, CType(2, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_3, CType(3, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_4, CType(4, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_5, CType(5, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_6, CType(6, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_7, CType(7, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_8, CType(8, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_9, CType(9, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_10, CType(10, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_11, CType(11, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_12, CType(12, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_13, CType(13, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_14, CType(14, Short)) //Me.txtFloatNegative.SetIndex(_txtFloatNegative_15, CType(15, Short)) //Me.txtInteger.SetIndex(_txtInteger_0, CType(0, Short)) //Me.txtInteger.SetIndex(_txtInteger_2, CType(2, Short)) this.Shape1.SetIndex(_Shape1_3, Convert.ToInt16(3)); this.Shape1.SetIndex(_Shape1_0, Convert.ToInt16(0)); this.Shape1.SetIndex(_Shape1_1, Convert.ToInt16(1)); this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2)); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); //CType(Me.txtInteger, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.txtFloatNegative, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.txtFloat, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.txtFields, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lblCG, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using NQuery.Syntax; namespace NQuery.Authoring.Completion.Providers { internal sealed class KeywordCompletionProvider : ICompletionProvider { public IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, int position) { var syntaxTree = semanticModel.SyntaxTree; var root = syntaxTree.Root; // For certain constructs we never want to show a keyword completion. if (root.InComment(position) || root.InLiteral(position) || root.GuaranteedInUserGivenName(position) || IsInPropertyAccess(root, position)) { return Enumerable.Empty<CompletionItem>(); } return from k in GetAvailableKeywords(syntaxTree, position) let text = k.GetText() select new CompletionItem(text, text, null, Glyph.Keyword); } private static IEnumerable<SyntaxKind> GetAvailableKeywords(SyntaxTree syntaxTree, int position) { // NOT // CAST // COALESCE // NULLIF // TRUE // FALSE // EXISTS // CASE if (IsBeforeExpression(syntaxTree, position)) { yield return SyntaxKind.NotKeyword; yield return SyntaxKind.CastKeyword; yield return SyntaxKind.CoalesceKeyword; yield return SyntaxKind.NullIfKeyword; yield return SyntaxKind.TrueKeyword; yield return SyntaxKind.FalseKeyword; yield return SyntaxKind.ExistsKeyword; yield return SyntaxKind.CaseKeyword; } // AND // OR // IS // SOUNDS // SIMILAR // BETWEEN // IN if (IsAfterExpression(syntaxTree, position)) { yield return SyntaxKind.AndKeyword; yield return SyntaxKind.OrKeyword; yield return SyntaxKind.IsKeyword; yield return SyntaxKind.SoundsKeyword; yield return SyntaxKind.SimilarKeyword; yield return SyntaxKind.BetweenKeyword; yield return SyntaxKind.InKeyword; } // NULL if (IsBeforeExpression(syntaxTree, position) || InIsNullAfterIsKeyword(syntaxTree, position)) { yield return SyntaxKind.NullKeyword; } // LIKE if (IsAfterExpression(syntaxTree, position) || IsAfterSoundsKeyword(syntaxTree, position)) { yield return SyntaxKind.LikeKeyword; } // TO if (IsAfterSimilarKeyword(syntaxTree, position)) { yield return SyntaxKind.ToKeyword; } // DISTINCT if (IsAfterSelectKeyword(syntaxTree, position)) { yield return SyntaxKind.DistinctKeyword; } // TOP if (IsAfterSelectKeyword(syntaxTree, position) || IsAfterDistinctKeyword(syntaxTree, position) || IsAfterAllKeyword(syntaxTree, position)) { yield return SyntaxKind.TopKeyword; } // WITH if (IsBeforeQuery(syntaxTree, position) || IsInTopClauseAfterValue(syntaxTree, position)) { yield return SyntaxKind.WithKeyword; } // RECURSIVE if (IsAfterWithKeyword(syntaxTree, position)) { yield return SyntaxKind.RecursiveKeyword; } // TIES if (IsAfterWithKeyword(syntaxTree, position)) { yield return SyntaxKind.TiesKeyword; } // AS if (IsAfterExpressionSelectColumn(syntaxTree, position) || IsAfterNamedTableReference(syntaxTree, position) || IsInAliasAndNoAs(syntaxTree, position) || IsInCastAfterExpression(syntaxTree, position) || IsInCommonTableExpressionAfterNameOrColumnList(syntaxTree, position)) { yield return SyntaxKind.AsKeyword; } // WHEN if (IsInCaseAndAfterLabelOrAtStart(syntaxTree, position)) { yield return SyntaxKind.WhenKeyword; } // THEN if (IsInCaseLabelAndAfterExpression(syntaxTree, position)) yield return SyntaxKind.ThenKeyword; // ELSE // END if (IsInCaseAndAfterLabel(syntaxTree, position)) { yield return SyntaxKind.ElseKeyword; yield return SyntaxKind.EndKeyword; } // BY if (IsAfterOrderKeyword(syntaxTree, position) || IsAfterGroupKeyword(syntaxTree, position)) { yield return SyntaxKind.ByKeyword; } // ASC // DESC if (IsInOrderByAfterExpression(syntaxTree, position)) { yield return SyntaxKind.AscKeyword; yield return SyntaxKind.DescKeyword; } // SELECT if (IsBeforeSelectQuery(syntaxTree, position)) { yield return SyntaxKind.SelectKeyword; } // FROM if (InSelectQueryAndNoFromClause(syntaxTree, position)) { yield return SyntaxKind.FromKeyword; } // WHERE if (InSelectQueryAndNoWhereClause(syntaxTree, position)) { yield return SyntaxKind.WhereKeyword; } // GROUP if (InSelectQueryAndNoGroupByClause(syntaxTree, position)) { yield return SyntaxKind.GroupKeyword; } // HAVING if (InSelectQueryAndNoHavingClause(syntaxTree, position)) { yield return SyntaxKind.HavingKeyword; } // ORDER // UNION // INTERSECT // EXCEPT if (IsAfterQuery(syntaxTree, position)) { yield return SyntaxKind.OrderKeyword; yield return SyntaxKind.UnionKeyword; yield return SyntaxKind.IntersectKeyword; yield return SyntaxKind.ExceptKeyword; } // All if (IsAfterSelectKeyword(syntaxTree, position) || IsAfterUnionKeyword(syntaxTree, position) || IsAfterAllAnyOperator(syntaxTree, position)) { yield return SyntaxKind.AllKeyword; } // ANY // SOME if (IsAfterAllAnyOperator(syntaxTree, position)) { yield return SyntaxKind.AnyKeyword; yield return SyntaxKind.SomeKeyword; } // JOIN if (IsAfterTableReference(syntaxTree, position) || IsAfterInnerKeyword(syntaxTree, position) || IsAfterOuterKeyword(syntaxTree, position) || IsAfterLeftKeyword(syntaxTree, position) || IsAfterRightKeyword(syntaxTree, position) || IsAfterFullKeyword(syntaxTree, position) || IsAfterCrossKeyword(syntaxTree, position)) { yield return SyntaxKind.JoinKeyword; } // INNER // CROSS // LEFT // RIGHT // FULL if (IsAfterTableReference(syntaxTree, position)) { yield return SyntaxKind.InnerKeyword; yield return SyntaxKind.CrossKeyword; yield return SyntaxKind.LeftKeyword; yield return SyntaxKind.RightKeyword; yield return SyntaxKind.FullKeyword; } // LEFT // RIGHT // FULL if (IsAfterLeftKeyword(syntaxTree, position) || IsAfterRightKeyword(syntaxTree, position) || IsAfterFullKeyword(syntaxTree, position)) { yield return SyntaxKind.OuterKeyword; } // ON if (IsInConditionedJoinedTableReferenceAfterLeft(syntaxTree, position)) { yield return SyntaxKind.OnKeyword; } } private static bool IsAfterQuery(SyntaxTree syntaxTree, int position) { if (IsAfterNode<QuerySyntax>(syntaxTree, position)) return true; // FROM test xx| var token = syntaxTree.Root.FindTokenOnLeft(position); if (token is null) return false; var selectQuery = token.Parent.AncestorsAndSelf().OfType<SelectQuerySyntax>().FirstOrDefault(); return selectQuery is not null && token == selectQuery.LastToken(); } private static bool IsInPropertyAccess(SyntaxNode root, int position) { var token = root.FindTokenOnLeft(position); if (token is null || !token.Span.ContainsOrTouches(position)) return false; var propertyAccess = token.Parent.AncestorsAndSelf().OfType<PropertyAccessExpressionSyntax>().FirstOrDefault(); return propertyAccess is not null && (propertyAccess.Dot == token || propertyAccess.Name == token); } private static bool IsAfterNode<T>(SyntaxTree syntaxTree, int position) where T : SyntaxNode { var token = syntaxTree.Root.FindTokenOnLeft(position).GetPreviousIfCurrentContainsOrTouchesPosition(position); if (token is null) return false; return token.Parent .AncestorsAndSelf() .OfType<T>() .Any(parent => parent.LastToken() == token || parent.LastToken(includeZeroLength: true) == token); } private static bool IsBeforeNode<T>(SyntaxTree syntaxTree, int position) where T : SyntaxNode { var token = syntaxTree.Root.FindTokenContext(position); if (token is null) return false; return token.Parent .AncestorsAndSelf() .OfType<T>() .Any(parent => parent.FirstToken() == token || parent.FirstToken(includeZeroLength: true) == token); } private static bool IsAfterToken(SyntaxTree syntaxTree, int position, SyntaxKind syntaxKind) { var token = syntaxTree.Root.FindTokenOnLeft(position).GetPreviousIfCurrentContainsOrTouchesPosition(position); return token is not null && token.Kind == syntaxKind; } private static bool IsAfterExpression(SyntaxTree syntaxTree, int position) { return IsAfterNode<ExpressionSyntax>(syntaxTree, position); } private static bool IsBeforeExpression(SyntaxTree syntaxTree, int position) { return IsBeforeNode<ExpressionSyntax>(syntaxTree, position); } private static bool IsBeforeSelectQuery(SyntaxTree syntaxTree, int position) { if (IsBeforeQuery(syntaxTree, position)) return true; var token = syntaxTree.Root.FindTokenOnLeft(position); if (token is null) return false; // (| // (S| var parenthesizedExpression = token.Parent.AncestorsAndSelf().OfType<ParenthesizedExpressionSyntax>().FirstOrDefault(); if (parenthesizedExpression is not null) { if (token == parenthesizedExpression.LeftParenthesis || token.Kind.IsIdentifierOrKeyword() && token.GetPreviousToken() == parenthesizedExpression.LeftParenthesis) return true; } // expression IN (| // expression IN (S| var inExpression = token.Parent.AncestorsAndSelf().OfType<InExpressionSyntax>().FirstOrDefault(); if (inExpression is not null) { if (token == inExpression.ArgumentList.LeftParenthesis || token.Kind.IsIdentifierOrKeyword() && token.GetPreviousToken() == inExpression.ArgumentList.LeftParenthesis) return true; } return false; } private static bool InSelectQueryAndNoFromClause(SyntaxTree syntaxTree, int position) { var tokenAtCaret = syntaxTree.Root.FindTokenOnLeft(position); var token = tokenAtCaret.GetPreviousIfCurrentContainsOrTouchesPosition(position); var selectQuery = token?.Parent.AncestorsAndSelf().OfType<SelectQuerySyntax>().FirstOrDefault(); if (selectQuery is null) return false; if (selectQuery.FromClause is not null && selectQuery.FromClause.FromKeyword != tokenAtCaret) return false; var lastTokenInSelect = selectQuery.SelectClause.LastToken(); return token == lastTokenInSelect || tokenAtCaret == lastTokenInSelect; } private static bool InSelectQueryAndNoWhereClause(SyntaxTree syntaxTree, int position) { var tokenAtCaret = syntaxTree.Root.FindTokenOnLeft(position); var token = tokenAtCaret.GetPreviousIfCurrentContainsOrTouchesPosition(position); var selectQuery = token?.Parent.AncestorsAndSelf().OfType<SelectQuerySyntax>().FirstOrDefault(); if (selectQuery is null) return false; if (selectQuery.WhereClause is not null && selectQuery.WhereClause.WhereKeyword != tokenAtCaret) return false; var previousClause = selectQuery.FromClause ?? (SyntaxNode)selectQuery.SelectClause; var lastTokenInSelect = previousClause.LastToken(); return token == lastTokenInSelect || tokenAtCaret == lastTokenInSelect; } private static bool InSelectQueryAndNoGroupByClause(SyntaxTree syntaxTree, int position) { var tokenAtCaret = syntaxTree.Root.FindTokenOnLeft(position); var token = tokenAtCaret.GetPreviousIfCurrentContainsOrTouchesPosition(position); var selectQuery = token?.Parent.AncestorsAndSelf().OfType<SelectQuerySyntax>().FirstOrDefault(); if (selectQuery is null) return false; if (selectQuery.GroupByClause is not null && selectQuery.GroupByClause.GroupKeyword != tokenAtCaret) return false; var previousClause = selectQuery.WhereClause ?? selectQuery.FromClause ?? (SyntaxNode)selectQuery.SelectClause; var lastTokenInSelect = previousClause.LastToken(); return token == lastTokenInSelect || tokenAtCaret == lastTokenInSelect; } private static bool InSelectQueryAndNoHavingClause(SyntaxTree syntaxTree, int position) { var tokenAtCaret = syntaxTree.Root.FindTokenOnLeft(position); var token = tokenAtCaret.GetPreviousIfCurrentContainsOrTouchesPosition(position); var selectQuery = token?.Parent.AncestorsAndSelf().OfType<SelectQuerySyntax>().FirstOrDefault(); if (selectQuery is null) return false; if (selectQuery.HavingClause is not null && selectQuery.HavingClause.HavingKeyword != tokenAtCaret) return false; var previousClause = selectQuery.GroupByClause ?? selectQuery.WhereClause ?? selectQuery.FromClause ?? (SyntaxNode)selectQuery.SelectClause; var lastTokenInSelect = previousClause.LastToken(); return token == lastTokenInSelect || tokenAtCaret == lastTokenInSelect; } private static bool IsInTopClauseAfterValue(SyntaxTree syntaxTree, int position) { var token = syntaxTree.Root.FindTokenOnLeft(position).GetPreviousIfCurrentContainsOrTouchesPosition(position); if (token is null) return false; return token.Parent is TopClauseSyntax topClause && topClause.Value == token; } private static bool IsBeforeQuery(SyntaxTree syntaxTree, int position) { var token = syntaxTree.Root.FindToken(position); if (token is not null && token.Kind == SyntaxKind.EndOfFileToken && syntaxTree.Root.Root is not ExpressionSyntax) return true; return IsBeforeNode<QuerySyntax>(syntaxTree, position); } private static bool InIsNullAfterIsKeyword(SyntaxTree syntaxTree, int position) { var token = syntaxTree.Root.FindTokenOnLeft(position).GetPreviousIfCurrentContainsOrTouchesPosition(position); if (token is null) return false; return token.Parent is IsNullExpressionSyntax isNullExpression && isNullExpression.IsKeyword == token; } private static bool IsInOrderByAfterExpression(SyntaxTree syntaxTree, int position) { var token = syntaxTree.Root.FindTokenOnLeft(position).GetPreviousIfCurrentContainsOrTouchesPosition(position); var orderByColumn = token?.Parent.AncestorsAndSelf().OfType<OrderByColumnSyntax>().FirstOrDefault(); if (orderByColumn is null) return false; return orderByColumn.ColumnSelector.Span.End <= position; } private static bool IsInCaseAndAfterLabelOrAtStart(SyntaxTree syntaxTree, int position) { return IsBeforeExpression(syntaxTree, position) || IsAfterExpression(syntaxTree, position); } private static bool IsInCaseLabelAndAfterExpression(SyntaxTree syntaxTree, int position) { return IsBeforeExpression(syntaxTree, position) || IsAfterExpression(syntaxTree, position); } private static bool IsInCaseAndAfterLabel(SyntaxTree syntaxTree, int position) { return IsBeforeExpression(syntaxTree, position) || IsAfterExpression(syntaxTree, position); } private static bool IsAfterExpressionSelectColumn(SyntaxTree syntaxTree, int position) { var token = syntaxTree.Root.FindTokenContext(position); var node = token.Parent.AncestorsAndSelf().OfType<ExpressionSelectColumnSyntax>().FirstOrDefault(); return node is not null && node.Alias is null; } private static bool IsAfterNamedTableReference(SyntaxTree syntaxTree, int position) { var token = syntaxTree.Root.FindTokenContext(position); var node = token.Parent.AncestorsAndSelf().OfType<NamedTableReferenceSyntax>().FirstOrDefault(); return node is not null && node.Alias is null; } private static bool IsInAliasAndNoAs(SyntaxTree syntaxTree, int position) { var token = syntaxTree.Root.FindTokenContext(position); return token.Parent is AliasSyntax { AsKeyword: null }; } private static bool IsInCastAfterExpression(SyntaxTree syntaxTree, int position) { var token = syntaxTree.Root.FindTokenContext(position); if (token is null) return false; var castExpression = token.Parent.AncestorsAndSelf().OfType<CastExpressionSyntax>().FirstOrDefault(); return castExpression is not null && castExpression.Expression.Span.End <= position; } private static bool IsInCommonTableExpressionAfterNameOrColumnList(SyntaxTree syntaxTree, int position) { var token = syntaxTree.Root.FindTokenContext(position); var expression = token?.Parent.AncestorsAndSelf().OfType<CommonTableExpressionSyntax>().FirstOrDefault(); if (expression is null) return false; return expression.ColumnNameList is null && expression.Name.Span.End <= position || expression.ColumnNameList is not null && expression.ColumnNameList.Span.End <= position; } private static bool IsAfterAllAnyOperator(SyntaxTree syntaxTree, int position) { var tokenAtCaret = syntaxTree.Root.FindTokenOnLeft(position); var token = tokenAtCaret.GetPreviousIfCurrentContainsOrTouchesPosition(position); if (token is null) return false; var allAny = token.Parent.AncestorsAndSelf().OfType<AllAnySubselectSyntax>().FirstOrDefault(); if (allAny is not null && allAny.Keyword == tokenAtCaret) return true; var binaryExpression = token.Parent.AncestorsAndSelf().OfType<BinaryExpressionSyntax>().FirstOrDefault(); return binaryExpression is not null && binaryExpression.Kind.IsValidAllAnyOperator() && token == binaryExpression.OperatorToken; } private static bool IsAfterTableReference(SyntaxTree syntaxTree, int position) { return IsAfterNode<TableReferenceSyntax>(syntaxTree, position); } private static bool IsInConditionedJoinedTableReferenceAfterLeft(SyntaxTree syntaxTree, int position) { var tokenAtCaret = syntaxTree.Root.FindTokenOnLeft(position); var token = tokenAtCaret.GetPreviousIfCurrentContainsOrTouchesPosition(position); // JOIN foo f | var join = token?.Parent.AncestorsAndSelf().OfType<ConditionedJoinedTableReferenceSyntax>().FirstOrDefault(); if (@join is null) return false; var lastOfRight = join.Right.LastToken(); return token == lastOfRight || tokenAtCaret == lastOfRight; } private static bool IsAfterWithKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.WithKeyword); } private static bool IsAfterAllKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.AllKeyword); } private static bool IsAfterDistinctKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.DistinctKeyword); } private static bool IsAfterSelectKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.SelectKeyword); } private static bool IsAfterUnionKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.UnionKeyword); } private static bool IsAfterSoundsKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.SoundsKeyword); } private static bool IsAfterSimilarKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.SimilarKeyword); } private static bool IsAfterOrderKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.OrderKeyword); } private static bool IsAfterGroupKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.GroupKeyword); } private static bool IsAfterInnerKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.InnerKeyword); } private static bool IsAfterOuterKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.OuterKeyword); } private static bool IsAfterLeftKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.LeftKeyword); } private static bool IsAfterRightKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.RightKeyword); } private static bool IsAfterFullKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.FullKeyword); } private static bool IsAfterCrossKeyword(SyntaxTree syntaxTree, int position) { return IsAfterToken(syntaxTree, position, SyntaxKind.CrossKeyword); } } }
// Copyright 2003-2004 DigitalCraftsmen - http://www.digitalcraftsmen.com.br/ // // 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 Castle.ManagementExtensions.Default { using System; using System.Reflection; /// <summary> /// Summary description for MDefaultServer. /// </summary> public class MDefaultServer : MarshalByRefObject, MServer { protected MRegistry registry; public MDefaultServer() { // TODO: Allow customisation of MRegistry registry = new Default.MDefaultRegistry(this); SetupRegistry(); } private void SetupRegistry() { RegisterManagedObject(registry, MConstants.REGISTRY_NAME); } #region MServer Members /// <summary> /// TODO: Summary /// </summary> /// <param name="typeName"></param> /// <returns></returns> public Object Instantiate(String typeName) { if (typeName == null) { throw new ArgumentNullException("typeName"); } Type targetType = Type.GetType(typeName, true, true); object instance = AppDomain.CurrentDomain.CreateInstanceAndUnwrap( targetType.Assembly.FullName, targetType.FullName); return instance; } /// <summary> /// Instantiates the specified type using the server domain. /// </summary> /// <param name="typeName"></param> /// <param name="typeName"></param> /// <returns></returns> public Object Instantiate(String assemblyName, String typeName) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (typeName == null) { throw new ArgumentNullException("typeName"); } object instance = AppDomain.CurrentDomain.CreateInstanceAndUnwrap( assemblyName, typeName); return instance; } /// <summary> /// TODO: Summary /// </summary> /// <param name="typeName"></param> /// <param name="name"></param> /// <returns></returns> public ManagedInstance CreateManagedObject(String typeName, ManagedObjectName name) { if (typeName == null) { throw new ArgumentNullException("typeName"); } if (name == null) { throw new ArgumentNullException("name"); } Object instance = Instantiate(typeName); return RegisterManagedObject(instance, name); } /// <summary> /// TODO: Summary /// </summary> /// <param name="assemblyName"></param> /// <param name="typeName"></param> /// <param name="name"></param> /// <returns></returns> public ManagedInstance CreateManagedObject(String assemblyName, String typeName, ManagedObjectName name) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (typeName == null) { throw new ArgumentNullException("typeName"); } if (name == null) { throw new ArgumentNullException("name"); } Object instance = Instantiate(assemblyName, typeName); return RegisterManagedObject(instance, name); } /// <summary> /// TODO: Summary /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <returns></returns> public ManagedInstance RegisterManagedObject(Object instance, ManagedObjectName name) { if (instance == null) { throw new ArgumentNullException("instance"); } if (name == null) { throw new ArgumentNullException("name"); } return registry.RegisterManagedObject(instance, name); } /// <summary> /// TODO: Summary /// </summary> /// <param name="name"></param> /// <returns></returns> public ManagedInstance GetManagedInstance(ManagedObjectName name) { if (name == null) { throw new ArgumentNullException("name"); } return registry.GetManagedInstance(name); } /// <summary> /// TODO: Summary /// </summary> /// <param name="name"></param> public void UnregisterManagedObject(ManagedObjectName name) { if (name == null) { throw new ArgumentNullException("name"); } registry.UnregisterManagedObject(name); } /// <summary> /// Invokes an action in managed object /// </summary> /// <param name="name"></param> /// <param name="action"></param> /// <param name="args"></param> /// <param name="signature"></param> /// <returns></returns> /// <exception cref="InvalidDomainException">If domain name is not found.</exception> public Object Invoke(ManagedObjectName name, String action, Object[] args, Type[] signature) { if (name == null) { throw new ArgumentNullException("name"); } if (action == null) { throw new ArgumentNullException("action"); } return registry.Invoke(name, action, args, signature); } /// <summary> /// Returns the info (attributes and operations) about the specified object. /// </summary> /// <param name="name"></param> /// <returns></returns> /// <exception cref="InvalidDomainException">If domain name is not found.</exception> public ManagementInfo GetManagementInfo(ManagedObjectName name) { if (name == null) { throw new ArgumentNullException("name"); } return registry.GetManagementInfo(name); } /// <summary> /// Gets an attribute value of the specified managed object. /// </summary> /// <param name="name"></param> /// <param name="attributeName"></param> /// <returns></returns> /// <exception cref="InvalidDomainException">If domain name is not found.</exception> public Object GetAttribute(ManagedObjectName name, String attributeName) { if (name == null) { throw new ArgumentNullException("name"); } if (attributeName == null) { throw new ArgumentNullException("attributeName"); } return registry.GetAttributeValue(name, attributeName); } /// <summary> /// Sets an attribute value of the specified managed object. /// </summary> /// <param name="name"></param> /// <param name="attributeName"></param> /// <param name="attributeValue"></param> /// <exception cref="InvalidDomainException">If domain name is not found.</exception> public void SetAttribute(ManagedObjectName name, String attributeName, Object attributeValue) { if (name == null) { throw new ArgumentNullException("name"); } if (attributeName == null) { throw new ArgumentNullException("attributeName"); } registry.SetAttributeValue(name, attributeName, attributeValue); } /// <summary> /// Returns an array of registered domains. /// </summary> /// <returns>a list of domains</returns> public String[] GetDomains() { return registry.GetDomains(); } /// <summary> /// Queries the registerd components. /// </summary> /// <returns></returns> public ManagedObjectName[] Query(ManagedObjectName query) { return registry.Query(query); } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities.Statements { using System; using System.Activities.DynamicUpdate; using System.Activities.Validation; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Collections; using System.Windows.Markup; using System.Collections.ObjectModel; [ContentProperty("Action")] public sealed class InvokeAction : NativeActivity { IList<Argument> actionArguments; public InvokeAction() { this.actionArguments = new ValidatingCollection<Argument> { // disallow null values OnAddValidationCallback = item => { if (item == null) { throw FxTrace.Exception.ArgumentNull("item"); } } }; } [DefaultValue(null)] public ActivityAction Action { get; set; } protected override void CacheMetadata(NativeActivityMetadata metadata) { metadata.AddDelegate(this.Action); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action); } } [ContentProperty("Action")] public sealed class InvokeAction<T> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T> Argument { get; set; } [DefaultValue(null)] public ActivityAction<T> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void CacheMetadata(NativeActivityMetadata metadata) { metadata.AddDelegate(this.Action); RuntimeArgument runtimeArgument = new RuntimeArgument("Argument", typeof(T), ArgumentDirection.In, true); metadata.Bind(this.Argument, runtimeArgument); metadata.SetArgumentsCollection(new Collection<RuntimeArgument> { runtimeArgument }); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) // no-op { return; } context.ScheduleAction<T>(Action, Argument.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) // no-op { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7, T8> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [RequiredArgument] public InArgument<T8> Argument8 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context), Argument8.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [RequiredArgument] public InArgument<T8> Argument8 { get; set; } [RequiredArgument] public InArgument<T9> Argument9 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context), Argument8.Get(context), Argument9.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [RequiredArgument] public InArgument<T8> Argument8 { get; set; } [RequiredArgument] public InArgument<T9> Argument9 { get; set; } [RequiredArgument] public InArgument<T10> Argument10 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context), Argument8.Get(context), Argument9.Get(context), Argument10.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [RequiredArgument] public InArgument<T8> Argument8 { get; set; } [RequiredArgument] public InArgument<T9> Argument9 { get; set; } [RequiredArgument] public InArgument<T10> Argument10 { get; set; } [RequiredArgument] public InArgument<T11> Argument11 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context), Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [RequiredArgument] public InArgument<T8> Argument8 { get; set; } [RequiredArgument] public InArgument<T9> Argument9 { get; set; } [RequiredArgument] public InArgument<T10> Argument10 { get; set; } [RequiredArgument] public InArgument<T11> Argument11 { get; set; } [RequiredArgument] public InArgument<T12> Argument12 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context), Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context), Argument12.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [RequiredArgument] public InArgument<T8> Argument8 { get; set; } [RequiredArgument] public InArgument<T9> Argument9 { get; set; } [RequiredArgument] public InArgument<T10> Argument10 { get; set; } [RequiredArgument] public InArgument<T11> Argument11 { get; set; } [RequiredArgument] public InArgument<T12> Argument12 { get; set; } [RequiredArgument] public InArgument<T13> Argument13 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context), Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context), Argument12.Get(context), Argument13.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [RequiredArgument] public InArgument<T8> Argument8 { get; set; } [RequiredArgument] public InArgument<T9> Argument9 { get; set; } [RequiredArgument] public InArgument<T10> Argument10 { get; set; } [RequiredArgument] public InArgument<T11> Argument11 { get; set; } [RequiredArgument] public InArgument<T12> Argument12 { get; set; } [RequiredArgument] public InArgument<T13> Argument13 { get; set; } [RequiredArgument] public InArgument<T14> Argument14 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context), Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context), Argument12.Get(context), Argument13.Get(context), Argument14.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [RequiredArgument] public InArgument<T8> Argument8 { get; set; } [RequiredArgument] public InArgument<T9> Argument9 { get; set; } [RequiredArgument] public InArgument<T10> Argument10 { get; set; } [RequiredArgument] public InArgument<T11> Argument11 { get; set; } [RequiredArgument] public InArgument<T12> Argument12 { get; set; } [RequiredArgument] public InArgument<T13> Argument13 { get; set; } [RequiredArgument] public InArgument<T14> Argument14 { get; set; } [RequiredArgument] public InArgument<T15> Argument15 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context), Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context), Argument12.Get(context), Argument13.Get(context), Argument14.Get(context), Argument15.Get(context)); } } [ContentProperty("Action")] public sealed class InvokeAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> : NativeActivity { public InvokeAction() { } [RequiredArgument] public InArgument<T1> Argument1 { get; set; } [RequiredArgument] public InArgument<T2> Argument2 { get; set; } [RequiredArgument] public InArgument<T3> Argument3 { get; set; } [RequiredArgument] public InArgument<T4> Argument4 { get; set; } [RequiredArgument] public InArgument<T5> Argument5 { get; set; } [RequiredArgument] public InArgument<T6> Argument6 { get; set; } [RequiredArgument] public InArgument<T7> Argument7 { get; set; } [RequiredArgument] public InArgument<T8> Argument8 { get; set; } [RequiredArgument] public InArgument<T9> Argument9 { get; set; } [RequiredArgument] public InArgument<T10> Argument10 { get; set; } [RequiredArgument] public InArgument<T11> Argument11 { get; set; } [RequiredArgument] public InArgument<T12> Argument12 { get; set; } [RequiredArgument] public InArgument<T13> Argument13 { get; set; } [RequiredArgument] public InArgument<T14> Argument14 { get; set; } [RequiredArgument] public InArgument<T15> Argument15 { get; set; } [RequiredArgument] public InArgument<T16> Argument16 { get; set; } [DefaultValue(null)] public ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> Action { get; set; } protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity) { metadata.AllowUpdateInsideThisActivity(); } protected override void Execute(NativeActivityContext context) { if (Action == null || Action.Handler == null) { return; } context.ScheduleAction(Action, Argument1.Get(context), Argument2.Get(context), Argument3.Get(context), Argument4.Get(context), Argument5.Get(context), Argument6.Get(context), Argument7.Get(context), Argument8.Get(context), Argument9.Get(context), Argument10.Get(context), Argument11.Get(context), Argument12.Get(context), Argument13.Get(context), Argument14.Get(context), Argument15.Get(context), Argument16.Get(context)); } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Runtime.InteropServices; using System.Windows.Forms; using XenAdmin.Core; namespace XenAdmin.Controls { // Taken from http://209.85.165.104/search?q=cache:hnUUN2Zhi7YJ:www.developersdex.com/vb/message.asp%3Fp%3D2927%26r%3D5855234+NativeMethods.GetDCEx&hl=en&ct=clnk&cd=1&gl=uk&client=firefox-a public class BlueBorderPanel : DoubleBufferedPanel { private Color borderColor = Drawing.XPBorderColor; public Color BorderColor { get { return borderColor; } set { if (borderColor != value) { borderColor = value; NativeMethods.SendMessage(this.Handle, NativeMethods.WM_NCPAINT, (IntPtr)1, IntPtr.Zero); } } } protected override void OnResize(EventArgs e) { base.OnResize(e); NativeMethods.SendMessage(this.Handle, NativeMethods.WM_NCPAINT, (IntPtr)1, IntPtr.Zero); } protected override void WndProc(ref Message m) { if (m.Msg == NativeMethods.WM_NCPAINT) { if (this.Parent != null) { NCPaint(); m.WParam = GetHRegion(); base.DefWndProc(ref m); NativeMethods.DeleteObject(m.WParam); m.Result = (IntPtr)1; } } base.WndProc(ref m); } private void NCPaint() { if (this.Parent == null) return; if (this.Width <= 0 || this.Height <= 0) return; IntPtr windowDC = NativeMethods.GetDCEx(this.Handle, IntPtr.Zero, NativeMethods.DCX_CACHE | NativeMethods.DCX_WINDOW | NativeMethods.DCX_CLIPSIBLINGS | NativeMethods.DCX_LOCKWINDOWUPDATE); if (windowDC.Equals(IntPtr.Zero)) return; using (Bitmap bm = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb)) { using (Graphics g = Graphics.FromImage(bm)) { Rectangle borderRect = new Rectangle(0, 0, Width - 1, Height - 1); using (Pen borderPen = new Pen(this.borderColor, 1)) { borderPen.Alignment = PenAlignment.Inset; g.DrawRectangle(borderPen, borderRect); } // Create and Apply a Clip Region to the WindowDC using (Region Rgn = new Region(new Rectangle(0, 0, Width, Height))) { Rgn.Exclude(new Rectangle(1, 1, Width - 2, Height - 2)); IntPtr hRgn = Rgn.GetHrgn(g); if (!hRgn.Equals(IntPtr.Zero)) NativeMethods.SelectClipRgn(windowDC, hRgn); IntPtr bmDC = g.GetHdc(); IntPtr hBmp = bm.GetHbitmap(); IntPtr oldDC = NativeMethods.SelectObject(bmDC, hBmp); NativeMethods.BitBlt(windowDC, 0, 0, bm.Width, bm.Height, bmDC, 0, 0, NativeMethods.SRCCOPY); NativeMethods.SelectClipRgn(windowDC, IntPtr.Zero); NativeMethods.DeleteObject(hRgn); g.ReleaseHdc(bmDC); NativeMethods.SelectObject(oldDC, hBmp); NativeMethods.DeleteObject(hBmp); bm.Dispose(); } } } NativeMethods.ReleaseDC(this.Handle, windowDC); } private IntPtr GetHRegion() { //Define a Clip Region to pass back to WM_NCPAINTs wParam. //Must be in Screen Coordinates. IntPtr hRgn; Rectangle winRect = this.Parent.RectangleToScreen(this.Bounds); Rectangle clientRect = this.RectangleToScreen(this.ClientRectangle); Region updateRegion = new Region(winRect); updateRegion.Complement(clientRect); using (Graphics g = this.CreateGraphics()) hRgn = updateRegion.GetHrgn(g); updateRegion.Dispose(); return hRgn; } } internal class NativeMethods { [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [DllImport("gdi32.dll")] public static extern int SelectClipRgn(IntPtr hdc, IntPtr hrgn); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("user32.dll")] public static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hrgnClip, int flags); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); public const int WM_NCPAINT = 0x85; public const int DCX_WINDOW = 0x1; public const int DCX_CACHE = 0x2; public const int DCX_CLIPCHILDREN = 0x8; public const int DCX_CLIPSIBLINGS = 0x10; public const int DCX_LOCKWINDOWUPDATE = 0x400; public const int SRCCOPY = 0xCC0020; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private class PostProcessor { private readonly SemanticModel _semanticModel; private readonly int _contextPosition; public PostProcessor(SemanticModel semanticModel, int contextPosition) { Contract.ThrowIfNull(semanticModel); _semanticModel = semanticModel; _contextPosition = contextPosition; } public IEnumerable<StatementSyntax> RemoveRedundantBlock(IEnumerable<StatementSyntax> statements) { // it must have only one statement if (statements.Count() != 1) { return statements; } // that statement must be a block var block = statements.Single() as BlockSyntax; if (block == null) { return statements; } // we have a block, remove them return RemoveRedundantBlock(block); } private IEnumerable<StatementSyntax> RemoveRedundantBlock(BlockSyntax block) { // if block doesn't have any statement if (block.Statements.Count == 0) { // either remove the block if it doesn't have any trivia, or return as it is if // there are trivia attached to block return (block.OpenBraceToken.GetAllTrivia().IsEmpty() && block.CloseBraceToken.GetAllTrivia().IsEmpty()) ? SpecializedCollections.EmptyEnumerable<StatementSyntax>() : SpecializedCollections.SingletonEnumerable<StatementSyntax>(block); } // okay transfer asset attached to block to statements var firstStatement = block.Statements.First(); var firstToken = firstStatement.GetFirstToken(includeZeroWidth: true); var firstTokenWithAsset = block.OpenBraceToken.CopyAnnotationsTo(firstToken).WithPrependedLeadingTrivia(block.OpenBraceToken.GetAllTrivia()); var lastStatement = block.Statements.Last(); var lastToken = lastStatement.GetLastToken(includeZeroWidth: true); var lastTokenWithAsset = block.CloseBraceToken.CopyAnnotationsTo(lastToken).WithAppendedTrailingTrivia(block.CloseBraceToken.GetAllTrivia()); // create new block with new tokens block = block.ReplaceTokens(new[] { firstToken, lastToken }, (o, c) => (o == firstToken) ? firstTokenWithAsset : lastTokenWithAsset); // return only statements without the wrapping block return block.Statements; } public IEnumerable<StatementSyntax> MergeDeclarationStatements(IEnumerable<StatementSyntax> statements) { if (statements.FirstOrDefault() == null) { return statements; } return MergeDeclarationStatementsWorker(statements); } private IEnumerable<StatementSyntax> MergeDeclarationStatementsWorker(IEnumerable<StatementSyntax> statements) { var map = new Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>>(); foreach (var statement in statements) { if (!IsDeclarationMergable(statement)) { foreach (var declStatement in GetMergedDeclarationStatements(map)) { yield return declStatement; } yield return statement; continue; } AppendDeclarationStatementToMap(statement as LocalDeclarationStatementSyntax, map); } // merge leftover if (map.Count <= 0) { yield break; } foreach (var declStatement in GetMergedDeclarationStatements(map)) { yield return declStatement; } } private void AppendDeclarationStatementToMap( LocalDeclarationStatementSyntax statement, Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>> map) { Contract.ThrowIfNull(statement); var type = _semanticModel.GetSpeculativeTypeInfo(_contextPosition, statement.Declaration.Type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; Contract.ThrowIfNull(type); map.GetOrAdd(type, _ => new List<LocalDeclarationStatementSyntax>()).Add(statement); } private IEnumerable<LocalDeclarationStatementSyntax> GetMergedDeclarationStatements( Dictionary<ITypeSymbol, List<LocalDeclarationStatementSyntax>> map) { foreach (var keyValuePair in map) { Contract.ThrowIfFalse(keyValuePair.Value.Count > 0); // merge all variable decl for current type var variables = new List<VariableDeclaratorSyntax>(); foreach (var statement in keyValuePair.Value) { foreach (var variable in statement.Declaration.Variables) { variables.Add(variable); } } // and create one decl statement // use type name from the first decl statement yield return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(keyValuePair.Value.First().Declaration.Type, SyntaxFactory.SeparatedList(variables))); } map.Clear(); } private bool IsDeclarationMergable(StatementSyntax statement) { Contract.ThrowIfNull(statement); // to be mergable, statement must be // 1. decl statement without any extra info // 2. no initialization on any of its decls // 3. no trivia except whitespace // 4. type must be known var declarationStatement = statement as LocalDeclarationStatementSyntax; if (declarationStatement == null) { return false; } if (declarationStatement.Modifiers.Count > 0 || declarationStatement.IsConst || declarationStatement.IsMissing) { return false; } if (ContainsAnyInitialization(declarationStatement)) { return false; } if (!ContainsOnlyWhitespaceTrivia(declarationStatement)) { return false; } var semanticInfo = _semanticModel.GetSpeculativeTypeInfo(_contextPosition, declarationStatement.Declaration.Type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; if (semanticInfo == null || semanticInfo.TypeKind == TypeKind.Error || semanticInfo.TypeKind == TypeKind.Unknown) { return false; } return true; } private bool ContainsAnyInitialization(LocalDeclarationStatementSyntax statement) { foreach (var variable in statement.Declaration.Variables) { if (variable.Initializer != null) { return true; } } return false; } private static bool ContainsOnlyWhitespaceTrivia(StatementSyntax statement) { foreach (var token in statement.DescendantTokens()) { foreach (var trivia in token.LeadingTrivia.Concat(token.TrailingTrivia)) { if (trivia.Kind() != SyntaxKind.WhitespaceTrivia && trivia.Kind() != SyntaxKind.EndOfLineTrivia) { return false; } } } return true; } public IEnumerable<StatementSyntax> RemoveInitializedDeclarationAndReturnPattern(IEnumerable<StatementSyntax> statements) { // if we have inline temp variable as service, we could just use that service here. // since it is not a service right now, do very simple clean up if (statements.ElementAtOrDefault(2) != null) { return statements; } var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax; var returnStatement = statements.ElementAtOrDefault(1) as ReturnStatementSyntax; if (declaration == null || returnStatement == null) { return statements; } if (declaration.Declaration == null || declaration.Declaration.Variables.Count != 1 || declaration.Declaration.Variables[0].Initializer == null || declaration.Declaration.Variables[0].Initializer.Value == null || declaration.Declaration.Variables[0].Initializer.Value is StackAllocArrayCreationExpressionSyntax || returnStatement.Expression == null) { return statements; } if (!ContainsOnlyWhitespaceTrivia(declaration) || !ContainsOnlyWhitespaceTrivia(returnStatement)) { return statements; } var variableName = declaration.Declaration.Variables[0].Identifier.ToString(); if (returnStatement.Expression.ToString() != variableName) { return statements; } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.ReturnStatement(declaration.Declaration.Variables[0].Initializer.Value)); } public IEnumerable<StatementSyntax> RemoveDeclarationAssignmentPattern(IEnumerable<StatementSyntax> statements) { // if we have inline temp variable as service, we could just use that service here. // since it is not a service right now, do very simple clean up var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax; var assignment = statements.ElementAtOrDefault(1) as ExpressionStatementSyntax; if (declaration == null || assignment == null) { return statements; } if (ContainsAnyInitialization(declaration) || declaration.Declaration == null || declaration.Declaration.Variables.Count != 1 || assignment.Expression == null || assignment.Expression.Kind() != SyntaxKind.SimpleAssignmentExpression) { return statements; } if (!ContainsOnlyWhitespaceTrivia(declaration) || !ContainsOnlyWhitespaceTrivia(assignment)) { return statements; } var variableName = declaration.Declaration.Variables[0].Identifier.ToString(); var assignmentExpression = assignment.Expression as AssignmentExpressionSyntax; if (assignmentExpression.Left == null || assignmentExpression.Right == null || assignmentExpression.Left.ToString() != variableName) { return statements; } var variable = declaration.Declaration.Variables[0].WithInitializer(SyntaxFactory.EqualsValueClause(assignmentExpression.Right)); return SpecializedCollections.SingletonEnumerable<StatementSyntax>( declaration.WithDeclaration( declaration.Declaration.WithVariables( SyntaxFactory.SingletonSeparatedList(variable)))).Concat(statements.Skip(2)); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using UnityEngine; namespace GenesisRage { public abstract class SafeChutePart { public object partModule; public bool dewarpedAtDeploy = false; public bool dewarpedAtGround = false; public SafeChutePart(PartModule pm) { partModule = pm; #if DEBUG SafeChuteModule.SCprint("Added SafeChutePart with module "+pm.moduleName + " from part "+pm.part.name); #endif } public abstract bool isDeployed(); } public class SafeChuteSSTUPart : SafeChutePart { public override bool isDeployed() { //return (isMainChuteDeployed() || isDrogueChuteDeployed()); return isMainChuteDeployed(); } private string getChuteState() { return ((string)partModule.GetType().GetField("chutePersistence").GetValue(partModule)); } public bool isMainChuteDeployed() { string chuteState = getChuteState(); return chuteState.Contains("MAIN_DEPLOYING_FULL") || chuteState.Contains("MAIN_DEPLOYING_SEMI") || chuteState.Contains("MAIN_FULL_DEPLOYED") || chuteState.Contains("MAIN_SEMI_DEPLOYED"); } public bool isDrogueChuteDeployed() { string chuteState = getChuteState(); return chuteState.Contains("DROGUE_DEPLOYING_FULL") || chuteState.Contains("DROGUE_DEPLOYING_SEMI") || chuteState.Contains("DROGUE_FULL_DEPLOYED") || chuteState.Contains("DROGUE_SEMI_DEPLOYED"); } public SafeChuteSSTUPart(PartModule pm) : base(pm) { } } public class SafeChuteFARPart : SafeChutePart { public override bool isDeployed() { return ((string)partModule.GetType().GetField("depState").GetValue(partModule) == "DEPLOYED"); } public SafeChuteFARPart(PartModule pm) : base(pm) {} } public class SafeChuteRCPart : SafeChutePart { public override bool isDeployed() { System.Collections.IList pms = (System.Collections.IList)partModule.GetType().GetField("parachutes").GetValue(partModule); for (int i = pms.Count - 1; i >= 0; --i) { if ((string)pms[i].GetType().GetField("depState").GetValue(pms[i]) == "DEPLOYED") { return true; } } return false; } public SafeChuteRCPart(PartModule pm) : base(pm) {} } public class SafeChuteStockPart:SafeChutePart { public override bool isDeployed() { return (((ModuleParachute)partModule).deploymentState == ModuleParachute.deploymentStates.DEPLOYED); } public SafeChuteStockPart(PartModule pm):base(pm) {} } [KSPAddon(KSPAddon.Startup.Flight, false)] public class SafeChuteModule : MonoBehaviour { Vessel vessel; float deWarpGrnd; double maxAlt; List<SafeChutePart> safeParts = new List<SafeChutePart>(); public void Awake() { // load XML config file, set default values if file doesnt exist KSP.IO.PluginConfiguration cfg = KSP.IO.PluginConfiguration.CreateForType<GenesisRage.SafeChuteModule>(null); cfg.load(); deWarpGrnd = (float)cfg.GetValue<double>("DeWarpGround", 15.0f); maxAlt = (double)cfg.GetValue<double>("MaxAltitude", 10000.0f); SCprint (String.Format("DeWarpGround = {0}, MaxAltitude = {1}", deWarpGrnd, maxAlt)); } public void Start() { ListChutes(); GameEvents.onVesselChange.Add(ListChutes); // onVesselChange - switching between vessels with [ or ] keys GameEvents.onVesselStandardModification.Add(ListChutes); // onVesselStandardModification collects various vessel events and fires them off with a single one. // Specifically - onPartAttach,onPartRemove,onPartCouple,onPartDie,onPartUndock,onVesselWasModified,onVesselPartCountChanged } public void ListChutes(Vessel gameEventVessel=null) { #if DEBUG SCprint("ListChutes"); #endif vessel = FlightGlobals.ActiveVessel; if (vessel==null) { return; } safeParts.Clear(); // grab every parachute part from active vessel if (vessel.Parts == null) { return; } for (int i = vessel.Parts.Count - 1; i >= 0; --i){ for (int j = vessel.parts[i].Modules.Count - 1; j >= 0; --j){ #if DEBUG SCprint(i.ToString() + "/" + j.ToString() + ": " + vessel.parts[i].Modules[j].moduleName); #endif switch (vessel.parts[i].Modules[j].moduleName) { case "ModuleParachute": safeParts.Add(new SafeChuteStockPart(vessel.parts[i].Modules[j])); break; case "RealChuteModule": safeParts.Add(new SafeChuteRCPart (vessel.parts[i].Modules[j])); break; case "RealChuteFAR": safeParts.Add(new SafeChuteFARPart (vessel.parts[i].Modules[j])); break; case "SSTUModularParachute": safeParts.Add(new SafeChuteSSTUPart (vessel.parts[i].Modules[j])); break; } } } } public void FixedUpdate() { // only proceed if we're FLYING and time warp is engaged if (FlightGlobals.ActiveVessel.situation == Vessel.Situations.FLYING && TimeWarp.CurrentRateIndex > 0 ) { // only proceed if the active vessel has parachutes if (safeParts.Count > 0) { // only proceed if current altitude is within range double alt = vessel.altitude; if (alt > 0.0f && alt < maxAlt) { for (int i = safeParts.Count - 1; i >= 0; --i) { if (!safeParts[i].dewarpedAtDeploy && safeParts[i].isDeployed()) { safeParts[i].dewarpedAtDeploy = true; TimeWarp.SetRate(0, true, true); } if (!safeParts[i].dewarpedAtGround) { float altGrnd = (float)vessel.radarAltitude; if ((altGrnd < deWarpGrnd && altGrnd > 0.0f) || (alt < deWarpGrnd && alt > 0.0f)) { safeParts[i].dewarpedAtGround = true; TimeWarp.SetRate(0, true, true); } } } } } } } #if DEBUG public void OnGUI() { if (HighLogic.LoadedScene == GameScenes.FLIGHT) { GUI.enabled = false; GUILayout.BeginArea(new Rect(100,100,400,400)); GUILayout.BeginVertical("box"); int i = 0; GUILayout.Label("SafeChute"); GUILayout.Label("DeWarp:" + deWarpGrnd + " Current:" + vessel.heightFromTerrain.ToString("F02") + "/" + vessel.altitude.ToString("F02") + "/" + vessel.radarAltitude.ToString("F02")); foreach (SafeChutePart part in safeParts) { GUILayout.Label("#" + i.ToString()+ " dewarpedAtDeploy:" + part.dewarpedAtDeploy + " dewarpedAtGround:" + part.dewarpedAtGround); i++; } GUILayout.EndVertical(); GUILayout.EndArea(); GUI.enabled = true; } } #endif static public void SCprint(string tacos) { print("[SafeChute]: " + tacos); // tacos are awesome } } }
using Abp.Domain.Entities; using Abp.Domain.Entities.Auditing; using Abp.Domain.Repositories; using Abp.EntityHistory; using Abp.Events.Bus.Entities; using Abp.Extensions; using Abp.Json; using Abp.Threading; using Abp.Timing; using Abp.Zero.SampleApp.EntityHistory; using Castle.MicroKernel.Registration; using NSubstitute; using Shouldly; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Threading; using Abp.Application.Editions; using Abp.Application.Features; using Abp.Authorization.Roles; using Abp.Zero.SampleApp.TPH; using Xunit; namespace Abp.Zero.SampleApp.Tests.EntityHistory { public class SimpleEntityHistory_Test : SampleAppTestBase { private readonly IRepository<Advertisement> _advertisementRepository; private readonly IRepository<Blog> _blogRepository; private readonly IRepository<Post, Guid> _postRepository; private readonly IRepository<Comment> _commentRepository; private readonly IRepository<Student> _studentRepository; private IEntityHistoryStore _entityHistoryStore; public SimpleEntityHistory_Test() { _advertisementRepository = Resolve<IRepository<Advertisement>>(); _blogRepository = Resolve<IRepository<Blog>>(); _postRepository = Resolve<IRepository<Post, Guid>>(); _commentRepository = Resolve<IRepository<Comment>>(); _studentRepository = Resolve<IRepository<Student>>(); var user = GetDefaultTenantAdmin(); AbpSession.TenantId = user.TenantId; AbpSession.UserId = user.Id; Resolve<IEntityHistoryConfiguration>().IsEnabledForAnonymousUsers = true; } protected override void PreInitialize() { base.PreInitialize(); _entityHistoryStore = Substitute.For<IEntityHistoryStore>(); LocalIocManager.IocContainer.Register( Component.For<IEntityHistoryStore>().Instance(_entityHistoryStore).LifestyleSingleton() ); } #region CASES WRITE HISTORY [Fact] public void Should_Write_History_For_Tracked_Entities_Create() { /* Advertisement does not have Audited attribute. */ Resolve<IEntityHistoryConfiguration>().Selectors.Add("Selected", typeof(Advertisement)); int? advertisementId = null; WithUnitOfWork(() => { var advertisement = new Advertisement { Banner = "tracked-advertisement" }; advertisementId = _advertisementRepository.InsertAndGetId(advertisement); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Advertisement).FullName); entityChange.ChangeTime.ShouldNotBeNull(); entityChange.ChangeType.ShouldBe(EntityChangeType.Created); entityChange.EntityId.ShouldBe(advertisementId.ToJsonString()); entityChange.PropertyChanges.Count.ShouldBe(1); var propertyChange1 = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Advertisement.Banner)); propertyChange1.OriginalValue.ShouldBeNull(); propertyChange1.NewValue.ShouldNotBeNull(); // Check "who did this change" s.ImpersonatorTenantId.ShouldBe(AbpSession.ImpersonatorTenantId); s.ImpersonatorUserId.ShouldBe(AbpSession.ImpersonatorUserId); s.TenantId.ShouldBe(AbpSession.TenantId); s.UserId.ShouldBe(AbpSession.UserId); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_Tracked_Entities_Create_To_Database() { // Forward calls from substitute to implementation var entityHistoryStore = Resolve<EntityHistoryStore>(); _entityHistoryStore.When(x => x.SaveAsync(Arg.Any<EntityChangeSet>())) .Do(callback => AsyncHelper.RunSync(() => entityHistoryStore.SaveAsync(callback.Arg<EntityChangeSet>())) ); _entityHistoryStore.When(x => x.Save(Arg.Any<EntityChangeSet>())) .Do(callback => entityHistoryStore.Save(callback.Arg<EntityChangeSet>())); UsingDbContext((context) => { context.EntityChanges.Count(e => e.TenantId == 1).ShouldBe(0); context.EntityChangeSets.Count(e => e.TenantId == 1).ShouldBe(0); context.EntityPropertyChanges.Count(e => e.TenantId == 1).ShouldBe(0); }); /* Advertisement does not have Audited attribute. */ Resolve<IEntityHistoryConfiguration>().Selectors.Add("Selected", typeof(Advertisement)); var justNow = Clock.Now; Thread.Sleep(1); WithUnitOfWork(() => { _advertisementRepository.InsertAndGetId(new Advertisement { Banner = "tracked-advertisement" }); }); UsingDbContext((context) => { context.EntityChanges.Count(e => e.TenantId == 1).ShouldBe(1); context.EntityChangeSets.Count(e => e.TenantId == 1).ShouldBe(1); context.EntityChangeSets.Single().CreationTime.ShouldBeGreaterThan(justNow); context.EntityPropertyChanges.Count(e => e.TenantId == 1).ShouldBe(1); }); } [Fact] public void Should_Write_History_For_TPH_Tracked_Entities_Create() { Resolve<IEntityHistoryConfiguration>().Selectors.Add("Selected", typeof(Student)); var student = new Student() { Name = "TestName", IdCard = "TestIdCard", Address = "TestAddress", Grade = 1 }; _studentRepository.Insert(student); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Student).FullName); entityChange.ChangeTime.ShouldNotBeNull(); entityChange.ChangeType.ShouldBe(EntityChangeType.Created); entityChange.EntityId.ShouldBe(student.Id.ToJsonString()); entityChange.PropertyChanges.Count.ShouldBe(4); //Name,IdCard,Address,Grade var propertyChange1 = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Student.Name)); propertyChange1.OriginalValue.ShouldBeNull(); propertyChange1.NewValue.ShouldNotBeNull(); var propertyChange2 = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Student.IdCard)); propertyChange2.OriginalValue.ShouldBeNull(); propertyChange2.NewValue.ShouldNotBeNull(); var propertyChange3 = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Student.Address)); propertyChange3.OriginalValue.ShouldBeNull(); propertyChange3.NewValue.ShouldNotBeNull(); var propertyChange4 = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Student.Grade)); propertyChange4.OriginalValue.ShouldBeNull(); propertyChange4.NewValue.ShouldNotBeNull(); // Check "who did this change" s.ImpersonatorTenantId.ShouldBe(AbpSession.ImpersonatorTenantId); s.ImpersonatorUserId.ShouldBe(AbpSession.ImpersonatorUserId); s.TenantId.ShouldBe(AbpSession.TenantId); s.UserId.ShouldBe(AbpSession.UserId); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_TPH_Tracked_Entities_Create_To_Database() { // Forward calls from substitute to implementation var entityHistoryStore = Resolve<EntityHistoryStore>(); _entityHistoryStore.When(x => x.SaveAsync(Arg.Any<EntityChangeSet>())) .Do(callback => AsyncHelper.RunSync(() => entityHistoryStore.SaveAsync(callback.Arg<EntityChangeSet>())) ); _entityHistoryStore.When(x => x.Save(Arg.Any<EntityChangeSet>())) .Do(callback => entityHistoryStore.Save(callback.Arg<EntityChangeSet>())); UsingDbContext((context) => { context.EntityChanges.Count(e => e.TenantId == 1).ShouldBe(0); context.EntityChangeSets.Count(e => e.TenantId == 1).ShouldBe(0); context.EntityPropertyChanges.Count(e => e.TenantId == 1).ShouldBe(0); }); Resolve<IEntityHistoryConfiguration>().Selectors.Add("Selected", typeof(Student)); var justNow = Clock.Now; Thread.Sleep(1); var student = new Student() { Name = "TestName", IdCard = "TestIdCard", Address = "TestAddress", Grade = 1 }; _studentRepository.Insert(student); UsingDbContext((context) => { context.EntityChanges.Count(e => e.TenantId == 1).ShouldBe(1); context.EntityChangeSets.Count(e => e.TenantId == 1).ShouldBe(1); context.EntityChangeSets.Single().CreationTime.ShouldBeGreaterThan(justNow); context.EntityPropertyChanges.Count(e => e.TenantId == 1).ShouldBe(4); //Name,IdCard,Address,Grade }); } [Fact] public void Should_Write_History_For_Tracked_Entities_Update() { /* Advertisement does not have Audited attribute. */ Resolve<IEntityHistoryConfiguration>().Selectors.Add("Selected", typeof(Advertisement)); WithUnitOfWork(() => { var advertisement1 = _advertisementRepository.Single(a => a.Banner == "test-advertisement-1"); advertisement1.Banner = "test-advertisement-1-updated"; _advertisementRepository.Update(advertisement1); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Advertisement).FullName); entityChange.ChangeType.ShouldBe(EntityChangeType.Updated); entityChange.EntityId.ShouldBe(entityChange.EntityEntry.As<DbEntityEntry>().Entity.As<IEntity>().Id.ToJsonString()); entityChange.PropertyChanges.Count.ShouldBe(1); var propertyChange = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Advertisement.Banner)); propertyChange.NewValue.ShouldBe("test-advertisement-1-updated".ToJsonString()); propertyChange.OriginalValue.ShouldBe("test-advertisement-1".ToJsonString()); propertyChange.PropertyTypeFullName.ShouldBe(typeof(Advertisement).GetProperty(nameof(Advertisement.Banner)).PropertyType.FullName); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_Audited_Entities_Create() { /* Blog has Audited attribute. */ var blog2Id = CreateBlogAndGetId(); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Blog).FullName); entityChange.ChangeTime.ShouldBe(entityChange.EntityEntry.As<DbEntityEntry>().Entity.As<IHasCreationTime>().CreationTime); entityChange.ChangeType.ShouldBe(EntityChangeType.Created); entityChange.EntityId.ShouldBe(blog2Id.ToJsonString()); entityChange.PropertyChanges.Count.ShouldBe(3); var propertyChange1 = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Blog.Url)); propertyChange1.OriginalValue.ShouldBeNull(); propertyChange1.NewValue.ShouldNotBeNull(); var propertyChange2 = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Blog.More)); propertyChange2.OriginalValue.ShouldBeNull(); propertyChange2.NewValue.ShouldNotBeNull(); var propertyChange3 = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Blog.CreationTime)); propertyChange3.OriginalValue.ShouldBeNull(); propertyChange3.NewValue.ShouldNotBeNull(); // Check "who did this change" s.ImpersonatorTenantId.ShouldBe(AbpSession.ImpersonatorTenantId); s.ImpersonatorUserId.ShouldBe(AbpSession.ImpersonatorUserId); s.TenantId.ShouldBe(AbpSession.TenantId); s.UserId.ShouldBe(AbpSession.UserId); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_Audited_Entities_Create_To_Database() { // Forward calls from substitute to implementation var entityHistoryStore = Resolve<EntityHistoryStore>(); _entityHistoryStore.When(x => x.SaveAsync(Arg.Any<EntityChangeSet>())) .Do(callback => AsyncHelper.RunSync(() => entityHistoryStore.SaveAsync(callback.Arg<EntityChangeSet>())) ); _entityHistoryStore.When(x => x.Save(Arg.Any<EntityChangeSet>())) .Do(callback => entityHistoryStore.Save(callback.Arg<EntityChangeSet>())); UsingDbContext((context) => { context.EntityChanges.Count(e => e.TenantId == 1).ShouldBe(0); context.EntityChangeSets.Count(e => e.TenantId == 1).ShouldBe(0); context.EntityPropertyChanges.Count(e => e.TenantId == 1).ShouldBe(0); }); var justNow = Clock.Now; Thread.Sleep(1); var blog2Id = CreateBlogAndGetId(); UsingDbContext((context) => { context.EntityChanges.Count(e => e.TenantId == 1).ShouldBe(1); context.EntityChangeSets.Count(e => e.TenantId == 1).ShouldBe(1); context.EntityChangeSets.Single().CreationTime.ShouldBeGreaterThan(justNow); context.EntityPropertyChanges.Count(e => e.TenantId == 1).ShouldBe(3); }); } [Fact] public void Should_Write_History_For_Audited_Entities_Update() { /* Blog has Audited attribute. */ var newValue = "http://testblog1-changed.myblogs.com"; var originalValue = UpdateBlogUrlAndGetOriginalValue(newValue); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Blog).FullName); entityChange.ChangeType.ShouldBe(EntityChangeType.Updated); entityChange.EntityId.ShouldBe(entityChange.EntityEntry.As<DbEntityEntry>().Entity.As<IEntity>().Id.ToJsonString()); entityChange.PropertyChanges.Count.ShouldBe(1); var propertyChange = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Blog.Url)); propertyChange.NewValue.ShouldBe(newValue.ToJsonString()); propertyChange.OriginalValue.ShouldBe(originalValue.ToJsonString()); propertyChange.PropertyTypeFullName.ShouldBe(typeof(Blog).GetProperty(nameof(Blog.Url)).PropertyType.FullName); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_Audited_Entities_Update_Only_Modified_Properties() { var originalValue = "http://testblog2.myblogs.com"; var newValue = "http://testblog2-changed.myblogs.com"; WithUnitOfWork(() => { var blog2 = _blogRepository.Single(b => b.Url == originalValue); // Update only the Url of the Blog blog2.ChangeUrl(newValue); _blogRepository.Update(blog2); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Blog).FullName); entityChange.ChangeType.ShouldBe(EntityChangeType.Updated); entityChange.EntityId.ShouldBe(entityChange.EntityEntry.As<DbEntityEntry>().Entity.As<IEntity>().Id.ToJsonString()); entityChange.PropertyChanges.Count.ShouldBe(1); var propertyChange = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Blog.Url)); propertyChange.NewValue.ShouldBe(newValue.ToJsonString()); propertyChange.OriginalValue.ShouldBe(originalValue.ToJsonString()); propertyChange.PropertyTypeFullName.ShouldBe(typeof(Blog).GetProperty(nameof(Blog.Url)).PropertyType.FullName); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_Audited_Entities_Update_Complex() { /* Blog has Audited attribute. */ int blog1Id = 0; var newValue = new BlogEx { BloggerName = "blogger-2" }; BlogEx originalValue = null; WithUnitOfWork(() => { var blog1 = _blogRepository.Single(b => b.More.BloggerName == "blogger-1"); blog1Id = blog1.Id; originalValue = new BlogEx { BloggerName = blog1.More.BloggerName }; blog1.More.BloggerName = newValue.BloggerName; _blogRepository.Update(blog1); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Blog).FullName); entityChange.ChangeType.ShouldBe(EntityChangeType.Updated); entityChange.EntityId.ShouldBe(blog1Id.ToJsonString()); entityChange.PropertyChanges.Count.ShouldBe(1); var propertyChange = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Blog.More)); propertyChange.NewValue.ShouldBe(newValue.ToJsonString()); propertyChange.OriginalValue.ShouldBe(originalValue.ToJsonString()); propertyChange.PropertyTypeFullName.ShouldBe(typeof(Blog).GetProperty(nameof(Blog.More)).PropertyType.FullName); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_Audited_Property_Foreign_Key() { /* Post.BlogId has Audited attribute. */ var blogId = CreateBlogAndGetId(); Guid post1Id = Guid.Empty; WithUnitOfWork(() => { var blog2 = _blogRepository.Single(b => b.Id == 2); var post1 = _postRepository.Single(p => p.Body == "test-post-1-body"); post1Id = post1.Id; // Change foreign key by assigning navigation property post1.Blog = blog2; _postRepository.Update(post1); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Post).FullName); entityChange.ChangeType.ShouldBe(EntityChangeType.Updated); entityChange.EntityId.ShouldBe(post1Id.ToJsonString()); entityChange.PropertyChanges.Count.ShouldBe(1); var propertyChange = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Post.BlogId)); propertyChange.NewValue.ShouldBe("2"); propertyChange.OriginalValue.ShouldBe("1"); propertyChange.PropertyTypeFullName.ShouldBe(typeof(Post).GetProperty(nameof(Post.BlogId)).PropertyType.FullName); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_Audited_Property_Foreign_Key_Collection() { WithUnitOfWork(() => { var blog1 = _blogRepository.Single(b => b.Name == "test-blog-1"); var post10 = new Post { Blog = blog1, Title = "test-post-10-title", Body = "test-post-10-body" }; // Change navigation property by adding into collection blog1.Posts.Add(post10); _blogRepository.Update(blog1); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(2); /* Post is not in Configuration.Selectors */ /* Post.Blog has Audited attribute */ var entityChangePost = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Post).FullName); entityChangePost.ChangeType.ShouldBe(EntityChangeType.Created); entityChangePost.PropertyChanges.Count.ShouldBe(1); var propertyChange1 = entityChangePost.PropertyChanges.Single(pc => pc.PropertyName == nameof(Post.BlogId)); propertyChange1.OriginalValue.ShouldBeNull(); propertyChange1.NewValue.ShouldNotBeNull(); /* Blog has Audited attribute. */ var entityChangeBlog = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Blog).FullName); entityChangeBlog.ChangeType.ShouldBe(EntityChangeType.Updated); entityChangeBlog.PropertyChanges.Count.ShouldBe(0); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_Audited_Property_Foreign_Key_Shadow() { /* Comment has Audited attribute. */ var post1KeyValue = new Dictionary<string, object>(); var post2KeyValue = new Dictionary<string, object>(); WithUnitOfWork(() => { var post2 = _postRepository.Single(p => p.Body == "test-post-2-body"); post2KeyValue.Add("Id", post2.Id); var comment1 = _commentRepository.Single(c => c.Content == "test-comment-1-content"); post1KeyValue.Add("Id", comment1.Post.Id); // Change foreign key by assigning navigation property comment1.Post = post2; _commentRepository.Update(comment1); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Comment).FullName); entityChange.PropertyChanges.Count.ShouldBe(1); var propertyChange = entityChange.PropertyChanges.Single(pc => pc.PropertyName == nameof(Comment.Post)); propertyChange.NewValue.ShouldBe(post2KeyValue.ToJsonString()); propertyChange.OriginalValue.ShouldBe(post1KeyValue.ToJsonString()); propertyChange.PropertyTypeFullName.ShouldBe(typeof(Comment).GetProperty(nameof(Comment.Post)).PropertyType.FullName); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_But_Not_For_Property_If_Disabled_History_Tracking() { /* Blog.Name has DisableAuditing attribute. */ WithUnitOfWork(() => { var blog1 = _blogRepository.Single(b => b.Name == "test-blog-1"); blog1.Name = null; _blogRepository.Update(blog1); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(Blog).FullName); entityChange.ChangeType.ShouldBe(EntityChangeType.Updated); entityChange.EntityId.ShouldBe(entityChange.EntityEntry.As<DbEntityEntry>().Entity.As<IEntity>().Id.ToJsonString()); entityChange.PropertyChanges.Count.ShouldBe(0); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_TPH_Tracked_Entities_With_One_To_Many_Relationship_Create() { var studentId = CreateStudentAndGetId(); Resolve<IEntityHistoryConfiguration>().Selectors.Add("Selected", typeof(Student), typeof(StudentLectureNote)); _entityHistoryStore.ClearReceivedCalls(); WithUnitOfWork(() => { var student = _studentRepository.Get(studentId); var lectureNote = new StudentLectureNote() { Student = student, CourseName = "Course1", Note = 100 }; student.LectureNotes.Add(lectureNote); _studentRepository.Update(student); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(StudentLectureNote).FullName); entityChange.ChangeTime.ShouldNotBeNull(); entityChange.ChangeType.ShouldBe(EntityChangeType.Created); entityChange.PropertyChanges.Count.ShouldBe(3); entityChange.PropertyChanges.Single(p => p.PropertyName == nameof(StudentLectureNote.StudentId)) .NewValue.ShouldBe(studentId.ToString()); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_TPH_Tracked_Entities_With_One_To_One_Relationship_Changes_Create() { var studentId = CreateStudentAndGetId(); Resolve<IEntityHistoryConfiguration>().Selectors.Add("Selected", typeof(Student), typeof(CitizenshipInformation)); _entityHistoryStore.ClearReceivedCalls(); WithUnitOfWork(() => { var student = _studentRepository.Get(studentId); var citizenshipInformation = new CitizenshipInformation() { Student = student, CitizenShipId = "123qwe" }; student.CitizenshipInformation = citizenshipInformation; _studentRepository.Update(student); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(CitizenshipInformation).FullName); entityChange.ChangeTime.ShouldNotBeNull(); entityChange.ChangeType.ShouldBe(EntityChangeType.Created); entityChange.PropertyChanges.Count.ShouldBe(1); entityChange.PropertyChanges.Single(p => p.PropertyName == nameof(CitizenshipInformation.CitizenShipId)) .NewValue.ShouldBe("\"123qwe\""); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } [Fact] public void Should_Write_History_For_TPH_Tracked_Entities_With_One_To_One_Relationship_Changes_Update() { var studentId = CreateStudentWithCitizenshipAndGetId(); Resolve<IEntityHistoryConfiguration>().Selectors.Add("Selected", typeof(Student), typeof(CitizenshipInformation)); _entityHistoryStore.ClearReceivedCalls(); WithUnitOfWork(() => { var student = _studentRepository.GetAll().Include(x => x.CitizenshipInformation).Single(x => x.Id == studentId); student.CitizenshipInformation.CitizenShipId = "qwe123"; _studentRepository.Update(student); }); Predicate<EntityChangeSet> predicate = s => { s.EntityChanges.Count.ShouldBe(1); var entityChange = s.EntityChanges.Single(ec => ec.EntityTypeFullName == typeof(CitizenshipInformation).FullName); entityChange.ChangeTime.ShouldNotBeNull(); entityChange.ChangeType.ShouldBe(EntityChangeType.Updated); entityChange.PropertyChanges.Count.ShouldBe(1); var idChange = entityChange.PropertyChanges.Single(p => p.PropertyName == nameof(CitizenshipInformation.CitizenShipId)); idChange.OriginalValue.ShouldBe("\"123qwe\""); idChange.NewValue.ShouldBe("\"qwe123\""); return true; }; _entityHistoryStore.Received().Save(Arg.Is<EntityChangeSet>(s => predicate(s))); } private int CreateStudentAndGetId() { var student = new Student() { Name = "TestName", IdCard = "TestIdCard", Address = "TestAddress", Grade = 1, }; return _studentRepository.InsertAndGetId(student); } private int CreateStudentWithCitizenshipAndGetId() { var student = new Student() { Name = "TestName", IdCard = "TestIdCard", Address = "TestAddress", Grade = 1, CitizenshipInformation = new CitizenshipInformation() { CitizenShipId = "123qwe" } }; return _studentRepository.InsertAndGetId(student); } #endregion #region CASES DON'T WRITE HISTORY [Fact] public void Should_Not_Write_History_If_Disabled() { Resolve<IEntityHistoryConfiguration>().IsEnabled = false; /* Blog has Audited attribute. */ var newValue = "http://testblog1-changed.myblogs.com"; var originalValue = UpdateBlogUrlAndGetOriginalValue(newValue); _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } [Fact] public void Should_Not_Write_History_If_Not_Audited_And_Not_Selected() { /* Advertisement does not have Audited attribute. */ Resolve<IEntityHistoryConfiguration>().Selectors.Clear(); WithUnitOfWork(() => { _advertisementRepository.Insert(new Advertisement { Banner = "not-selected-advertisement" }); }); _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } [Fact] public void Should_Not_Write_History_If_Ignored() { Resolve<IEntityHistoryConfiguration>().IgnoredTypes.Add(typeof(Blog)); /* Blog has Audited attribute. */ var newValue = "http://testblog1-changed.myblogs.com"; var originalValue = UpdateBlogUrlAndGetOriginalValue(newValue); _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } [Fact] public void Should_Not_Write_History_If_Selected_But_Ignored() { Resolve<IEntityHistoryConfiguration>().Selectors.Add("Selected", typeof(Blog)); Resolve<IEntityHistoryConfiguration>().IgnoredTypes.Add(typeof(Blog)); /* Blog has Audited attribute. */ var newValue = "http://testblog1-changed.myblogs.com"; var originalValue = UpdateBlogUrlAndGetOriginalValue(newValue); _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } [Fact] public void Should_Not_Write_History_If_Property_Has_No_Audited_Attribute() { /* Advertisement.Banner does not have Audited attribute. */ WithUnitOfWork(() => { var advertisement1 = _advertisementRepository.Single(a => a.Banner == "test-advertisement-1"); advertisement1.Banner = null; _advertisementRepository.Update(advertisement1); }); _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } [Fact] public void Should_Not_Write_History_If_Invalid_Entity_Has_Property_With_Audited_Attribute_Created() { //Act UsingDbContext((context) => { context.Categories.Add(new Category { DisplayName = "My Category" }); context.SaveChanges(); }); //Assert _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } [Fact] public void Should_Not_Write_History_If_Invalid_Entity_Has_Property_With_Audited_Attribute_Updated() { //Arrange UsingDbContext((context) => { context.Categories.Add(new Category { DisplayName = "My Category" }); context.SaveChanges(); }); _entityHistoryStore.ClearReceivedCalls(); //Act UsingDbContext((context) => { var category = context.Categories.Single(c => c.DisplayName == "My Category"); category.DisplayName = "Invalid Category"; context.SaveChanges(); }); //Assert _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } [Fact] public void Should_Not_Write_History_If_Invalid_Entity_Has_Property_With_Audited_Attribute_Deleted() { //Arrange UsingDbContext((context) => { context.Categories.Add(new Category { DisplayName = "My Category" }); context.SaveChanges(); }); _entityHistoryStore.ClearReceivedCalls(); //Act UsingDbContext((context) => { var category = context.Categories.Single(c => c.DisplayName == "My Category"); context.Categories.Remove(category); context.SaveChanges(); }); //Assert _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } [Fact] public void Should_Not_Write_History_For_Audited_Entity_By_Default() { //Arrange UsingDbContext((context) => { context.Countries.Add(new Country { CountryCode = "My Country" }); context.SaveChanges(); }); //Assert _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } [Fact] public void Should_Not_Write_History_For_Not_Audited_Entities_Shadow_Property() { // PermissionSetting has Discriminator column (shadow property) for RolePermissionSetting //Arrange UsingDbContext((context) => { var role = context.Roles.FirstOrDefault(); role.ShouldNotBeNull(); context.RolePermissions.Add(new RolePermissionSetting() { Name = "Test", RoleId = role.Id }); context.SaveChanges(); }); //Assert _entityHistoryStore.DidNotReceive().Save(Arg.Any<EntityChangeSet>()); } #endregion private int CreateBlogAndGetId() { int blog2Id = 0; WithUnitOfWork(() => { var blog2 = new Blog("test-blog-2", "http://testblog2.myblogs.com", "blogger-2"); blog2Id = _blogRepository.InsertAndGetId(blog2); }); return blog2Id; } private string UpdateBlogUrlAndGetOriginalValue(string newValue) { string originalValue = null; WithUnitOfWork(() => { var blog1 = _blogRepository.Single(b => b.Name == "test-blog-1"); originalValue = blog1.Url; blog1.ChangeUrl(newValue); _blogRepository.Update(blog1); }); return originalValue; } } #region Helpers internal static class IEnumerableExtensions { internal static EntityPropertyChange FirstOrDefault(this IEnumerable<EntityPropertyChange> enumerable) { var enumerator = enumerable.GetEnumerator(); enumerator.MoveNext(); return enumerator.Current; } } #endregion }
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.S3.Model { /// <summary> /// Container for the parameters to the GetObject operation. /// <para>Retrieves objects from Amazon S3.</para> /// </summary> public partial class GetObjectRequest : AmazonWebServiceRequest { private string bucketName; DateTime? modifiedSinceDate; DateTime? unmodifiedSinceDate; string etagToMatch; string etagToNotMatch; private string key; private ByteRange byteRange; private DateTime? responseExpires; private string versionId; private ResponseHeaderOverrides responseHeaders; private ServerSideEncryptionCustomerMethod serverSideCustomerEncryption; private string serverSideEncryptionCustomerProvidedKey; private string serverSideEncryptionCustomerProvidedKeyMD5; /// <summary> /// The name of the bucket containing the object. /// </summary> public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } // Check to see if Bucket property is set internal bool IsSetBucketName() { return this.bucketName != null; } /// <summary> /// ETag to be matched as a pre-condition for returning the object, /// otherwise a PreconditionFailed signal is returned. /// </summary> public string EtagToMatch { get { return this.etagToMatch; } set { this.etagToMatch = value; } } // Check to see if EtagToMatch property is set internal bool IsSetEtagToMatch() { return this.etagToMatch != null; } /// <summary> /// Returns the object only if it has been modified since the specified time, /// otherwise returns a PreconditionFailed. /// </summary> public DateTime ModifiedSinceDate { get { return this.modifiedSinceDate ?? default(DateTime); } set { this.modifiedSinceDate = value; } } // Check to see if ModifiedSinceDate property is set internal bool IsSetModifiedSinceDate() { return this.modifiedSinceDate.HasValue; } /// <summary> /// ETag that should not be matched as a pre-condition for returning the object, /// otherwise a PreconditionFailed signal is returned. /// </summary> public string EtagToNotMatch { get { return this.etagToNotMatch; } set { this.etagToNotMatch = value; } } // Check to see if EtagToNotMatch property is set internal bool IsSetEtagToNotMatch() { return this.etagToNotMatch != null; } /// <summary> /// Returns the object only if it has not been modified since the specified time, /// otherwise returns a PreconditionFailed. /// </summary> public DateTime UnmodifiedSinceDate { get { return this.unmodifiedSinceDate ?? default(DateTime); } set { this.unmodifiedSinceDate = value; } } // Check to see if UnmodifiedSinceDate property is set internal bool IsSetUnmodifiedSinceDate() { return this.unmodifiedSinceDate.HasValue; } public string Key { get { return this.key; } set { this.key = value; } } // Check to see if Key property is set internal bool IsSetKey() { return this.key != null; } /// <summary> /// Downloads the specified range bytes of an object. /// </summary> public ByteRange ByteRange { get { return this.byteRange; } set { this.byteRange = value; } } // Check to see if ByteRange property is set internal bool IsSetByteRange() { return this.byteRange != null; } /// <summary> /// A set of response headers that should be returned with the object. /// </summary> public ResponseHeaderOverrides ResponseHeaderOverrides { get { if (this.responseHeaders == null) { this.responseHeaders = new ResponseHeaderOverrides(); } return this.responseHeaders; } set { this.responseHeaders = value; } } /// <summary> /// Sets the Expires header of the response. /// /// </summary> public DateTime ResponseExpires { get { return this.responseExpires ?? default(DateTime); } set { this.responseExpires = value; } } // Check to see if ResponseExpires property is set internal bool IsSetResponseExpires() { return this.responseExpires.HasValue; } /// <summary> /// VersionId used to reference a specific version of the object. /// /// </summary> public string VersionId { get { return this.versionId; } set { this.versionId = value; } } // Check to see if VersionId property is set internal bool IsSetVersionId() { return this.versionId != null; } /// <summary> /// The Server-side encryption algorithm to be used with the customer provided key. /// /// </summary> public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod { get { return this.serverSideCustomerEncryption; } set { this.serverSideCustomerEncryption = value; } } // Check to see if ServerSideEncryptionCustomerMethod property is set internal bool IsSetServerSideEncryptionCustomerMethod() { return this.serverSideCustomerEncryption != null && this.serverSideCustomerEncryption != ServerSideEncryptionCustomerMethod.None; } /// <summary> /// The base64-encoded encryption key for Amazon S3 to use to decrypt the object /// <para> /// Using the encryption key you provide as part of your request Amazon S3 manages both the encryption, as it writes /// to disks, and decryption, when you access your objects. Therefore, you don't need to maintain any data encryption code. The only /// thing you do is manage the encryption keys you provide. /// </para> /// <para> /// When you retrieve an object, you must provide the same encryption key as part of your request. Amazon S3 first verifies /// the encryption key you provided matches, and then decrypts the object before returning the object data to you. /// </para> /// <para> /// Important: Amazon S3 does not store the encryption key you provide. /// </para> /// </summary> public string ServerSideEncryptionCustomerProvidedKey { get { return this.serverSideEncryptionCustomerProvidedKey; } set { this.serverSideEncryptionCustomerProvidedKey = value; } } /// <summary> /// Checks if ServerSideEncryptionCustomerProvidedKey property is set. /// </summary> /// <returns>true if ServerSideEncryptionCustomerProvidedKey property is set.</returns> internal bool IsSetServerSideEncryptionCustomerProvidedKey() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionCustomerProvidedKey); } /// <summary> /// The MD5 of the customer encryption key specified in the ServerSideEncryptionCustomerProvidedKey property. The MD5 is /// base 64 encoded. This field is optional, the SDK will calculate the MD5 if this is not set. /// </summary> public string ServerSideEncryptionCustomerProvidedKeyMD5 { get { return this.serverSideEncryptionCustomerProvidedKeyMD5; } set { this.serverSideEncryptionCustomerProvidedKeyMD5 = value; } } /// <summary> /// Checks if ServerSideEncryptionCustomerProvidedKeyMD5 property is set. /// </summary> /// <returns>true if ServerSideEncryptionCustomerProvidedKey property is set.</returns> internal bool IsSetServerSideEncryptionCustomerProvidedKeyMD5() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionCustomerProvidedKeyMD5); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using System.Xml; using System.Diagnostics; using Microsoft.VisualStudio.Shell; using System.Text.RegularExpressions; using EnvDTE; /* * Based on the code found here: * http://www.codeproject.com/KB/cs/VsMultipleFileGenerator.aspx */ namespace ConfigurationSectionDesigner { internal static class VsHelper { static VSDOCUMENTPRIORITY[] StandardDocumentPriority = new VSDOCUMENTPRIORITY[(int)VSDOCUMENTPRIORITY.DP_Standard]; /// <summary> /// Get the current Hierarchy /// </summary> /// <param name="provider"></param> /// <returns></returns> public static IVsHierarchy GetCurrentHierarchy(IServiceProvider provider) { DTE vs = (DTE)provider.GetService(typeof(DTE)); if (vs == null) throw new InvalidOperationException("DTE not found."); return ToHierarchy(vs.SelectedItems.Item(1).ProjectItem.ContainingProject); } /// <summary> /// Get the hierarchy corresponding to a Project /// </summary> /// <param name="project"></param> /// <returns></returns> public static IVsHierarchy _oldToHierarchy(EnvDTE.Project project) { if (project == null) throw new ArgumentNullException("project"); string projectGuid = null; // DTE does not expose the project GUID that exists at in the msbuild project file. // Cannot use MSBuild object model because it uses a static instance of the Engine, // and using the Project will cause it to be unloaded from the engine when the // GC collects the variable that we declare. using (XmlReader projectReader = XmlReader.Create(project.FileName)) { projectReader.MoveToContent(); if (projectReader.NameTable != null) { object nodeName = projectReader.NameTable.Add("ProjectGuid"); while (projectReader.Read()) { if (Object.Equals(projectReader.LocalName, nodeName)) { projectGuid = (String)projectReader.ReadElementContentAsString(); break; } } } } Debug.Assert(!String.IsNullOrEmpty(projectGuid)); // ABM 20140904: With a null projectGuid, we should NEVER try call GetHierarchy. // TODO: Determine if this error should be fatal, or soft. Handle accordingly. At least log it. if (string.IsNullOrEmpty(projectGuid)) { // TODO: Quickly added to indicate a problem in code flow. Better exception/error handling should be implemented. throw new Exception("Could not locate a ProjectGuid in this project's source file."); } IServiceProvider serviceProvider = new ServiceProvider(project.DTE as Microsoft.VisualStudio.OLE.Interop.IServiceProvider); return VsShellUtilities.GetHierarchy(serviceProvider, new Guid(projectGuid)); } /// <summary> /// Get the hierarchy corresponding to a Project. /// </summary> /// <remarks> /// The original ToHierarchy method has problems when project hasn't yet been written to file. /// This function addresses that. /// /// http://www.codeproject.com/Articles/16515/Creating-a-Custom-Tool-to-Generate-Multiple-Files?msg=3962376#xx3962376xx /// </remarks> /// <param name="project"></param> /// <returns></returns> private static IVsHierarchy ToHierarchy(EnvDTE.Project project) { if (project == null) throw new ArgumentNullException("project"); string uniqueName = project.UniqueName; IVsSolution solution = (IVsSolution)Package.GetGlobalService(typeof(SVsSolution)); IVsHierarchy hierarchy; solution.GetProjectOfUniqueName(uniqueName, out hierarchy); return hierarchy; } /// <summary> /// Converts an EnvDTE.Project to a Visual Studio project hierarchy. /// </summary> /// <param name="project"></param> /// <returns></returns> public static IVsProject3 ToVsProject(EnvDTE.Project project) { if (project == null) throw new ArgumentNullException("project"); IVsProject3 vsProject = ToHierarchy(project) as IVsProject3; if (vsProject == null) { throw new ArgumentException("Project is not a recognized VS project."); } return vsProject; } /// <summary> /// Converts a Visual Studio project hierarchy to an EnvDTE.Project. /// </summary> /// <param name="hierarchy"></param> /// <returns></returns> public static EnvDTE.Project ToDteProject(IVsHierarchy hierarchy) { if (hierarchy == null) throw new ArgumentNullException("hierarchy"); object prjObject = null; if (hierarchy.GetProperty(0xfffffffe, -2027, out prjObject) >= 0) { return (EnvDTE.Project)prjObject; } else { throw new ArgumentException("Hierarchy is not a project."); } } /// <summary> /// Converts a Visual Studio project hierarchy to an EnvDTE.Project. /// </summary> /// <param name="project"></param> /// <returns></returns> public static EnvDTE.Project ToDteProject(IVsProject project) { if (project == null) throw new ArgumentNullException("project"); return ToDteProject(project as IVsHierarchy); } #region NEW public static bool FindProjectContainingFile(string projectItemFilePath, out ProjectItem projectItem, out Project parentProject) { projectItem = null; parentProject = null; DTE dte = (DTE)Package.GetGlobalService(typeof(DTE)); //foreach (var project in dte.Solution.FindProjectItem()) projectItem = dte.Solution.FindProjectItem(projectItemFilePath); if (projectItem != null) { parentProject = projectItem.ContainingProject; if (parentProject != null) { return true; } } return false; } #endregion #region OLD /// <summary> /// Locates the corresponding EnvDTE.ProjectItem associated with <paramref name="file"/>. /// </summary> /// <param name="project">the project to search through.</param> /// <param name="file">the path of the file we are locating.</param> /// <returns></returns> public static EnvDTE.ProjectItem FindProjectItem(EnvDTE.Project project, string file) { return FindProjectItem(project.ProjectItems, file); } /// <summary> /// Locates the corresponding EnvDTE.ProjectItem associated with <paramref name="file"/>. /// </summary> /// <param name="items">the items to search through.</param> /// <param name="file">the path of the file we are locating.</param> /// <returns></returns> public static EnvDTE.ProjectItem FindProjectItem(EnvDTE.ProjectItems items, string file) { string atom = file.Substring(0, file.IndexOf("\\") + 1); foreach (EnvDTE.ProjectItem item in items) { //if ( item //if (item.ProjectItems.Count > 0) if (atom.StartsWith(item.Name)) { // then step in EnvDTE.ProjectItem ritem = FindProjectItem(item.ProjectItems, file.Substring(file.IndexOf("\\") + 1)); if (ritem != null) return ritem; } if (Regex.IsMatch(item.Name, file)) { return item; } if (item.ProjectItems.Count > 0) { EnvDTE.ProjectItem ritem = FindProjectItem(item.ProjectItems, file.Substring(file.IndexOf("\\") + 1)); if (ritem != null) return ritem; } } return null; } /// <summary> /// Locates the corresponding EnvDTE.ProjectItem's whos name matches the regex <paramref name="match"/>. /// </summary> /// <param name="items">the items to search through.</param> /// <param name="match">the regex match string.</param> /// <returns></returns> public static List<EnvDTE.ProjectItem> FindProjectItems(EnvDTE.ProjectItems items, string match) { List<EnvDTE.ProjectItem> values = new List<EnvDTE.ProjectItem>(); foreach (EnvDTE.ProjectItem item in items) { if (Regex.IsMatch(item.Name, match)) { values.Add(item); } if (item.ProjectItems.Count > 0) { values.AddRange(FindProjectItems(item.ProjectItems, match)); } } return values; } // TODO: Figure out what we are trying to achieve here. Do we need these complicated methods? Can we use standard VSHELPER functions to get access to a simpler object and search that way? /// <summary> /// Looks through the <paramref name="project"/> and all subitems / subprojects to find the project hosting the active configuration section designer window. /// </summary> /// <remarks> /// Checks if <paramref name="csdDocumentFilePath"/> is inside <paramref name="project"/>. If true, the id of /// <paramref name="csdDocumentFilePath"/> is located and used to return the CSD file as a ProjectItem object /// <paramref name="configurationSectionModelFile"/>. /// </remarks> /// <param name="project">the parent project.</param> /// <param name="configurationSectionModelFile">(out) the project item represented by csdDocumentFilePath, if found (ex: MyProject\ConfigurationSection.csd).</param> /// <param name="csdDocumentFilePath">the file path of the CSD project item.</param> /// <returns><c>true</c> if found; otherwise <c>false</c>.</returns> public static bool TryFindProjectItemWithFilePath(Project project, string csdDocumentFilePath, out ProjectItem configurationSectionModelFile) { return TryFindProjectItemWithFilePath(project, StandardDocumentPriority, csdDocumentFilePath, out configurationSectionModelFile); } /// <summary> /// Looks through the <paramref name="project"/> and all subitems / subprojects to find the project hosting the active configuration section designer window. /// </summary> /// <remarks> /// Checks if <paramref name="csdDocumentFilePath"/> is inside <paramref name="project"/>. If true, the id of /// <paramref name="csdDocumentFilePath"/> is located and used to return the CSD file as a ProjectItem object /// <paramref name="configurationSectionModelFile"/>. /// </remarks> /// <param name="project">the parent project.</param> /// <param name="docPriority">Specifies the priority level of a document within a project.</param> /// <param name="configurationSectionModelFile">(out) the project item represented by csdDocumentFilePath, if found (ex: MyProject\ConfigurationSection.csd).</param> /// <param name="csdDocumentFilePath">the file path of the CSD project item.</param> /// <returns><c>true</c> if found; otherwise <c>false</c>.</returns> public static bool TryFindProjectItemWithFilePath(Project project, VSDOCUMENTPRIORITY[] docPriority, string csdDocumentFilePath, out ProjectItem configurationSectionModelFile) { Diagnostics.DebugWrite("VsHelper.TryFindProjectItemWithFilePath (VH.TFP)."); bool projectFound = false; configurationSectionModelFile = null; // Nothing useful for this project. Process the next one. if (string.IsNullOrEmpty(project.FileName) || !File.Exists(project.FileName)) { Diagnostics.DebugWrite("VH.TFP >> Nothing useful found in this current dte.Solution.Projects item. Continuing loop..."); return false; } // obtain a reference to the current project as an IVsProject type IVsProject vsProject = VsHelper.ToVsProject(project); // ABM - Issue 10435: 2nd WindowsService project results in FAILURE here. Diagnostics.DebugWrite("VH.TFP >> IVsProject vsProject = VsHelper.ToVsProject( project='{0}' )", project.Name); int iFound = 0; uint itemId = 0; // this locates, and returns a handle to our source file, as a ProjectItem int result = vsProject.IsDocumentInProject(csdDocumentFilePath, out iFound, docPriority, out itemId); // ABM - Issue 10435: WindowsService project results in iFound=0!!! // itemid: Pointer to the item identifier of the document within the project. // NOTE: itemId is either a specific id pointing to the file, or is one of VSITEMID enumeration. // VSITEMID represents Special items inside a VsHierarchy: /* public enum VSITEMID { Selection = 4294967293, // all the currently selected items. // represents the currently selected item or items, which can include the root of the hierarchy. Root = 4294967294, // the hierarchy itself. // represents the root of a project hierarchy and is used to identify the entire hierarchy, as opposed to a single item. Nil = 4294967295, // no node.// represents the absence of a project item. This value is used when there is no current selection. } * http://visual-studio.todaysummary.com/q_visual-studio_76086.html * * http://msdn.microsoft.com/en-us/subscriptions/downloads/microsoft.visualstudio.shell.interop.ivshierarchy(v=vs.100).aspx */ if (result != VSConstants.S_OK) throw new Exception("Unexpected error calling IVsProject.IsDocumentInProject."); Diagnostics.DebugWrite("VH.TFP >> vsProject.IsDocumentInProject(inputFilePath, out iFound={0}, pdwPriority, out itemId={1}).", iFound, itemId); // TODO: [abm] Below here, project build failed! Error was "type is not of VsProject". This only occured on a brand new // project with brand new csd. After failed rebuild attempt of project, it all worked. // Find out why and fix (or create warning message) to guide future users! Not yet reproducible... // if this source file is found in this project if (iFound != 0 && itemId != 0) { Diagnostics.DebugWrite("VH.TFP >> (iFound != 0 && itemId != 0) == TRUE!!!"); Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleSp = null; vsProject.GetItemContext(itemId, out oleSp); if (oleSp != null) { Diagnostics.DebugWrite("VH.TFP >> vsProject.GetItemContext( itemId, out oleSp ) >> oleSp != null! Getting ServiceProvider sp..."); ServiceProvider sp = new ServiceProvider(oleSp); // convert our handle to a ProjectItem configurationSectionModelFile = sp.GetService(typeof(ProjectItem)) as ProjectItem; if (configurationSectionModelFile != null) { Diagnostics.DebugWrite("VH.TFP >> configurationSectionModelFile = sp.GetService( typeof( ProjectItem ) ) as ProjectItem is NOT null! Setting this._project to the project we were working on..."); // We now have what we need. Stop looking. projectFound = true; } } } return projectFound; } /// <summary> /// Recursively traverses the Solution hierarchy looking for the CSD document designated by <paramref name="filePath"/>, and /// the project it is found in. /// </summary> /// <remarks> /// The recursion in this method has gotten ugly and complex, but it appears to work. It may be nice to find a more elegant solution /// to the problem of locating these items in the future. [a.moore] /// </remarks> /// <param name="csdDocumentFilePath">The path of the CSD file to locate.</param> /// <param name="parentProject">(out) the parent project of the file, if found.</param> /// <param name="fileProjectItem">(out) the project item representation of the CSD file, if found.</param> /// <returns><c>true</c> if found, otherwise <c>false</c></returns> public static bool TryFindProjectItemAndParentProject(string csdDocumentFilePath, out Project parentProject, out ProjectItem fileProjectItem) { Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject (Sol Level) >> csdDocumentFilePath = '{0}'.", csdDocumentFilePath); parentProject = null; fileProjectItem = null; DTE dte = (DTE)Package.GetGlobalService(typeof(DTE)); foreach (Project project in dte.Solution.Projects) { Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> Current project = '{0}'.", project.Name ?? "<null>"); if (project.ProjectItems != null && project.ProjectItems.Count > 0) { Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> project.ProjectItems != null && Number of project items ({0}) > 0", project.ProjectItems.Count); // First, look for the project at the solution level (No solution folders, subprojects, etc). if (TryFindProjectItemWithFilePath(project, csdDocumentFilePath, out fileProjectItem)) { // The project was found at the solution level. parentProject = project; Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> PROJECT FOUND! Name='{0}'", project.Name); return true; } else { // Project NOT found at the solution level. Start drilling down into sub project items... Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> TryFindProjectItemWithFilePath(project, filePath, out fileProjectItem) == FALSE"); if (_TryFindProjectItemAndParentProject(csdDocumentFilePath, project.ProjectItems, out parentProject, out fileProjectItem)) { // The project was found after drilling down. Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> PROJECT FOUND! Name='{0}'", project.Name); return true; } } } } return false; } /// <summary> /// Recursively traverses the Solution hierarchy, starting at <paramref name="currentProjectItems"/>, looking for /// the project item designated by <paramref name="filePath"/>, and it's parent project. /// </summary> /// <remarks> /// The recursion in this method has gotten ugly and complex, but it appears to work. It may be nice to find a more elegant solution /// to the problem of locating these items in the future. [a.moore] /// </remarks> /// <param name="filePath">The path of the CSD file to locate.</param> /// <param name="currentProjectItems">Project item hiearchy we are traversing to find possible SubProjects (IE. in solution folder type)</param> /// <param name="parentProject">(out) the parent project of the file, if found.</param> /// <param name="fileProjectItem">(out) the project item representation of the CSD file, if found.</param> /// <returns><c>true</c> if found, otherwise <c>false</c></returns> private static bool _TryFindProjectItemAndParentProject(string filePath, ProjectItems currentProjectItems, out Project parentProject, out ProjectItem fileProjectItem) { // TODO: Would it be safe to only check subitems if current item is a solution folder? We are checking alot of items that would never have sub projects. Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject (ProjectItems Level) >> currentProjectItems.Count = '{0}'.", currentProjectItems.Count); parentProject = null; fileProjectItem = null; // Already checked by calling method, but leaving null check for future use... if (currentProjectItems == null) { throw new ArgumentException("currentProjectItems cannot be null."); } foreach (ProjectItem projectItem in currentProjectItems) { Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> Current projectItem = '{0}', projectItem.ProjectItems.Count={1},", projectItem.Name, (projectItem.ProjectItems != null ? projectItem.ProjectItems.Count.ToString() : "0")); if (projectItem.SubProject != null) // Check SubProject. { Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> projectItem.SubProject EXISTS."); // If item was matched to file or recursive call returned true, exit. if ((!string.IsNullOrEmpty(projectItem.SubProject.FullName) && TryFindProjectItemWithFilePath(projectItem.SubProject, filePath, out fileProjectItem))) { Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> PROJECT FOUND in SubProject!"); parentProject = projectItem.SubProject; return true; } // Look through the SubProject's project items. if (projectItem.SubProject.ProjectItems != null && _TryFindProjectItemAndParentProject(filePath, projectItem.SubProject.ProjectItems, out parentProject, out fileProjectItem)) { Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> PROJECT FOUND in SubProject.ProjectItems!"); return true; } } else if ( projectItem.ProjectItems != null && projectItem.ProjectItems.Count > 0 && _TryFindProjectItemAndParentProject(filePath, projectItem.ProjectItems, out parentProject, out fileProjectItem) ) // Check project items. { Diagnostics.DebugWrite("VsHelper.TryFindProjectItemAndParentProject >> PROJECT FOUND in projectItem!"); return true; } } return false; } #endregion /// <summary> /// Gets a list of all project references. /// </summary> /// <remarks> /// REF=http://www.codeproject.com/KB/macros/EnvDTE.aspx /// </remarks> /// <returns></returns> public static List<KeyValuePair<string, string>> GetReferences(Project project) { if (project.Object is VSLangProj.VSProject) { VSLangProj.VSProject vsproject = (VSLangProj.VSProject)project.Object; List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(); foreach (VSLangProj.Reference reference in vsproject.References) { if (reference.StrongName) //System.Configuration, Version=2.0.0.0, //Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A list.Add(new KeyValuePair<string, string>(reference.Identity, reference.Identity + ", Version=" + reference.Version + ", Culture=" + (string.IsNullOrEmpty(reference.Culture) ? "neutral" : reference.Culture) + ", PublicKeyToken=" + reference.PublicKeyToken)); else list.Add(new KeyValuePair<string, string>( reference.Identity, reference.Path)); } return list; } else if (project.Object is VsWebSite.VSWebSite) { VsWebSite.VSWebSite vswebsite = (VsWebSite.VSWebSite)project.Object; //List<string> list = new List<string>(); List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(); foreach (VsWebSite.AssemblyReference reference in vswebsite.References) { string value = ""; if (reference.FullPath != "") { FileInfo f = new FileInfo(reference.FullPath + ".refresh"); if (f.Exists) { using (FileStream stream = f.OpenRead()) { using (StreamReader r = new StreamReader(stream)) { value = r.ReadToEnd().Trim(); } } } } if (value == "") { list.Add(new KeyValuePair<string, string>(reference.Name, reference.StrongName)); } else { list.Add(new KeyValuePair<string, string>(reference.Name, value)); } } return list; } else { throw new Exception("Currently, system is only set up to " + "do references for normal projects."); } } /// <summary> /// Adds a reference to the selected project. /// </summary> /// <remarks> /// REF=http://www.codeproject.com/KB/macros/EnvDTE.aspx /// </remarks> /// <param name="project"></param> /// <param name="referenceStrIdentity"></param> /// <param name="browseUrl"></param> public static void AddProjectReference(Project project, string referenceStrIdentity, string browseUrl) { //browseUrl is either the File Path or the Strong Name //(System.Configuration, Version=2.0.0.0, Culture=neutral, // PublicKeyToken=B03F5F7F11D50A3A) string path = ""; if (!browseUrl.StartsWith(referenceStrIdentity)) { //it is a path path = browseUrl; } if (project.Object is VSLangProj.VSProject) { VSLangProj.VSProject vsproject = (VSLangProj.VSProject)project.Object; VSLangProj.Reference reference = null; try { reference = vsproject.References.Find(referenceStrIdentity); } catch (Exception) { //it failed to find one, so it must not exist. //But it decided to error for the fun of it. :) } if (reference == null) { if (path == "") vsproject.References.Add(browseUrl); else vsproject.References.Add(path); } else { throw new Exception("Reference already exists."); } } else if (project.Object is VsWebSite.VSWebSite) { VsWebSite.VSWebSite vswebsite = (VsWebSite.VSWebSite)project.Object; VsWebSite.AssemblyReference reference = null; try { foreach (VsWebSite.AssemblyReference r in vswebsite.References) { if (r.Name == referenceStrIdentity) { reference = r; break; } } } catch (Exception) { //it failed to find one, so it must not exist. //But it decided to error for the fun of it. :) } if (reference == null) { if (path == "") vswebsite.References.AddFromGAC(browseUrl); else vswebsite.References.AddFromFile(path); } else { throw new Exception("Reference already exists."); } } else { throw new Exception("Currently, system is only set up " + "to do references for normal projects."); } } /// <summary> /// Gets a value indicating whether or not a given item is under source control. /// </summary> /// <param name="dte">The dte object.</param> /// <param name="item">The item to ispect.</param> /// <returns><c>true</c> if under source control, <c>false</c> otherwise</returns> public static bool IsItemUnderSourceControl(DTE dte, ProjectItem item) { if (dte == null) throw new ArgumentNullException("dte"); for (short i = 0; i < item.FileCount; i++) { if (dte.SourceControl.IsItemUnderSCC(item.FileNames[i])) return true; } if (item.ProjectItems != null) { return item.ProjectItems.Cast<ProjectItem>().Any(projectItem => IsItemUnderSourceControl(dte, projectItem)); } else { return false; } } /// <summary> /// Performa a checkout for a given item. /// </summary> /// <param name="dte">The dte object.</param> /// <param name="item">The item to checkout.</param> public static void CheckoutItem(DTE dte, ProjectItem item) { CheckoutItem(dte, item, true); } /// <summary> /// Performa a checkout for a given item. /// </summary> /// <param name="dte">The dte object.</param> /// <param name="item">The item to checkout.</param> /// <param name="recursive">If true, any subitems for this item will also be checked out.</param> public static void CheckoutItem(DTE dte, ProjectItem item, bool recursive) { if (dte == null) throw new ArgumentNullException("dte"); for (short i = 0; i < item.FileCount; i++) { string itemPath = item.FileNames[i]; if (!dte.SourceControl.IsItemCheckedOut(itemPath)) { dte.SourceControl.CheckOutItem(itemPath); } } if (recursive && item.ProjectItems != null) { foreach (ProjectItem childItem in item.ProjectItems.Cast<ProjectItem>()) { CheckoutItem(dte, childItem); } } } } // See http://blogs.msdn.com/b/mshneer/archive/2009/12/07/interop-type-xxx-cannot-be-embedded-use-the-applicable-interface-instead.aspx // for more info on why we have this. public abstract class EnvDTEConstants { public const string vsDocumentKindText = "{8E7B96A8-E33D-11D0-A6D5-00C04FB67F6A}"; public const string vsWindowKindOutput = "{34E76E81-EE4A-11D0-AE2E-00A0C90FFFC3}"; public const string vsSolutionFolderType = "2150E333-8FDC-42a3-9474-1A3956D46DE8"; } // TODO: Move to common area. public class Diagnostics { public const bool ForceReleaseModeDebugLogging = true; /* public static void DebugWriteLine(string format, params object[] args) { DebugWrite(format + "\r\n", args); } */ public static void DebugWrite(string format, params object[] args) { if (ForceReleaseModeDebugLogging) { System.Diagnostics.Debugger.Log(0, "", string.Format(CultureInfo.InvariantCulture, format, args)); } else { Debug.Write(string.Format(CultureInfo.InvariantCulture, format, args)); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { /// <summary> /// An immutable unordered dictionary implementation. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableDictionaryDebuggerProxy<,>))] public sealed partial class ImmutableDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, IImmutableDictionaryInternal<TKey, TValue>, IHashKeyCollection<TKey>, IDictionary<TKey, TValue>, IDictionary { /// <summary> /// An empty immutable dictionary with default equality comparers. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ImmutableDictionary<TKey, TValue> Empty = new ImmutableDictionary<TKey, TValue>(); /// <summary> /// The singleton delegate that freezes the contents of hash buckets when the root of the data structure is frozen. /// </summary> private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = (kv) => kv.Value.Freeze(); /// <summary> /// The number of elements in the collection. /// </summary> private readonly int _count; /// <summary> /// The root node of the tree that stores this map. /// </summary> private readonly SortedInt32KeyNode<HashBucket> _root; /// <summary> /// The comparer used when comparing hash buckets. /// </summary> private readonly Comparers _comparers; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}"/> class. /// </summary> /// <param name="root">The root.</param> /// <param name="comparers">The comparers.</param> /// <param name="count">The number of elements in the map.</param> private ImmutableDictionary(SortedInt32KeyNode<HashBucket> root, Comparers comparers, int count) : this(Requires.NotNullPassthrough(comparers, "comparers")) { Requires.NotNull(root, "root"); root.Freeze(s_FreezeBucketAction); _root = root; _count = count; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}"/> class. /// </summary> /// <param name="comparers">The comparers.</param> private ImmutableDictionary(Comparers comparers = null) { _comparers = comparers ?? Comparers.Get(EqualityComparer<TKey>.Default, EqualityComparer<TValue>.Default); _root = SortedInt32KeyNode<HashBucket>.EmptyNode; } /// <summary> /// How to respond when a key collision is discovered. /// </summary> internal enum KeyCollisionBehavior { /// <summary> /// Sets the value for the given key, even if that overwrites an existing value. /// </summary> SetValue, /// <summary> /// Skips the mutating operation if a key conflict is detected. /// </summary> Skip, /// <summary> /// Throw an exception if the key already exists with a different key. /// </summary> ThrowIfValueDifferent, /// <summary> /// Throw an exception if the key already exists regardless of its value. /// </summary> ThrowAlways, } /// <summary> /// The result of a mutation operation. /// </summary> internal enum OperationResult { /// <summary> /// The change was applied and did not require a change to the number of elements in the collection. /// </summary> AppliedWithoutSizeChange, /// <summary> /// The change required element(s) to be added or removed from the collection. /// </summary> SizeChanged, /// <summary> /// No change was required (the operation ended in a no-op). /// </summary> NoChangeRequired, } #region Public Properties /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public ImmutableDictionary<TKey, TValue> Clear() { return this.IsEmpty ? this : EmptyWithComparers(_comparers); } /// <summary> /// Gets the number of elements in this collection. /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return this.Count == 0; } } /// <summary> /// Gets the key comparer. /// </summary> public IEqualityComparer<TKey> KeyComparer { get { return _comparers.KeyComparer; } } /// <summary> /// Gets the value comparer used to determine whether values are equal. /// </summary> public IEqualityComparer<TValue> ValueComparer { get { return _comparers.ValueComparer; } } /// <summary> /// Gets the keys in the map. /// </summary> public IEnumerable<TKey> Keys { get { foreach (var bucket in _root) { foreach (var item in bucket.Value) { yield return item.Key; } } } } /// <summary> /// Gets the values in the map. /// </summary> public IEnumerable<TValue> Values { get { foreach (var bucket in _root) { foreach (var item in bucket.Value) { yield return item.Value; } } } } #endregion #region IImmutableDictionary<TKey,TValue> Properties /// <summary> /// Gets the empty instance. /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear() { return this.Clear(); } #endregion #region IDictionary<TKey, TValue> Properties /// <summary> /// Gets the keys. /// </summary> ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return new KeysCollectionAccessor<TKey, TValue>(this); } } /// <summary> /// Gets the values. /// </summary> ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return new ValuesCollectionAccessor<TKey, TValue>(this); } } #endregion /// <summary> /// Gets a data structure that captures the current state of this map, as an input into a query or mutating function. /// </summary> private MutationInput Origin { get { return new MutationInput(this); } } /// <summary> /// Gets the <typeparamref name="TValue"/> with the specified key. /// </summary> public TValue this[TKey key] { get { Requires.NotNullAllowStructs(key, "key"); TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(); } } /// <summary> /// Gets or sets the <typeparamref name="TValue"/> with the specified key. /// </summary> TValue IDictionary<TKey, TValue>.this[TKey key] { get { return this[key]; } set { throw new NotSupportedException(); } } #region ICollection<KeyValuePair<TKey, TValue>> Properties bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } #endregion #region Public methods /// <summary> /// Creates a collection with the same contents as this collection that /// can be efficiently mutated across multiple operations using standard /// mutable interfaces. /// </summary> /// <remarks> /// This is an O(1) operation and results in only a single (small) memory allocation. /// The mutable collection that is returned is *not* thread-safe. /// </remarks> [Pure] public Builder ToBuilder() { // We must not cache the instance created here and return it to various callers. // Those who request a mutable collection must get references to the collection // that version independently of each other. return new Builder(this); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> Add(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); var result = Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) { Requires.NotNull(pairs, "pairs"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); return this.AddRange(pairs, false); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> SetItem(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); Contract.Ensures(!Contract.Result<ImmutableDictionary<TKey, TValue>>().IsEmpty); var result = Add(key, value, KeyCollisionBehavior.SetValue, this.Origin); return result.Finalize(this); } /// <summary> /// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary. /// </summary> /// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param> /// <returns>An immutable dictionary.</returns> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public ImmutableDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) { Requires.NotNull(items, "items"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); var result = AddRange(items, this.Origin, KeyCollisionBehavior.SetValue); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> Remove(TKey key) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); var result = Remove(key, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, "keys"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); int count = _count; var root = _root; foreach (var key in keys) { int hashCode = this.KeyComparer.GetHashCode(key); HashBucket bucket; if (root.TryGetValue(hashCode, out bucket)) { OperationResult result; var newBucket = bucket.Remove(key, _comparers.KeyOnlyComparer, out result); root = UpdateRoot(root, hashCode, newBucket, _comparers.HashBucketEqualityComparer); if (result == OperationResult.SizeChanged) { count--; } } } return this.Wrap(root, count); } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(TKey key) { Requires.NotNullAllowStructs(key, "key"); return ContainsKey(key, this.Origin); } /// <summary> /// Determines whether [contains] [the specified key value pair]. /// </summary> /// <param name="pair">The key value pair.</param> /// <returns> /// <c>true</c> if [contains] [the specified key value pair]; otherwise, <c>false</c>. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> pair) { return Contains(pair, this.Origin); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetValue(TKey key, out TValue value) { Requires.NotNullAllowStructs(key, "key"); return TryGetValue(key, this.Origin, out value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { Requires.NotNullAllowStructs(equalKey, "equalKey"); return TryGetKey(equalKey, this.Origin, out actualKey); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { if (keyComparer == null) { keyComparer = EqualityComparer<TKey>.Default; } if (valueComparer == null) { valueComparer = EqualityComparer<TValue>.Default; } if (this.KeyComparer == keyComparer) { if (this.ValueComparer == valueComparer) { return this; } else { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. var comparers = _comparers.WithValueComparer(valueComparer); return new ImmutableDictionary<TKey, TValue>(_root, comparers, _count); } } else { var comparers = Comparers.Get(keyComparer, valueComparer); var set = new ImmutableDictionary<TKey, TValue>(comparers); set = set.AddRange(this, avoidToHashMap: true); return set; } } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> [Pure] public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer) { return this.WithComparers(keyComparer, _comparers.ValueComparer); } /// <summary> /// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) { foreach (KeyValuePair<TKey, TValue> item in this) { if (this.ValueComparer.Equals(value, item.Value)) { return true; } } return false; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(_root); } #endregion #region IImmutableDictionary<TKey,TValue> Methods /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value) { return this.Add(key, value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value) { return this.SetItem(key, value); } /// <summary> /// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary. /// </summary> /// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param> /// <returns>An immutable dictionary.</returns> IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) { return this.SetItems(items); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) { return this.AddRange(pairs); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys) { return this.RemoveRange(keys); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface /// </summary> [ExcludeFromCodeCoverage] IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key) { return this.Remove(key); } #endregion #region IDictionary<TKey, TValue> Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param> /// <param name="value">The object to use as the value of the element to add.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>. /// </exception> /// <exception cref="NotSupportedException"> /// The <see cref="IDictionary{TKey, TValue}"/> is read-only. /// </exception> void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { throw new NotSupportedException(); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null. /// </exception> /// <exception cref="NotSupportedException"> /// The <see cref="IDictionary{TKey, TValue}"/> is read-only. /// </exception> bool IDictionary<TKey, TValue>.Remove(TKey key) { throw new NotSupportedException(); } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Methods void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { throw new NotSupportedException(); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (var item in this) { array[arrayIndex++] = item; } } #endregion #region IDictionary Properties /// <summary> /// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size. /// </summary> /// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns> bool IDictionary.IsFixedSize { get { return true; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IDictionary.IsReadOnly { get { return true; } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Keys { get { return new KeysCollectionAccessor<TKey, TValue>(this); } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Values { get { return new ValuesCollectionAccessor<TKey, TValue>(this); } } #endregion /// <summary> /// Gets the root node (for testing purposes). /// </summary> internal SortedInt32KeyNode<HashBucket> Root { get { return _root; } } #region IDictionary Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param> /// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param> void IDictionary.Add(object key, object value) { throw new NotSupportedException(); } /// <summary> /// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param> /// <returns> /// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false. /// </returns> bool IDictionary.Contains(object key) { return this.ContainsKey((TKey)key); } /// <summary> /// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </summary> /// <returns> /// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </returns> IDictionaryEnumerator IDictionary.GetEnumerator() { return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator()); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The key of the element to remove.</param> void IDictionary.Remove(object key) { throw new NotSupportedException(); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> object IDictionary.this[object key] { get { return this[(TKey)key]; } set { throw new NotSupportedException(); } } /// <summary> /// Clears this instance. /// </summary> /// <exception cref="System.NotSupportedException"></exception> void IDictionary.Clear() { throw new NotSupportedException(); } #endregion #region ICollection Methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (var item in this) { array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++); } } #endregion #region ICollection Properties /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { // This is immutable, so it is always thread-safe. return true; } } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Gets an empty collection with the specified comparers. /// </summary> /// <param name="comparers">The comparers.</param> /// <returns>The empty dictionary.</returns> [Pure] private static ImmutableDictionary<TKey, TValue> EmptyWithComparers(Comparers comparers) { Requires.NotNull(comparers, "comparers"); return Empty._comparers == comparers ? Empty : new ImmutableDictionary<TKey, TValue>(comparers); } /// <summary> /// Attempts to discover an <see cref="ImmutableDictionary{TKey, TValue}"/> instance beneath some enumerable sequence /// if one exists. /// </summary> /// <param name="sequence">The sequence that may have come from an immutable map.</param> /// <param name="other">Receives the concrete <see cref="ImmutableDictionary{TKey, TValue}"/> typed value if one can be found.</param> /// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns> private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, out ImmutableDictionary<TKey, TValue> other) { other = sequence as ImmutableDictionary<TKey, TValue>; if (other != null) { return true; } var builder = sequence as Builder; if (builder != null) { other = builder.ToImmutable(); return true; } return false; } #region Static query and manipulator methods /// <summary> /// Performs the operation on a given data structure. /// </summary> private static bool ContainsKey(TKey key, MutationInput origin) { int hashCode = origin.KeyComparer.GetHashCode(key); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { TValue value; return bucket.TryGetValue(key, origin.KeyOnlyComparer, out value); } return false; } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static bool Contains(KeyValuePair<TKey, TValue> keyValuePair, MutationInput origin) { int hashCode = origin.KeyComparer.GetHashCode(keyValuePair.Key); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { TValue value; return bucket.TryGetValue(keyValuePair.Key, origin.KeyOnlyComparer, out value) && origin.ValueComparer.Equals(value, keyValuePair.Value); } return false; } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static bool TryGetValue(TKey key, MutationInput origin, out TValue value) { int hashCode = origin.KeyComparer.GetHashCode(key); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { return bucket.TryGetValue(key, origin.KeyOnlyComparer, out value); } value = default(TValue); return false; } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static bool TryGetKey(TKey equalKey, MutationInput origin, out TKey actualKey) { int hashCode = origin.KeyComparer.GetHashCode(equalKey); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { return bucket.TryGetKey(equalKey, origin.KeyOnlyComparer, out actualKey); } actualKey = equalKey; return false; } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static MutationResult Add(TKey key, TValue value, KeyCollisionBehavior behavior, MutationInput origin) { Requires.NotNullAllowStructs(key, "key"); OperationResult result; int hashCode = origin.KeyComparer.GetHashCode(key); HashBucket bucket = origin.Root.GetValueOrDefault(hashCode); var newBucket = bucket.Add(key, value, origin.KeyOnlyComparer, origin.ValueComparer, behavior, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin); } var newRoot = UpdateRoot(origin.Root, hashCode, newBucket, origin.HashBucketComparer); return new MutationResult(newRoot, result == OperationResult.SizeChanged ? +1 : 0); } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static MutationResult AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items, MutationInput origin, KeyCollisionBehavior collisionBehavior = KeyCollisionBehavior.ThrowIfValueDifferent) { Requires.NotNull(items, "items"); int countAdjustment = 0; var newRoot = origin.Root; foreach (var pair in items) { int hashCode = origin.KeyComparer.GetHashCode(pair.Key); HashBucket bucket = newRoot.GetValueOrDefault(hashCode); OperationResult result; var newBucket = bucket.Add(pair.Key, pair.Value, origin.KeyOnlyComparer, origin.ValueComparer, collisionBehavior, out result); newRoot = UpdateRoot(newRoot, hashCode, newBucket, origin.HashBucketComparer); if (result == OperationResult.SizeChanged) { countAdjustment++; } } return new MutationResult(newRoot, countAdjustment); } /// <summary> /// Performs the operation on a given data structure. /// </summary> private static MutationResult Remove(TKey key, MutationInput origin) { int hashCode = origin.KeyComparer.GetHashCode(key); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { OperationResult result; var newRoot = UpdateRoot(origin.Root, hashCode, bucket.Remove(key, origin.KeyOnlyComparer, out result), origin.HashBucketComparer); return new MutationResult(newRoot, result == OperationResult.SizeChanged ? -1 : 0); } return new MutationResult(origin); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, HashBucket newBucket, IEqualityComparer<HashBucket> hashBucketComparer) { bool mutated; if (newBucket.IsEmpty) { return root.Remove(hashCode, out mutated); } else { bool replacedExistingValue; return root.SetItem(hashCode, newBucket, hashBucketComparer, out replacedExistingValue, out mutated); } } #endregion /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="comparers">The comparers.</param> /// <param name="count">The number of elements in the data structure.</param> /// <returns> /// The immutable collection. /// </returns> private static ImmutableDictionary<TKey, TValue> Wrap(SortedInt32KeyNode<HashBucket> root, Comparers comparers, int count) { Requires.NotNull(root, "root"); Requires.NotNull(comparers, "comparers"); Requires.Range(count >= 0, "count"); return new ImmutableDictionary<TKey, TValue>(root, comparers, count); } /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="adjustedCountIfDifferentRoot">The adjusted count if the root has changed.</param> /// <returns>The immutable collection.</returns> private ImmutableDictionary<TKey, TValue> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot) { if (root == null) { return this.Clear(); } if (_root != root) { return root.IsEmpty ? this.Clear() : new ImmutableDictionary<TKey, TValue>(root, _comparers, adjustedCountIfDifferentRoot); } return this; } /// <summary> /// Bulk adds entries to the map. /// </summary> /// <param name="pairs">The entries to add.</param> /// <param name="avoidToHashMap"><c>true</c> when being called from <see cref="WithComparers(IEqualityComparer{TKey}, IEqualityComparer{TValue})"/> to avoid <see cref="T:System.StackOverflowException"/>.</param> [Pure] private ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool avoidToHashMap) { Requires.NotNull(pairs, "pairs"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); // Some optimizations may apply if we're an empty list. if (this.IsEmpty && !avoidToHashMap) { // If the items being added actually come from an ImmutableDictionary<TKey, TValue> // then there is no value in reconstructing it. ImmutableDictionary<TKey, TValue> other; if (TryCastToImmutableMap(pairs, out other)) { return other.WithComparers(this.KeyComparer, this.ValueComparer); } } var result = AddRange(pairs, this.Origin); return result.Finalize(this); } } }
/* * Copyright 2005 OpenXRI Foundation * Subsequently ported and altered by Andrew Arnott and Troels Thomsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using DotNetXri.Syntax.Xri3.Impl.Parser; namespace DotNetXri.Syntax.Xri3.Impl { public class XRI3Reference : XRI3SyntaxComponent, XRIReference { private Rule rule; private XRI3 xri; private XRI3Path path; private XRI3Query query; private XRI3Fragment fragment; public XRI3Reference(string value) { this.rule = XRI3Util.getParser().parse("xri-reference", value); this.read(); } public XRI3Reference(XRIReference xriReference, XRISyntaxComponent xriPart) { StringBuilder buffer = new StringBuilder(); buffer.Append(xriReference.ToString()); buffer.Append(xriPart.ToString()); this.rule = XRI3Util.getParser().parse("xri-reference", buffer.ToString()); this.read(); } public XRI3Reference(XRIReference xriReference, string xriPart) { StringBuilder buffer = new StringBuilder(); buffer.Append(xriReference.ToString()); buffer.Append(xriPart); this.rule = XRI3Util.getParser().parse("xri-reference", buffer.ToString()); this.read(); } internal XRI3Reference(Rule rule) { this.rule = rule; this.read(); } private void reset() { this.xri = null; this.path = null; this.query = null; this.fragment = null; } private void read() { this.reset(); object obj = this.rule; // xri_reference // read xri or relative_xri_ref from xri_reference IList<Rule> list_xri_reference = ((Parser.Parser.xri_reference)obj).rules; if (list_xri_reference.Count < 1) return; obj = list_xri_reference[0]; // xri or relative_xri_ref // xri or relative_xri_ref ? if (obj is Parser.Parser.xri) { this.xri = new XRI3((Parser.Parser.xri)obj); } else if (obj is Parser.Parser.relative_xri_ref) { // read relative_xri_part from relative_xri_ref IList<Rule> list_relative_xri_ref = ((Parser.Parser.relative_xri_ref)obj).rules; if (list_relative_xri_ref.Count < 1) return; obj = list_relative_xri_ref[0]; // relative_xri_part // read xri_path_abs or xri_path_noscheme or ipath_empty from relative_xri_part IList<Rule> list_relative_xri_part = ((Parser.Parser.relative_xri_part)obj).rules; if (list_relative_xri_part.Count < 1) return; obj = list_relative_xri_part[0]; // xri_path_abs or xri_path_noscheme or ipath_empty // read xri_path_abs or xri_path_noscheme or ipath_emptry ? if (obj is Parser.Parser.xri_path_abs) { this.path = new XRI3Path((Parser.Parser.xri_path_abs)obj); } else if (obj is Parser.Parser.xri_path_noscheme) { this.path = new XRI3Path((Parser.Parser.xri_path_noscheme)obj); } else if (obj is Parser.Parser.ipath_empty) { this.path = new XRI3Path((Parser.Parser.ipath_empty)obj); } else { throw new InvalidCastException(obj.GetType().Name); } // read iquery from relative_xri_ref if (list_relative_xri_ref.Count < 3) return; obj = list_relative_xri_ref[2]; // iquery this.query = new XRI3Query((Parser.Parser.iquery)obj); // read ifragment from relative_xri_ref if (list_relative_xri_ref.Count < 5) return; obj = list_relative_xri_ref[4]; // ifragment this.fragment = new XRI3Fragment((Parser.Parser.ifragment)obj); } else { throw new InvalidCastException(obj.GetType().Name); } } public Rule ParserObject { get { return this.rule; } } public bool hasScheme() { if (this.xri != null) return (this.xri.hasScheme()); return (false); } public bool hasAuthority() { if (this.xri != null) return (this.xri.hasAuthority()); return (false); } public bool hasPath() { if (this.xri != null) return (this.xri.hasPath()); return (this.path != null); } public bool hasQuery() { if (this.xri != null) return (this.xri.hasQuery()); return (this.query != null); } public bool hasFragment() { if (this.xri != null) return (this.xri.hasFragment()); return (this.fragment != null); } public string Scheme { get { if (this.xri != null) return (this.xri.Scheme); return (null); } } public XRIAuthority Authority { get { if (this.xri != null) return (this.xri.Authority); return (null); } } public XRIPath Path { get { if (this.xri != null) return (this.xri.Path); return (this.path); } } public XRIQuery Query { get { if (this.xri != null) return (this.xri.Query); return (this.query); } } public XRIFragment Fragment { get { if (this.xri != null) return (this.xri.Fragment); return (this.fragment); } } public string toIRINormalForm() { if (this.xri != null) return (this.xri.toIRINormalForm()); return (base.toIRINormalForm()); } public bool isValidXRI() { XRI xri; try { xri = this.toXRI(); } catch (Exception) { return (false); } return (xri != null); } public XRI toXRI() { return (new XRI3(this.ToString())); } public XRI3 toXRI3() { return (new XRI3(this.ToString())); } } }
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord (Big Room) * C# Port: Ben Baker (HeadSoft) * Copyright (c) Big Room Ventures Ltd. 2008 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using FlintSharp.Behaviours; using FlintSharp.Activities; using FlintSharp.Counters; using FlintSharp.Easing; using FlintSharp.Emitters; using FlintSharp.EnergyEasing; using FlintSharp.Initializers; using FlintSharp.Particles; using FlintSharp.Zones; namespace FlintSharp.Zones { /// <summary> /// The TextZone zone defines a text zone. The zone implementation is /// almost same as BitmapDataZone. /// </summary> public class TextZone : IZone { private List<Point> m_validPoints = new List<Point>(); private Bitmap m_bitmap; private string m_text = string.Empty; private Font m_font; private FontFamily m_fontFamily; private FontStyle m_fontStyle = FontStyle.Regular; private double m_fontSize = 10.0; private bool m_textChanged = true; private bool m_fontChanged = true; /// <summary> /// Constructor. /// </summary> public TextZone() { m_fontFamily = System.Drawing.FontFamily.GenericSansSerif; } /// <summary> /// A text string to be drawn. /// </summary> public string Text { get { return m_text; } set { m_text = value; m_textChanged = true; } } /// <summary> /// A font object used when the text is draw. /// </summary> public Font Font { get { return m_font; } set { m_font = value; m_textChanged = true; } } public string FontFamily { get { return m_fontFamily.Name; } set { m_fontFamily = new FontFamily(value); m_fontChanged = true; } } public FontStyle FontStyle { get { return m_fontStyle; } set { m_fontStyle = value; m_fontChanged = true; } } public double FontSize { get { return m_fontSize; } set { m_fontSize = value; m_fontChanged = true; } } /// <summary> /// A horizontal offset to apply to the pixels in the BitmapData object /// to reposition the zone /// </summary> public double OffsetX { get; set; } /// <summary> /// A vertical offset to apply to the pixels in the BitmapData object /// to reposition the zone /// </summary> public double OffsetY { get; set; } /// <summary> /// A scale factor to stretch the bitmap horizontally /// </summary> public double ScaleX { get; set; } /// <summary> /// A scale factor to stretch the bitmap vertically /// </summary> public double ScaleY { get; set; } public int DivideX { get; set; } public int DivideY { get; set; } /// <summary> /// Measures the string extent. /// </summary> private SizeF MeasureString() { using (Bitmap dummy = new Bitmap(1, 1)) using (Graphics g = Graphics.FromImage(dummy)) { return g.MeasureString(Text, Font); } } /// <summary> /// Creates the bitmap image which the string is drawn. /// </summary> private Bitmap CreateFontBitmap() { SizeF size = MeasureString(); Bitmap bitmap = new Bitmap( (int)Math.Ceiling(size.Width) + 1, (int)Math.Ceiling(size.Height) + 1, PixelFormat.Format24bppRgb); using (Graphics g = Graphics.FromImage(bitmap)) { // For speed g.SmoothingMode = SmoothingMode.None; #if !MONO g.InterpolationMode = InterpolationMode.Low; g.CompositingQuality = CompositingQuality.Default; #else g.InterpolationMode = InterpolationMode.Invalid; g.CompositingQuality = CompositingQuality.Invalid; #endif // This line makes DrawString fail. //g.CompositingMode = CompositingMode.SourceCopy; g.DrawString(Text, Font, Brushes.White, new PointF(0, 0), null); } return bitmap; } /// <summary> /// This method forces the zone to revaluate the font object. /// </summary> private void UpdateFont() { m_font = new Font(m_fontFamily, (float)m_fontSize, m_fontStyle, GraphicsUnit.Pixel); m_fontChanged = false; m_textChanged = true; } /// <summary> /// This method forces the zone to revaluate itself. It should be called whenever the /// contents of the Text object change. However, it is an intensive method and /// calling it frequently will likely slow your code down. /// </summary> private void UpdateBitmap() { Bitmap bitmap = CreateFontBitmap(); List<Point> validPoints = new List<Point>(); for (int y = 0; y < bitmap.Height; ++y) { for (int x = 0; x < bitmap.Width; ++x) { Color c = bitmap.GetPixel(x, y); if (c.R > 90) validPoints.Add(new Point(x, y)); } } m_bitmap = bitmap; m_validPoints = validPoints; m_textChanged = false; } /// <summary> /// Recreates the bitmap or the font if need. /// </summary> private void UpdateIfNeed() { if (m_fontChanged) UpdateFont(); if (m_textChanged) UpdateBitmap(); } /// <summary> /// The contains method determines whether a point is inside the zone. /// </summary> /// <param name="x">The x location to test for.</param> /// <param name="y">The x location to test for.</param> /// <returns>true if point is inside the zone, false if it is outside.</returns> public bool Contains(double x, double y) { UpdateIfNeed(); if (m_bitmap == null) return false; double w2 = m_bitmap.Width / 2.0; double h2 = m_bitmap.Height / 2.0; int newX = (int)Math.Round((x - OffsetX) / ScaleX + w2); int newY = (int)Math.Round((y - OffsetY) / ScaleY + h2); if (newX < 0 || newX > m_bitmap.Width) return false; if (newY < 0 || newY > m_bitmap.Height) return false; Color c = m_bitmap.GetPixel(newX, newY); return (c.R > 90); } private System.Windows.Point CalcPoint(int index, double rx, double ry) { Point p = m_validPoints[index]; // Adjust the point to center. double w2 = m_bitmap.Width / 2.0; double h2 = m_bitmap.Height / 2.0; double rateX = 1.0 + rx; double rateY = 1.0 + ry; return new System.Windows.Point( (p.X + rateX - w2) * ScaleX + OffsetX, (p.Y + rateY - h2) * ScaleY + OffsetY); } /// <summary> /// Counts of the particles. /// </summary> public int Count() { UpdateIfNeed(); return (m_validPoints.Count * DivideX * DivideY); } /// <summary> /// The list of the particle points. /// </summary> public IEnumerable<System.Windows.Point> GetLocationList() { UpdateIfNeed(); double offsetX = 0.5 / DivideX; double offsetY = 0.5 / DivideY; for (var index = 0; index < m_validPoints.Count; ++index) { for (var dx = 0; dx < DivideX; ++dx) { for (var dy = 0; dy < DivideY; ++dy) { // offset + 0.0 <= rate < offset + 1.0 double rateX = offsetX + (double)dx / DivideX; double rateY = offsetY + (double)dy / DivideY; yield return CalcPoint(index, rateX, rateY); } } } } /// <summary> /// The getLocation method returns a random point inside the zone. /// </summary> /// <returns>a random point inside the zone.</returns> public System.Windows.Point GetLocation() { UpdateIfNeed(); return CalcPoint( Utils.Random.Next(m_validPoints.Count), (double)Utils.Random.Next(DivideX) / DivideX, (double)Utils.Random.Next(DivideY) / DivideY); } /// <summary> /// The getArea method returns the size of the zone. /// It's used by the MultiZone class to manage the balancing between the /// different zones. /// </summary> /// <returns>the size of the zone.</returns> public double GetArea() { UpdateIfNeed(); return m_validPoints.Count * ScaleX * ScaleY; } /// <summary> /// Manages collisions between a particle and the zone. The particle will collide with the line defined /// for this zone. In the interests of speed, the collisions are not exactly accurate at the ends of the /// line, but are accurate enough to ensure the particle doesn't pass through the line and to look /// realistic in most circumstances. The collisionRadius of the particle is used when calculating the collision. /// </summary> /// <param name="particle">The particle to be tested for collision with the zone.</param> /// <param name="bounce">The coefficient of restitution for the collision.</param> /// <returns>Whether a collision occured.</returns> public bool CollideParticle(Particle particle, double bounce = 1) { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; using System.Globalization; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { private void EmitBlockExpression(Expression expr, CompilationFlags flags) { // emit body Emit((BlockExpression)expr, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsDefaultType)); } private void Emit(BlockExpression node, CompilationFlags flags) { int count = node.ExpressionCount; if (count == 0) { return; } EnterScope(node); CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask; CompilationFlags tailCall = flags & CompilationFlags.EmitAsTailCallMask; for (int index = 0; index < count - 1; index++) { var e = node.GetExpression(index); var next = node.GetExpression(index + 1); CompilationFlags tailCallFlag; if (tailCall != CompilationFlags.EmitAsNoTail) { var g = next as GotoExpression; if (g != null && (g.Value == null || !Significant(g.Value)) && ReferenceLabel(g.Target).CanReturn) { // Since tail call flags are not passed into EmitTryExpression, CanReturn means the goto will be emitted // as Ret. Therefore we can emit the current expression with tail call. tailCallFlag = CompilationFlags.EmitAsTail; } else { // In the middle of the block. // We may do better here by marking it as Tail if the following expressions are not going to emit any IL. tailCallFlag = CompilationFlags.EmitAsMiddle; } } else { tailCallFlag = CompilationFlags.EmitAsNoTail; } flags = UpdateEmitAsTailCallFlag(flags, tailCallFlag); EmitExpressionAsVoid(e, flags); } // if the type of Block it means this is not a Comma // so we will force the last expression to emit as void. // We don't need EmitAsType flag anymore, should only pass // the EmitTailCall field in flags to emitting the last expression. if (emitAs == CompilationFlags.EmitAsVoidType || node.Type == typeof(void)) { EmitExpressionAsVoid(node.GetExpression(count - 1), tailCall); } else { EmitExpressionAsType(node.GetExpression(count - 1), node.Type, tailCall); } ExitScope(node); } private void EnterScope(object node) { if (HasVariables(node) && (_scope.MergedScopes == null || !_scope.MergedScopes.Contains(node))) { CompilerScope scope; if (!_tree.Scopes.TryGetValue(node, out scope)) { // // Very often, we want to compile nodes as reductions // rather than as IL, but usually they need to allocate // some IL locals. To support this, we allow emitting a // BlockExpression that was not bound by VariableBinder. // This works as long as the variables are only used // locally -- i.e. not closed over. // // User-created blocks will never hit this case; only our // internally reduced nodes will. // scope = new CompilerScope(node, false) { NeedsClosure = _scope.NeedsClosure }; } _scope = scope.Enter(this, _scope); Debug.Assert(_scope.Node == node); } } private static bool HasVariables(object node) { var block = node as BlockExpression; if (block != null) { return block.Variables.Count > 0; } return ((CatchBlock)node).Variable != null; } private void ExitScope(object node) { if (_scope.Node == node) { _scope = _scope.Exit(); } } private void EmitDefaultExpression(Expression expr) { var node = (DefaultExpression)expr; if (node.Type != typeof(void)) { // emit default(T) _ilg.EmitDefault(node.Type); } } private void EmitLoopExpression(Expression expr) { LoopExpression node = (LoopExpression)expr; PushLabelBlock(LabelScopeKind.Statement); LabelInfo breakTarget = DefineLabel(node.BreakLabel); LabelInfo continueTarget = DefineLabel(node.ContinueLabel); continueTarget.MarkWithEmptyStack(); EmitExpressionAsVoid(node.Body); _ilg.Emit(OpCodes.Br, continueTarget.Label); PopLabelBlock(LabelScopeKind.Statement); breakTarget.MarkWithEmptyStack(); } #region SwitchExpression private void EmitSwitchExpression(Expression expr, CompilationFlags flags) { SwitchExpression node = (SwitchExpression)expr; if (node.Cases.Count == 0) { // Emit the switch value in case it has side-effects, but as void // since the value is ignored. EmitExpressionAsVoid(node.SwitchValue); // Now if there is a default body, it happens unconditionally. if (node.DefaultBody != null) { EmitExpressionAsType(node.DefaultBody, node.Type, flags); } else { // If there are no cases and no default then the type must be void. // Assert that earlier validation caught any exceptions to that. Debug.Assert(expr.Type == typeof(void)); } return; } // Try to emit it as an IL switch. Works for integer types. if (TryEmitSwitchInstruction(node, flags)) { return; } // Try to emit as a hashtable lookup. Works for strings. if (TryEmitHashtableSwitch(node, flags)) { return; } // // Fall back to a series of tests. We need to IL gen instead of // transform the tree to avoid stack overflow on a big switch. // var switchValue = Expression.Parameter(node.SwitchValue.Type, "switchValue"); var testValue = Expression.Parameter(GetTestValueType(node), "testValue"); _scope.AddLocal(this, switchValue); _scope.AddLocal(this, testValue); EmitExpression(node.SwitchValue); _scope.EmitSet(switchValue); // Emit tests var labels = new Label[node.Cases.Count]; var isGoto = new bool[node.Cases.Count]; for (int i = 0, n = node.Cases.Count; i < n; i++) { DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]); foreach (Expression test in node.Cases[i].TestValues) { // Pull the test out into a temp so it runs on the same // stack as the switch. This simplifies spilling. EmitExpression(test); _scope.EmitSet(testValue); Debug.Assert(TypeUtils.AreReferenceAssignable(testValue.Type, test.Type)); EmitExpressionAndBranch(true, Expression.Equal(switchValue, testValue, false, node.Comparison), labels[i]); } } // Define labels Label end = _ilg.DefineLabel(); Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); // Emit the case and default bodies EmitSwitchCases(node, labels, isGoto, @default, end, flags); } /// <summary> /// Gets the common test test value type of the SwitchExpression. /// </summary> private static Type GetTestValueType(SwitchExpression node) { if (node.Comparison == null) { // If we have no comparison, all right side types must be the // same. return node.Cases[0].TestValues[0].Type; } // Otherwise, get the type from the method. Type result = node.Comparison.GetParametersCached()[1].ParameterType.GetNonRefType(); if (node.IsLifted) { result = TypeUtils.GetNullableType(result); } return result; } private sealed class SwitchLabel { internal readonly decimal Key; internal readonly Label Label; // Boxed version of Key, preserving the original type. internal readonly object Constant; internal SwitchLabel(decimal key, object @constant, Label label) { Key = key; Constant = @constant; Label = label; } } private sealed class SwitchInfo { internal readonly SwitchExpression Node; internal readonly LocalBuilder Value; internal readonly Label Default; internal readonly Type Type; internal readonly bool IsUnsigned; internal readonly bool Is64BitSwitch; internal SwitchInfo(SwitchExpression node, LocalBuilder value, Label @default) { Node = node; Value = value; Default = @default; Type = Node.SwitchValue.Type; IsUnsigned = TypeUtils.IsUnsigned(Type); var code = Type.GetTypeCode(); Is64BitSwitch = code == TypeCode.UInt64 || code == TypeCode.Int64; } } private static bool FitsInBucket(List<SwitchLabel> buckets, decimal key, int count) { Debug.Assert(key > buckets[buckets.Count - 1].Key); decimal jumpTableSlots = key - buckets[0].Key + 1; if (jumpTableSlots > int.MaxValue) { return false; } // density must be > 50% return (buckets.Count + count) * 2 > jumpTableSlots; } private static void MergeBuckets(List<List<SwitchLabel>> buckets) { while (buckets.Count > 1) { List<SwitchLabel> first = buckets[buckets.Count - 2]; List<SwitchLabel> second = buckets[buckets.Count - 1]; if (!FitsInBucket(first, second[second.Count - 1].Key, second.Count)) { return; } // Merge them first.AddRange(second); buckets.RemoveAt(buckets.Count - 1); } } // Add key to a new or existing bucket private static void AddToBuckets(List<List<SwitchLabel>> buckets, SwitchLabel key) { if (buckets.Count > 0) { List<SwitchLabel> last = buckets[buckets.Count - 1]; if (FitsInBucket(last, key.Key, 1)) { last.Add(key); // we might be able to merge now MergeBuckets(buckets); return; } } // else create a new bucket buckets.Add(new List<SwitchLabel> { key }); } // Determines if the type is an integer we can switch on. private static bool CanOptimizeSwitchType(Type valueType) { // enums & char are allowed switch (valueType.GetTypeCode()) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Char: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return true; default: return false; } } // Tries to emit switch as a jmp table private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags flags) { // If we have a comparison, bail if (node.Comparison != null) { return false; } // Make sure the switch value type and the right side type // are types we can optimize Type type = node.SwitchValue.Type; if (!CanOptimizeSwitchType(type) || !TypeUtils.AreEquivalent(type, node.Cases[0].TestValues[0].Type)) { return false; } // Make sure all test values are constant, or we can't emit the // jump table. if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) { return false; } // // We can emit the optimized switch, let's do it. // // Build target labels, collect keys. var labels = new Label[node.Cases.Count]; var isGoto = new bool[node.Cases.Count]; var uniqueKeys = new Set<decimal>(); var keys = new List<SwitchLabel>(); for (int i = 0; i < node.Cases.Count; i++) { DefineSwitchCaseLabel(node.Cases[i], out labels[i], out isGoto[i]); foreach (ConstantExpression test in node.Cases[i].TestValues) { // Guaranteed to work thanks to CanOptimizeSwitchType. // // Use decimal because it can hold Int64 or UInt64 without // precision loss or signed/unsigned conversions. decimal key = ConvertSwitchValue(test.Value); // Only add each key once. If it appears twice, it's // allowed, but can't be reached. if (!uniqueKeys.Contains(key)) { keys.Add(new SwitchLabel(key, test.Value, labels[i])); uniqueKeys.Add(key); } } } // Sort the keys, and group them into buckets. keys.Sort((x, y) => Math.Sign(x.Key - y.Key)); var buckets = new List<List<SwitchLabel>>(); foreach (var key in keys) { AddToBuckets(buckets, key); } // Emit the switchValue LocalBuilder value = GetLocal(node.SwitchValue.Type); EmitExpression(node.SwitchValue); _ilg.Emit(OpCodes.Stloc, value); // Create end label, and default label if needed Label end = _ilg.DefineLabel(); Label @default = (node.DefaultBody == null) ? end : _ilg.DefineLabel(); // Emit the switch var info = new SwitchInfo(node, value, @default); EmitSwitchBuckets(info, buckets, 0, buckets.Count - 1); // Emit the case bodies and default EmitSwitchCases(node, labels, isGoto, @default, end, flags); FreeLocal(value); return true; } private static decimal ConvertSwitchValue(object value) { if (value is char) { return (int)(char)value; } return Convert.ToDecimal(value, CultureInfo.InvariantCulture); } /// <summary> /// Creates the label for this case. /// Optimization: if the body is just a goto, and we can branch /// to it, put the goto target directly in the jump table. /// </summary> private void DefineSwitchCaseLabel(SwitchCase @case, out Label label, out bool isGoto) { var jump = @case.Body as GotoExpression; // if it's a goto with no value if (jump != null && jump.Value == null) { // Reference the label from the switch. This will cause us to // analyze the jump target and determine if it is safe. LabelInfo jumpInfo = ReferenceLabel(jump.Target); // If we have are allowed to emit the "branch" opcode, then we // can jump directly there from the switch's jump table. // (Otherwise, we need to emit the goto later as a "leave".) if (jumpInfo.CanBranch) { label = jumpInfo.Label; isGoto = true; return; } } // otherwise, just define a new label label = _ilg.DefineLabel(); isGoto = false; } private void EmitSwitchCases(SwitchExpression node, Label[] labels, bool[] isGoto, Label @default, Label end, CompilationFlags flags) { // Jump to default (to handle the fallthrough case) _ilg.Emit(OpCodes.Br, @default); // Emit the cases for (int i = 0, n = node.Cases.Count; i < n; i++) { // If the body is a goto, we already emitted an optimized // branch directly to it. No need to emit anything else. if (isGoto[i]) { continue; } _ilg.MarkLabel(labels[i]); EmitExpressionAsType(node.Cases[i].Body, node.Type, flags); // Last case doesn't need branch if (node.DefaultBody != null || i < n - 1) { if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { //The switch case is at the tail of the lambda so //it is safe to emit a Ret. _ilg.Emit(OpCodes.Ret); } else { _ilg.Emit(OpCodes.Br, end); } } } // Default value if (node.DefaultBody != null) { _ilg.MarkLabel(@default); EmitExpressionAsType(node.DefaultBody, node.Type, flags); } _ilg.MarkLabel(end); } private void EmitSwitchBuckets(SwitchInfo info, List<List<SwitchLabel>> buckets, int first, int last) { if (first == last) { EmitSwitchBucket(info, buckets[first]); return; } // Split the buckets into two groups, and use an if test to find // the right bucket. This ensures we'll only need O(lg(B)) tests // where B is the number of buckets int mid = (int)(((long)first + last + 1) / 2); if (first == mid - 1) { EmitSwitchBucket(info, buckets[first]); } else { // If the first half contains more than one, we need to emit an // explicit guard Label secondHalf = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldloc, info.Value); _ilg.EmitConstant(buckets[mid - 1].Last().Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, secondHalf); EmitSwitchBuckets(info, buckets, first, mid - 1); _ilg.MarkLabel(secondHalf); } EmitSwitchBuckets(info, buckets, mid, last); } private void EmitSwitchBucket(SwitchInfo info, List<SwitchLabel> bucket) { // No need for switch if we only have one value if (bucket.Count == 1) { _ilg.Emit(OpCodes.Ldloc, info.Value); _ilg.EmitConstant(bucket[0].Constant); _ilg.Emit(OpCodes.Beq, bucket[0].Label); return; } // // If we're switching off of Int64/UInt64, we need more guards here // because we'll have to narrow the switch value to an Int32, and // we can't do that unless the value is in the right range. // Label? after = null; if (info.Is64BitSwitch) { after = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldloc, info.Value); _ilg.EmitConstant(bucket.Last().Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Bgt_Un : OpCodes.Bgt, after.Value); _ilg.Emit(OpCodes.Ldloc, info.Value); _ilg.EmitConstant(bucket[0].Constant); _ilg.Emit(info.IsUnsigned ? OpCodes.Blt_Un : OpCodes.Blt, after.Value); } _ilg.Emit(OpCodes.Ldloc, info.Value); // Normalize key decimal key = bucket[0].Key; if (key != 0) { _ilg.EmitConstant(bucket[0].Constant); _ilg.Emit(OpCodes.Sub); } if (info.Is64BitSwitch) { _ilg.Emit(OpCodes.Conv_I4); } // Collect labels int len = (int)(bucket[bucket.Count - 1].Key - bucket[0].Key + 1); Label[] jmpLabels = new Label[len]; // Initialize all labels to the default int slot = 0; foreach (SwitchLabel label in bucket) { while (key++ != label.Key) { jmpLabels[slot++] = info.Default; } jmpLabels[slot++] = label.Label; } // check we used all keys and filled all slots Debug.Assert(key == bucket[bucket.Count - 1].Key + 1); Debug.Assert(slot == jmpLabels.Length); // Finally, emit the switch instruction _ilg.Emit(OpCodes.Switch, jmpLabels); if (info.Is64BitSwitch) { _ilg.MarkLabel(after.Value); } } private bool TryEmitHashtableSwitch(SwitchExpression node, CompilationFlags flags) { // If we have a comparison other than string equality, bail MethodInfo equality = typeof(string).GetMethod("op_Equality", new[] { typeof(string), typeof(string) }); if (!equality.IsStatic) { equality = null; } if (node.Comparison != equality) { return false; } // All test values must be constant. int tests = 0; foreach (SwitchCase c in node.Cases) { foreach (Expression t in c.TestValues) { if (!(t is ConstantExpression)) { return false; } tests++; } } // Must have >= 7 labels for it to be worth it. if (tests < 7) { return false; } // If we're in a DynamicMethod, we could just build the dictionary // immediately. But that would cause the two code paths to be more // different than they really need to be. var initializers = new List<ElementInit>(tests); var cases = new List<SwitchCase>(node.Cases.Count); int nullCase = -1; MethodInfo add = typeof(Dictionary<string, int>).GetMethod("Add", new[] { typeof(string), typeof(int) }); for (int i = 0, n = node.Cases.Count; i < n; i++) { foreach (ConstantExpression t in node.Cases[i].TestValues) { if (t.Value != null) { initializers.Add(Expression.ElementInit(add, t, Expression.Constant(i))); } else { nullCase = i; } } cases.Add(Expression.SwitchCase(node.Cases[i].Body, Expression.Constant(i))); } // Create the field to hold the lazily initialized dictionary MemberExpression dictField = CreateLazyInitializedField<Dictionary<string, int>>("dictionarySwitch"); // If we happen to initialize it twice (multithreaded case), it's // not the end of the world. The C# compiler does better here by // emitting a volatile access to the field. Expression dictInit = Expression.Condition( Expression.Equal(dictField, Expression.Constant(null, dictField.Type)), Expression.Assign( dictField, Expression.ListInit( Expression.New( typeof(Dictionary<string, int>).GetConstructor(new[] { typeof(int) }), Expression.Constant(initializers.Count) ), initializers ) ), dictField ); // // Create a tree like: // // switchValue = switchValueExpression; // if (switchValue == null) { // switchIndex = nullCase; // } else { // if (_dictField == null) { // _dictField = new Dictionary<string, int>(count) { { ... }, ... }; // } // if (!_dictField.TryGetValue(switchValue, out switchIndex)) { // switchIndex = -1; // } // } // switch (switchIndex) { // case 0: ... // case 1: ... // ... // default: // } // var switchValue = Expression.Variable(typeof(string), "switchValue"); var switchIndex = Expression.Variable(typeof(int), "switchIndex"); var reduced = Expression.Block( new[] { switchIndex, switchValue }, Expression.Assign(switchValue, node.SwitchValue), Expression.IfThenElse( Expression.Equal(switchValue, Expression.Constant(null, typeof(string))), Expression.Assign(switchIndex, Expression.Constant(nullCase)), Expression.IfThenElse( Expression.Call(dictInit, "TryGetValue", null, switchValue, switchIndex), Expression.Empty(), Expression.Assign(switchIndex, Expression.Constant(-1)) ) ), Expression.Switch(node.Type, switchIndex, node.DefaultBody, null, cases) ); EmitExpression(reduced, flags); return true; } #endregion private void CheckRethrow() { // Rethrow is only valid inside a catch. for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) { if (j.Kind == LabelScopeKind.Catch) { return; } else if (j.Kind == LabelScopeKind.Finally) { // Rethrow from inside finally is not verifiable break; } } throw Error.RethrowRequiresCatch(); } #region TryStatement private void CheckTry() { // Try inside a filter is not verifiable for (LabelScopeInfo j = _labelBlock; j != null; j = j.Parent) { if (j.Kind == LabelScopeKind.Filter) { throw Error.TryNotAllowedInFilter(); } } } private void EmitSaveExceptionOrPop(CatchBlock cb) { if (cb.Variable != null) { // If the variable is present, store the exception // in the variable. _scope.EmitSet(cb.Variable); } else { // Otherwise, pop it off the stack. _ilg.Emit(OpCodes.Pop); } } private void EmitTryExpression(Expression expr) { var node = (TryExpression)expr; CheckTry(); //****************************************************************** // 1. ENTERING TRY //****************************************************************** PushLabelBlock(LabelScopeKind.Try); _ilg.BeginExceptionBlock(); //****************************************************************** // 2. Emit the try statement body //****************************************************************** EmitExpression(node.Body); Type tryType = expr.Type; LocalBuilder value = null; if (tryType != typeof(void)) { //store the value of the try body value = GetLocal(tryType); _ilg.Emit(OpCodes.Stloc, value); } //****************************************************************** // 3. Emit the catch blocks //****************************************************************** foreach (CatchBlock cb in node.Handlers) { PushLabelBlock(LabelScopeKind.Catch); // Begin the strongly typed exception block if (cb.Filter == null) { _ilg.BeginCatchBlock(cb.Test); } else { _ilg.BeginExceptFilterBlock(); } EnterScope(cb); EmitCatchStart(cb); // // Emit the catch block body // EmitExpression(cb.Body); if (tryType != typeof(void)) { //store the value of the catch block body _ilg.Emit(OpCodes.Stloc, value); } ExitScope(cb); PopLabelBlock(LabelScopeKind.Catch); } //****************************************************************** // 4. Emit the finally block //****************************************************************** if (node.Finally != null || node.Fault != null) { PushLabelBlock(LabelScopeKind.Finally); if (node.Finally != null) { _ilg.BeginFinallyBlock(); } else { _ilg.BeginFaultBlock(); } // Emit the body EmitExpressionAsVoid(node.Finally ?? node.Fault); _ilg.EndExceptionBlock(); PopLabelBlock(LabelScopeKind.Finally); } else { _ilg.EndExceptionBlock(); } if (tryType != typeof(void)) { _ilg.Emit(OpCodes.Ldloc, value); FreeLocal(value); } PopLabelBlock(LabelScopeKind.Try); } /// <summary> /// Emits the start of a catch block. The exception value that is provided by the /// CLR is stored in the variable specified by the catch block or popped if no /// variable is provided. /// </summary> private void EmitCatchStart(CatchBlock cb) { if (cb.Filter == null) { EmitSaveExceptionOrPop(cb); return; } // emit filter block. Filter blocks are untyped so we need to do // the type check ourselves. Label endFilter = _ilg.DefineLabel(); Label rightType = _ilg.DefineLabel(); // skip if it's not our exception type, but save // the exception if it is so it's available to the // filter _ilg.Emit(OpCodes.Isinst, cb.Test); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brtrue, rightType); _ilg.Emit(OpCodes.Pop); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br, endFilter); // it's our type, save it and emit the filter. _ilg.MarkLabel(rightType); EmitSaveExceptionOrPop(cb); PushLabelBlock(LabelScopeKind.Filter); EmitExpression(cb.Filter); PopLabelBlock(LabelScopeKind.Filter); // begin the catch, clear the exception, we've // already saved it _ilg.MarkLabel(endFilter); _ilg.BeginCatchBlock(null); _ilg.Emit(OpCodes.Pop); } #endregion } }
// http://bytes.com/topic/net/insights/797169-reading-parsing-ini-file-c using System; using System.IO; using System.Collections; public class IniParser { private Hashtable keyPairs = new Hashtable(); private String iniFilePath; private struct SectionPair { public String Section; public String Key; } /// <summary> /// Opens the INI file at the given path and enumerates the values in the IniParser. /// </summary> /// <param name="iniPath">Full path to INI file.</param> public IniParser(String iniPath) { TextReader iniFile = null; String strLine = null; String currentRoot = null; String[] keyPair = null; iniFilePath = iniPath; if (File.Exists(iniPath)) { try { iniFile = new StreamReader(iniPath); strLine = iniFile.ReadLine(); while (strLine != null) { strLine = strLine.Trim().ToUpper(); if (strLine != "") { if (strLine.StartsWith("[") && strLine.EndsWith("]")) { currentRoot = strLine.Substring(1, strLine.Length - 2); } else { keyPair = strLine.Split(new char[] { '=' }, 2); SectionPair sectionPair; String value = null; if (currentRoot == null) currentRoot = "ROOT"; sectionPair.Section = currentRoot; sectionPair.Key = keyPair[0]; if (keyPair.Length > 1) value = keyPair[1]; keyPairs.Add(sectionPair, value); } } strLine = iniFile.ReadLine(); } } catch (Exception ex) { throw ex; } finally { if (iniFile != null) iniFile.Close(); } } else throw new FileNotFoundException("Unable to locate " + iniPath); } /// <summary> /// Returns the value for the given section, key pair. /// </summary> /// <param name="sectionName">Section name.</param> /// <param name="settingName">Key name.</param> public String GetSetting(String sectionName, String settingName) { SectionPair sectionPair; sectionPair.Section = sectionName.ToUpper(); sectionPair.Key = settingName.ToUpper(); return (String)keyPairs[sectionPair]; } /// <summary> /// Enumerates all lines for given section. /// </summary> /// <param name="sectionName">Section to enum.</param> public String[] EnumSection(String sectionName) { ArrayList tmpArray = new ArrayList(); foreach (SectionPair pair in keyPairs.Keys) { if (pair.Section == sectionName.ToUpper()) tmpArray.Add(pair.Key); } return (String[])tmpArray.ToArray(typeof(String)); } /// <summary> /// Adds or replaces a setting to the table to be saved. /// </summary> /// <param name="sectionName">Section to add under.</param> /// <param name="settingName">Key name to add.</param> /// <param name="settingValue">Value of key.</param> public void AddSetting(String sectionName, String settingName, String settingValue) { SectionPair sectionPair; sectionPair.Section = sectionName.ToUpper(); sectionPair.Key = settingName.ToUpper(); if (keyPairs.ContainsKey(sectionPair)) keyPairs.Remove(sectionPair); keyPairs.Add(sectionPair, settingValue); } /// <summary> /// Adds or replaces a setting to the table to be saved with a null value. /// </summary> /// <param name="sectionName">Section to add under.</param> /// <param name="settingName">Key name to add.</param> public void AddSetting(String sectionName, String settingName) { AddSetting(sectionName, settingName, null); } /// <summary> /// Remove a setting. /// </summary> /// <param name="sectionName">Section to add under.</param> /// <param name="settingName">Key name to add.</param> public void DeleteSetting(String sectionName, String settingName) { SectionPair sectionPair; sectionPair.Section = sectionName.ToUpper(); sectionPair.Key = settingName.ToUpper(); if (keyPairs.ContainsKey(sectionPair)) keyPairs.Remove(sectionPair); } /// <summary> /// Save settings to new file. /// </summary> /// <param name="newFilePath">New file path.</param> public void SaveSettings(String newFilePath) { ArrayList sections = new ArrayList(); String tmpValue = ""; String strToSave = ""; foreach (SectionPair sectionPair in keyPairs.Keys) { if (!sections.Contains(sectionPair.Section)) sections.Add(sectionPair.Section); } foreach (String section in sections) { strToSave += ("[" + section + "]\r\n"); foreach (SectionPair sectionPair in keyPairs.Keys) { if (sectionPair.Section == section) { tmpValue = (String)keyPairs[sectionPair]; if (tmpValue != null) tmpValue = "=" + tmpValue; strToSave += (sectionPair.Key + tmpValue + "\r\n"); } } strToSave += "\r\n"; } try { TextWriter tw = new StreamWriter(newFilePath); tw.Write(strToSave); tw.Close(); } catch (Exception ex) { throw ex; } } /// <summary> /// Save settings back to ini file. /// </summary> public void SaveSettings() { SaveSettings(iniFilePath); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.Common; using System.Data.SqlTypes; using System.IO; using System.Linq; using System.Text; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class UdtTest { [CheckConnStrSetupFact] public static void GetSchemaTableTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr)) using (SqlCommand cmd = new SqlCommand("select hierarchyid::Parse('/1/') as col0", conn)) { conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo)) { DataTable schemaTable = reader.GetSchemaTable(); DataTestUtility.AssertEqualsWithDescription(1, schemaTable.Rows.Count, "Unexpected schema table row count."); string columnName = (string)(string)schemaTable.Rows[0][schemaTable.Columns["ColumnName"]]; DataTestUtility.AssertEqualsWithDescription("col0", columnName, "Unexpected column name."); string dataTypeName = (string)schemaTable.Rows[0][schemaTable.Columns["DataTypeName"]]; DataTestUtility.AssertEqualsWithDescription("Northwind.sys.hierarchyid", dataTypeName, "Unexpected data type name."); string udtAssemblyName = (string)schemaTable.Rows[0][schemaTable.Columns["UdtAssemblyQualifiedName"]]; Assert.True(udtAssemblyName?.StartsWith("Microsoft.SqlServer.Types.SqlHierarchyId"), "Unexpected UDT assembly name: " + udtAssemblyName); } } } [CheckConnStrSetupFact] public static void TestUdtSqlParameterThrowsPlatformNotSupportedException() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); // This command is not executed on the server since we should throw well before we send the query command.CommandText = "select @p as col0"; command.Parameters.Add(new SqlParameter { ParameterName = "@p", SqlDbType = SqlDbType.Udt, Direction = ParameterDirection.Input, }); Assert.Throws<PlatformNotSupportedException>(() => { command.ExecuteReader(); }); command.Parameters.Clear(); command.Parameters.Add(new SqlParameter { ParameterName = "@p", SqlDbType = SqlDbType.Udt, Direction = ParameterDirection.InputOutput, }); Assert.Throws<PlatformNotSupportedException>(() => { command.ExecuteReader(); }); command.Parameters.Clear(); command.Parameters.Add(new SqlParameter { ParameterName = "@p", SqlDbType = SqlDbType.Udt, Direction = ParameterDirection.Output, }); Assert.Throws<PlatformNotSupportedException>(() => { command.ExecuteReader(); }); } } [CheckConnStrSetupFact] public static void TestUdtZeroByte() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/') as col0"; using (SqlDataReader reader = command.ExecuteReader()) { Assert.True(reader.Read()); Assert.False(reader.IsDBNull(0)); SqlBytes sqlBytes = reader.GetSqlBytes(0); Assert.False(sqlBytes.IsNull, "Expected a zero length byte array"); Assert.True(sqlBytes.Length == 0, "Expected a zero length byte array"); } } } [CheckConnStrSetupFact] public static void TestUdtSqlDataReaderGetSqlBytesSequentialAccess() { TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.SequentialAccess); } [CheckConnStrSetupFact] public static void TestUdtSqlDataReaderGetSqlBytes() { TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.Default); } private static void TestUdtSqlDataReaderGetSqlBytes(CommandBehavior behavior) { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2"; using (SqlDataReader reader = command.ExecuteReader(behavior)) { Assert.True(reader.Read()); SqlBytes sqlBytes = null; sqlBytes = reader.GetSqlBytes(0); Assert.Equal("5ade", ToHexString(sqlBytes.Value)); sqlBytes = reader.GetSqlBytes(1); Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(sqlBytes.Value)); sqlBytes = reader.GetSqlBytes(2); Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(sqlBytes.Value)); if (behavior == CommandBehavior.Default) { sqlBytes = reader.GetSqlBytes(0); Assert.Equal("5ade", ToHexString(sqlBytes.Value)); } } } } [CheckConnStrSetupFact] public static void TestUdtSqlDataReaderGetBytesSequentialAccess() { TestUdtSqlDataReaderGetBytes(CommandBehavior.SequentialAccess); } [CheckConnStrSetupFact] public static void TestUdtSqlDataReaderGetBytes() { TestUdtSqlDataReaderGetBytes(CommandBehavior.Default); } private static void TestUdtSqlDataReaderGetBytes(CommandBehavior behavior) { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2"; using (SqlDataReader reader = command.ExecuteReader(behavior)) { Assert.True(reader.Read()); int byteCount = 0; byte[] bytes = null; byteCount = (int)reader.GetBytes(0, 0, null, 0, 0); Assert.True(byteCount > 0); bytes = new byte[byteCount]; reader.GetBytes(0, 0, bytes, 0, bytes.Length); Assert.Equal("5ade", ToHexString(bytes)); byteCount = (int)reader.GetBytes(1, 0, null, 0, 0); Assert.True(byteCount > 0); bytes = new byte[byteCount]; reader.GetBytes(1, 0, bytes, 0, bytes.Length); Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(bytes)); byteCount = (int)reader.GetBytes(2, 0, null, 0, 0); Assert.True(byteCount > 0); bytes = new byte[byteCount]; reader.GetBytes(2, 0, bytes, 0, bytes.Length); Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(bytes)); if (behavior == CommandBehavior.Default) { byteCount = (int)reader.GetBytes(0, 0, null, 0, 0); Assert.True(byteCount > 0); bytes = new byte[byteCount]; reader.GetBytes(0, 0, bytes, 0, bytes.Length); Assert.Equal("5ade", ToHexString(bytes)); } } } } [CheckConnStrSetupFact] public static void TestUdtSqlDataReaderGetStreamSequentialAccess() { TestUdtSqlDataReaderGetStream(CommandBehavior.SequentialAccess); } [CheckConnStrSetupFact] public static void TestUdtSqlDataReaderGetStream() { TestUdtSqlDataReaderGetStream(CommandBehavior.Default); } private static void TestUdtSqlDataReaderGetStream(CommandBehavior behavior) { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2"; using (SqlDataReader reader = command.ExecuteReader(behavior)) { Assert.True(reader.Read()); MemoryStream buffer = null; byte[] bytes = null; buffer = new MemoryStream(); using (Stream stream = reader.GetStream(0)) { stream.CopyTo(buffer); } bytes = buffer.ToArray(); Assert.Equal("5ade", ToHexString(bytes)); buffer = new MemoryStream(); using (Stream stream = reader.GetStream(1)) { stream.CopyTo(buffer); } bytes = buffer.ToArray(); Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(bytes)); buffer = new MemoryStream(); using (Stream stream = reader.GetStream(2)) { stream.CopyTo(buffer); } bytes = buffer.ToArray(); Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(bytes)); if (behavior == CommandBehavior.Default) { buffer = new MemoryStream(); using (Stream stream = reader.GetStream(0)) { stream.CopyTo(buffer); } bytes = buffer.ToArray(); Assert.Equal("5ade", ToHexString(bytes)); } } } } [CheckConnStrSetupFact] public static void TestUdtSchemaMetadata() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2"; using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SchemaOnly)) { ReadOnlyCollection<DbColumn> columns = reader.GetColumnSchema(); DbColumn column = null; // Validate Microsoft.SqlServer.Types.SqlHierarchyId, Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91 column = columns[0]; Assert.Equal(column.ColumnName, "col0"); Assert.Equal(typeof(byte[]), column.DataType); Assert.NotNull(column.UdtAssemblyQualifiedName); AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlHierarchyId"); // Validate Microsoft.SqlServer.Types.SqlGeometry, Microsoft.SqlServer.Types, Version = 11.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91 column = columns[1]; Assert.Equal(column.ColumnName, "col1"); Assert.Equal(typeof(byte[]), column.DataType); Assert.NotNull(column.UdtAssemblyQualifiedName); AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlGeometry"); // Validate Microsoft.SqlServer.Types.SqlGeography, Microsoft.SqlServer.Types, Version = 11.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91 column = columns[2]; Assert.Equal(column.ColumnName, "col2"); Assert.Equal(typeof(byte[]), column.DataType); Assert.NotNull(column.UdtAssemblyQualifiedName); AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlGeography"); } } } private static void AssertSqlUdtAssemblyQualifiedName(string assemblyQualifiedName, string expectedType) { List<string> parts = assemblyQualifiedName.Split(',').Select(x => x.Trim()).ToList(); string type = parts[0]; string assembly = parts.Count < 2 ? string.Empty : parts[1]; string version = parts.Count < 3 ? string.Empty : parts[2]; string culture = parts.Count < 4 ? string.Empty : parts[3]; string token = parts.Count < 5 ? string.Empty : parts[4]; Assert.Equal(expectedType, type); Assert.Equal("Microsoft.SqlServer.Types", assembly); Assert.True(version.StartsWith("Version")); Assert.True(culture.StartsWith("Culture")); Assert.True(token.StartsWith("PublicKeyToken")); } private static string ToHexString(byte[] bytes) { StringBuilder hex = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) { hex.AppendFormat("{0:x2}", b); } return hex.ToString(); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Net.Http; using System.Security.Claims; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using FluentAssertions; using IdentityModel; using IdentityServer.IntegrationTests.Common; using IdentityServer4; using IdentityServer4.Configuration; using IdentityServer4.Models; using IdentityServer4.Test; using Microsoft.IdentityModel.Logging; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; using Xunit; namespace IdentityServer.IntegrationTests.Endpoints.Authorize { public class JwtRequestAuthorizeTests { private const string Category = "Authorize endpoint with JWT requests"; private readonly IdentityServerPipeline _mockPipeline = new IdentityServerPipeline(); private readonly Client _client; private readonly string _symmetricJwk = @"{ 'kty': 'oct', 'use': 'sig', 'kid': '1', 'k': 'nYA-IFt8xTsdBHe9hunvizcp3Dt7f6qGqudq18kZHNtvqEGjJ9Ud-9x3kbQ-LYfLHS3xM2MpFQFg1JzT_0U_F8DI40oby4TvBDGszP664UgA8_5GjB7Flnrlsap1NlitvNpgQX3lpyTvC2zVuQ-UVsXbBDAaSBUSlnw7SE4LM8Ye2WYZrdCCXL8yAX9vIR7vf77yvNTEcBCI6y4JlvZaqMB4YKVSfygs8XqGGCHjLpE5bvI-A4ESbAUX26cVFvCeDg9pR6HK7BmwPMlO96krgtKZcXEJtUELYPys6-rbwAIdmxJxKxpgRpt0FRv_9fm6YPwG7QivYBX-vRwaodL1TA', 'alg': 'HS256'}"; private readonly RsaSecurityKey _rsaKey; public JwtRequestAuthorizeTests() { IdentityModelEventSource.ShowPII = true; _rsaKey = CryptoHelper.CreateRsaSecurityKey(); _mockPipeline.Clients.AddRange(new Client[] { _client = new Client { ClientName = "Client with keys", ClientId = "client", Enabled = true, RequireRequestObject = true, RedirectUris = { "https://client/callback" }, ClientSecrets = { new Secret { // x509 cert as base64 string Type = IdentityServerConstants.SecretTypes.X509CertificateBase64, Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert)) }, new Secret { // symmetric key as JWK Type = IdentityServerConstants.SecretTypes.JsonWebKey, Value = _symmetricJwk }, new Secret { // RSA key as JWK Type = IdentityServerConstants.SecretTypes.JsonWebKey, Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromRSASecurityKey(_rsaKey)) }, new Secret { // x509 cert as JWK Type = IdentityServerConstants.SecretTypes.JsonWebKey, Value = JsonConvert.SerializeObject(JsonWebKeyConverter.ConvertFromX509SecurityKey(new X509SecurityKey(TestCert.Load()))) } }, AllowedGrantTypes = GrantTypes.Implicit, AllowedScopes = new List<string> { "openid", "profile", "api1", "api2" } }, }); _mockPipeline.Users.Add(new TestUser { SubjectId = "bob", Username = "bob", Claims = new Claim[] { new Claim("name", "Bob Loblaw"), new Claim("email", "bob@loblaw.com"), new Claim("role", "Attorney") } }); _mockPipeline.IdentityScopes.AddRange(new IdentityResource[] { new IdentityResources.OpenId(), new IdentityResources.Profile(), new IdentityResources.Email() }); _mockPipeline.ApiScopes.AddRange(new ApiResource[] { new ApiResource { Name = "api", Scopes = { new Scope { Name = "api1" }, new Scope { Name = "api2" } } } }); _mockPipeline.Initialize(); } string CreateRequestJwt(string issuer, string audience, SigningCredentials credential, Claim[] claims) { var handler = new JwtSecurityTokenHandler(); handler.OutboundClaimTypeMap.Clear(); var token = handler.CreateJwtSecurityToken( issuer: issuer, audience: audience, signingCredentials: credential, subject: Identity.Create("pwd", claims)); return handler.WriteToken(token); } [Fact] [Trait("Category", Category)] public async Task missing_request_object_should_fail() { var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", scope: "openid profile", state: "123state", nonce: "123nonce", redirectUri: "https://client/callback"); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Client must use request object, but no request or request_uri parameter present"); _mockPipeline.LoginRequest.Should().BeNull(); } [Fact] [Trait("Category", Category)] public async Task authorize_should_accept_valid_JWT_request_object_parameters_using_X509_certificate() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.LoginRequest.Should().NotBeNull(); _mockPipeline.LoginRequest.ClientId.Should().Be(_client.ClientId); _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); _mockPipeline.LoginRequest.RequestObjectValues.Count.Should().Be(11); _mockPipeline.LoginRequest.RequestObjectValues.Should().ContainKey("foo"); _mockPipeline.LoginRequest.RequestObjectValues["foo"].Should().Be("123foo"); } [Fact] [Trait("Category", Category)] public async Task authorize_should_accept_valid_JWT_request_object_parameters_using_symmetric_jwk() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new SigningCredentials(new Microsoft.IdentityModel.Tokens.JsonWebKey(_symmetricJwk), "HS256"), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.LoginRequest.Should().NotBeNull(); _mockPipeline.LoginRequest.ClientId.Should().Be(_client.ClientId); _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); _mockPipeline.LoginRequest.RequestObjectValues.Count.Should().Be(11); _mockPipeline.LoginRequest.RequestObjectValues.Should().ContainKey("foo"); _mockPipeline.LoginRequest.RequestObjectValues["foo"].Should().Be("123foo"); } [Fact] [Trait("Category", Category)] public async Task authorize_should_accept_valid_JWT_request_object_parameters_using_rsa_jwk() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new SigningCredentials(_rsaKey, "RS256"), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.LoginRequest.Should().NotBeNull(); _mockPipeline.LoginRequest.ClientId.Should().Be(_client.ClientId); _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); _mockPipeline.LoginRequest.RequestObjectValues.Count.Should().Be(11); _mockPipeline.LoginRequest.RequestObjectValues.Should().ContainKey("foo"); _mockPipeline.LoginRequest.RequestObjectValues["foo"].Should().Be("123foo"); } [Fact] [Trait("Category", Category)] public async Task jwt_values_should_have_precedence_over_query_params() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new SigningCredentials(_rsaKey, "RS256"), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", scope: "bad", state: "bad", nonce: "bad", redirectUri: "bad", acrValues: "bad", loginHint: "bad", extra: new { display = "bad", ui_locales = "bad", foo = "bad", request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.LoginRequest.Should().NotBeNull(); _mockPipeline.LoginRequest.ClientId.Should().Be(_client.ClientId); _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); _mockPipeline.LoginRequest.RequestObjectValues.Count.Should().Be(11); _mockPipeline.LoginRequest.RequestObjectValues.Should().ContainKey("foo"); _mockPipeline.LoginRequest.RequestObjectValues["foo"].Should().Be("123foo"); } [Fact] [Trait("Category", Category)] public async Task authorize_should_accept_complex_objects_in_request_object() { var someObj = new { foo = new { bar = "bar" }, baz = "baz" }; var someObjJson = JsonConvert.SerializeObject(someObj); var someArr = new[] { "a", "b", "c" }; var someArrJson = JsonConvert.SerializeObject(someArr); var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), new Claim("someObj", someObjJson, Microsoft.IdentityModel.JsonWebTokens.JsonClaimValueTypes.Json), new Claim("someArr", someArrJson, Microsoft.IdentityModel.JsonWebTokens.JsonClaimValueTypes.JsonArray), }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.LoginRequest.Should().NotBeNull(); _mockPipeline.LoginRequest.Parameters["someObj"].Should().NotBeNull(); var someObj2 = JsonConvert.DeserializeObject(_mockPipeline.LoginRequest.Parameters["someObj"], someObj.GetType()); someObj.Should().BeEquivalentTo(someObj2); _mockPipeline.LoginRequest.Parameters["someArr"].Should().NotBeNull(); var someArr2 = JsonConvert.DeserializeObject<string[]>(_mockPipeline.LoginRequest.Parameters["someArr"]); someArr2.Should().Contain(new[] { "a", "c", "b" }); someArr2.Length.Should().Be(3); _mockPipeline.LoginRequest.RequestObjectValues.Count.Should().Be(13); _mockPipeline.LoginRequest.RequestObjectValues["someObj"].Should().NotBeNull(); someObj2 = JsonConvert.DeserializeObject(_mockPipeline.LoginRequest.RequestObjectValues["someObj"], someObj.GetType()); someObj.Should().BeEquivalentTo(someObj2); _mockPipeline.LoginRequest.RequestObjectValues["someArr"].Should().NotBeNull(); someArr2 = JsonConvert.DeserializeObject<string[]>(_mockPipeline.LoginRequest.Parameters["someArr"]); someArr2.Should().Contain(new[] { "a", "c", "b" }); someArr2.Length.Should().Be(3); } [Fact] [Trait("Category", Category)] public async Task authorize_should_reject_jwt_request_without_client_id() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); var url = _mockPipeline.CreateAuthorizeUrl( responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid client_id"); _mockPipeline.LoginRequest.Should().BeNull(); } [Fact] [Trait("Category", Category)] public async Task authorize_should_reject_jwt_request_if_audience_is_incorrect() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: "invalid", credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); _mockPipeline.LoginRequest.Should().BeNull(); } [Fact] [Trait("Category", Category)] public async Task authorize_should_reject_jwt_request_if_issuer_does_not_match_client_id() { var requestJwt = CreateRequestJwt( issuer: "invalid", audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); _mockPipeline.LoginRequest.Should().BeNull(); } [Fact] [Trait("Category", Category)] public async Task authorize_should_reject_jwt_request_that_includes_request_param() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), new Claim("request", "request") }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); _mockPipeline.LoginRequest.Should().BeNull(); } [Fact] [Trait("Category", Category)] public async Task authorize_should_reject_jwt_request_that_includes_request_uri_param() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), new Claim("request_uri", "request_uri") }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); _mockPipeline.LoginRequest.Should().BeNull(); } [Fact] [Trait("Category", Category)] public async Task authorize_should_reject_jwt_request_if_response_type_does_not_match() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("response_type", "id_token token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo") }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); _mockPipeline.LoginRequest.Should().BeNull(); } [Fact] [Trait("Category", Category)] public async Task authorize_should_reject_jwt_request_if_client_id_does_not_match() { var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("response_type", "id_token"), new Claim("client_id", "invalid"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo") }); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorMessage.Error.Should().Be("invalid_request"); _mockPipeline.ErrorMessage.ErrorDescription.Should().Be("Invalid JWT request"); _mockPipeline.LoginRequest.Should().BeNull(); } [Fact] [Trait("Category", Category)] public async Task authorize_should_ignore_request_uri_when_feature_is_disabled() { _mockPipeline.Options.Endpoints.EnableJwtRequestUri = false; var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); _mockPipeline.JwtRequestMessageHandler.OnInvoke = req => { req.RequestUri.Should().Be(new Uri("http://client_jwt")); return Task.CompletedTask; }; _mockPipeline.JwtRequestMessageHandler.Response.Content = new StringContent(requestJwt); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request_uri = "http://client_jwt" }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorWasCalled.Should().BeTrue(); _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeFalse(); } [Fact] [Trait("Category", Category)] public async Task authorize_should_accept_request_uri_with_valid_jwt() { _mockPipeline.Options.Endpoints.EnableJwtRequestUri = true; var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); _mockPipeline.JwtRequestMessageHandler.OnInvoke = req => { req.RequestUri.Should().Be(new Uri("http://client_jwt")); return Task.CompletedTask; }; _mockPipeline.JwtRequestMessageHandler.Response.Content = new StringContent(requestJwt); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request_uri = "http://client_jwt" }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.LoginRequest.Should().NotBeNull(); _mockPipeline.LoginRequest.ClientId.Should().Be(_client.ClientId); _mockPipeline.LoginRequest.DisplayMode.Should().Be("popup"); _mockPipeline.LoginRequest.UiLocales.Should().Be("ui_locale_value"); _mockPipeline.LoginRequest.IdP.Should().Be("idp_value"); _mockPipeline.LoginRequest.Tenant.Should().Be("tenant_value"); _mockPipeline.LoginRequest.LoginHint.Should().Be("login_hint_value"); _mockPipeline.LoginRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); _mockPipeline.LoginRequest.Parameters.AllKeys.Should().Contain("foo"); _mockPipeline.LoginRequest.Parameters["foo"].Should().Be("123foo"); _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeTrue(); } [Fact] [Trait("Category", Category)] public async Task request_uri_response_returns_500_should_fail() { _mockPipeline.Options.Endpoints.EnableJwtRequestUri = true; _mockPipeline.JwtRequestMessageHandler.Response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request_uri = "http://client_jwt" }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorWasCalled.Should().BeTrue(); _mockPipeline.LoginRequest.Should().BeNull(); _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeTrue(); } [Fact] [Trait("Category", Category)] public async Task request_uri_response_returns_404_should_fail() { _mockPipeline.Options.Endpoints.EnableJwtRequestUri = true; _mockPipeline.JwtRequestMessageHandler.Response = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request_uri = "http://client_jwt" }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorWasCalled.Should().BeTrue(); _mockPipeline.LoginRequest.Should().BeNull(); _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeTrue(); } [Fact] [Trait("Category", Category)] public async Task request_uri_length_too_long_should_fail() { _mockPipeline.Options.Endpoints.EnableJwtRequestUri = true; var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request_uri = "http://" + new string('x', 512) }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorWasCalled.Should().BeTrue(); _mockPipeline.LoginRequest.Should().BeNull(); _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeFalse(); } [Fact] [Trait("Category", Category)] public async Task both_request_and_request_uri_params_should_fail() { _mockPipeline.Options.Endpoints.EnableJwtRequestUri = true; var requestJwt = CreateRequestJwt( issuer: _client.ClientId, audience: IdentityServerPipeline.BaseUrl, credential: new X509SigningCredentials(TestCert.Load()), claims: new[] { new Claim("client_id", _client.ClientId), new Claim("response_type", "id_token"), new Claim("scope", "openid profile"), new Claim("state", "123state"), new Claim("nonce", "123nonce"), new Claim("redirect_uri", "https://client/callback"), new Claim("acr_values", "acr_1 acr_2 tenant:tenant_value idp:idp_value"), new Claim("login_hint", "login_hint_value"), new Claim("display", "popup"), new Claim("ui_locales", "ui_locale_value"), new Claim("foo", "123foo"), }); _mockPipeline.JwtRequestMessageHandler.Response.Content = new StringContent(requestJwt); var url = _mockPipeline.CreateAuthorizeUrl( clientId: _client.ClientId, responseType: "id_token", extra: new { request = requestJwt, request_uri = "http://client_jwt" }); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ErrorWasCalled.Should().BeTrue(); _mockPipeline.LoginRequest.Should().BeNull(); _mockPipeline.JwtRequestMessageHandler.InvokeWasCalled.Should().BeFalse(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAdGroupLabelServiceClientTest { [Category("Autogenerated")][Test] public void GetAdGroupLabelRequestObject() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupLabelRequest request = new GetAdGroupLabelRequest { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), }; gagvr::AdGroupLabel expectedResponse = new gagvr::AdGroupLabel { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupLabel response = client.GetAdGroupLabel(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupLabelRequestObjectAsync() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupLabelRequest request = new GetAdGroupLabelRequest { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), }; gagvr::AdGroupLabel expectedResponse = new gagvr::AdGroupLabel { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupLabel responseCallSettings = await client.GetAdGroupLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupLabel responseCancellationToken = await client.GetAdGroupLabelAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupLabel() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupLabelRequest request = new GetAdGroupLabelRequest { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), }; gagvr::AdGroupLabel expectedResponse = new gagvr::AdGroupLabel { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupLabel response = client.GetAdGroupLabel(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupLabelAsync() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupLabelRequest request = new GetAdGroupLabelRequest { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), }; gagvr::AdGroupLabel expectedResponse = new gagvr::AdGroupLabel { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupLabel responseCallSettings = await client.GetAdGroupLabelAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupLabel responseCancellationToken = await client.GetAdGroupLabelAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupLabelResourceNames() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupLabelRequest request = new GetAdGroupLabelRequest { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), }; gagvr::AdGroupLabel expectedResponse = new gagvr::AdGroupLabel { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupLabel response = client.GetAdGroupLabel(request.ResourceNameAsAdGroupLabelName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupLabelResourceNamesAsync() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupLabelRequest request = new GetAdGroupLabelRequest { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), }; gagvr::AdGroupLabel expectedResponse = new gagvr::AdGroupLabel { ResourceNameAsAdGroupLabelName = gagvr::AdGroupLabelName.FromCustomerAdGroupLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[LABEL_ID]"), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupLabel responseCallSettings = await client.GetAdGroupLabelAsync(request.ResourceNameAsAdGroupLabelName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupLabel responseCancellationToken = await client.GetAdGroupLabelAsync(request.ResourceNameAsAdGroupLabelName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupLabelsRequestObject() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupLabelsRequest request = new MutateAdGroupLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupLabelOperation(), }, PartialFailure = false, ValidateOnly = true, }; MutateAdGroupLabelsResponse expectedResponse = new MutateAdGroupLabelsResponse { Results = { new MutateAdGroupLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupLabelsResponse response = client.MutateAdGroupLabels(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupLabelsRequestObjectAsync() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupLabelsRequest request = new MutateAdGroupLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupLabelOperation(), }, PartialFailure = false, ValidateOnly = true, }; MutateAdGroupLabelsResponse expectedResponse = new MutateAdGroupLabelsResponse { Results = { new MutateAdGroupLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupLabelsResponse responseCallSettings = await client.MutateAdGroupLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupLabelsResponse responseCancellationToken = await client.MutateAdGroupLabelsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupLabels() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupLabelsRequest request = new MutateAdGroupLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupLabelOperation(), }, }; MutateAdGroupLabelsResponse expectedResponse = new MutateAdGroupLabelsResponse { Results = { new MutateAdGroupLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupLabelsResponse response = client.MutateAdGroupLabels(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupLabelsAsync() { moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupLabelService.AdGroupLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupLabelsRequest request = new MutateAdGroupLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupLabelOperation(), }, }; MutateAdGroupLabelsResponse expectedResponse = new MutateAdGroupLabelsResponse { Results = { new MutateAdGroupLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupLabelServiceClient client = new AdGroupLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupLabelsResponse responseCallSettings = await client.MutateAdGroupLabelsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupLabelsResponse responseCancellationToken = await client.MutateAdGroupLabelsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using OrchardCore.Entities; using OrchardCore.Modules; using OrchardCore.Scripting; using OrchardCore.Settings; using OrchardCore.Users.Events; using OrchardCore.Users.Handlers; using OrchardCore.Users.Models; using OrchardCore.Users.Services; using OrchardCore.Users.ViewModels; using IWorkflowManager = OrchardCore.Workflows.Services.IWorkflowManager; using SignInResult = Microsoft.AspNetCore.Identity.SignInResult; namespace OrchardCore.Users.Controllers { [Authorize] public class AccountController : Controller { private readonly IUserService _userService; private readonly SignInManager<IUser> _signInManager; private readonly UserManager<IUser> _userManager; private readonly ILogger _logger; private readonly ISiteService _siteService; private readonly IEnumerable<ILoginFormEvent> _accountEvents; private readonly IScriptingManager _scriptingManager; private readonly IDataProtectionProvider _dataProtectionProvider; private readonly IClock _clock; private readonly IDistributedCache _distributedCache; private readonly IEnumerable<IExternalLoginEventHandler> _externalLoginHandlers; private readonly IStringLocalizer S; public AccountController( IUserService userService, SignInManager<IUser> signInManager, UserManager<IUser> userManager, ILogger<AccountController> logger, ISiteService siteService, IStringLocalizer<AccountController> stringLocalizer, IEnumerable<ILoginFormEvent> accountEvents, IScriptingManager scriptingManager, IClock clock, IDistributedCache distributedCache, IDataProtectionProvider dataProtectionProvider, IEnumerable<IExternalLoginEventHandler> externalLoginHandlers) { _signInManager = signInManager; _userManager = userManager; _userService = userService; _logger = logger; _siteService = siteService; _accountEvents = accountEvents; _scriptingManager = scriptingManager; _clock = clock; _distributedCache = distributedCache; _dataProtectionProvider = dataProtectionProvider; _externalLoginHandlers = externalLoginHandlers; S = stringLocalizer; } [HttpGet] [AllowAnonymous] public async Task<IActionResult> Login(string returnUrl = null) { if (HttpContext.User != null && HttpContext.User.Identity.IsAuthenticated) { returnUrl = null; } // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); var loginSettings = (await _siteService.GetSiteSettingsAsync()).As<LoginSettings>(); if (loginSettings.UseExternalProviderIfOnlyOneDefined) { var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync(); if (schemes.Count() == 1) { var provider = schemes.First().Name; var dataProtector = _dataProtectionProvider.CreateProtector(nameof(DefaultExternalLogin)) .ToTimeLimitedDataProtector(); var token = Guid.NewGuid(); var expiration = new TimeSpan(0, 0, 5); var protectedToken = dataProtector.Protect(token.ToString(), _clock.UtcNow.Add(expiration)); await _distributedCache.SetAsync(token.ToString(), token.ToByteArray(), new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = expiration }); return RedirectToAction(nameof(DefaultExternalLogin), new { protectedToken, returnUrl }); } } ViewData["ReturnUrl"] = returnUrl; return View(); } [HttpGet] [AllowAnonymous] public async Task<IActionResult> DefaultExternalLogin(string protectedToken, string returnUrl = null) { var loginSettings = (await _siteService.GetSiteSettingsAsync()).As<LoginSettings>(); if (loginSettings.UseExternalProviderIfOnlyOneDefined) { var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync(); if (schemes.Count() == 1) { var dataProtector = _dataProtectionProvider.CreateProtector(nameof(DefaultExternalLogin)) .ToTimeLimitedDataProtector(); try { Guid token; if (Guid.TryParse(dataProtector.Unprotect(protectedToken), out token)) { byte[] tokenBytes = await _distributedCache.GetAsync(token.ToString()); var cacheToken = new Guid(tokenBytes); if (token.Equals(cacheToken)) { return ExternalLogin(schemes.First().Name, returnUrl); } } } catch (Exception ex) { _logger.LogError(ex, "An error occurred while validating DefaultExternalLogin token"); } } } return RedirectToAction(nameof(Login)); } private async Task<bool> AddConfirmEmailError(IUser user) { var registrationSettings = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>(); if (registrationSettings.UsersMustValidateEmail == true) { // Require that the users have a confirmed email before they can log on. if (!await _userManager.IsEmailConfirmedAsync(user)) { ModelState.AddModelError(string.Empty, S["You must confirm your email."]); return true; } } return false; } private bool AddUserEnabledError(IUser user) { var localUser = user as User; if (localUser == null || !localUser.IsEnabled) { ModelState.AddModelError(String.Empty, S["Your account is disabled. Please contact an administrator."]); return true; } return false; } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (model == null) throw new ArgumentNullException(nameof(model)); if (TryValidateModel(model) && ModelState.IsValid) { var disableLocalLogin = (await _siteService.GetSiteSettingsAsync()).As<LoginSettings>().DisableLocalLogin; if (disableLocalLogin) { ModelState.AddModelError("", S["Local login is disabled."]); } else { await _accountEvents.InvokeAsync((e, model, modelState) => e.LoggingInAsync(model.UserName, (key, message) => modelState.AddModelError(key, message)), model, ModelState, _logger); var user = await _userManager.FindByNameAsync(model.UserName); // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true if (user != null) { var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, lockoutOnFailure: false); if (result.Succeeded) { if (!await AddConfirmEmailError(user) && !AddUserEnabledError(user)) { result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation(1, "User logged in."); await _accountEvents.InvokeAsync((e, model) => e.LoggedInAsync(model.UserName), model, _logger); return await LoggedInActionResult(user, returnUrl); } } } } ModelState.AddModelError(string.Empty, S["Invalid login attempt."]); await _accountEvents.InvokeAsync((e, model) => e.LoggingInFailedAsync(model.UserName), model, _logger); } } // If we got this far, something failed, redisplay form return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); _logger.LogInformation(4, "User logged out."); return Redirect("~/"); } [HttpGet] public IActionResult ChangePassword() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (TryValidateModel(model) && ModelState.IsValid) { var user = await _userService.GetAuthenticatedUserAsync(User); if (await _userService.ChangePasswordAsync(user, model.CurrentPassword, model.Password, (key, message) => ModelState.AddModelError(key, message))) { return RedirectToLocal(Url.Action("ChangePasswordConfirmation")); } } return View(model); } [HttpGet] public IActionResult ChangePasswordConfirmation() { return View(); } private void AddIdentityErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return Redirect("~/"); } } private async Task<IActionResult> LoggedInActionResult(IUser user, string returnUrl = null, ExternalLoginInfo info = null) { var workflowManager = HttpContext.RequestServices.GetService<IWorkflowManager>(); if (workflowManager != null) { var input = new Dictionary<string, object>(); input["UserName"] = user.UserName; input["Claims"] = info == null ? Enumerable.Empty<SerializableClaim>() : info.Principal.GetSerializableClaims(); input["Roles"] = ((User)user).RoleNames; input["Provider"] = info?.LoginProvider; await workflowManager.TriggerEventAsync(nameof(Workflows.Activities.UserLoggedInEvent), input: input, correlationId: ((User)user).Id.ToString()); } if (info != null) { var identityResult = await _signInManager.UpdateExternalAuthenticationTokensAsync(info); if (!identityResult.Succeeded) { _logger.LogError("Error updating the external authentication tokens."); } } return RedirectToLocal(returnUrl); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return Challenge(properties, provider); } private async Task<SignInResult> ExternalLoginSignInAsync(IUser user, ExternalLoginInfo info) { var claims = info.Principal.GetSerializableClaims(); var userRoles = await _userManager.GetRolesAsync(user); var context = new UpdateRolesContext(user, info.LoginProvider, claims, userRoles); string[] rolesToAdd = new string[0]; string[] rolesToRemove = new string[0]; var loginSettings = (await _siteService.GetSiteSettingsAsync()).As<LoginSettings>(); if (loginSettings.UseScriptToSyncRoles) { try { var jsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var script = $"js: function syncRoles(context) {{\n{loginSettings.SyncRolesScript}\n}}\nvar context={JsonConvert.SerializeObject(context, jsonSerializerSettings)};\nsyncRoles(context);\nreturn context;"; dynamic evaluationResult = _scriptingManager.Evaluate(script, null, null, null); rolesToAdd = (evaluationResult.rolesToAdd as object[]).Select(i => i.ToString()).ToArray(); rolesToRemove = (evaluationResult.rolesToRemove as object[]).Select(i => i.ToString()).ToArray(); } catch (Exception ex) { _logger.LogError(ex, "Error Syncing Roles From External Provider {0}", info.LoginProvider); } } else { foreach (var item in _externalLoginHandlers) { try { await item.UpdateRoles(context); } catch (Exception ex) { _logger.LogError(ex, "{externalLoginHandler} - IExternalLoginHandler.UpdateRoles threw an exception", item.GetType()); } } rolesToAdd = context.RolesToAdd; rolesToRemove = context.RolesToRemove; } await _userManager.AddToRolesAsync(user, rolesToAdd.Distinct()); await _userManager.RemoveFromRolesAsync(user, rolesToRemove.Distinct()); return await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true); } [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { _logger.LogError("Error from external provider: {Error}", remoteError); return RedirectToAction(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { _logger.LogError("Could not get external login info."); return RedirectToAction(nameof(Login)); } var registrationSettings = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>(); var user = await _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey); if (user != null) { if (!await AddConfirmEmailError(user)) { await _accountEvents.InvokeAsync((e, user, modelState) => e.LoggingInAsync(user.UserName, (key, message) => modelState.AddModelError(key, message)), user, ModelState, _logger); var signInResult = await ExternalLoginSignInAsync(user, info); if (signInResult.Succeeded) { return await LoggedInActionResult(user, returnUrl, info); } else { ModelState.AddModelError(string.Empty, S["Invalid login attempt."]); } } } else { var email = info.Principal.FindFirstValue(ClaimTypes.Email) ?? info.Principal.FindFirstValue("email"); if (!string.IsNullOrWhiteSpace(email)) user = await _userManager.FindByEmailAsync(email); ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; if (user != null) { // Link external login to an existing user ViewData["UserName"] = user.UserName; ViewData["Email"] = email; return View("LinkExternalLogin"); } else { // no user could be matched, check if a new user can register if (registrationSettings.UsersCanRegister == UserRegistrationType.NoRegistration) { string message = S["Site does not allow user registration."]; _logger.LogWarning(message); ModelState.AddModelError("", message); } else { var externalLoginViewModel = new RegisterExternalLoginViewModel(); externalLoginViewModel.NoPassword = registrationSettings.NoPasswordForExternalUsers; externalLoginViewModel.NoEmail = registrationSettings.NoEmailForExternalUsers; externalLoginViewModel.NoUsername = registrationSettings.NoUsernameForExternalUsers; // If registrationSettings.NoUsernameForExternalUsers is true, this username will not be used externalLoginViewModel.UserName = await GenerateUsername(info); externalLoginViewModel.Email = email; // The user doesn't exist, if no information required, we can create the account locally // instead of redirecting to the ExternalLogin var noInformationRequired = externalLoginViewModel.NoPassword && externalLoginViewModel.NoEmail && externalLoginViewModel.NoUsername; if (noInformationRequired) { user = await this.RegisterUser(new RegisterViewModel() { UserName = externalLoginViewModel.UserName, Email = externalLoginViewModel.Email, Password = null, ConfirmPassword = null }, S["Confirm your account"], _logger); // If the registration was successful we can link the external provider and redirect the user if (user != null) { var identityResult = await _signInManager.UserManager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName)); if (identityResult.Succeeded) { _logger.LogInformation(3, "User account linked to {loginProvider} provider.", info.LoginProvider); // We have created/linked to the local user, so we must verify the login. // If it does not succeed, the user is not allowed to login var signInResult = await ExternalLoginSignInAsync(user, info); if (signInResult.Succeeded) { return await LoggedInActionResult(user, returnUrl, info); } else { ModelState.AddModelError(string.Empty, S["Invalid login attempt."]); return View(nameof(Login)); } } AddIdentityErrors(identityResult); } } return View("RegisterExternalLogin", externalLoginViewModel); } } } return RedirectToAction(nameof(Login)); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> RegisterExternalLogin(RegisterExternalLoginViewModel model, string returnUrl = null) { IUser user = null; var settings = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>(); var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { _logger.LogWarning("Error loading external login info."); return NotFound(); } if (settings.UsersCanRegister == UserRegistrationType.NoRegistration) { _logger.LogWarning("Site does not allow user registration.", model.UserName, model.Email); return NotFound(); } ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; model.NoPassword = settings.NoPasswordForExternalUsers; model.NoEmail = settings.NoEmailForExternalUsers; model.NoUsername = settings.NoUsernameForExternalUsers; ModelState.Clear(); if (model.NoEmail) { var email = info.Principal.FindFirstValue(ClaimTypes.Email) ?? info.Principal.FindFirstValue("email"); model.Email = email; } if (model.NoUsername) { model.UserName = await GenerateUsername(info); } if (model.NoPassword) { model.Password = null; model.ConfirmPassword = null; } if (TryValidateModel(model) && ModelState.IsValid) { user = await this.RegisterUser(new RegisterViewModel() { UserName = model.UserName, Email = model.Email, Password = model.Password, ConfirmPassword = model.ConfirmPassword }, S["Confirm your account"], _logger); if (user is null) { ModelState.AddModelError(string.Empty, "Registration Failed."); } else { var identityResult = await _signInManager.UserManager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName)); if (identityResult.Succeeded) { _logger.LogInformation(3, "User account linked to {provider} provider.", info.LoginProvider); // we have created/linked to the local user, so we must verify the login. If it does not succeed, // the user is not allowed to login var signInResult = await ExternalLoginSignInAsync(user, info); if (signInResult.Succeeded) { return await LoggedInActionResult(user, returnUrl, info); } } AddIdentityErrors(identityResult); } } return View("RegisterExternalLogin", model); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> LinkExternalLogin(LinkExternalLoginViewModel model, string returnUrl = null) { var settings = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>(); var info = await _signInManager.GetExternalLoginInfoAsync(); var email = info.Principal.FindFirstValue(ClaimTypes.Email) ?? info.Principal.FindFirstValue("email"); var user = await _userManager.FindByEmailAsync(email); if (info == null) { _logger.LogWarning("Error loading external login info."); return NotFound(); } if (user == null) { _logger.LogWarning("Suspicious login detected from external provider. {provider} with key [{providerKey}] for {identity}", info.LoginProvider, info.ProviderKey, info.Principal?.Identity?.Name); return RedirectToAction(nameof(Login)); } await _accountEvents.InvokeAsync((e, model, modelState) => e.LoggingInAsync(user.UserName, (key, message) => modelState.AddModelError(key, message)), model, ModelState, _logger); var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); if (!signInResult.Succeeded) { user = null; ModelState.AddModelError(string.Empty, S["Invalid login attempt."]); } else { var identityResult = await _signInManager.UserManager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName)); if (identityResult.Succeeded) { _logger.LogInformation(3, "User account linked to {provider} provider.", info.LoginProvider); // we have created/linked to the local user, so we must verify the login. If it does not succeed, // the user is not allowed to login if ((await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false)).Succeeded) { return await LoggedInActionResult(user, returnUrl, info); } } AddIdentityErrors(identityResult); } return RedirectToAction(nameof(Login)); } [HttpGet] public async Task<IActionResult> ExternalLogins() { var user = await _userManager.GetUserAsync(User); if (user == null) { return Forbid(); } var model = new ExternalLoginsViewModel { CurrentLogins = await _userManager.GetLoginsAsync(user) }; model.OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()) .Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider)) .ToList(); model.ShowRemoveButton = await _userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1; //model.StatusMessage = StatusMessage; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LinkLogin(string provider) { // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action(nameof(LinkLoginCallback)); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return new ChallengeResult(provider, properties); } [HttpGet] public async Task<IActionResult> LinkLoginCallback() { var user = await _userManager.GetUserAsync(User); if (user == null) { _logger.LogError("Unable to load user with ID '{UserId}'.", _userManager.GetUserId(User)); return RedirectToAction(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { _logger.LogError("Unexpected error occurred loading external login info for user '{UserName}'.", user.UserName); return RedirectToAction(nameof(Login)); } var result = await _userManager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName)); if (!result.Succeeded) { _logger.LogError("Unexpected error occurred adding external login info for user '{UserName}'.", user.UserName); return RedirectToAction(nameof(Login)); } // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); //StatusMessage = "The external login was added."; return RedirectToAction(nameof(ExternalLogins)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel model) { var user = await _userManager.GetUserAsync(User); if (user == null) { _logger.LogError("Unable to load user with ID '{UserId}'.", _userManager.GetUserId(User)); return RedirectToAction(nameof(Login)); } var result = await _userManager.RemoveLoginAsync(user, model.LoginProvider, model.ProviderKey); if (!result.Succeeded) { _logger.LogError("Unexpected error occurred adding external login info for user '{UserName}'.", user.UserName); return RedirectToAction(nameof(Login)); } await _signInManager.SignInAsync(user, isPersistent: false); //StatusMessage = "The external login was removed."; return RedirectToAction(nameof(ExternalLogins)); } private async Task<string> GenerateUsername(ExternalLoginInfo info) { var now = new TimeSpan(_clock.UtcNow.Ticks) - new TimeSpan(DateTime.UnixEpoch.Ticks); var ret = string.Concat("u" + Convert.ToInt32(now.TotalSeconds).ToString()); var registrationSettings = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>(); var externalClaims = info == null ? null : info.Principal.GetSerializableClaims(); if (registrationSettings.UseScriptToGenerateUsername) { var context = new { userName = string.Empty, loginProvider = info?.LoginProvider, externalClaims }; var jsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var script = $"js: function generateUsername(context) {{\n{registrationSettings.GenerateUsernameScript}\n}}\nvar context = {JsonConvert.SerializeObject(context, jsonSerializerSettings)};\ngenerateUsername(context);\nreturn context;"; try { dynamic evaluationResult = _scriptingManager.Evaluate(script, null, null, null); if (evaluationResult?.userName == null) throw new Exception("GenerateUsernameScript did not return a username"); return evaluationResult.userName; } catch (Exception ex) { _logger.LogError(ex, "Error evaluating GenerateUsernameScript({context})", context); } } else { var userNames = new Dictionary<Type, string>(); foreach (var item in _externalLoginHandlers) { try { var userName = await item.GenerateUserName(info.LoginProvider, externalClaims.ToArray()); if (!string.IsNullOrWhiteSpace(userName)) { if (userNames.Count == 0) { ret = userName; } userNames.Add(item.GetType(), userName); } } catch (Exception ex) { _logger.LogError(ex, "{externalLoginHandler} - IExternalLoginHandler.GenerateUserName threw an exception", item.GetType()); } } if (userNames.Count > 1) { _logger.LogWarning("More than one IExternalLoginHandler generated username. Used first one registered, {externalLoginHandler}", userNames.FirstOrDefault().Key); } } return ret; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.CSharp; using Microsoft.Build.Tasks.Xaml; using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Globalization; using System.IO; using System.Reflection; using System.Xaml; using Microsoft.Build.Evaluation; using Xunit; namespace Microsoft.Build.UnitTests { internal static class XamlTestHelpers { // the following are used for the tests in XamlTaskFactory_Tests.cs and XamlDataDrivenToolTask_Tests.cs // make as robust as possible private const string fakeXml = @"<ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`> <Rule Name=`FakeTask`> <BoolProperty Name=`Always` Switch=`/always` /> <!-- Basic types --> <BoolProperty Name=`BasicReversible` Switch=`/Br` ReverseSwitch=`/BrF` /> <BoolProperty Name=`BasicNonreversible` Switch=`/Bn` /> <EnumProperty Name=`BasicString`> <EnumValue Name=`Enum1` Switch=`/Bs1` /> <EnumValue Name=`Enum2` Switch=`/Bs2` /> </EnumProperty> <StringListProperty Name=`BasicStringArray` Switch=`/Bsa` /> <IntProperty Name=`BasicInteger` Switch=`/Bi` /> <StringProperty Name=`BasicFileWSwitch` Switch=`/Bfws` /> <StringProperty Name=`BasicFileWOSwitch` /> <StringProperty Name=`BasicDirectory` /> <DynamicEnumProperty Name=`BasicDynamicEnum` /> <!-- More Complex types --> <BoolProperty Name=`ComplexReversible` Switch=`/Cr:CT` ReverseSwitch=`/Cr:CF` Separator=`:` /> <BoolProperty Name=`ComplexNonreversibleWArgument` Switch=`/Cnrwa`> <Argument Property=`ComplexFile` IsRequired=`true` /> </BoolProperty> <EnumProperty Name=`ComplexString` IsRequired=`true`> <EnumValue Name=`LegalValue1` Switch=`/Lv1` /> <EnumValue Name=`LegalValue2` Switch=`/Lv2` /> </EnumProperty> <StringListProperty Name=`ComplexStringArray` Switch=`/Csa` Separator=`;` /> <StringProperty Name=`ComplexFileNoDefault` /> <IntProperty Name=`ComplexInteger` Switch=`/Ci` MinValue=`64` MaxValue=`255` /> <!-- Dependencies, fallbacks, and so on --> <BoolProperty Name=`OtherNonreversible` Switch=`/Onr`> <Argument IsRequired=`true` Property=`ComplexFileNoDefault` /> </BoolProperty> <StringProperty Name=`ComplexDirectory` /> <StringListProperty Name=`OutputFile` Switch=`/Of` Separator=`;` /> <StringListProperty Name=`InputFile` /> </Rule> </ProjectSchemaDefinitions> "; public const string QuotingQuotesXml = @"<ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`> <Rule Name=`FakeTask`> <!-- Quoted: If the quote mechanism isn't working, all the tests will fail with exceptions related to compiling. --> <EnumProperty Name=`Quoted`> <EnumValue Name=`Value1` Switch=`/foo: &quot;bar&quot;` /> </EnumProperty> </Rule> </ProjectSchemaDefinitions> "; public const string QuotingBackslashXml = @"<ProjectSchemaDefinitions xmlns=`clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework` xmlns:x=`http://schemas.microsoft.com/winfx/2006/xaml` xmlns:sys=`clr-namespace:System;assembly=mscorlib` xmlns:impl=`clr-namespace:Microsoft.VisualStudio.Project.Contracts.Implementation;assembly=Microsoft.VisualStudio.Project.Contracts.Implementation`> <Rule Name=`FakeTask`> <!-- Quoted: If the quote mechanism isn't working, all the tests will fail with exceptions related to compiling. --> <EnumProperty Name=`Quoted`> <EnumValue Name=`Value2` Switch=`/foo: a\$bar` /> </EnumProperty> </Rule> </ProjectSchemaDefinitions> "; private static string s_pathToMSBuildBinaries = null; /// <summary> /// Returns the path to the MSBuild binaries /// </summary> public static string PathToMSBuildBinaries { get { if (s_pathToMSBuildBinaries == null) { Toolset currentToolset = ProjectCollection.GlobalProjectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion); Assert.NotNull(currentToolset); // String.Format("For some reason, we couldn't get the current ({0}) toolset!", ObjectModelHelpers.MSBuildDefaultToolsVersion) s_pathToMSBuildBinaries = currentToolset.ToolsPath; } return s_pathToMSBuildBinaries; } } public static Assembly SetupGeneratedCode() { return SetupGeneratedCode(fakeXml); } public static Assembly SetupGeneratedCode(string xml) { TaskParser tp = null; try { tp = LoadAndParse(xml, "FakeTask"); } catch (XamlParseException) { Assert.True(false, "Parse of FakeTask XML failed"); } TaskGenerator tg = new TaskGenerator(tp); CodeCompileUnit compileUnit = tg.GenerateCode(); CodeDomProvider codeGenerator = CodeDomProvider.CreateProvider("CSharp"); using (StringWriter sw = new StringWriter(CultureInfo.CurrentCulture)) { CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = true; options.BracingStyle = "C"; codeGenerator.GenerateCodeFromCompileUnit(compileUnit, sw, options); CSharpCodeProvider provider = new CSharpCodeProvider(); // Build the parameters for source compilation. CompilerParameters cp = new CompilerParameters(); // Add an assembly reference. cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.Data.dll"); cp.ReferencedAssemblies.Add("System.Xml.dll"); cp.ReferencedAssemblies.Add(Path.Combine(PathToMSBuildBinaries, "Microsoft.Build.Framework.dll")); cp.ReferencedAssemblies.Add(Path.Combine(PathToMSBuildBinaries, "Microsoft.Build.Utilities.Core.dll")); cp.ReferencedAssemblies.Add(Path.Combine(PathToMSBuildBinaries, "Microsoft.Build.Tasks.Core.dll")); // Generate an executable instead of // a class library. cp.GenerateExecutable = false; // Set the assembly file name to generate. cp.GenerateInMemory = true; // Invoke compilation CompilerResults cr = provider.CompileAssemblyFromSource(cp, sw.ToString()); foreach (CompilerError error in cr.Errors) { Console.WriteLine(error.ToString()); } if (cr.Errors.Count > 0) { Console.WriteLine(sw.ToString()); } Assert.Empty(cr.Errors); if (cr.Errors.Count > 0) { foreach (CompilerError error in cr.Errors) { Console.WriteLine(error.ErrorText); } } return cr.CompiledAssembly; } } /// <summary> /// used for testing. Will load snippets of xml into the task generator /// </summary> /// <param name="s"></param> /// <returns></returns> public static TaskParser LoadAndParse(string s, string desiredRule) { TaskParser tp = new TaskParser(); tp.Parse(s.Replace("`", "\""), desiredRule); return tp; } /// <summary> /// This method is a method to set any property in a task to a certain value /// </summary> /// <param name="propertyName"></param> /// <param name="parameters"></param> public static void SetProperty(object instance, string propertyName, params object[] parameters) { try { instance.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, instance, parameters, CultureInfo.CurrentCulture); } catch (TargetInvocationException e) { throw e.InnerException; } } /// <summary> /// This method returns the certain attribute for a property (the value it is set to) /// </summary> /// <param name="propertyName"></param> /// <param name="parameters"></param> public static object GetProperty(object instance, string propertyName, params object[] parameters) { try { return instance.GetType().InvokeMember(propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty, null, instance, parameters, CultureInfo.CurrentCulture); } catch (TargetInvocationException e) { throw e.InnerException; } } /// <summary> /// This method gets called to call the GenerateResponseFileCommands method /// </summary> /// <param name="taskObject"></param> /// <returns></returns> public static string GenerateCommandLine(object task) { try { return (string)task.GetType().InvokeMember("GetCommandLine_ForUnitTestsOnly", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, task, new object[] { }); } catch (TargetInvocationException e) { throw e.InnerException; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprRecienNacido class. /// </summary> [Serializable] public partial class AprRecienNacidoCollection : ActiveList<AprRecienNacido, AprRecienNacidoCollection> { public AprRecienNacidoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprRecienNacidoCollection</returns> public AprRecienNacidoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprRecienNacido o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_RecienNacido table. /// </summary> [Serializable] public partial class AprRecienNacido : ActiveRecord<AprRecienNacido>, IActiveRecord { #region .ctors and Default Settings public AprRecienNacido() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprRecienNacido(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprRecienNacido(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprRecienNacido(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_RecienNacido", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdRecienNacido = new TableSchema.TableColumn(schema); colvarIdRecienNacido.ColumnName = "idRecienNacido"; colvarIdRecienNacido.DataType = DbType.Int32; colvarIdRecienNacido.MaxLength = 0; colvarIdRecienNacido.AutoIncrement = true; colvarIdRecienNacido.IsNullable = false; colvarIdRecienNacido.IsPrimaryKey = true; colvarIdRecienNacido.IsForeignKey = false; colvarIdRecienNacido.IsReadOnly = false; colvarIdRecienNacido.DefaultSetting = @""; colvarIdRecienNacido.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdRecienNacido); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema); colvarIdPaciente.ColumnName = "idPaciente"; colvarIdPaciente.DataType = DbType.Int32; colvarIdPaciente.MaxLength = 0; colvarIdPaciente.AutoIncrement = false; colvarIdPaciente.IsNullable = true; colvarIdPaciente.IsPrimaryKey = false; colvarIdPaciente.IsForeignKey = false; colvarIdPaciente.IsReadOnly = false; colvarIdPaciente.DefaultSetting = @""; colvarIdPaciente.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPaciente); TableSchema.TableColumn colvarPeso = new TableSchema.TableColumn(schema); colvarPeso.ColumnName = "Peso"; colvarPeso.DataType = DbType.Double; colvarPeso.MaxLength = 0; colvarPeso.AutoIncrement = false; colvarPeso.IsNullable = true; colvarPeso.IsPrimaryKey = false; colvarPeso.IsForeignKey = false; colvarPeso.IsReadOnly = false; colvarPeso.DefaultSetting = @""; colvarPeso.ForeignKeyTableName = ""; schema.Columns.Add(colvarPeso); TableSchema.TableColumn colvarPerimetroCefalico = new TableSchema.TableColumn(schema); colvarPerimetroCefalico.ColumnName = "PerimetroCefalico"; colvarPerimetroCefalico.DataType = DbType.Double; colvarPerimetroCefalico.MaxLength = 0; colvarPerimetroCefalico.AutoIncrement = false; colvarPerimetroCefalico.IsNullable = true; colvarPerimetroCefalico.IsPrimaryKey = false; colvarPerimetroCefalico.IsForeignKey = false; colvarPerimetroCefalico.IsReadOnly = false; colvarPerimetroCefalico.DefaultSetting = @""; colvarPerimetroCefalico.ForeignKeyTableName = ""; schema.Columns.Add(colvarPerimetroCefalico); TableSchema.TableColumn colvarLongitud = new TableSchema.TableColumn(schema); colvarLongitud.ColumnName = "Longitud"; colvarLongitud.DataType = DbType.Double; colvarLongitud.MaxLength = 0; colvarLongitud.AutoIncrement = false; colvarLongitud.IsNullable = true; colvarLongitud.IsPrimaryKey = false; colvarLongitud.IsForeignKey = false; colvarLongitud.IsReadOnly = false; colvarLongitud.DefaultSetting = @""; colvarLongitud.ForeignKeyTableName = ""; schema.Columns.Add(colvarLongitud); TableSchema.TableColumn colvarAPGAR1 = new TableSchema.TableColumn(schema); colvarAPGAR1.ColumnName = "APGAR1"; colvarAPGAR1.DataType = DbType.Int32; colvarAPGAR1.MaxLength = 0; colvarAPGAR1.AutoIncrement = false; colvarAPGAR1.IsNullable = true; colvarAPGAR1.IsPrimaryKey = false; colvarAPGAR1.IsForeignKey = false; colvarAPGAR1.IsReadOnly = false; colvarAPGAR1.DefaultSetting = @""; colvarAPGAR1.ForeignKeyTableName = ""; schema.Columns.Add(colvarAPGAR1); TableSchema.TableColumn colvarAPGAR5 = new TableSchema.TableColumn(schema); colvarAPGAR5.ColumnName = "APGAR5"; colvarAPGAR5.DataType = DbType.Int32; colvarAPGAR5.MaxLength = 0; colvarAPGAR5.AutoIncrement = false; colvarAPGAR5.IsNullable = true; colvarAPGAR5.IsPrimaryKey = false; colvarAPGAR5.IsForeignKey = false; colvarAPGAR5.IsReadOnly = false; colvarAPGAR5.DefaultSetting = @""; colvarAPGAR5.ForeignKeyTableName = ""; schema.Columns.Add(colvarAPGAR5); TableSchema.TableColumn colvarPesoAlAlta = new TableSchema.TableColumn(schema); colvarPesoAlAlta.ColumnName = "PesoAlAlta"; colvarPesoAlAlta.DataType = DbType.Double; colvarPesoAlAlta.MaxLength = 0; colvarPesoAlAlta.AutoIncrement = false; colvarPesoAlAlta.IsNullable = true; colvarPesoAlAlta.IsPrimaryKey = false; colvarPesoAlAlta.IsForeignKey = false; colvarPesoAlAlta.IsReadOnly = false; colvarPesoAlAlta.DefaultSetting = @""; colvarPesoAlAlta.ForeignKeyTableName = ""; schema.Columns.Add(colvarPesoAlAlta); TableSchema.TableColumn colvarGemelar = new TableSchema.TableColumn(schema); colvarGemelar.ColumnName = "Gemelar"; colvarGemelar.DataType = DbType.Boolean; colvarGemelar.MaxLength = 0; colvarGemelar.AutoIncrement = false; colvarGemelar.IsNullable = true; colvarGemelar.IsPrimaryKey = false; colvarGemelar.IsForeignKey = false; colvarGemelar.IsReadOnly = false; colvarGemelar.DefaultSetting = @""; colvarGemelar.ForeignKeyTableName = ""; schema.Columns.Add(colvarGemelar); TableSchema.TableColumn colvarNroGesta = new TableSchema.TableColumn(schema); colvarNroGesta.ColumnName = "NroGesta"; colvarNroGesta.DataType = DbType.Int32; colvarNroGesta.MaxLength = 0; colvarNroGesta.AutoIncrement = false; colvarNroGesta.IsNullable = true; colvarNroGesta.IsPrimaryKey = false; colvarNroGesta.IsForeignKey = false; colvarNroGesta.IsReadOnly = false; colvarNroGesta.DefaultSetting = @""; colvarNroGesta.ForeignKeyTableName = ""; schema.Columns.Add(colvarNroGesta); TableSchema.TableColumn colvarDiagnosticoNeonatalTemporal = new TableSchema.TableColumn(schema); colvarDiagnosticoNeonatalTemporal.ColumnName = "DiagnosticoNeonatalTemporal"; colvarDiagnosticoNeonatalTemporal.DataType = DbType.AnsiString; colvarDiagnosticoNeonatalTemporal.MaxLength = 50; colvarDiagnosticoNeonatalTemporal.AutoIncrement = false; colvarDiagnosticoNeonatalTemporal.IsNullable = true; colvarDiagnosticoNeonatalTemporal.IsPrimaryKey = false; colvarDiagnosticoNeonatalTemporal.IsForeignKey = false; colvarDiagnosticoNeonatalTemporal.IsReadOnly = false; colvarDiagnosticoNeonatalTemporal.DefaultSetting = @""; colvarDiagnosticoNeonatalTemporal.ForeignKeyTableName = ""; schema.Columns.Add(colvarDiagnosticoNeonatalTemporal); TableSchema.TableColumn colvarDiagnosticoNeonatalFisico = new TableSchema.TableColumn(schema); colvarDiagnosticoNeonatalFisico.ColumnName = "DiagnosticoNeonatalFisico"; colvarDiagnosticoNeonatalFisico.DataType = DbType.AnsiString; colvarDiagnosticoNeonatalFisico.MaxLength = 50; colvarDiagnosticoNeonatalFisico.AutoIncrement = false; colvarDiagnosticoNeonatalFisico.IsNullable = true; colvarDiagnosticoNeonatalFisico.IsPrimaryKey = false; colvarDiagnosticoNeonatalFisico.IsForeignKey = false; colvarDiagnosticoNeonatalFisico.IsReadOnly = false; colvarDiagnosticoNeonatalFisico.DefaultSetting = @""; colvarDiagnosticoNeonatalFisico.ForeignKeyTableName = ""; schema.Columns.Add(colvarDiagnosticoNeonatalFisico); TableSchema.TableColumn colvarScreeningRealizado = new TableSchema.TableColumn(schema); colvarScreeningRealizado.ColumnName = "ScreeningRealizado"; colvarScreeningRealizado.DataType = DbType.Boolean; colvarScreeningRealizado.MaxLength = 0; colvarScreeningRealizado.AutoIncrement = false; colvarScreeningRealizado.IsNullable = true; colvarScreeningRealizado.IsPrimaryKey = false; colvarScreeningRealizado.IsForeignKey = false; colvarScreeningRealizado.IsReadOnly = false; colvarScreeningRealizado.DefaultSetting = @""; colvarScreeningRealizado.ForeignKeyTableName = ""; schema.Columns.Add(colvarScreeningRealizado); TableSchema.TableColumn colvarScreeningNormal = new TableSchema.TableColumn(schema); colvarScreeningNormal.ColumnName = "ScreeningNormal"; colvarScreeningNormal.DataType = DbType.Boolean; colvarScreeningNormal.MaxLength = 0; colvarScreeningNormal.AutoIncrement = false; colvarScreeningNormal.IsNullable = true; colvarScreeningNormal.IsPrimaryKey = false; colvarScreeningNormal.IsForeignKey = false; colvarScreeningNormal.IsReadOnly = false; colvarScreeningNormal.DefaultSetting = @""; colvarScreeningNormal.ForeignKeyTableName = ""; schema.Columns.Add(colvarScreeningNormal); TableSchema.TableColumn colvarOEARealizado = new TableSchema.TableColumn(schema); colvarOEARealizado.ColumnName = "OEARealizado"; colvarOEARealizado.DataType = DbType.AnsiString; colvarOEARealizado.MaxLength = 50; colvarOEARealizado.AutoIncrement = false; colvarOEARealizado.IsNullable = true; colvarOEARealizado.IsPrimaryKey = false; colvarOEARealizado.IsForeignKey = false; colvarOEARealizado.IsReadOnly = false; colvarOEARealizado.DefaultSetting = @""; colvarOEARealizado.ForeignKeyTableName = ""; schema.Columns.Add(colvarOEARealizado); TableSchema.TableColumn colvarEmbarazoNormal = new TableSchema.TableColumn(schema); colvarEmbarazoNormal.ColumnName = "EmbarazoNormal"; colvarEmbarazoNormal.DataType = DbType.Boolean; colvarEmbarazoNormal.MaxLength = 0; colvarEmbarazoNormal.AutoIncrement = false; colvarEmbarazoNormal.IsNullable = true; colvarEmbarazoNormal.IsPrimaryKey = false; colvarEmbarazoNormal.IsForeignKey = false; colvarEmbarazoNormal.IsReadOnly = false; colvarEmbarazoNormal.DefaultSetting = @""; colvarEmbarazoNormal.ForeignKeyTableName = ""; schema.Columns.Add(colvarEmbarazoNormal); TableSchema.TableColumn colvarIdTipoParto = new TableSchema.TableColumn(schema); colvarIdTipoParto.ColumnName = "idTipoParto"; colvarIdTipoParto.DataType = DbType.Int32; colvarIdTipoParto.MaxLength = 0; colvarIdTipoParto.AutoIncrement = false; colvarIdTipoParto.IsNullable = true; colvarIdTipoParto.IsPrimaryKey = false; colvarIdTipoParto.IsForeignKey = true; colvarIdTipoParto.IsReadOnly = false; colvarIdTipoParto.DefaultSetting = @""; colvarIdTipoParto.ForeignKeyTableName = "APR_TipoParto"; schema.Columns.Add(colvarIdTipoParto); TableSchema.TableColumn colvarPesquizaNeonatal = new TableSchema.TableColumn(schema); colvarPesquizaNeonatal.ColumnName = "PesquizaNeonatal"; colvarPesquizaNeonatal.DataType = DbType.Boolean; colvarPesquizaNeonatal.MaxLength = 0; colvarPesquizaNeonatal.AutoIncrement = false; colvarPesquizaNeonatal.IsNullable = true; colvarPesquizaNeonatal.IsPrimaryKey = false; colvarPesquizaNeonatal.IsForeignKey = false; colvarPesquizaNeonatal.IsReadOnly = false; colvarPesquizaNeonatal.DefaultSetting = @""; colvarPesquizaNeonatal.ForeignKeyTableName = ""; schema.Columns.Add(colvarPesquizaNeonatal); TableSchema.TableColumn colvarHb12meses = new TableSchema.TableColumn(schema); colvarHb12meses.ColumnName = "Hb12meses"; colvarHb12meses.DataType = DbType.Boolean; colvarHb12meses.MaxLength = 0; colvarHb12meses.AutoIncrement = false; colvarHb12meses.IsNullable = true; colvarHb12meses.IsPrimaryKey = false; colvarHb12meses.IsForeignKey = false; colvarHb12meses.IsReadOnly = false; colvarHb12meses.DefaultSetting = @""; colvarHb12meses.ForeignKeyTableName = ""; schema.Columns.Add(colvarHb12meses); TableSchema.TableColumn colvarTA3 = new TableSchema.TableColumn(schema); colvarTA3.ColumnName = "TA3"; colvarTA3.DataType = DbType.Boolean; colvarTA3.MaxLength = 0; colvarTA3.AutoIncrement = false; colvarTA3.IsNullable = true; colvarTA3.IsPrimaryKey = false; colvarTA3.IsForeignKey = false; colvarTA3.IsReadOnly = false; colvarTA3.DefaultSetting = @""; colvarTA3.ForeignKeyTableName = ""; schema.Columns.Add(colvarTA3); TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema); colvarCreatedBy.ColumnName = "CreatedBy"; colvarCreatedBy.DataType = DbType.AnsiString; colvarCreatedBy.MaxLength = 50; colvarCreatedBy.AutoIncrement = false; colvarCreatedBy.IsNullable = true; colvarCreatedBy.IsPrimaryKey = false; colvarCreatedBy.IsForeignKey = false; colvarCreatedBy.IsReadOnly = false; colvarCreatedBy.DefaultSetting = @""; colvarCreatedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedBy); TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema); colvarCreatedOn.ColumnName = "CreatedOn"; colvarCreatedOn.DataType = DbType.DateTime; colvarCreatedOn.MaxLength = 0; colvarCreatedOn.AutoIncrement = false; colvarCreatedOn.IsNullable = true; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @""; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "ModifiedBy"; colvarModifiedBy.DataType = DbType.AnsiString; colvarModifiedBy.MaxLength = 50; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = true; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = false; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @""; colvarModifiedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedBy); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "ModifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = true; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @""; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_RecienNacido",schema); } } #endregion #region Props [XmlAttribute("IdRecienNacido")] [Bindable(true)] public int IdRecienNacido { get { return GetColumnValue<int>(Columns.IdRecienNacido); } set { SetColumnValue(Columns.IdRecienNacido, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("IdPaciente")] [Bindable(true)] public int? IdPaciente { get { return GetColumnValue<int?>(Columns.IdPaciente); } set { SetColumnValue(Columns.IdPaciente, value); } } [XmlAttribute("Peso")] [Bindable(true)] public double? Peso { get { return GetColumnValue<double?>(Columns.Peso); } set { SetColumnValue(Columns.Peso, value); } } [XmlAttribute("PerimetroCefalico")] [Bindable(true)] public double? PerimetroCefalico { get { return GetColumnValue<double?>(Columns.PerimetroCefalico); } set { SetColumnValue(Columns.PerimetroCefalico, value); } } [XmlAttribute("Longitud")] [Bindable(true)] public double? Longitud { get { return GetColumnValue<double?>(Columns.Longitud); } set { SetColumnValue(Columns.Longitud, value); } } [XmlAttribute("APGAR1")] [Bindable(true)] public int? APGAR1 { get { return GetColumnValue<int?>(Columns.APGAR1); } set { SetColumnValue(Columns.APGAR1, value); } } [XmlAttribute("APGAR5")] [Bindable(true)] public int? APGAR5 { get { return GetColumnValue<int?>(Columns.APGAR5); } set { SetColumnValue(Columns.APGAR5, value); } } [XmlAttribute("PesoAlAlta")] [Bindable(true)] public double? PesoAlAlta { get { return GetColumnValue<double?>(Columns.PesoAlAlta); } set { SetColumnValue(Columns.PesoAlAlta, value); } } [XmlAttribute("Gemelar")] [Bindable(true)] public bool? Gemelar { get { return GetColumnValue<bool?>(Columns.Gemelar); } set { SetColumnValue(Columns.Gemelar, value); } } [XmlAttribute("NroGesta")] [Bindable(true)] public int? NroGesta { get { return GetColumnValue<int?>(Columns.NroGesta); } set { SetColumnValue(Columns.NroGesta, value); } } [XmlAttribute("DiagnosticoNeonatalTemporal")] [Bindable(true)] public string DiagnosticoNeonatalTemporal { get { return GetColumnValue<string>(Columns.DiagnosticoNeonatalTemporal); } set { SetColumnValue(Columns.DiagnosticoNeonatalTemporal, value); } } [XmlAttribute("DiagnosticoNeonatalFisico")] [Bindable(true)] public string DiagnosticoNeonatalFisico { get { return GetColumnValue<string>(Columns.DiagnosticoNeonatalFisico); } set { SetColumnValue(Columns.DiagnosticoNeonatalFisico, value); } } [XmlAttribute("ScreeningRealizado")] [Bindable(true)] public bool? ScreeningRealizado { get { return GetColumnValue<bool?>(Columns.ScreeningRealizado); } set { SetColumnValue(Columns.ScreeningRealizado, value); } } [XmlAttribute("ScreeningNormal")] [Bindable(true)] public bool? ScreeningNormal { get { return GetColumnValue<bool?>(Columns.ScreeningNormal); } set { SetColumnValue(Columns.ScreeningNormal, value); } } [XmlAttribute("OEARealizado")] [Bindable(true)] public string OEARealizado { get { return GetColumnValue<string>(Columns.OEARealizado); } set { SetColumnValue(Columns.OEARealizado, value); } } [XmlAttribute("EmbarazoNormal")] [Bindable(true)] public bool? EmbarazoNormal { get { return GetColumnValue<bool?>(Columns.EmbarazoNormal); } set { SetColumnValue(Columns.EmbarazoNormal, value); } } [XmlAttribute("IdTipoParto")] [Bindable(true)] public int? IdTipoParto { get { return GetColumnValue<int?>(Columns.IdTipoParto); } set { SetColumnValue(Columns.IdTipoParto, value); } } [XmlAttribute("PesquizaNeonatal")] [Bindable(true)] public bool? PesquizaNeonatal { get { return GetColumnValue<bool?>(Columns.PesquizaNeonatal); } set { SetColumnValue(Columns.PesquizaNeonatal, value); } } [XmlAttribute("Hb12meses")] [Bindable(true)] public bool? Hb12meses { get { return GetColumnValue<bool?>(Columns.Hb12meses); } set { SetColumnValue(Columns.Hb12meses, value); } } [XmlAttribute("TA3")] [Bindable(true)] public bool? TA3 { get { return GetColumnValue<bool?>(Columns.TA3); } set { SetColumnValue(Columns.TA3, value); } } [XmlAttribute("CreatedBy")] [Bindable(true)] public string CreatedBy { get { return GetColumnValue<string>(Columns.CreatedBy); } set { SetColumnValue(Columns.CreatedBy, value); } } [XmlAttribute("CreatedOn")] [Bindable(true)] public DateTime? CreatedOn { get { return GetColumnValue<DateTime?>(Columns.CreatedOn); } set { SetColumnValue(Columns.CreatedOn, value); } } [XmlAttribute("ModifiedBy")] [Bindable(true)] public string ModifiedBy { get { return GetColumnValue<string>(Columns.ModifiedBy); } set { SetColumnValue(Columns.ModifiedBy, value); } } [XmlAttribute("ModifiedOn")] [Bindable(true)] public DateTime? ModifiedOn { get { return GetColumnValue<DateTime?>(Columns.ModifiedOn); } set { SetColumnValue(Columns.ModifiedOn, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.AprRelRecienNacidoDefectoCongenitoCollection colAprRelRecienNacidoDefectoCongenitoRecords; public DalSic.AprRelRecienNacidoDefectoCongenitoCollection AprRelRecienNacidoDefectoCongenitoRecords { get { if(colAprRelRecienNacidoDefectoCongenitoRecords == null) { colAprRelRecienNacidoDefectoCongenitoRecords = new DalSic.AprRelRecienNacidoDefectoCongenitoCollection().Where(AprRelRecienNacidoDefectoCongenito.Columns.IdRecienNacido, IdRecienNacido).Load(); colAprRelRecienNacidoDefectoCongenitoRecords.ListChanged += new ListChangedEventHandler(colAprRelRecienNacidoDefectoCongenitoRecords_ListChanged); } return colAprRelRecienNacidoDefectoCongenitoRecords; } set { colAprRelRecienNacidoDefectoCongenitoRecords = value; colAprRelRecienNacidoDefectoCongenitoRecords.ListChanged += new ListChangedEventHandler(colAprRelRecienNacidoDefectoCongenitoRecords_ListChanged); } } void colAprRelRecienNacidoDefectoCongenitoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprRelRecienNacidoDefectoCongenitoRecords[e.NewIndex].IdRecienNacido = IdRecienNacido; } } private DalSic.AprRelRecienNacidoEnfermedadCollection colAprRelRecienNacidoEnfermedadRecords; public DalSic.AprRelRecienNacidoEnfermedadCollection AprRelRecienNacidoEnfermedadRecords { get { if(colAprRelRecienNacidoEnfermedadRecords == null) { colAprRelRecienNacidoEnfermedadRecords = new DalSic.AprRelRecienNacidoEnfermedadCollection().Where(AprRelRecienNacidoEnfermedad.Columns.IdRecienNacido, IdRecienNacido).Load(); colAprRelRecienNacidoEnfermedadRecords.ListChanged += new ListChangedEventHandler(colAprRelRecienNacidoEnfermedadRecords_ListChanged); } return colAprRelRecienNacidoEnfermedadRecords; } set { colAprRelRecienNacidoEnfermedadRecords = value; colAprRelRecienNacidoEnfermedadRecords.ListChanged += new ListChangedEventHandler(colAprRelRecienNacidoEnfermedadRecords_ListChanged); } } void colAprRelRecienNacidoEnfermedadRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprRelRecienNacidoEnfermedadRecords[e.NewIndex].IdRecienNacido = IdRecienNacido; } } #endregion #region ForeignKey Properties /// <summary> /// Returns a AprTipoParto ActiveRecord object related to this AprRecienNacido /// /// </summary> public DalSic.AprTipoParto AprTipoParto { get { return DalSic.AprTipoParto.FetchByID(this.IdTipoParto); } set { SetColumnValue("idTipoParto", value.IdTipoParto); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEfector,int? varIdPaciente,double? varPeso,double? varPerimetroCefalico,double? varLongitud,int? varAPGAR1,int? varAPGAR5,double? varPesoAlAlta,bool? varGemelar,int? varNroGesta,string varDiagnosticoNeonatalTemporal,string varDiagnosticoNeonatalFisico,bool? varScreeningRealizado,bool? varScreeningNormal,string varOEARealizado,bool? varEmbarazoNormal,int? varIdTipoParto,bool? varPesquizaNeonatal,bool? varHb12meses,bool? varTA3,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn) { AprRecienNacido item = new AprRecienNacido(); item.IdEfector = varIdEfector; item.IdPaciente = varIdPaciente; item.Peso = varPeso; item.PerimetroCefalico = varPerimetroCefalico; item.Longitud = varLongitud; item.APGAR1 = varAPGAR1; item.APGAR5 = varAPGAR5; item.PesoAlAlta = varPesoAlAlta; item.Gemelar = varGemelar; item.NroGesta = varNroGesta; item.DiagnosticoNeonatalTemporal = varDiagnosticoNeonatalTemporal; item.DiagnosticoNeonatalFisico = varDiagnosticoNeonatalFisico; item.ScreeningRealizado = varScreeningRealizado; item.ScreeningNormal = varScreeningNormal; item.OEARealizado = varOEARealizado; item.EmbarazoNormal = varEmbarazoNormal; item.IdTipoParto = varIdTipoParto; item.PesquizaNeonatal = varPesquizaNeonatal; item.Hb12meses = varHb12meses; item.TA3 = varTA3; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdRecienNacido,int varIdEfector,int? varIdPaciente,double? varPeso,double? varPerimetroCefalico,double? varLongitud,int? varAPGAR1,int? varAPGAR5,double? varPesoAlAlta,bool? varGemelar,int? varNroGesta,string varDiagnosticoNeonatalTemporal,string varDiagnosticoNeonatalFisico,bool? varScreeningRealizado,bool? varScreeningNormal,string varOEARealizado,bool? varEmbarazoNormal,int? varIdTipoParto,bool? varPesquizaNeonatal,bool? varHb12meses,bool? varTA3,string varCreatedBy,DateTime? varCreatedOn,string varModifiedBy,DateTime? varModifiedOn) { AprRecienNacido item = new AprRecienNacido(); item.IdRecienNacido = varIdRecienNacido; item.IdEfector = varIdEfector; item.IdPaciente = varIdPaciente; item.Peso = varPeso; item.PerimetroCefalico = varPerimetroCefalico; item.Longitud = varLongitud; item.APGAR1 = varAPGAR1; item.APGAR5 = varAPGAR5; item.PesoAlAlta = varPesoAlAlta; item.Gemelar = varGemelar; item.NroGesta = varNroGesta; item.DiagnosticoNeonatalTemporal = varDiagnosticoNeonatalTemporal; item.DiagnosticoNeonatalFisico = varDiagnosticoNeonatalFisico; item.ScreeningRealizado = varScreeningRealizado; item.ScreeningNormal = varScreeningNormal; item.OEARealizado = varOEARealizado; item.EmbarazoNormal = varEmbarazoNormal; item.IdTipoParto = varIdTipoParto; item.PesquizaNeonatal = varPesquizaNeonatal; item.Hb12meses = varHb12meses; item.TA3 = varTA3; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdRecienNacidoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdPacienteColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn PesoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn PerimetroCefalicoColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn LongitudColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn APGAR1Column { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn APGAR5Column { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn PesoAlAltaColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn GemelarColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn NroGestaColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn DiagnosticoNeonatalTemporalColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn DiagnosticoNeonatalFisicoColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn ScreeningRealizadoColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn ScreeningNormalColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn OEARealizadoColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn EmbarazoNormalColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn IdTipoPartoColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn PesquizaNeonatalColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn Hb12mesesColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn TA3Column { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn CreatedByColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn CreatedOnColumn { get { return Schema.Columns[22]; } } public static TableSchema.TableColumn ModifiedByColumn { get { return Schema.Columns[23]; } } public static TableSchema.TableColumn ModifiedOnColumn { get { return Schema.Columns[24]; } } #endregion #region Columns Struct public struct Columns { public static string IdRecienNacido = @"idRecienNacido"; public static string IdEfector = @"idEfector"; public static string IdPaciente = @"idPaciente"; public static string Peso = @"Peso"; public static string PerimetroCefalico = @"PerimetroCefalico"; public static string Longitud = @"Longitud"; public static string APGAR1 = @"APGAR1"; public static string APGAR5 = @"APGAR5"; public static string PesoAlAlta = @"PesoAlAlta"; public static string Gemelar = @"Gemelar"; public static string NroGesta = @"NroGesta"; public static string DiagnosticoNeonatalTemporal = @"DiagnosticoNeonatalTemporal"; public static string DiagnosticoNeonatalFisico = @"DiagnosticoNeonatalFisico"; public static string ScreeningRealizado = @"ScreeningRealizado"; public static string ScreeningNormal = @"ScreeningNormal"; public static string OEARealizado = @"OEARealizado"; public static string EmbarazoNormal = @"EmbarazoNormal"; public static string IdTipoParto = @"idTipoParto"; public static string PesquizaNeonatal = @"PesquizaNeonatal"; public static string Hb12meses = @"Hb12meses"; public static string TA3 = @"TA3"; public static string CreatedBy = @"CreatedBy"; public static string CreatedOn = @"CreatedOn"; public static string ModifiedBy = @"ModifiedBy"; public static string ModifiedOn = @"ModifiedOn"; } #endregion #region Update PK Collections public void SetPKValues() { if (colAprRelRecienNacidoDefectoCongenitoRecords != null) { foreach (DalSic.AprRelRecienNacidoDefectoCongenito item in colAprRelRecienNacidoDefectoCongenitoRecords) { if (item.IdRecienNacido != IdRecienNacido) { item.IdRecienNacido = IdRecienNacido; } } } if (colAprRelRecienNacidoEnfermedadRecords != null) { foreach (DalSic.AprRelRecienNacidoEnfermedad item in colAprRelRecienNacidoEnfermedadRecords) { if (item.IdRecienNacido != IdRecienNacido) { item.IdRecienNacido = IdRecienNacido; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colAprRelRecienNacidoDefectoCongenitoRecords != null) { colAprRelRecienNacidoDefectoCongenitoRecords.SaveAll(); } if (colAprRelRecienNacidoEnfermedadRecords != null) { colAprRelRecienNacidoEnfermedadRecords.SaveAll(); } } #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the GuardiaTriage class. /// </summary> [Serializable] public partial class GuardiaTriageCollection : ActiveList<GuardiaTriage, GuardiaTriageCollection> { public GuardiaTriageCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>GuardiaTriageCollection</returns> public GuardiaTriageCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { GuardiaTriage o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Guardia_Triage table. /// </summary> [Serializable] public partial class GuardiaTriage : ActiveRecord<GuardiaTriage>, IActiveRecord { #region .ctors and Default Settings public GuardiaTriage() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public GuardiaTriage(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public GuardiaTriage(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public GuardiaTriage(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Guardia_Triage", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "id"; colvarId.DataType = DbType.Int32; colvarId.MaxLength = 0; colvarId.AutoIncrement = true; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @""; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarRegistroGuardia = new TableSchema.TableColumn(schema); colvarRegistroGuardia.ColumnName = "registroGuardia"; colvarRegistroGuardia.DataType = DbType.Int32; colvarRegistroGuardia.MaxLength = 0; colvarRegistroGuardia.AutoIncrement = false; colvarRegistroGuardia.IsNullable = false; colvarRegistroGuardia.IsPrimaryKey = false; colvarRegistroGuardia.IsForeignKey = true; colvarRegistroGuardia.IsReadOnly = false; colvarRegistroGuardia.DefaultSetting = @""; colvarRegistroGuardia.ForeignKeyTableName = "Guardia_Registros"; schema.Columns.Add(colvarRegistroGuardia); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = true; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarFechaHora = new TableSchema.TableColumn(schema); colvarFechaHora.ColumnName = "fechaHora"; colvarFechaHora.DataType = DbType.DateTime; colvarFechaHora.MaxLength = 0; colvarFechaHora.AutoIncrement = false; colvarFechaHora.IsNullable = false; colvarFechaHora.IsPrimaryKey = false; colvarFechaHora.IsForeignKey = false; colvarFechaHora.IsReadOnly = false; colvarFechaHora.DefaultSetting = @""; colvarFechaHora.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaHora); TableSchema.TableColumn colvarTensionArterial = new TableSchema.TableColumn(schema); colvarTensionArterial.ColumnName = "tensionArterial"; colvarTensionArterial.DataType = DbType.AnsiString; colvarTensionArterial.MaxLength = 50; colvarTensionArterial.AutoIncrement = false; colvarTensionArterial.IsNullable = true; colvarTensionArterial.IsPrimaryKey = false; colvarTensionArterial.IsForeignKey = false; colvarTensionArterial.IsReadOnly = false; colvarTensionArterial.DefaultSetting = @""; colvarTensionArterial.ForeignKeyTableName = ""; schema.Columns.Add(colvarTensionArterial); TableSchema.TableColumn colvarFrecuenciaCardiaca = new TableSchema.TableColumn(schema); colvarFrecuenciaCardiaca.ColumnName = "frecuenciaCardiaca"; colvarFrecuenciaCardiaca.DataType = DbType.Int32; colvarFrecuenciaCardiaca.MaxLength = 0; colvarFrecuenciaCardiaca.AutoIncrement = false; colvarFrecuenciaCardiaca.IsNullable = true; colvarFrecuenciaCardiaca.IsPrimaryKey = false; colvarFrecuenciaCardiaca.IsForeignKey = false; colvarFrecuenciaCardiaca.IsReadOnly = false; colvarFrecuenciaCardiaca.DefaultSetting = @""; colvarFrecuenciaCardiaca.ForeignKeyTableName = ""; schema.Columns.Add(colvarFrecuenciaCardiaca); TableSchema.TableColumn colvarFrecuenciaRespiratoria = new TableSchema.TableColumn(schema); colvarFrecuenciaRespiratoria.ColumnName = "frecuenciaRespiratoria"; colvarFrecuenciaRespiratoria.DataType = DbType.Int32; colvarFrecuenciaRespiratoria.MaxLength = 0; colvarFrecuenciaRespiratoria.AutoIncrement = false; colvarFrecuenciaRespiratoria.IsNullable = true; colvarFrecuenciaRespiratoria.IsPrimaryKey = false; colvarFrecuenciaRespiratoria.IsForeignKey = false; colvarFrecuenciaRespiratoria.IsReadOnly = false; colvarFrecuenciaRespiratoria.DefaultSetting = @""; colvarFrecuenciaRespiratoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarFrecuenciaRespiratoria); TableSchema.TableColumn colvarTemperatura = new TableSchema.TableColumn(schema); colvarTemperatura.ColumnName = "temperatura"; colvarTemperatura.DataType = DbType.Double; colvarTemperatura.MaxLength = 0; colvarTemperatura.AutoIncrement = false; colvarTemperatura.IsNullable = true; colvarTemperatura.IsPrimaryKey = false; colvarTemperatura.IsForeignKey = false; colvarTemperatura.IsReadOnly = false; colvarTemperatura.DefaultSetting = @""; colvarTemperatura.ForeignKeyTableName = ""; schema.Columns.Add(colvarTemperatura); TableSchema.TableColumn colvarSaturacionOxigeno = new TableSchema.TableColumn(schema); colvarSaturacionOxigeno.ColumnName = "saturacionOxigeno"; colvarSaturacionOxigeno.DataType = DbType.Int32; colvarSaturacionOxigeno.MaxLength = 0; colvarSaturacionOxigeno.AutoIncrement = false; colvarSaturacionOxigeno.IsNullable = true; colvarSaturacionOxigeno.IsPrimaryKey = false; colvarSaturacionOxigeno.IsForeignKey = false; colvarSaturacionOxigeno.IsReadOnly = false; colvarSaturacionOxigeno.DefaultSetting = @""; colvarSaturacionOxigeno.ForeignKeyTableName = ""; schema.Columns.Add(colvarSaturacionOxigeno); TableSchema.TableColumn colvarGlasgowOcular = new TableSchema.TableColumn(schema); colvarGlasgowOcular.ColumnName = "glasgow_ocular"; colvarGlasgowOcular.DataType = DbType.Int32; colvarGlasgowOcular.MaxLength = 0; colvarGlasgowOcular.AutoIncrement = false; colvarGlasgowOcular.IsNullable = true; colvarGlasgowOcular.IsPrimaryKey = false; colvarGlasgowOcular.IsForeignKey = false; colvarGlasgowOcular.IsReadOnly = false; colvarGlasgowOcular.DefaultSetting = @""; colvarGlasgowOcular.ForeignKeyTableName = ""; schema.Columns.Add(colvarGlasgowOcular); TableSchema.TableColumn colvarGlasgowVerbal = new TableSchema.TableColumn(schema); colvarGlasgowVerbal.ColumnName = "glasgow_verbal"; colvarGlasgowVerbal.DataType = DbType.Int32; colvarGlasgowVerbal.MaxLength = 0; colvarGlasgowVerbal.AutoIncrement = false; colvarGlasgowVerbal.IsNullable = true; colvarGlasgowVerbal.IsPrimaryKey = false; colvarGlasgowVerbal.IsForeignKey = false; colvarGlasgowVerbal.IsReadOnly = false; colvarGlasgowVerbal.DefaultSetting = @""; colvarGlasgowVerbal.ForeignKeyTableName = ""; schema.Columns.Add(colvarGlasgowVerbal); TableSchema.TableColumn colvarGlasgowMotor = new TableSchema.TableColumn(schema); colvarGlasgowMotor.ColumnName = "glasgow_motor"; colvarGlasgowMotor.DataType = DbType.Int32; colvarGlasgowMotor.MaxLength = 0; colvarGlasgowMotor.AutoIncrement = false; colvarGlasgowMotor.IsNullable = true; colvarGlasgowMotor.IsPrimaryKey = false; colvarGlasgowMotor.IsForeignKey = false; colvarGlasgowMotor.IsReadOnly = false; colvarGlasgowMotor.DefaultSetting = @""; colvarGlasgowMotor.ForeignKeyTableName = ""; schema.Columns.Add(colvarGlasgowMotor); TableSchema.TableColumn colvarPeso = new TableSchema.TableColumn(schema); colvarPeso.ColumnName = "peso"; colvarPeso.DataType = DbType.Double; colvarPeso.MaxLength = 0; colvarPeso.AutoIncrement = false; colvarPeso.IsNullable = true; colvarPeso.IsPrimaryKey = false; colvarPeso.IsForeignKey = false; colvarPeso.IsReadOnly = false; colvarPeso.DefaultSetting = @""; colvarPeso.ForeignKeyTableName = ""; schema.Columns.Add(colvarPeso); TableSchema.TableColumn colvarPupilasTamano = new TableSchema.TableColumn(schema); colvarPupilasTamano.ColumnName = "pupilas_tamano"; colvarPupilasTamano.DataType = DbType.AnsiString; colvarPupilasTamano.MaxLength = 50; colvarPupilasTamano.AutoIncrement = false; colvarPupilasTamano.IsNullable = true; colvarPupilasTamano.IsPrimaryKey = false; colvarPupilasTamano.IsForeignKey = false; colvarPupilasTamano.IsReadOnly = false; colvarPupilasTamano.DefaultSetting = @""; colvarPupilasTamano.ForeignKeyTableName = ""; schema.Columns.Add(colvarPupilasTamano); TableSchema.TableColumn colvarPupilasReactividad = new TableSchema.TableColumn(schema); colvarPupilasReactividad.ColumnName = "pupilas_reactividad"; colvarPupilasReactividad.DataType = DbType.AnsiString; colvarPupilasReactividad.MaxLength = 50; colvarPupilasReactividad.AutoIncrement = false; colvarPupilasReactividad.IsNullable = true; colvarPupilasReactividad.IsPrimaryKey = false; colvarPupilasReactividad.IsForeignKey = false; colvarPupilasReactividad.IsReadOnly = false; colvarPupilasReactividad.DefaultSetting = @""; colvarPupilasReactividad.ForeignKeyTableName = ""; schema.Columns.Add(colvarPupilasReactividad); TableSchema.TableColumn colvarPupilasSimetria = new TableSchema.TableColumn(schema); colvarPupilasSimetria.ColumnName = "pupilas_simetria"; colvarPupilasSimetria.DataType = DbType.AnsiString; colvarPupilasSimetria.MaxLength = 50; colvarPupilasSimetria.AutoIncrement = false; colvarPupilasSimetria.IsNullable = true; colvarPupilasSimetria.IsPrimaryKey = false; colvarPupilasSimetria.IsForeignKey = false; colvarPupilasSimetria.IsReadOnly = false; colvarPupilasSimetria.DefaultSetting = @""; colvarPupilasSimetria.ForeignKeyTableName = ""; schema.Columns.Add(colvarPupilasSimetria); TableSchema.TableColumn colvarSensorio = new TableSchema.TableColumn(schema); colvarSensorio.ColumnName = "sensorio"; colvarSensorio.DataType = DbType.AnsiString; colvarSensorio.MaxLength = 50; colvarSensorio.AutoIncrement = false; colvarSensorio.IsNullable = true; colvarSensorio.IsPrimaryKey = false; colvarSensorio.IsForeignKey = false; colvarSensorio.IsReadOnly = false; colvarSensorio.DefaultSetting = @""; colvarSensorio.ForeignKeyTableName = ""; schema.Columns.Add(colvarSensorio); TableSchema.TableColumn colvarSibilancia = new TableSchema.TableColumn(schema); colvarSibilancia.ColumnName = "sibilancia"; colvarSibilancia.DataType = DbType.AnsiString; colvarSibilancia.MaxLength = 50; colvarSibilancia.AutoIncrement = false; colvarSibilancia.IsNullable = true; colvarSibilancia.IsPrimaryKey = false; colvarSibilancia.IsForeignKey = false; colvarSibilancia.IsReadOnly = false; colvarSibilancia.DefaultSetting = @""; colvarSibilancia.ForeignKeyTableName = ""; schema.Columns.Add(colvarSibilancia); TableSchema.TableColumn colvarMuscAccesorio = new TableSchema.TableColumn(schema); colvarMuscAccesorio.ColumnName = "muscAccesorio"; colvarMuscAccesorio.DataType = DbType.AnsiString; colvarMuscAccesorio.MaxLength = 50; colvarMuscAccesorio.AutoIncrement = false; colvarMuscAccesorio.IsNullable = true; colvarMuscAccesorio.IsPrimaryKey = false; colvarMuscAccesorio.IsForeignKey = false; colvarMuscAccesorio.IsReadOnly = false; colvarMuscAccesorio.DefaultSetting = @""; colvarMuscAccesorio.ForeignKeyTableName = ""; schema.Columns.Add(colvarMuscAccesorio); TableSchema.TableColumn colvarIngresoAlimentacionCant = new TableSchema.TableColumn(schema); colvarIngresoAlimentacionCant.ColumnName = "ingresoAlimentacionCant"; colvarIngresoAlimentacionCant.DataType = DbType.AnsiString; colvarIngresoAlimentacionCant.MaxLength = 50; colvarIngresoAlimentacionCant.AutoIncrement = false; colvarIngresoAlimentacionCant.IsNullable = true; colvarIngresoAlimentacionCant.IsPrimaryKey = false; colvarIngresoAlimentacionCant.IsForeignKey = false; colvarIngresoAlimentacionCant.IsReadOnly = false; colvarIngresoAlimentacionCant.DefaultSetting = @""; colvarIngresoAlimentacionCant.ForeignKeyTableName = ""; schema.Columns.Add(colvarIngresoAlimentacionCant); TableSchema.TableColumn colvarIngresoAlimentacionTipo = new TableSchema.TableColumn(schema); colvarIngresoAlimentacionTipo.ColumnName = "ingresoAlimentacionTipo"; colvarIngresoAlimentacionTipo.DataType = DbType.AnsiString; colvarIngresoAlimentacionTipo.MaxLength = 50; colvarIngresoAlimentacionTipo.AutoIncrement = false; colvarIngresoAlimentacionTipo.IsNullable = true; colvarIngresoAlimentacionTipo.IsPrimaryKey = false; colvarIngresoAlimentacionTipo.IsForeignKey = false; colvarIngresoAlimentacionTipo.IsReadOnly = false; colvarIngresoAlimentacionTipo.DefaultSetting = @""; colvarIngresoAlimentacionTipo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIngresoAlimentacionTipo); TableSchema.TableColumn colvarIngresoSolucion = new TableSchema.TableColumn(schema); colvarIngresoSolucion.ColumnName = "ingresoSolucion"; colvarIngresoSolucion.DataType = DbType.AnsiString; colvarIngresoSolucion.MaxLength = 50; colvarIngresoSolucion.AutoIncrement = false; colvarIngresoSolucion.IsNullable = true; colvarIngresoSolucion.IsPrimaryKey = false; colvarIngresoSolucion.IsForeignKey = false; colvarIngresoSolucion.IsReadOnly = false; colvarIngresoSolucion.DefaultSetting = @""; colvarIngresoSolucion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIngresoSolucion); TableSchema.TableColumn colvarIngresoOtros = new TableSchema.TableColumn(schema); colvarIngresoOtros.ColumnName = "ingresoOtros"; colvarIngresoOtros.DataType = DbType.AnsiString; colvarIngresoOtros.MaxLength = 300; colvarIngresoOtros.AutoIncrement = false; colvarIngresoOtros.IsNullable = true; colvarIngresoOtros.IsPrimaryKey = false; colvarIngresoOtros.IsForeignKey = false; colvarIngresoOtros.IsReadOnly = false; colvarIngresoOtros.DefaultSetting = @""; colvarIngresoOtros.ForeignKeyTableName = ""; schema.Columns.Add(colvarIngresoOtros); TableSchema.TableColumn colvarEgresoDepos = new TableSchema.TableColumn(schema); colvarEgresoDepos.ColumnName = "egresoDepos"; colvarEgresoDepos.DataType = DbType.AnsiString; colvarEgresoDepos.MaxLength = 50; colvarEgresoDepos.AutoIncrement = false; colvarEgresoDepos.IsNullable = true; colvarEgresoDepos.IsPrimaryKey = false; colvarEgresoDepos.IsForeignKey = false; colvarEgresoDepos.IsReadOnly = false; colvarEgresoDepos.DefaultSetting = @""; colvarEgresoDepos.ForeignKeyTableName = ""; schema.Columns.Add(colvarEgresoDepos); TableSchema.TableColumn colvarEgresoOrina = new TableSchema.TableColumn(schema); colvarEgresoOrina.ColumnName = "egresoOrina"; colvarEgresoOrina.DataType = DbType.AnsiString; colvarEgresoOrina.MaxLength = 50; colvarEgresoOrina.AutoIncrement = false; colvarEgresoOrina.IsNullable = true; colvarEgresoOrina.IsPrimaryKey = false; colvarEgresoOrina.IsForeignKey = false; colvarEgresoOrina.IsReadOnly = false; colvarEgresoOrina.DefaultSetting = @""; colvarEgresoOrina.ForeignKeyTableName = ""; schema.Columns.Add(colvarEgresoOrina); TableSchema.TableColumn colvarEgresoVomito = new TableSchema.TableColumn(schema); colvarEgresoVomito.ColumnName = "egresoVomito"; colvarEgresoVomito.DataType = DbType.AnsiString; colvarEgresoVomito.MaxLength = 50; colvarEgresoVomito.AutoIncrement = false; colvarEgresoVomito.IsNullable = true; colvarEgresoVomito.IsPrimaryKey = false; colvarEgresoVomito.IsForeignKey = false; colvarEgresoVomito.IsReadOnly = false; colvarEgresoVomito.DefaultSetting = @""; colvarEgresoVomito.ForeignKeyTableName = ""; schema.Columns.Add(colvarEgresoVomito); TableSchema.TableColumn colvarEgresoSng = new TableSchema.TableColumn(schema); colvarEgresoSng.ColumnName = "egresoSng"; colvarEgresoSng.DataType = DbType.AnsiString; colvarEgresoSng.MaxLength = 50; colvarEgresoSng.AutoIncrement = false; colvarEgresoSng.IsNullable = true; colvarEgresoSng.IsPrimaryKey = false; colvarEgresoSng.IsForeignKey = false; colvarEgresoSng.IsReadOnly = false; colvarEgresoSng.DefaultSetting = @""; colvarEgresoSng.ForeignKeyTableName = ""; schema.Columns.Add(colvarEgresoSng); TableSchema.TableColumn colvarEgresoOtros = new TableSchema.TableColumn(schema); colvarEgresoOtros.ColumnName = "egresoOtros"; colvarEgresoOtros.DataType = DbType.AnsiString; colvarEgresoOtros.MaxLength = 300; colvarEgresoOtros.AutoIncrement = false; colvarEgresoOtros.IsNullable = true; colvarEgresoOtros.IsPrimaryKey = false; colvarEgresoOtros.IsForeignKey = false; colvarEgresoOtros.IsReadOnly = false; colvarEgresoOtros.DefaultSetting = @""; colvarEgresoOtros.ForeignKeyTableName = ""; schema.Columns.Add(colvarEgresoOtros); TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema); colvarObservaciones.ColumnName = "observaciones"; colvarObservaciones.DataType = DbType.AnsiString; colvarObservaciones.MaxLength = -1; colvarObservaciones.AutoIncrement = false; colvarObservaciones.IsNullable = true; colvarObservaciones.IsPrimaryKey = false; colvarObservaciones.IsForeignKey = false; colvarObservaciones.IsReadOnly = false; colvarObservaciones.DefaultSetting = @""; colvarObservaciones.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservaciones); TableSchema.TableColumn colvarAuditUser = new TableSchema.TableColumn(schema); colvarAuditUser.ColumnName = "audit_user"; colvarAuditUser.DataType = DbType.Int32; colvarAuditUser.MaxLength = 0; colvarAuditUser.AutoIncrement = false; colvarAuditUser.IsNullable = true; colvarAuditUser.IsPrimaryKey = false; colvarAuditUser.IsForeignKey = false; colvarAuditUser.IsReadOnly = false; colvarAuditUser.DefaultSetting = @""; colvarAuditUser.ForeignKeyTableName = ""; schema.Columns.Add(colvarAuditUser); TableSchema.TableColumn colvarEscalaDelDolor = new TableSchema.TableColumn(schema); colvarEscalaDelDolor.ColumnName = "escalaDelDolor"; colvarEscalaDelDolor.DataType = DbType.Int32; colvarEscalaDelDolor.MaxLength = 0; colvarEscalaDelDolor.AutoIncrement = false; colvarEscalaDelDolor.IsNullable = true; colvarEscalaDelDolor.IsPrimaryKey = false; colvarEscalaDelDolor.IsForeignKey = false; colvarEscalaDelDolor.IsReadOnly = false; colvarEscalaDelDolor.DefaultSetting = @""; colvarEscalaDelDolor.ForeignKeyTableName = ""; schema.Columns.Add(colvarEscalaDelDolor); TableSchema.TableColumn colvarIdClasificacion = new TableSchema.TableColumn(schema); colvarIdClasificacion.ColumnName = "idClasificacion"; colvarIdClasificacion.DataType = DbType.Int32; colvarIdClasificacion.MaxLength = 0; colvarIdClasificacion.AutoIncrement = false; colvarIdClasificacion.IsNullable = true; colvarIdClasificacion.IsPrimaryKey = false; colvarIdClasificacion.IsForeignKey = false; colvarIdClasificacion.IsReadOnly = false; colvarIdClasificacion.DefaultSetting = @""; colvarIdClasificacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdClasificacion); TableSchema.TableColumn colvarTriage = new TableSchema.TableColumn(schema); colvarTriage.ColumnName = "triage"; colvarTriage.DataType = DbType.Boolean; colvarTriage.MaxLength = 0; colvarTriage.AutoIncrement = false; colvarTriage.IsNullable = true; colvarTriage.IsPrimaryKey = false; colvarTriage.IsForeignKey = false; colvarTriage.IsReadOnly = false; colvarTriage.DefaultSetting = @"((0))"; colvarTriage.ForeignKeyTableName = ""; schema.Columns.Add(colvarTriage); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Guardia_Triage",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public int Id { get { return GetColumnValue<int>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("RegistroGuardia")] [Bindable(true)] public int RegistroGuardia { get { return GetColumnValue<int>(Columns.RegistroGuardia); } set { SetColumnValue(Columns.RegistroGuardia, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int? IdEfector { get { return GetColumnValue<int?>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("FechaHora")] [Bindable(true)] public DateTime FechaHora { get { return GetColumnValue<DateTime>(Columns.FechaHora); } set { SetColumnValue(Columns.FechaHora, value); } } [XmlAttribute("TensionArterial")] [Bindable(true)] public string TensionArterial { get { return GetColumnValue<string>(Columns.TensionArterial); } set { SetColumnValue(Columns.TensionArterial, value); } } [XmlAttribute("FrecuenciaCardiaca")] [Bindable(true)] public int? FrecuenciaCardiaca { get { return GetColumnValue<int?>(Columns.FrecuenciaCardiaca); } set { SetColumnValue(Columns.FrecuenciaCardiaca, value); } } [XmlAttribute("FrecuenciaRespiratoria")] [Bindable(true)] public int? FrecuenciaRespiratoria { get { return GetColumnValue<int?>(Columns.FrecuenciaRespiratoria); } set { SetColumnValue(Columns.FrecuenciaRespiratoria, value); } } [XmlAttribute("Temperatura")] [Bindable(true)] public double? Temperatura { get { return GetColumnValue<double?>(Columns.Temperatura); } set { SetColumnValue(Columns.Temperatura, value); } } [XmlAttribute("SaturacionOxigeno")] [Bindable(true)] public int? SaturacionOxigeno { get { return GetColumnValue<int?>(Columns.SaturacionOxigeno); } set { SetColumnValue(Columns.SaturacionOxigeno, value); } } [XmlAttribute("GlasgowOcular")] [Bindable(true)] public int? GlasgowOcular { get { return GetColumnValue<int?>(Columns.GlasgowOcular); } set { SetColumnValue(Columns.GlasgowOcular, value); } } [XmlAttribute("GlasgowVerbal")] [Bindable(true)] public int? GlasgowVerbal { get { return GetColumnValue<int?>(Columns.GlasgowVerbal); } set { SetColumnValue(Columns.GlasgowVerbal, value); } } [XmlAttribute("GlasgowMotor")] [Bindable(true)] public int? GlasgowMotor { get { return GetColumnValue<int?>(Columns.GlasgowMotor); } set { SetColumnValue(Columns.GlasgowMotor, value); } } [XmlAttribute("Peso")] [Bindable(true)] public double? Peso { get { return GetColumnValue<double?>(Columns.Peso); } set { SetColumnValue(Columns.Peso, value); } } [XmlAttribute("PupilasTamano")] [Bindable(true)] public string PupilasTamano { get { return GetColumnValue<string>(Columns.PupilasTamano); } set { SetColumnValue(Columns.PupilasTamano, value); } } [XmlAttribute("PupilasReactividad")] [Bindable(true)] public string PupilasReactividad { get { return GetColumnValue<string>(Columns.PupilasReactividad); } set { SetColumnValue(Columns.PupilasReactividad, value); } } [XmlAttribute("PupilasSimetria")] [Bindable(true)] public string PupilasSimetria { get { return GetColumnValue<string>(Columns.PupilasSimetria); } set { SetColumnValue(Columns.PupilasSimetria, value); } } [XmlAttribute("Sensorio")] [Bindable(true)] public string Sensorio { get { return GetColumnValue<string>(Columns.Sensorio); } set { SetColumnValue(Columns.Sensorio, value); } } [XmlAttribute("Sibilancia")] [Bindable(true)] public string Sibilancia { get { return GetColumnValue<string>(Columns.Sibilancia); } set { SetColumnValue(Columns.Sibilancia, value); } } [XmlAttribute("MuscAccesorio")] [Bindable(true)] public string MuscAccesorio { get { return GetColumnValue<string>(Columns.MuscAccesorio); } set { SetColumnValue(Columns.MuscAccesorio, value); } } [XmlAttribute("IngresoAlimentacionCant")] [Bindable(true)] public string IngresoAlimentacionCant { get { return GetColumnValue<string>(Columns.IngresoAlimentacionCant); } set { SetColumnValue(Columns.IngresoAlimentacionCant, value); } } [XmlAttribute("IngresoAlimentacionTipo")] [Bindable(true)] public string IngresoAlimentacionTipo { get { return GetColumnValue<string>(Columns.IngresoAlimentacionTipo); } set { SetColumnValue(Columns.IngresoAlimentacionTipo, value); } } [XmlAttribute("IngresoSolucion")] [Bindable(true)] public string IngresoSolucion { get { return GetColumnValue<string>(Columns.IngresoSolucion); } set { SetColumnValue(Columns.IngresoSolucion, value); } } [XmlAttribute("IngresoOtros")] [Bindable(true)] public string IngresoOtros { get { return GetColumnValue<string>(Columns.IngresoOtros); } set { SetColumnValue(Columns.IngresoOtros, value); } } [XmlAttribute("EgresoDepos")] [Bindable(true)] public string EgresoDepos { get { return GetColumnValue<string>(Columns.EgresoDepos); } set { SetColumnValue(Columns.EgresoDepos, value); } } [XmlAttribute("EgresoOrina")] [Bindable(true)] public string EgresoOrina { get { return GetColumnValue<string>(Columns.EgresoOrina); } set { SetColumnValue(Columns.EgresoOrina, value); } } [XmlAttribute("EgresoVomito")] [Bindable(true)] public string EgresoVomito { get { return GetColumnValue<string>(Columns.EgresoVomito); } set { SetColumnValue(Columns.EgresoVomito, value); } } [XmlAttribute("EgresoSng")] [Bindable(true)] public string EgresoSng { get { return GetColumnValue<string>(Columns.EgresoSng); } set { SetColumnValue(Columns.EgresoSng, value); } } [XmlAttribute("EgresoOtros")] [Bindable(true)] public string EgresoOtros { get { return GetColumnValue<string>(Columns.EgresoOtros); } set { SetColumnValue(Columns.EgresoOtros, value); } } [XmlAttribute("Observaciones")] [Bindable(true)] public string Observaciones { get { return GetColumnValue<string>(Columns.Observaciones); } set { SetColumnValue(Columns.Observaciones, value); } } [XmlAttribute("AuditUser")] [Bindable(true)] public int? AuditUser { get { return GetColumnValue<int?>(Columns.AuditUser); } set { SetColumnValue(Columns.AuditUser, value); } } [XmlAttribute("EscalaDelDolor")] [Bindable(true)] public int? EscalaDelDolor { get { return GetColumnValue<int?>(Columns.EscalaDelDolor); } set { SetColumnValue(Columns.EscalaDelDolor, value); } } [XmlAttribute("IdClasificacion")] [Bindable(true)] public int? IdClasificacion { get { return GetColumnValue<int?>(Columns.IdClasificacion); } set { SetColumnValue(Columns.IdClasificacion, value); } } [XmlAttribute("Triage")] [Bindable(true)] public bool? Triage { get { return GetColumnValue<bool?>(Columns.Triage); } set { SetColumnValue(Columns.Triage, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a GuardiaRegistro ActiveRecord object related to this GuardiaTriage /// /// </summary> public DalSic.GuardiaRegistro GuardiaRegistro { get { return DalSic.GuardiaRegistro.FetchByID(this.RegistroGuardia); } set { SetColumnValue("registroGuardia", value.Id); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varRegistroGuardia,int? varIdEfector,DateTime varFechaHora,string varTensionArterial,int? varFrecuenciaCardiaca,int? varFrecuenciaRespiratoria,double? varTemperatura,int? varSaturacionOxigeno,int? varGlasgowOcular,int? varGlasgowVerbal,int? varGlasgowMotor,double? varPeso,string varPupilasTamano,string varPupilasReactividad,string varPupilasSimetria,string varSensorio,string varSibilancia,string varMuscAccesorio,string varIngresoAlimentacionCant,string varIngresoAlimentacionTipo,string varIngresoSolucion,string varIngresoOtros,string varEgresoDepos,string varEgresoOrina,string varEgresoVomito,string varEgresoSng,string varEgresoOtros,string varObservaciones,int? varAuditUser,int? varEscalaDelDolor,int? varIdClasificacion,bool? varTriage) { GuardiaTriage item = new GuardiaTriage(); item.RegistroGuardia = varRegistroGuardia; item.IdEfector = varIdEfector; item.FechaHora = varFechaHora; item.TensionArterial = varTensionArterial; item.FrecuenciaCardiaca = varFrecuenciaCardiaca; item.FrecuenciaRespiratoria = varFrecuenciaRespiratoria; item.Temperatura = varTemperatura; item.SaturacionOxigeno = varSaturacionOxigeno; item.GlasgowOcular = varGlasgowOcular; item.GlasgowVerbal = varGlasgowVerbal; item.GlasgowMotor = varGlasgowMotor; item.Peso = varPeso; item.PupilasTamano = varPupilasTamano; item.PupilasReactividad = varPupilasReactividad; item.PupilasSimetria = varPupilasSimetria; item.Sensorio = varSensorio; item.Sibilancia = varSibilancia; item.MuscAccesorio = varMuscAccesorio; item.IngresoAlimentacionCant = varIngresoAlimentacionCant; item.IngresoAlimentacionTipo = varIngresoAlimentacionTipo; item.IngresoSolucion = varIngresoSolucion; item.IngresoOtros = varIngresoOtros; item.EgresoDepos = varEgresoDepos; item.EgresoOrina = varEgresoOrina; item.EgresoVomito = varEgresoVomito; item.EgresoSng = varEgresoSng; item.EgresoOtros = varEgresoOtros; item.Observaciones = varObservaciones; item.AuditUser = varAuditUser; item.EscalaDelDolor = varEscalaDelDolor; item.IdClasificacion = varIdClasificacion; item.Triage = varTriage; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varId,int varRegistroGuardia,int? varIdEfector,DateTime varFechaHora,string varTensionArterial,int? varFrecuenciaCardiaca,int? varFrecuenciaRespiratoria,double? varTemperatura,int? varSaturacionOxigeno,int? varGlasgowOcular,int? varGlasgowVerbal,int? varGlasgowMotor,double? varPeso,string varPupilasTamano,string varPupilasReactividad,string varPupilasSimetria,string varSensorio,string varSibilancia,string varMuscAccesorio,string varIngresoAlimentacionCant,string varIngresoAlimentacionTipo,string varIngresoSolucion,string varIngresoOtros,string varEgresoDepos,string varEgresoOrina,string varEgresoVomito,string varEgresoSng,string varEgresoOtros,string varObservaciones,int? varAuditUser,int? varEscalaDelDolor,int? varIdClasificacion,bool? varTriage) { GuardiaTriage item = new GuardiaTriage(); item.Id = varId; item.RegistroGuardia = varRegistroGuardia; item.IdEfector = varIdEfector; item.FechaHora = varFechaHora; item.TensionArterial = varTensionArterial; item.FrecuenciaCardiaca = varFrecuenciaCardiaca; item.FrecuenciaRespiratoria = varFrecuenciaRespiratoria; item.Temperatura = varTemperatura; item.SaturacionOxigeno = varSaturacionOxigeno; item.GlasgowOcular = varGlasgowOcular; item.GlasgowVerbal = varGlasgowVerbal; item.GlasgowMotor = varGlasgowMotor; item.Peso = varPeso; item.PupilasTamano = varPupilasTamano; item.PupilasReactividad = varPupilasReactividad; item.PupilasSimetria = varPupilasSimetria; item.Sensorio = varSensorio; item.Sibilancia = varSibilancia; item.MuscAccesorio = varMuscAccesorio; item.IngresoAlimentacionCant = varIngresoAlimentacionCant; item.IngresoAlimentacionTipo = varIngresoAlimentacionTipo; item.IngresoSolucion = varIngresoSolucion; item.IngresoOtros = varIngresoOtros; item.EgresoDepos = varEgresoDepos; item.EgresoOrina = varEgresoOrina; item.EgresoVomito = varEgresoVomito; item.EgresoSng = varEgresoSng; item.EgresoOtros = varEgresoOtros; item.Observaciones = varObservaciones; item.AuditUser = varAuditUser; item.EscalaDelDolor = varEscalaDelDolor; item.IdClasificacion = varIdClasificacion; item.Triage = varTriage; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn RegistroGuardiaColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn FechaHoraColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn TensionArterialColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn FrecuenciaCardiacaColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn FrecuenciaRespiratoriaColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn TemperaturaColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn SaturacionOxigenoColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn GlasgowOcularColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn GlasgowVerbalColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn GlasgowMotorColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn PesoColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn PupilasTamanoColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn PupilasReactividadColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn PupilasSimetriaColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn SensorioColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn SibilanciaColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn MuscAccesorioColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn IngresoAlimentacionCantColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn IngresoAlimentacionTipoColumn { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn IngresoSolucionColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn IngresoOtrosColumn { get { return Schema.Columns[22]; } } public static TableSchema.TableColumn EgresoDeposColumn { get { return Schema.Columns[23]; } } public static TableSchema.TableColumn EgresoOrinaColumn { get { return Schema.Columns[24]; } } public static TableSchema.TableColumn EgresoVomitoColumn { get { return Schema.Columns[25]; } } public static TableSchema.TableColumn EgresoSngColumn { get { return Schema.Columns[26]; } } public static TableSchema.TableColumn EgresoOtrosColumn { get { return Schema.Columns[27]; } } public static TableSchema.TableColumn ObservacionesColumn { get { return Schema.Columns[28]; } } public static TableSchema.TableColumn AuditUserColumn { get { return Schema.Columns[29]; } } public static TableSchema.TableColumn EscalaDelDolorColumn { get { return Schema.Columns[30]; } } public static TableSchema.TableColumn IdClasificacionColumn { get { return Schema.Columns[31]; } } public static TableSchema.TableColumn TriageColumn { get { return Schema.Columns[32]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"id"; public static string RegistroGuardia = @"registroGuardia"; public static string IdEfector = @"idEfector"; public static string FechaHora = @"fechaHora"; public static string TensionArterial = @"tensionArterial"; public static string FrecuenciaCardiaca = @"frecuenciaCardiaca"; public static string FrecuenciaRespiratoria = @"frecuenciaRespiratoria"; public static string Temperatura = @"temperatura"; public static string SaturacionOxigeno = @"saturacionOxigeno"; public static string GlasgowOcular = @"glasgow_ocular"; public static string GlasgowVerbal = @"glasgow_verbal"; public static string GlasgowMotor = @"glasgow_motor"; public static string Peso = @"peso"; public static string PupilasTamano = @"pupilas_tamano"; public static string PupilasReactividad = @"pupilas_reactividad"; public static string PupilasSimetria = @"pupilas_simetria"; public static string Sensorio = @"sensorio"; public static string Sibilancia = @"sibilancia"; public static string MuscAccesorio = @"muscAccesorio"; public static string IngresoAlimentacionCant = @"ingresoAlimentacionCant"; public static string IngresoAlimentacionTipo = @"ingresoAlimentacionTipo"; public static string IngresoSolucion = @"ingresoSolucion"; public static string IngresoOtros = @"ingresoOtros"; public static string EgresoDepos = @"egresoDepos"; public static string EgresoOrina = @"egresoOrina"; public static string EgresoVomito = @"egresoVomito"; public static string EgresoSng = @"egresoSng"; public static string EgresoOtros = @"egresoOtros"; public static string Observaciones = @"observaciones"; public static string AuditUser = @"audit_user"; public static string EscalaDelDolor = @"escalaDelDolor"; public static string IdClasificacion = @"idClasificacion"; public static string Triage = @"triage"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableLessThanTests { #region Test methods [Fact] public static void CheckNullableByteLessThanTest() { byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableCharLessThanTest() { char?[] array = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableDecimalLessThanTest() { decimal?[] array = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableDoubleLessThanTest() { double?[] array = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableFloatLessThanTest() { float?[] array = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableIntLessThanTest() { int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableLongLessThanTest() { long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteLessThanTest() { sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableShortLessThanTest() { short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableUIntLessThanTest() { uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableULongLessThanTest() { ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongLessThan(array[i], array[j]); } } } [Fact] public static void CheckNullableUShortLessThanTest() { ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortLessThan(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableByteLessThan(byte? a, byte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableCharLessThan(char? a, char? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableDecimalLessThan(decimal? a, decimal? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableDoubleLessThan(double? a, double? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableFloatLessThan(float? a, float? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableIntLessThan(int? a, int? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableLongLessThan(long? a, long? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableSByteLessThan(sbyte? a, sbyte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableShortLessThan(short? a, short? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableUIntLessThan(uint? a, uint? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableULongLessThan(ulong? a, ulong? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyNullableUShortLessThan(ushort? a, ushort? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.LessThan( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a < b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Common.Security { using System; using System.Collections.Generic; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Web; using Microsoft.Azure.Devices.Common.Data; public sealed class SharedAccessSignature : ISharedAccessSignatureCredential { readonly string iotHubName; readonly string signature; readonly string audience; readonly string encodedAudience; readonly string expiry; readonly string keyName; SharedAccessSignature(string iotHubName, DateTime expiresOn, string expiry, string keyName, string signature, string encodedAudience) { if (string.IsNullOrWhiteSpace(iotHubName)) { throw new ArgumentNullException("iotHubName"); } this.ExpiresOn = expiresOn; if (this.IsExpired()) { throw new UnauthorizedAccessException("The specified SAS token is expired"); } this.iotHubName = iotHubName; this.signature = signature; this.audience = HttpUtility.UrlDecode(encodedAudience); this.encodedAudience = encodedAudience; this.expiry = expiry; this.keyName = keyName ?? string.Empty; } public string IotHubName { get { return this.iotHubName; } } public DateTime ExpiresOn { get; private set; } public string KeyName { get { return this.keyName; } } public string Audience { get { return this.audience; } } public string Signature { get { return this.signature; } } public static SharedAccessSignature Parse(string iotHubName, string rawToken) { if (string.IsNullOrWhiteSpace(iotHubName)) { throw new ArgumentNullException("iotHubName"); } if (string.IsNullOrWhiteSpace(rawToken)) { throw new ArgumentNullException("rawToken"); } IDictionary<string, string> parsedFields = ExtractFieldValues(rawToken); string signature; if (!parsedFields.TryGetValue(SharedAccessSignatureConstants.SignatureFieldName, out signature)) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Missing field: {0}", SharedAccessSignatureConstants.SignatureFieldName)); } string expiry; if (!parsedFields.TryGetValue(SharedAccessSignatureConstants.ExpiryFieldName, out expiry)) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Missing field: {0}", SharedAccessSignatureConstants.ExpiryFieldName)); } // KeyName (skn) is optional. string keyName; parsedFields.TryGetValue(SharedAccessSignatureConstants.KeyNameFieldName, out keyName); string encodedAudience; if (!parsedFields.TryGetValue(SharedAccessSignatureConstants.AudienceFieldName, out encodedAudience)) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Missing field: {0}", SharedAccessSignatureConstants.AudienceFieldName)); } return new SharedAccessSignature(iotHubName, SharedAccessSignatureConstants.EpochTime + TimeSpan.FromSeconds(double.Parse(expiry, CultureInfo.InvariantCulture)), expiry, keyName, signature, encodedAudience); } public static bool IsSharedAccessSignature(string rawSignature) { if (string.IsNullOrWhiteSpace(rawSignature)) { return false; } IDictionary<string, string> parsedFields = ExtractFieldValues(rawSignature); string signature; bool isSharedAccessSignature = parsedFields.TryGetValue(SharedAccessSignatureConstants.SignatureFieldName, out signature); return isSharedAccessSignature; } public bool IsExpired() { return this.ExpiresOn + SharedAccessSignatureConstants.MaxClockSkew < DateTime.UtcNow; } public DateTime ExpiryTime() { return this.ExpiresOn + SharedAccessSignatureConstants.MaxClockSkew; } public void Authenticate(SharedAccessSignatureAuthorizationRule sasAuthorizationRule) { if (this.IsExpired()) { throw new UnauthorizedAccessException("The specified SAS token is expired."); } if (sasAuthorizationRule.PrimaryKey != null) { string primareyKeyComputedSignature = this.ComputeSignature(Convert.FromBase64String(sasAuthorizationRule.PrimaryKey)); if (string.Equals(this.signature, primareyKeyComputedSignature)) { return; } } if (sasAuthorizationRule.SecondaryKey != null) { string secondaryKeyComputedSignature = this.ComputeSignature(Convert.FromBase64String(sasAuthorizationRule.SecondaryKey)); if (string.Equals(this.signature, secondaryKeyComputedSignature)) { return; } } throw new UnauthorizedAccessException("The specified SAS token has an invalid signature. It does not match either the primary or secondary key."); } public void Authorize(string iotHubHostName) { SecurityHelper.ValidateIotHubHostName(iotHubHostName, this.IotHubName); } public void Authorize(Uri targetAddress) { if (targetAddress == null) { throw new ArgumentNullException("targetAddress"); } string target = targetAddress.Host + targetAddress.AbsolutePath; if (!target.StartsWith(this.audience.TrimEnd(new char[] { '/' }), StringComparison.OrdinalIgnoreCase)) { throw new UnauthorizedAccessException("Invalid target audience"); } } public string ComputeSignature(byte[] key) { List<string> fields = new List<string>(); fields.Add(this.encodedAudience); fields.Add(this.expiry); using (var hmac = new HMACSHA256(key)) { string value = string.Join("\n", fields); return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(value))); } } static IDictionary<string, string> ExtractFieldValues(string sharedAccessSignature) { string[] lines = sharedAccessSignature.Split(); if (!string.Equals(lines[0].Trim(), SharedAccessSignatureConstants.SharedAccessSignature, StringComparison.Ordinal) || lines.Length != 2) { throw new FormatException("Malformed signature"); } IDictionary<string, string> parsedFields = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); string[] fields = lines[1].Trim().Split(new string[] { SharedAccessSignatureConstants.PairSeparator }, StringSplitOptions.None); foreach (string field in fields) { if (field != string.Empty) { string[] fieldParts = field.Split(new string[]{ SharedAccessSignatureConstants.KeyValueSeparator }, StringSplitOptions.None); if (string.Equals(fieldParts[0], SharedAccessSignatureConstants.AudienceFieldName, StringComparison.OrdinalIgnoreCase)) { // We need to preserve the casing of the escape characters in the audience, // so defer decoding the URL until later. parsedFields.Add(fieldParts[0], fieldParts[1]); } else { parsedFields.Add(fieldParts[0], HttpUtility.UrlDecode(fieldParts[1])); } } } return parsedFields; } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2005AutoHideStrip : AutoHideStripBase { private class TabVS2005 : Tab { internal TabVS2005(IDockContent content) : base(content) { } private int m_tabX = 0; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth = 0; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } } private const int _ImageHeight = 16; private const int _ImageWidth = 16; private const int _ImageGapTop = 2; private const int _ImageGapLeft = 4; private const int _ImageGapRight = 2; private const int _ImageGapBottom = 2; private const int _TextGapLeft = 0; private const int _TextGapRight = 0; private const int _TabGapTop = 3; private const int _TabGapLeft = 4; private const int _TabGapBetween = 10; #region Customizable Properties public Font TextFont { get { return DockPanel.Skin.AutoHideStripSkin.TextFont; } } private static StringFormat _stringFormatTabHorizontal; private StringFormat StringFormatTabHorizontal { get { if (_stringFormatTabHorizontal == null) { _stringFormatTabHorizontal = new StringFormat(); _stringFormatTabHorizontal.Alignment = StringAlignment.Near; _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center; _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap; _stringFormatTabHorizontal.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabHorizontal; } } private static StringFormat _stringFormatTabVertical; private StringFormat StringFormatTabVertical { get { if (_stringFormatTabVertical == null) { _stringFormatTabVertical = new StringFormat(); _stringFormatTabVertical.Alignment = StringAlignment.Near; _stringFormatTabVertical.LineAlignment = StringAlignment.Center; _stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; _stringFormatTabVertical.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabVertical; } } private static int ImageHeight { get { return _ImageHeight; } } private static int ImageWidth { get { return _ImageWidth; } } private static int ImageGapTop { get { return _ImageGapTop; } } private static int ImageGapLeft { get { return _ImageGapLeft; } } private static int ImageGapRight { get { return _ImageGapRight; } } private static int ImageGapBottom { get { return _ImageGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int TabGapTop { get { return _TabGapTop; } } private static int TabGapLeft { get { return _TabGapLeft; } } private static int TabGapBetween { get { return _TabGapBetween; } } private static Pen PenTabBorder { get { return SystemPens.GrayText; } } #endregion private static Matrix _matrixIdentity = new Matrix(); private static Matrix MatrixIdentity { get { return _matrixIdentity; } } private static DockState[] _dockStates; private static DockState[] DockStates { get { if (_dockStates == null) { _dockStates = new DockState[4]; _dockStates[0] = DockState.DockLeftAutoHide; _dockStates[1] = DockState.DockRightAutoHide; _dockStates[2] = DockState.DockTopAutoHide; _dockStates[3] = DockState.DockBottomAutoHide; } return _dockStates; } } private static GraphicsPath _graphicsPath; internal static GraphicsPath GraphicsPath { get { if (_graphicsPath == null) _graphicsPath = new GraphicsPath(); return _graphicsPath; } } public VS2005AutoHideStrip(DockPanel panel) : base(panel) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); BackColor = SystemColors.ControlLight; } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; Color startColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.StartColor; Color endColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { g.FillRectangle(brush, ClientRectangle); } DrawTabStrip(g); } protected override void OnLayout(LayoutEventArgs levent) { CalculateTabs(); base.OnLayout(levent); } private void DrawTabStrip(Graphics g) { DrawTabStrip(g, DockState.DockTopAutoHide); DrawTabStrip(g, DockState.DockBottomAutoHide); DrawTabStrip(g, DockState.DockLeftAutoHide); DrawTabStrip(g, DockState.DockRightAutoHide); } private void DrawTabStrip(Graphics g, DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return; Matrix matrixIdentity = g.Transform; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { Matrix matrixRotated = new Matrix(); matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); g.Transform = matrixRotated; } foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2005 tab in pane.AutoHideTabs) DrawTab(g, tab); } g.Transform = matrixIdentity; } private void CalculateTabs() { CalculateTabs(DockState.DockTopAutoHide); CalculateTabs(DockState.DockBottomAutoHide); CalculateTabs(DockState.DockLeftAutoHide); CalculateTabs(DockState.DockRightAutoHide); } private void CalculateTabs(DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); int x = TabGapLeft + rectTabStrip.X; foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2005 tab in pane.AutoHideTabs) { int width = imageWidth + ImageGapLeft + ImageGapRight + TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width + TextGapLeft + TextGapRight; tab.TabX = x; tab.TabWidth = width; x += width; } x += TabGapBetween; } } private Rectangle RtlTransform(Rectangle rect, DockState dockState) { Rectangle rectTransformed; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) rectTransformed = rect; else rectTransformed = DrawHelper.RtlTransform(this, rect); return rectTransformed; } private GraphicsPath GetTabOutline(TabVS2005 tab, bool transformed, bool rtlTransform) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTab = GetTabRectangle(tab, transformed); if (rtlTransform) rectTab = RtlTransform(rectTab, dockState); bool upTab = (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockBottomAutoHide); DrawHelper.GetRoundedCornerTab(GraphicsPath, rectTab, upTab); return GraphicsPath; } private void DrawTab(Graphics g, TabVS2005 tab) { Rectangle rectTabOrigin = GetTabRectangle(tab); if (rectTabOrigin.IsEmpty) return; DockState dockState = tab.Content.DockHandler.DockState; IDockContent content = tab.Content; GraphicsPath path = GetTabOutline(tab, false, true); Color startColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.StartColor; Color endColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.EndColor; LinearGradientMode gradientMode = DockPanel.Skin.AutoHideStripSkin.TabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectTabOrigin, startColor, endColor, gradientMode), path); g.DrawPath(PenTabBorder, path); // Set no rotate for drawing icon and text using (Matrix matrixRotate = g.Transform) { g.Transform = MatrixIdentity; // Draw the icon Rectangle rectImage = rectTabOrigin; rectImage.X += ImageGapLeft; rectImage.Y += ImageGapTop; int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); rectImage.Height = imageHeight; rectImage.Width = imageWidth; rectImage = GetTransformedRectangle(dockState, rectImage); if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { // The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right. Rectangle rectTransform = RtlTransform(rectImage, dockState); Point[] rotationPoints = { new Point(rectTransform.X + rectTransform.Width, rectTransform.Y), new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height), new Point(rectTransform.X, rectTransform.Y) }; using (Icon rotatedIcon = new Icon(((Form)content).Icon, 16, 16)) { g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints); } } else { // Draw the icon normally without any rotation. g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState)); } // Draw the text Rectangle rectText = rectTabOrigin; rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState); Color textColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.TextColor; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabVertical); else g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabHorizontal); // Set rotate back g.Transform = matrixRotate; } } private Rectangle GetLogicalTabStripRectangle(DockState dockState) { return GetLogicalTabStripRectangle(dockState, false); } private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) { if (!DockHelper.IsDockStateAutoHide(dockState)) return Rectangle.Empty; int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; int rightPanes = GetPanes(DockState.DockRightAutoHide).Count; int topPanes = GetPanes(DockState.DockTopAutoHide).Count; int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; int x, y, width, height; height = MeasureHeight(); if (dockState == DockState.DockLeftAutoHide && leftPanes > 0) { x = 0; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockRightAutoHide && rightPanes > 0) { x = Width - height; if (leftPanes != 0 && x < height) x = height; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockTopAutoHide && topPanes > 0) { x = leftPanes == 0 ? 0 : height; y = 0; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0) { x = leftPanes == 0 ? 0 : height; y = Height - height; if (topPanes != 0 && y < height) y = height; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else return Rectangle.Empty; if (width == 0 || height == 0) { return Rectangle.Empty; } var rect = new Rectangle(x, y, width, height); return transformed ? GetTransformedRectangle(dockState, rect) : rect; } private Rectangle GetTabRectangle(TabVS2005 tab) { return GetTabRectangle(tab, false); } private Rectangle GetTabRectangle(TabVS2005 tab, bool transformed) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return Rectangle.Empty; int x = tab.TabX; int y = rectTabStrip.Y + (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ? 0 : TabGapTop); int width = tab.TabWidth; int height = rectTabStrip.Height - TabGapTop; if (!transformed) return new Rectangle(x, y, width, height); else return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) { if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) return rect; PointF[] pts = new PointF[1]; // the center of the rectangle pts[0].X = (float)rect.X + (float)rect.Width / 2; pts[0].Y = (float)rect.Y + (float)rect.Height / 2; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); using (var matrix = new Matrix()) { matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); matrix.TransformPoints(pts); } return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F), (int)(pts[0].Y - (float)rect.Width / 2 + .5F), rect.Height, rect.Width); } protected override IDockContent HitTest(Point ptMouse) { foreach (DockState state in DockStates) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); if (!rectTabStrip.Contains(ptMouse)) continue; foreach (Pane pane in GetPanes(state)) { foreach (TabVS2005 tab in pane.AutoHideTabs) { GraphicsPath path = GetTabOutline(tab, true, true); if (path.IsVisible(ptMouse)) return tab.Content; } } } return null; } protected internal override int MeasureHeight() { return Math.Max(ImageGapBottom + ImageGapTop + ImageHeight, TextFont.Height) + TabGapTop; } protected override void OnRefreshChanges() { CalculateTabs(); Invalidate(); } protected override AutoHideStripBase.Tab CreateTab(IDockContent content) { return new TabVS2005(content); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text.RegularExpressions; using Xunit; public partial class RegexMatchTests { /* Tested Methods: public static Match Match(string input); Using "n" Regex option. Only explicitly named groups should be captured : Actual - "([0-9]*)\\s(?<s>[a-z_A-Z]+)", "n" "200 dollars" public static Match Match(string input); Single line mode "s". Includes new line character. : Actual - "([^/]+)","s" "abc\n" public static Match Match(string input); "x" option. Removes unescaped white space from the pattern. : Actual - " ([^/]+) ","x" "abc" public static Match Match(string input); "x" option. Removes unescaped white space from the pattern. : Actual - "\x20([^/]+)\x20","x" "abc" */ [Fact] public static void RegexMatchTestCase8() { //////////// Global Variables used for all tests String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; Regex r; Match m; Match match; String strMatch1 = "200 dollars"; Int32[] iMatch1 = { 0, 11 } ; String[] strGroup1 = { "200 dollars", "dollars" } ; Int32[,] iGroup1 = { { 0, 11 } , { 4, 7 } } ; String[][] strGrpCap1 = new String[2][]; strGrpCap1[0] = new String[] { "200 dollars" } ; strGrpCap1[1] = new String[] { "dollars" } ; Int32[][] iGrpCap1 = new Int32[2][]; iGrpCap1[0] = new Int32[] { 0, 11 } ; //This is ignored iGrpCap1[1] = new Int32[] { 4, 7 } ; //The first half contains the Index and the latter half the Lengths Int32[] iGrpCapCnt1 = { 1, 1 } ; //0 is ignored String strMatch2 = "abc\nsfc"; Int32[] iMatch2 = { 0, 7 } ; String[] strGroup2 = { "abc\nsfc", "abc\nsfc" } ; Int32[,] iGroup2 = { { 0, 7 } , { 0, 7 } } ; String[][] strGrpCap2 = new String[2][]; strGrpCap2[0] = new String[] { "abc\nsfc" } ; strGrpCap2[1] = new String[] { "abc\nsfc" } ; Int32[][] iGrpCap2 = new Int32[2][]; iGrpCap2[0] = new Int32[] { 0, 11 } ; //This is ignored iGrpCap2[1] = new Int32[] { 0, 7 } ; //The first half contains the Index and the latter half the Lengths Int32[] iGrpCapCnt2 = { 1, 1 } ; //0 is ignored try { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// // [] public static Match Match(string input); Using "n" Regex option. Only explicitly named groups should be captured : Actual - "([0-9]*)\\s(?<s>[a-z_A-Z]+)", "n" //"200 dollars" //----------------------------------------------------------------- strLoc = "Loc_498yg"; iCountTestcases++; r = new Regex(@"([0-9]*)\s(?<s>[a-z_A-Z]+)", RegexOptions.ExplicitCapture); match = r.Match("200 dollars"); if (!match.Success) { iCountErrors++; Console.WriteLine("Err_234fsadg! doesnot match"); } else { if (!match.Value.Equals(strMatch1) || (match.Index != iMatch1[0]) || (match.Length != iMatch1[1]) || (match.Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_98275dsg: unexpected return result"); } //Match.Captures always is Match if (!match.Captures[0].Value.Equals(strMatch1) || (match.Captures[0].Index != iMatch1[0]) || (match.Captures[0].Length != iMatch1[1])) { iCountErrors++; Console.WriteLine("Err_2046gsg! unexpected return result"); } if (match.Groups.Count != 2) { iCountErrors++; Console.WriteLine("Err_75324sg! unexpected return result"); } //Group 0 always is the Match if (!match.Groups[0].Value.Equals(strMatch1) || (match.Groups[0].Index != iMatch1[0]) || (match.Groups[0].Length != iMatch1[1]) || (match.Groups[0].Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_2046gsg! unexpected return result"); } //Group 0's Capture is always the Match if (!match.Groups[0].Captures[0].Value.Equals(strMatch1) || (match.Groups[0].Captures[0].Index != iMatch1[0]) || (match.Groups[0].Captures[0].Length != iMatch1[1])) { iCountErrors++; Console.WriteLine("Err_2975edg!! unexpected return result"); } for (int i = 1; i < match.Groups.Count; i++) { if (!match.Groups[i].Value.Equals(strGroup1[i]) || (match.Groups[i].Index != iGroup1[i, 0]) || (match.Groups[i].Length != iGroup1[i, 1]) || (match.Groups[i].Captures.Count != iGrpCapCnt1[i])) { iCountErrors++; Console.WriteLine("Err_1954eg_" + i + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>, CaptureCount = <{6}:{7}>", match.Groups[i].Value, match.Groups[i].Index, match.Groups[i].Length, strGroup1[i], iGroup1[i, 0], iGroup1[i, 1], match.Groups[i].Captures.Count, iGrpCapCnt1[i]); } for (int j = 0; j < match.Groups[i].Captures.Count; j++) { if (!match.Groups[i].Captures[j].Value.Equals(strGrpCap1[i][j]) || (match.Groups[i].Captures[j].Index != iGrpCap1[i][j]) || (match.Groups[i].Captures[j].Length != iGrpCap1[i][match.Groups[i].Captures.Count + j])) { iCountErrors++; Console.WriteLine("Err_5072dn_" + i + "_" + j + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>", match.Groups[i].Captures[j].Value, match.Groups[i].Captures[j].Index, match.Groups[i].Captures[j].Length, strGrpCap1[i][j], iGrpCap1[i][j], iGrpCap1[i][match.Groups[i].Captures.Count + j]); } } } } // [] public static Match Match(string input); Single line mode "s". Includes new line character. : Actual - "([^/]+)","s" //"abc\n" //----------------------------------------------------------------- strLoc = "Loc_298vy"; iCountTestcases++; r = new Regex("(.*)", RegexOptions.Singleline); match = r.Match("abc\nsfc"); if (!match.Success) { iCountErrors++; Console.WriteLine("Err_87543! doesnot match"); } else { if (!match.Value.Equals(strMatch2) || (match.Index != iMatch2[0]) || (match.Length != iMatch2[1]) || (match.Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_827345sdf! unexpected return result"); } //Match.Captures always is Match if (!match.Captures[0].Value.Equals(strMatch2) || (match.Captures[0].Index != iMatch2[0]) || (match.Captures[0].Length != iMatch2[1])) { iCountErrors++; Console.WriteLine("Err_1074sf! unexpected return result"); } if (match.Groups.Count != 2) { iCountErrors++; Console.WriteLine("Err_2175sgg! unexpected return result"); } //Group 0 always is the Match if (!match.Groups[0].Value.Equals(strMatch2) || (match.Groups[0].Index != iMatch2[0]) || (match.Groups[0].Length != iMatch2[1]) || (match.Groups[0].Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_68217fdgs! unexpected return result"); } //Group 0's Capture is always the Match if (!match.Groups[0].Captures[0].Value.Equals(strMatch2) || (match.Groups[0].Captures[0].Index != iMatch2[0]) || (match.Groups[0].Captures[0].Length != iMatch2[1])) { iCountErrors++; Console.WriteLine("Err_139wn!! unexpected return result"); } for (int i = 1; i < match.Groups.Count; i++) { if (!match.Groups[i].Value.Equals(strGroup2[i]) || (match.Groups[i].Index != iGroup2[i, 0]) || (match.Groups[i].Length != iGroup2[i, 1]) || (match.Groups[i].Captures.Count != iGrpCapCnt2[i])) { iCountErrors++; Console.WriteLine("Err_107vxg_" + i + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>, CaptureCount = <{6}:{7}>", match.Groups[i].Value, match.Groups[i].Index, match.Groups[i].Length, strGroup2[i], iGroup2[i, 0], iGroup2[i, 1], match.Groups[i].Captures.Count, iGrpCapCnt2[i]); } for (int j = 0; j < match.Groups[i].Captures.Count; j++) { if (!match.Groups[i].Captures[j].Value.Equals(strGrpCap2[i][j]) || (match.Groups[i].Captures[j].Index != iGrpCap2[i][j]) || (match.Groups[i].Captures[j].Length != iGrpCap2[i][match.Groups[i].Captures.Count + j])) { iCountErrors++; Console.WriteLine("Err_745dsgg_" + i + "_" + j + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>", match.Groups[i].Captures[j].Value, match.Groups[i].Captures[j].Index, match.Groups[i].Captures[j].Length, strGrpCap2[i][j], iGrpCap2[i][j], iGrpCap2[i][match.Groups[i].Captures.Count + j]); } } } } // [] public static Match Match(string input); "x" option. Removes unescaped white space from the pattern. : Actual - " ([^/]+) ","x" //"abc" //----------------------------------------------------------------- strLoc = "Loc_746tegd"; iCountTestcases++; r = new Regex(" ((.)+) ", RegexOptions.IgnorePatternWhitespace); m = r.Match("abc"); if (!m.Success) { iCountErrors++; Console.WriteLine("Err_452wfdf! doesnot match"); } // [] public static Match Match(string input); "x" option. Removes unescaped white space from the pattern. : Actual - "\x20([^/]+)\x20","x" //"abc" //----------------------------------------------------------------- strLoc = "Loc_563rfg"; iCountTestcases++; r = new Regex("\x20([^/]+)\x20\x20\x20\x20\x20\x20\x20", RegexOptions.IgnorePatternWhitespace); m = r.Match(" abc "); if (!m.Success) { iCountErrors++; Console.WriteLine("Err_865rfsg! doesnot match"); } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics Assert.Equal(0, iCountErrors); } }
using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Xml; using SIL.Xml; namespace SIL.WritingSystems.Migration.WritingSystemsLdmlV0To1Migration { public class LdmlAdaptorV0 { private readonly XmlNamespaceManager _nameSpaceManager; public LdmlAdaptorV0() { _nameSpaceManager = MakeNameSpaceManager(); } public void Read(string filePath, WritingSystemDefinitionV0 ws) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (ws == null) { throw new ArgumentNullException("ws"); } var settings = new XmlReaderSettings { NameTable = _nameSpaceManager.NameTable, ValidationType = ValidationType.None, XmlResolver = null, DtdProcessing = DtdProcessing.Parse }; using (XmlReader reader = XmlReader.Create(filePath, settings)) { ReadLdml(reader, ws); } } public void Read(XmlReader xmlReader, WritingSystemDefinitionV0 ws) { if (xmlReader == null) { throw new ArgumentNullException("xmlReader"); } if (ws == null) { throw new ArgumentNullException("ws"); } var settings = new XmlReaderSettings { NameTable = _nameSpaceManager.NameTable, ConformanceLevel = ConformanceLevel.Auto, ValidationType = ValidationType.None, XmlResolver = null, DtdProcessing = DtdProcessing.Parse }; using (XmlReader reader = XmlReader.Create(xmlReader, settings)) { ReadLdml(reader, ws); } } private static bool FindElement(XmlReader reader, string name) { return XmlHelpersV0.FindNextElementInSequence(reader, name, LdmlNodeComparerV0.CompareElementNames); } private void ReadLdml(XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(reader != null); Debug.Assert(ws != null); if (reader.MoveToContent() != XmlNodeType.Element || reader.Name != "ldml") { throw new ApplicationException("Unable to load writing system definition: Missing <ldml> tag."); } reader.Read(); if (FindElement(reader, "identity")) { ReadIdentityElement(reader, ws); } if (FindElement(reader, "layout")) { ReadLayoutElement(reader, ws); } if (FindElement(reader, "collations")) { ReadCollationsElement(reader, ws); } while (FindElement(reader, "special")) { ReadTopLevelSpecialElement(reader, ws); } ws.StoreID = ""; } protected virtual void ReadTopLevelSpecialElement(XmlReader reader, WritingSystemDefinitionV0 ws) { if (reader.GetAttribute("xmlns:palaso") != null) { reader.ReadStartElement("special"); ws.Abbreviation = GetSpecialValue(reader, "palaso", "abbreviation"); ws.DefaultFontName = GetSpecialValue(reader, "palaso", "defaultFontFamily"); float fontSize; if (float.TryParse(GetSpecialValue(reader, "palaso", "defaultFontSize"), out fontSize)) { ws.DefaultFontSize = fontSize; } ws.Keyboard = GetSpecialValue(reader, "palaso", "defaultKeyboard"); string isLegacyEncoded = GetSpecialValue(reader, "palaso", "isLegacyEncoded"); if (!String.IsNullOrEmpty(isLegacyEncoded)) { ws.IsLegacyEncoded = Convert.ToBoolean(isLegacyEncoded); } ws.LanguageName = GetSpecialValue(reader, "palaso", "languageName"); ws.SpellCheckingId = GetSpecialValue(reader, "palaso", "spellCheckingId"); while (reader.NodeType != XmlNodeType.EndElement) { reader.Read(); } reader.ReadEndElement(); } else { reader.Skip(); } } private void ReadIdentityElement(XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.Name == "identity"); using (XmlReader identityReader = reader.ReadSubtree()) { identityReader.MoveToContent(); identityReader.ReadStartElement("identity"); if (FindElement(identityReader, "version")) { ws.VersionNumber = identityReader.GetAttribute("number") ?? string.Empty; if (!identityReader.IsEmptyElement) { ws.VersionDescription = identityReader.ReadString(); identityReader.ReadEndElement(); } } string dateTime = GetSubNodeAttributeValue(identityReader, "generation", "date"); DateTime modified = DateTime.UtcNow; if (!string.IsNullOrEmpty(dateTime.Trim()) && !DateTime.TryParse(dateTime, out modified)) { //CVS format: "$Date: 2008/06/18 22:52:35 $" modified = DateTime.ParseExact(dateTime, "'$Date: 'yyyy/MM/dd HH:mm:ss $", null, DateTimeStyles.AssumeUniversal); } ws.DateModified = modified; ws.ISO639 = GetSubNodeAttributeValue(identityReader, "language", "type"); ws.Script = GetSubNodeAttributeValue(identityReader, "script", "type"); ws.Region = GetSubNodeAttributeValue(identityReader, "territory", "type"); ws.Variant = GetSubNodeAttributeValue(identityReader, "variant", "type"); // move to end of identity node while (identityReader.Read()) { } } if (!reader.IsEmptyElement) { reader.ReadEndElement(); } } private void ReadLayoutElement(XmlReader reader, WritingSystemDefinitionV0 ws) { // The orientation node has two attributes, "lines" and "characters" which define direction of writing. // The valid values are: "top-to-bottom", "bottom-to-top", "left-to-right", and "right-to-left" // Currently we only handle horizontal character orders with top-to-bottom line order, so // any value other than characters right-to-left, we treat as our default left-to-right order. // This probably works for many scripts such as various East Asian scripts which traditionally // are top-to-bottom characters and right-to-left lines, but can also be written with // left-to-right characters and top-to-bottom lines. Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.Name == "layout"); using (XmlReader layoutReader = reader.ReadSubtree()) { layoutReader.MoveToContent(); layoutReader.ReadStartElement("layout"); ws.RightToLeftScript = GetSubNodeAttributeValue(layoutReader, "orientation", "characters") == "right-to-left"; while (layoutReader.Read()) { } } if (!reader.IsEmptyElement) { reader.ReadEndElement(); } } private void ReadCollationsElement(XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(reader.NodeType == XmlNodeType.Element && reader.Name == "collations"); using (XmlReader collationsReader = reader.ReadSubtree()) { collationsReader.MoveToContent(); collationsReader.ReadStartElement("collations"); bool found = false; while (FindElement(collationsReader, "collation")) { // having no type is the same as type=standard, and is the only one we're interested in string typeValue = collationsReader.GetAttribute("type"); if (string.IsNullOrEmpty(typeValue) || typeValue == "standard") { found = true; break; } reader.Skip(); } if (found) { reader.MoveToElement(); string collationXml = reader.ReadInnerXml(); ReadCollationElement(collationXml, ws); } while (collationsReader.Read()) { } } if (!reader.IsEmptyElement) { reader.ReadEndElement(); } } private void ReadCollationElement(string collationXml, WritingSystemDefinitionV0 ws) { Debug.Assert(collationXml != null); Debug.Assert(ws != null); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; readerSettings.ConformanceLevel = ConformanceLevel.Fragment; using (XmlReader collationReader = XmlReader.Create(new StringReader(collationXml), readerSettings)) { if (FindElement(collationReader, "special")) { collationReader.Read(); string rulesTypeAsString = GetSpecialValue(collationReader, "palaso", "sortRulesType"); if (!String.IsNullOrEmpty(rulesTypeAsString)) { ws.SortUsing = (WritingSystemDefinitionV0.SortRulesType)Enum.Parse(typeof(WritingSystemDefinitionV0.SortRulesType), rulesTypeAsString); } } } switch (ws.SortUsing) { case WritingSystemDefinitionV0.SortRulesType.OtherLanguage: ReadCollationRulesForOtherLanguage(collationXml, ws); break; case WritingSystemDefinitionV0.SortRulesType.CustomSimple: ReadCollationRulesForCustomSimple(collationXml, ws); break; case WritingSystemDefinitionV0.SortRulesType.CustomICU: ReadCollationRulesForCustomICU(collationXml, ws); break; case WritingSystemDefinitionV0.SortRulesType.DefaultOrdering: break; default: string message = string.Format("Unhandled SortRulesType '{0}' while writing LDML definition file.", ws.SortUsing); throw new ApplicationException(message); } } private void ReadCollationRulesForOtherLanguage(string collationXml, WritingSystemDefinitionV0 ws) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; readerSettings.ConformanceLevel = ConformanceLevel.Fragment; using (XmlReader collationReader = XmlReader.Create(new StringReader(collationXml), readerSettings)) { bool foundValue = false; if (FindElement(collationReader, "base")) { if (!collationReader.IsEmptyElement && collationReader.ReadToDescendant("alias")) { string sortRules = collationReader.GetAttribute("source"); if (sortRules != null) { ws.SortRules = sortRules; foundValue = true; } } } if (!foundValue) { // missing base alias element, fall back to ICU rules ws.SortUsing = WritingSystemDefinitionV0.SortRulesType.CustomICU; ReadCollationRulesForCustomICU(collationXml, ws); } } } private void ReadCollationRulesForCustomICU(string collationXml, WritingSystemDefinitionV0 ws) { ws.SortRules = LdmlCollationParserV0.GetIcuRulesFromCollationNode(collationXml); } private void ReadCollationRulesForCustomSimple(string collationXml, WritingSystemDefinitionV0 ws) { string rules; if (LdmlCollationParserV0.TryGetSimpleRulesFromCollationNode(collationXml, out rules)) { ws.SortRules = rules; return; } // fall back to ICU rules if Simple rules don't work ws.SortUsing = WritingSystemDefinitionV0.SortRulesType.CustomICU; ReadCollationRulesForCustomICU(collationXml, ws); } public void Write(string filePath, WritingSystemDefinitionV0 ws, Stream oldFile) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (ws == null) { throw new ArgumentNullException("ws"); } XmlReader reader = null; try { if (oldFile != null) { var readerSettings = new XmlReaderSettings { NameTable = _nameSpaceManager.NameTable, ConformanceLevel = ConformanceLevel.Auto, ValidationType = ValidationType.None, XmlResolver = null, DtdProcessing = DtdProcessing.Parse, IgnoreWhitespace = true }; reader = XmlReader.Create(oldFile, readerSettings); } using (XmlWriter writer = XmlWriter.Create(filePath, CanonicalXmlSettings.CreateXmlWriterSettings())) { writer.WriteStartDocument(); WriteLdml(writer, reader, ws); writer.Close(); } } finally { if (reader != null) { reader.Close(); } } } public void Write(XmlWriter xmlWriter, WritingSystemDefinitionV0 ws, XmlReader xmlReader) { if (xmlWriter == null) { throw new ArgumentNullException("xmlWriter"); } if (ws == null) { throw new ArgumentNullException("ws"); } XmlReader reader = null; try { if (xmlReader != null) { var settings = new XmlReaderSettings { NameTable = _nameSpaceManager.NameTable, ConformanceLevel = ConformanceLevel.Auto, ValidationType = ValidationType.None, XmlResolver = null, DtdProcessing = DtdProcessing.Parse }; reader = XmlReader.Create(xmlReader, settings); } WriteLdml(xmlWriter, reader, ws); } finally { if (reader != null) { reader.Close(); } } } private void WriteLdml(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); writer.WriteStartElement("ldml"); if (reader != null) { reader.MoveToContent(); reader.ReadStartElement("ldml"); CopyUntilElement(writer, reader, "identity"); } WriteIdentityElement(writer, reader, ws); if (reader != null) { CopyUntilElement(writer, reader, "layout"); } WriteLayoutElement(writer, reader, ws); if (reader != null) { CopyUntilElement(writer, reader, "collations"); } WriteCollationsElement(writer, reader, ws); if (reader != null) { CopyUntilElement(writer, reader, "special"); } WriteTopLevelSpecialElements(writer, ws); if (reader != null) { CopyOtherSpecialElements(writer, reader); CopyToEndElement(writer, reader); } writer.WriteEndElement(); } private void CopyUntilElement(XmlWriter writer, XmlReader reader, string elementName) { Debug.Assert(writer != null); Debug.Assert(reader != null); Debug.Assert(!string.IsNullOrEmpty(elementName)); if (reader.NodeType == XmlNodeType.None) { reader.Read(); } while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && (reader.NodeType != XmlNodeType.Element || LdmlNodeComparerV0.CompareElementNames(reader.Name, elementName) < 0)) { // XmlWriter.WriteNode doesn't do anything if the node type is Attribute if (reader.NodeType == XmlNodeType.Attribute) { writer.WriteAttributes(reader, false); } else { writer.WriteNode(reader, false); } } } private void CopyToEndElement(XmlWriter writer, XmlReader reader) { Debug.Assert(writer != null); Debug.Assert(reader != null); while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement) { // XmlWriter.WriteNode doesn't do anything if the node type is Attribute if (reader.NodeType == XmlNodeType.Attribute) { writer.WriteAttributes(reader, false); } else { writer.WriteNode(reader, false); } } // either read the end element or no-op if EOF reader.Read(); } private void CopyOtherSpecialElements(XmlWriter writer, XmlReader reader) { Debug.Assert(writer != null); Debug.Assert(reader != null); while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && (reader.NodeType != XmlNodeType.Element || reader.Name == "special")) { if (reader.NodeType == XmlNodeType.Element) { bool knownNS = IsKnownSpecialElement(reader); reader.MoveToElement(); if (knownNS) { reader.Skip(); continue; } } writer.WriteNode(reader, false); } } private bool IsKnownSpecialElement(XmlReader reader) { while (reader.MoveToNextAttribute()) { if (reader.Name.StartsWith("xmlns:") && _nameSpaceManager.HasNamespace(reader.Name.Substring(6, reader.Name.Length - 6))) return true; } return false; } public void FillWithDefaults(string rfc4646, WritingSystemDefinitionV0 ws) { string id = rfc4646.ToLower(); switch (id) { case "en-latn": ws.ISO639 = "en"; ws.LanguageName = "English"; ws.Abbreviation = "eng"; ws.Script = "Latn"; break; default: ws.Script = "Latn"; break; } } protected string GetSpecialValue(XmlReader reader, string ns, string field) { if (!XmlHelpersV0.FindNextElementInSequence(reader, ns + ":" + field, _nameSpaceManager.LookupNamespace(ns), string.Compare)) { return string.Empty; } return reader.GetAttribute("value") ?? string.Empty; } private string GetSubNodeAttributeValue(XmlReader reader, string elementName, string attributeName) { return FindElement(reader, elementName) ? (reader.GetAttribute(attributeName) ?? string.Empty) : string.Empty; } private XmlNamespaceManager MakeNameSpaceManager() { XmlNamespaceManager m = new XmlNamespaceManager(new NameTable()); AddNamespaces(m); return m; } protected virtual void AddNamespaces(XmlNamespaceManager m) { m.AddNamespace("palaso", "urn://palaso.org/ldmlExtensions/v1"); } private void WriteElementWithAttribute(XmlWriter writer, string elementName, string attributeName, string value) { writer.WriteStartElement(elementName); writer.WriteAttributeString(attributeName, value); writer.WriteEndElement(); } protected void WriteSpecialValue(XmlWriter writer, string ns, string field, string value) { if (String.IsNullOrEmpty(value)) { return; } writer.WriteStartElement(field, _nameSpaceManager.LookupNamespace(ns)); writer.WriteAttributeString("value", value); writer.WriteEndElement(); } private void WriteIdentityElement(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); bool needToCopy = reader != null && reader.NodeType == XmlNodeType.Element && reader.Name == "identity"; writer.WriteStartElement("identity"); writer.WriteStartElement("version"); writer.WriteAttributeString("number", ws.VersionNumber); writer.WriteString(ws.VersionDescription); writer.WriteEndElement(); WriteElementWithAttribute(writer, "generation", "date", String.Format("{0:s}", ws.DateModified)); WriteElementWithAttribute(writer, "language", "type", ws.ISO639); if (!String.IsNullOrEmpty(ws.Script)) { WriteElementWithAttribute(writer, "script", "type", ws.Script); } if (!String.IsNullOrEmpty(ws.Region)) { WriteElementWithAttribute(writer, "territory", "type", ws.Region); } if (!String.IsNullOrEmpty(ws.Variant)) { WriteElementWithAttribute(writer, "variant", "type", ws.Variant); } if (needToCopy) { if (reader.IsEmptyElement) { reader.Skip(); } else { reader.Read(); // move past "identity" element} // <special> is the only node we possibly left out and need to copy FindElement(reader, "special"); CopyToEndElement(writer, reader); } } writer.WriteEndElement(); } private void WriteLayoutElement(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); bool needToCopy = reader != null && reader.NodeType == XmlNodeType.Element && reader.Name == "identity"; // if we're left-to-right, we don't need to write out default values bool needLayoutElement = ws.RightToLeftScript; if (needLayoutElement) { writer.WriteStartElement("layout"); writer.WriteStartElement("orientation"); // omit default value for "lines" attribute writer.WriteAttributeString("characters", "right-to-left"); writer.WriteEndElement(); } if (needToCopy) { if (reader.IsEmptyElement) { reader.Skip(); } else { reader.Read(); // skip any existing orientation and alias element, and copy the rest if (FindElement(reader, "orientation")) { reader.Skip(); } if (reader.NodeType != XmlNodeType.EndElement && !needLayoutElement) { needLayoutElement = true; writer.WriteStartElement("layout"); } CopyToEndElement(writer, reader); } } if (needLayoutElement) { writer.WriteEndElement(); } } protected void WriteBeginSpecialElement(XmlWriter writer, string ns) { writer.WriteStartElement("special"); writer.WriteAttributeString("xmlns", ns, null, _nameSpaceManager.LookupNamespace(ns)); } protected virtual void WriteTopLevelSpecialElements(XmlWriter writer, WritingSystemDefinitionV0 ws) { WriteBeginSpecialElement(writer, "palaso"); WriteSpecialValue(writer, "palaso", "abbreviation", ws.Abbreviation); WriteSpecialValue(writer, "palaso", "defaultFontFamily", ws.DefaultFontName); if (ws.DefaultFontSize != 0) { WriteSpecialValue(writer, "palaso", "defaultFontSize", ws.DefaultFontSize.ToString()); } WriteSpecialValue(writer, "palaso", "defaultKeyboard", ws.Keyboard); if (ws.IsLegacyEncoded) { WriteSpecialValue(writer, "palaso", "isLegacyEncoded", ws.IsLegacyEncoded.ToString()); } WriteSpecialValue(writer, "palaso", "languageName", ws.LanguageName); if (ws.SpellCheckingId != ws.ISO639) { WriteSpecialValue(writer, "palaso", "spellCheckingId", ws.SpellCheckingId); } writer.WriteEndElement(); } private void WriteCollationsElement(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); bool needToCopy = reader != null && reader.NodeType == XmlNodeType.Element && reader.Name == "collations"; writer.WriteStartElement("collations"); if (needToCopy) { if (reader.IsEmptyElement) { reader.Skip(); needToCopy = false; } else { reader.ReadStartElement("collations"); if (FindElement(reader, "alias")) { reader.Skip(); } CopyUntilElement(writer, reader, "collation"); } } WriteCollationElement(writer, reader, ws); if (needToCopy) { CopyToEndElement(writer, reader); } writer.WriteEndElement(); } private void WriteCollationElement(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); bool needToCopy = reader != null && reader.NodeType == XmlNodeType.Element && reader.Name == "collation"; if (needToCopy) { string collationType = reader.GetAttribute("type"); needToCopy = String.IsNullOrEmpty(collationType) || collationType == "standard"; } if (needToCopy && reader.IsEmptyElement) { reader.Skip(); needToCopy = false; } if (ws.SortUsing == WritingSystemDefinitionV0.SortRulesType.DefaultOrdering && !needToCopy) return; if (needToCopy && reader.IsEmptyElement) { reader.Skip(); needToCopy = false; } if (!needToCopy) { // set to null if we don't need to copy to make it easier to tell in the methods we call reader = null; } else { reader.ReadStartElement("collation"); while (reader.NodeType == XmlNodeType.Attribute) { reader.Read(); } } if (ws.SortUsing != WritingSystemDefinitionV0.SortRulesType.DefaultOrdering) { writer.WriteStartElement("collation"); switch (ws.SortUsing) { case WritingSystemDefinitionV0.SortRulesType.OtherLanguage: WriteCollationRulesFromOtherLanguage(writer, reader, ws); break; case WritingSystemDefinitionV0.SortRulesType.CustomSimple: WriteCollationRulesFromCustomSimple(writer, reader, ws); break; case WritingSystemDefinitionV0.SortRulesType.CustomICU: WriteCollationRulesFromCustomIcu(writer, reader, ws); break; default: string message = string.Format("Unhandled SortRulesType '{0}' while writing LDML definition file.", ws.SortUsing); throw new ApplicationException(message); } WriteBeginSpecialElement(writer, "palaso"); WriteSpecialValue(writer, "palaso", "sortRulesType", ws.SortUsing.ToString()); writer.WriteEndElement(); if (needToCopy) { if (FindElement(reader, "special")) { CopyOtherSpecialElements(writer, reader); } CopyToEndElement(writer, reader); } writer.WriteEndElement(); } else if (needToCopy) { bool startElementWritten = false; if (FindElement(reader, "special")) { // write out any other special elements while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && (reader.NodeType != XmlNodeType.Element || reader.Name == "special")) { if (reader.NodeType == XmlNodeType.Element) { bool knownNS = IsKnownSpecialElement(reader); reader.MoveToElement(); if (knownNS) { reader.Skip(); continue; } } if (!startElementWritten) { writer.WriteStartElement("collation"); startElementWritten = true; } writer.WriteNode(reader, false); } } if (!reader.EOF && reader.NodeType != XmlNodeType.EndElement) { // copy any other elements if (!startElementWritten) { writer.WriteStartElement("collation"); startElementWritten = true; } CopyToEndElement(writer, reader); } if (startElementWritten) writer.WriteEndElement(); } } private void WriteCollationRulesFromOtherLanguage(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); Debug.Assert(ws.SortUsing == WritingSystemDefinitionV0.SortRulesType.OtherLanguage); // Since the alias element gets all information from another source, // we should remove all other elements in this collation element. We // leave "special" elements as they are custom data from some other app. writer.WriteStartElement("base"); WriteElementWithAttribute(writer, "alias", "source", ws.SortRules); writer.WriteEndElement(); if (reader != null) { // don't copy anything, but skip to the 1st special node FindElement(reader, "special"); } } private void WriteCollationRulesFromCustomSimple(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); Debug.Assert(ws.SortUsing == WritingSystemDefinitionV0.SortRulesType.CustomSimple); var parser = new SimpleRulesParser(); string message; // avoid throwing exception, just don't save invalid data if (!parser.ValidateSimpleRules(ws.SortRules ?? string.Empty, out message)) { return; } string icu = parser.ConvertToIcuRules(ws.SortRules ?? string.Empty); WriteCollationRulesFromIcuString(writer, reader, icu); } private void WriteCollationRulesFromCustomIcu(XmlWriter writer, XmlReader reader, WritingSystemDefinitionV0 ws) { Debug.Assert(writer != null); Debug.Assert(ws != null); Debug.Assert(ws.SortUsing == WritingSystemDefinitionV0.SortRulesType.CustomICU); WriteCollationRulesFromIcuString(writer, reader, ws.SortRules); } private void WriteCollationRulesFromIcuString(XmlWriter writer, XmlReader reader, string icu) { Debug.Assert(writer != null); icu = icu ?? string.Empty; if (reader != null) { // don't copy any alias that would override our rules if (FindElement(reader, "alias")) { reader.Skip(); } CopyUntilElement(writer, reader, "settings"); // for now we'll omit anything in the suppress_contractions and optimize nodes FindElement(reader, "special"); } var parser = new IcuRulesParser(false); string message; // avoid throwing exception, just don't save invalid data if (!parser.ValidateIcuRules(icu, out message)) { return; } parser.WriteIcuRules(writer, icu); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.CompilerServices; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; public sealed class DataContractSerializer : XmlObjectSerializer { private Type _rootType; private DataContract _rootContract; // post-surrogate private bool _needsContractNsAtRoot; private XmlDictionaryString _rootName; private XmlDictionaryString _rootNamespace; private int _maxItemsInObjectGraph; private bool _ignoreExtensionDataObject; private bool _preserveObjectReferences; private ReadOnlyCollection<Type> _knownTypeCollection; internal IList<Type> knownTypeList; internal DataContractDictionary knownDataContracts; private DataContractResolver _dataContractResolver; private ISerializationSurrogateProvider _serializationSurrogateProvider; private bool _serializeReadOnlyTypes; private static SerializationOption _option = SerializationOption.ReflectionAsBackup; private static bool _optionAlreadySet; public static SerializationOption Option { get { return _option; } set { if (_optionAlreadySet) { throw new InvalidOperationException("Can only set once"); } _optionAlreadySet = true; _option = value; } } public DataContractSerializer(Type type) : this(type, (IEnumerable<Type>)null) { } public DataContractSerializer(Type type, IEnumerable<Type> knownTypes) { Initialize(type, knownTypes, int.MaxValue, false, false, null, false); } public DataContractSerializer(Type type, string rootName, string rootNamespace) : this(type, rootName, rootNamespace, null) { } public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable<Type> knownTypes) { XmlDictionary dictionary = new XmlDictionary(2); Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, int.MaxValue, false, false, null, false); } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace) : this(type, rootName, rootNamespace, null) { } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes) { Initialize(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false, null, false); } #if NET_NATIVE public DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences) #else internal DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences) #endif { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, null, false); } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, DataContractResolver dataContractResolver) { Initialize(type, rootName, rootNamespace, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, /*dataContractSurrogate,*/ dataContractResolver, false); } public DataContractSerializer(Type type, DataContractSerializerSettings settings) { if (settings == null) { settings = new DataContractSerializerSettings(); } Initialize(type, settings.RootName, settings.RootNamespace, settings.KnownTypes, settings.MaxItemsInObjectGraph, false, settings.PreserveObjectReferences, settings.DataContractResolver, settings.SerializeReadOnlyTypes); } private void Initialize(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, DataContractResolver dataContractResolver, bool serializeReadOnlyTypes) { CheckNull(type, "type"); _rootType = type; if (knownTypes != null) { this.knownTypeList = new List<Type>(); foreach (Type knownType in knownTypes) { this.knownTypeList.Add(knownType); } } if (maxItemsInObjectGraph < 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maxItemsInObjectGraph), SR.Format(SR.ValueMustBeNonNegative))); _maxItemsInObjectGraph = maxItemsInObjectGraph; _ignoreExtensionDataObject = ignoreExtensionDataObject; _preserveObjectReferences = preserveObjectReferences; _dataContractResolver = dataContractResolver; _serializeReadOnlyTypes = serializeReadOnlyTypes; } private void Initialize(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, DataContractResolver dataContractResolver, bool serializeReadOnlyTypes) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractResolver, serializeReadOnlyTypes); // validate root name and namespace are both non-null _rootName = rootName; _rootNamespace = rootNamespace; } public ReadOnlyCollection<Type> KnownTypes { get { if (_knownTypeCollection == null) { if (knownTypeList != null) { _knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList); } else { _knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>()); } } return _knownTypeCollection; } } internal override DataContractDictionary KnownDataContracts { get { if (this.knownDataContracts == null && this.knownTypeList != null) { // This assignment may be performed concurrently and thus is a race condition. // It's safe, however, because at worse a new (and identical) dictionary of // data contracts will be created and re-assigned to this field. Introduction // of a lock here could lead to deadlocks. this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList); } return this.knownDataContracts; } } public int MaxItemsInObjectGraph { get { return _maxItemsInObjectGraph; } } internal ISerializationSurrogateProvider SerializationSurrogateProvider { get { return _serializationSurrogateProvider; } set { _serializationSurrogateProvider = value; } } public bool PreserveObjectReferences { get { return _preserveObjectReferences; } } public bool IgnoreExtensionDataObject { get { return _ignoreExtensionDataObject; } } public DataContractResolver DataContractResolver { get { return _dataContractResolver; } } public bool SerializeReadOnlyTypes { get { return _serializeReadOnlyTypes; } } private DataContract RootContract { get { if (_rootContract == null) { _rootContract = DataContract.GetDataContract((_serializationSurrogateProvider == null) ? _rootType : GetSurrogatedType(_serializationSurrogateProvider, _rootType)); _needsContractNsAtRoot = CheckIfNeedsContractNsAtRoot(_rootName, _rootNamespace, _rootContract); } return _rootContract; } } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) { InternalWriteObject(writer, graph, null); } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { InternalWriteStartObject(writer, graph); InternalWriteObjectContent(writer, graph, dataContractResolver); InternalWriteEndObject(writer); } public override void WriteObject(XmlWriter writer, object graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteStartObject(XmlWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlDictionaryWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public override object ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlDictionaryReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { WriteRootElement(writer, RootContract, _rootName, _rootNamespace, _needsContractNsAtRoot); } internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { InternalWriteObjectContent(writer, graph, null); } internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); DataContract contract = RootContract; Type declaredType = contract.UnderlyingType; Type graphType = (graph == null) ? declaredType : graph.GetType(); if (_serializationSurrogateProvider != null) { graph = SurrogateToDataContractType(_serializationSurrogateProvider, graph, declaredType, ref graphType); } if (dataContractResolver == null) dataContractResolver = this.DataContractResolver; if (graph == null) { if (IsRootXmlAny(_rootName, contract)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeNull, declaredType))); WriteNull(writer); } else { if (declaredType == graphType) { if (contract.CanContainReferences) { XmlObjectSerializerWriteContext context = XmlObjectSerializerWriteContext.CreateContext(this, contract , dataContractResolver ); context.HandleGraphAtTopLevel(writer, graph, contract); context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle); } else { contract.WriteXmlValue(writer, graph, null); } } else { XmlObjectSerializerWriteContext context = null; if (IsRootXmlAny(_rootName, contract)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType))); contract = GetDataContract(contract, declaredType, graphType); context = XmlObjectSerializerWriteContext.CreateContext(this, RootContract , dataContractResolver ); if (contract.CanContainReferences) { context.HandleGraphAtTopLevel(writer, graph, contract); } context.OnHandleIsReference(writer, contract, graph); context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType); } } } internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) { if (declaredType.GetTypeInfo().IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { return declaredTypeContract; } else if (declaredType.IsArray)//Array covariance is not supported in XSD { return declaredTypeContract; } else { return DataContract.GetDataContract(objectType.TypeHandle, objectType, SerializationMode.SharedContract); } } internal override void InternalWriteEndObject(XmlWriterDelegator writer) { if (!IsRootXmlAny(_rootName, RootContract)) { writer.WriteEndElement(); } } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { return InternalReadObject(xmlReader, verifyObjectName, null); } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver dataContractResolver) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); if (dataContractResolver == null) dataContractResolver = this.DataContractResolver; #if NET_NATIVE // Give the root contract a chance to initialize or pre-verify the read RootContract.PrepareToRead(xmlReader); #endif if (verifyObjectName) { if (!InternalIsStartObject(xmlReader)) { XmlDictionaryString expectedName; XmlDictionaryString expectedNs; if (_rootName == null) { expectedName = RootContract.TopLevelElementName; expectedNs = RootContract.TopLevelElementNamespace; } else { expectedName = _rootName; expectedNs = _rootNamespace; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElement, expectedNs, expectedName), xmlReader)); } } else if (!IsStartElement(xmlReader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader)); } DataContract contract = RootContract; if (contract.IsPrimitive && object.ReferenceEquals(contract.UnderlyingType, _rootType) /*handle Nullable<T> differently*/) { return contract.ReadXmlValue(xmlReader, null); } if (IsRootXmlAny(_rootName, contract)) { return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, contract as XmlDataContract, false /*isMemberType*/); } XmlObjectSerializerReadContext context = XmlObjectSerializerReadContext.CreateContext(this, contract, dataContractResolver); return context.InternalDeserialize(xmlReader, _rootType, contract, null, null); } internal override bool InternalIsStartObject(XmlReaderDelegator reader) { return IsRootElement(reader, RootContract, _rootName, _rootNamespace); } internal override Type GetSerializeType(object graph) { return (graph == null) ? _rootType : graph.GetType(); } internal override Type GetDeserializeType() { return _rootType; } internal static object SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider, object oldObj, Type surrogatedDeclaredType, ref Type objType) { object obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType); if (obj != oldObj) { objType = obj != null ? obj.GetType() : Globals.TypeOfObject; } return obj; } internal static Type GetSurrogatedType(ISerializationSurrogateProvider serializationSurrogateProvider, Type type) { return DataContractSurrogateCaller.GetDataContractType(serializationSurrogateProvider, DataContract.UnwrapNullableType(type)); } } }
//--------------------------------------------------------------------- // <copyright file="NavigationProperty.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.EntityModel.SchemaObjectModel { using System.Data.Metadata.Edm; using System.Diagnostics; using System.Globalization; using System.Xml; /// <summary> /// Summary description for Association. /// </summary> [System.Diagnostics.DebuggerDisplay("Name={Name}, Relationship={_unresolvedRelationshipName}, FromRole={_unresolvedFromEndRole}, ToRole={_unresolvedToEndRole}")] internal sealed class NavigationProperty : Property { private string _unresolvedFromEndRole = null; private string _unresolvedToEndRole = null; private string _unresolvedRelationshipName = null; private IRelationshipEnd _fromEnd = null; private IRelationshipEnd _toEnd = null; private IRelationship _relationship = null; /// <summary> /// /// </summary> /// <param name="parent"></param> public NavigationProperty(SchemaEntityType parent) : base(parent) { } /// <summary> /// /// </summary> public new SchemaEntityType ParentElement { get { return base.ParentElement as SchemaEntityType; } } internal IRelationship Relationship { get { return _relationship; } } internal IRelationshipEnd ToEnd { get { return _toEnd; } } internal IRelationshipEnd FromEnd { get { return _fromEnd; } } /// <summary> /// Gets the Type of the property /// </summary> public override SchemaType Type { get { if (_toEnd == null || _toEnd.Type == null) { return null; } return _toEnd.Type; } } protected override bool HandleAttribute(XmlReader reader) { if (base.HandleAttribute(reader)) { return true; } else if (CanHandleAttribute(reader, XmlConstants.Relationship)) { HandleAssociationAttribute(reader); return true; } else if (CanHandleAttribute(reader, XmlConstants.FromRole)) { HandleFromRoleAttribute(reader); return true; } else if (CanHandleAttribute(reader, XmlConstants.ToRole)) { HandleToRoleAttribute(reader); return true; } else if (CanHandleAttribute(reader, XmlConstants.ContainsTarget)) { // EF does not support this EDM 3.0 attribute, so ignore it. return true; } return false; } /// <summary> /// /// </summary> internal override void ResolveTopLevelNames() { base.ResolveTopLevelNames(); SchemaType element; if (!Schema.ResolveTypeName(this, _unresolvedRelationshipName, out element)) return; _relationship = element as IRelationship; if (_relationship == null) { AddError(ErrorCode.BadNavigationProperty, EdmSchemaErrorSeverity.Error, System.Data.Entity.Strings.BadNavigationPropertyRelationshipNotRelationship(_unresolvedRelationshipName)); return; } bool foundBothEnds = true; if (!_relationship.TryGetEnd(_unresolvedFromEndRole, out _fromEnd)) { AddError(ErrorCode.BadNavigationProperty, EdmSchemaErrorSeverity.Error, System.Data.Entity.Strings.BadNavigationPropertyUndefinedRole(_unresolvedFromEndRole, _relationship.FQName)); foundBothEnds = false; } if (!_relationship.TryGetEnd(_unresolvedToEndRole, out _toEnd)) { AddError(ErrorCode.BadNavigationProperty, EdmSchemaErrorSeverity.Error, System.Data.Entity.Strings.BadNavigationPropertyUndefinedRole(_unresolvedToEndRole, _relationship.FQName)); foundBothEnds = false; } if (foundBothEnds && _fromEnd == _toEnd) { AddError(ErrorCode.BadNavigationProperty, EdmSchemaErrorSeverity.Error, System.Data.Entity.Strings.BadNavigationPropertyRolesCannotBeTheSame); } } /// <summary> /// /// </summary> internal override void Validate() { base.Validate(); System.Diagnostics.Debug.Assert(_fromEnd != null && _toEnd != null, "FromEnd and ToEnd must not be null in Validate. ResolveNames must have resolved it or added error"); if (_fromEnd.Type != ParentElement) { AddError(ErrorCode.BadNavigationProperty, EdmSchemaErrorSeverity.Error, System.Data.Entity.Strings.BadNavigationPropertyBadFromRoleType(this.Name, _fromEnd.Type.FQName, _fromEnd.Name, _relationship.FQName, ParentElement.FQName)); } StructuredType type = _toEnd.Type; } #region Private Methods /// <summary> /// /// </summary> /// <param name="reader"></param> private void HandleToRoleAttribute(XmlReader reader) { _unresolvedToEndRole = HandleUndottedNameAttribute(reader, _unresolvedToEndRole); } /// <summary> /// /// </summary> /// <param name="reader"></param> private void HandleFromRoleAttribute(XmlReader reader) { _unresolvedFromEndRole = HandleUndottedNameAttribute(reader, _unresolvedFromEndRole); } /// <summary> /// /// </summary> /// <param name="reader"></param> private void HandleAssociationAttribute(XmlReader reader) { Debug.Assert(_unresolvedRelationshipName == null, string.Format(CultureInfo.CurrentCulture, "{0} is already defined", reader.Name)); string association; if (!Utils.GetDottedName(this.Schema, reader, out association)) return; _unresolvedRelationshipName = association; } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Analyzer = Lucene.Net.Analysis.Analyzer; using BooleanClause = Lucene.Net.Search.BooleanClause; using BooleanQuery = Lucene.Net.Search.BooleanQuery; using MultiPhraseQuery = Lucene.Net.Search.MultiPhraseQuery; using PhraseQuery = Lucene.Net.Search.PhraseQuery; using Query = Lucene.Net.Search.Query; namespace Lucene.Net.QueryParsers { /// <summary> A QueryParser which constructs queries to search multiple fields. /// /// /// </summary> /// <version> $Revision: 564236 $ /// </version> public class MultiFieldQueryParser : QueryParser { protected internal System.String[] fields; protected internal System.Collections.IDictionary boosts; /// <summary> Creates a MultiFieldQueryParser. /// Allows passing of a map with term to Boost, and the boost to apply to each term. /// /// <p>It will, when parse(String query) /// is called, construct a query like this (assuming the query consists of /// two terms and you specify the two fields <code>title</code> and <code>body</code>):</p> /// /// <code> /// (title:term1 body:term1) (title:term2 body:term2) /// </code> /// /// <p>When setDefaultOperator(AND_OPERATOR) is set, the result will be:</p> /// /// <code> /// +(title:term1 body:term1) +(title:term2 body:term2) /// </code> /// /// <p>When you pass a boost (title=>5 body=>10) you can get </p> /// /// <code> /// +(title:term1^5.0 body:term1^10.0) +(title:term2^5.0 body:term2^10.0) /// </code> /// /// <p>In other words, all the query's terms must appear, but it doesn't matter in /// what fields they appear.</p> /// </summary> public MultiFieldQueryParser(System.String[] fields, Analyzer analyzer, System.Collections.IDictionary boosts):this(fields, analyzer) { this.boosts = boosts; } /// <summary> Creates a MultiFieldQueryParser. /// /// <p>It will, when parse(String query) /// is called, construct a query like this (assuming the query consists of /// two terms and you specify the two fields <code>title</code> and <code>body</code>):</p> /// /// <code> /// (title:term1 body:term1) (title:term2 body:term2) /// </code> /// /// <p>When setDefaultOperator(AND_OPERATOR) is set, the result will be:</p> /// /// <code> /// +(title:term1 body:term1) +(title:term2 body:term2) /// </code> /// /// <p>In other words, all the query's terms must appear, but it doesn't matter in /// what fields they appear.</p> /// </summary> public MultiFieldQueryParser(System.String[] fields, Analyzer analyzer) : base(null, analyzer) { this.fields = fields; } public override Query GetFieldQuery(System.String field, System.String queryText, int slop) { if (field == null) { System.Collections.ArrayList clauses = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); for (int i = 0; i < fields.Length; i++) { Query q = GetFieldQuery(fields[i], queryText); if (q != null) { //If the user passes a map of boosts if (boosts != null) { //Get the boost from the map and apply them System.Single boost = (System.Single) boosts[fields[i]]; //if (boost != null) // {{Aroush-2.1 there is no null for 'boost' if (boosts[fields[i]] != null) // {{Aroush-2.1 will this line do? { q.SetBoost((float) boost); } } ApplySlop(q, slop); clauses.Add(new BooleanClause(q, BooleanClause.Occur.SHOULD)); } } if (clauses.Count == 0) // happens for stopwords return null; return GetBooleanQuery(clauses, true); } Query q2 = base.GetFieldQuery(field, queryText); ApplySlop(q2, slop); return q2; } private void ApplySlop(Query q, int slop) { if (q is PhraseQuery) { ((PhraseQuery)q).SetSlop(slop); } if (q is MultiPhraseQuery) { ((MultiPhraseQuery)q).SetSlop(slop); } } public override Query GetFieldQuery(System.String field, System.String queryText) { return GetFieldQuery(field, queryText, 0); } public override Query GetFuzzyQuery(System.String field, System.String termStr, float minSimilarity) { if (field == null) { System.Collections.ArrayList clauses = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetFuzzyQuery(fields[i], termStr, minSimilarity), BooleanClause.Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetFuzzyQuery(field, termStr, minSimilarity); } public override Query GetPrefixQuery(System.String field, System.String termStr) { if (field == null) { System.Collections.ArrayList clauses = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetPrefixQuery(fields[i], termStr), BooleanClause.Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetPrefixQuery(field, termStr); } public override Query GetWildcardQuery(System.String field, System.String termStr) { if (field == null) { System.Collections.ArrayList clauses = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetWildcardQuery(fields[i], termStr), BooleanClause.Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetWildcardQuery(field, termStr); } public override Query GetRangeQuery(System.String field, System.String part1, System.String part2, bool inclusive) { if (field == null) { System.Collections.ArrayList clauses = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetRangeQuery(fields[i], part1, part2, inclusive), BooleanClause.Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetRangeQuery(field, part1, part2, inclusive); } /// <summary> Parses a query which searches on the fields specified. /// <p> /// If x fields are specified, this effectively constructs: /// <pre> /// <code> /// (field1:query1) (field2:query2) (field3:query3)...(fieldx:queryx) /// </code> /// </pre> /// </summary> /// <param name="queries">Queries strings to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException if query parsing fails </throws> /// <throws> IllegalArgumentException if the length of the queries array differs </throws> /// <summary> from the length of the fields array /// </summary> public static Query Parse(System.String[] queries, System.String[] fields, Analyzer analyzer) { if (queries.Length != fields.Length) throw new System.ArgumentException("queries.length != fields.length"); BooleanQuery bQuery = new BooleanQuery(); for (int i = 0; i < fields.Length; i++) { QueryParser qp = new QueryParser(fields[i], analyzer); Query q = qp.Parse(queries[i]); if (q != null && (!(q is BooleanQuery) || ((BooleanQuery) q).GetClauses().Length > 0)) { bQuery.Add(q, BooleanClause.Occur.SHOULD); } } return bQuery; } /// <summary> Parses a query, searching on the fields specified. /// Use this if you need to specify certain fields as required, /// and others as prohibited. /// <p><pre> /// Usage: /// <code> /// String[] fields = {"filename", "contents", "description"}; /// BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, /// BooleanClause.Occur.MUST, /// BooleanClause.Occur.MUST_NOT}; /// MultiFieldQueryParser.parse("query", fields, flags, analyzer); /// </code> /// </pre> /// <p> /// The code above would construct a query: /// <pre> /// <code> /// (filename:query) +(contents:query) -(description:query) /// </code> /// </pre> /// /// </summary> /// <param name="query">Query string to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="flags">Flags describing the fields /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException if query parsing fails </throws> /// <throws> IllegalArgumentException if the length of the fields array differs </throws> /// <summary> from the length of the flags array /// </summary> public static Query Parse(System.String query, System.String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer) { if (fields.Length != flags.Length) throw new System.ArgumentException("fields.length != flags.length"); BooleanQuery bQuery = new BooleanQuery(); for (int i = 0; i < fields.Length; i++) { QueryParser qp = new QueryParser(fields[i], analyzer); Query q = qp.Parse(query); if (q != null && (!(q is BooleanQuery) || ((BooleanQuery) q).GetClauses().Length > 0)) { bQuery.Add(q, flags[i]); } } return bQuery; } /// <summary> Parses a query, searching on the fields specified. /// Use this if you need to specify certain fields as required, /// and others as prohibited. /// <p><pre> /// Usage: /// <code> /// String[] query = {"query1", "query2", "query3"}; /// String[] fields = {"filename", "contents", "description"}; /// BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, /// BooleanClause.Occur.MUST, /// BooleanClause.Occur.MUST_NOT}; /// MultiFieldQueryParser.parse(query, fields, flags, analyzer); /// </code> /// </pre> /// <p> /// The code above would construct a query: /// <pre> /// <code> /// (filename:query1) +(contents:query2) -(description:query3) /// </code> /// </pre> /// /// </summary> /// <param name="queries">Queries string to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="flags">Flags describing the fields /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException if query parsing fails </throws> /// <throws> IllegalArgumentException if the length of the queries, fields, </throws> /// <summary> and flags array differ /// </summary> public static Query Parse(System.String[] queries, System.String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer) { if (!(queries.Length == fields.Length && queries.Length == flags.Length)) throw new System.ArgumentException("queries, fields, and flags array have have different length"); BooleanQuery bQuery = new BooleanQuery(); for (int i = 0; i < fields.Length; i++) { QueryParser qp = new QueryParser(fields[i], analyzer); Query q = qp.Parse(queries[i]); if (q != null && (!(q is BooleanQuery) || ((BooleanQuery) q).GetClauses().Length > 0)) { bQuery.Add(q, flags[i]); } } return bQuery; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using MigAz.Azure.MigrationTarget; using MigAz.Azure.Core.Interface; using System.Collections.Generic; using System; using MigAz.Azure.Core.Generator; using System.Threading.Tasks; using MigAz.Azure.Core; using System.Linq; namespace MigAz.Azure { public class ExportArtifacts : IExportArtifacts { private List<MigAzGeneratorAlert> _Alerts = new List<MigAzGeneratorAlert>(); public delegate Task AfterResourceValidationHandler(); public event AfterResourceValidationHandler AfterResourceValidation; public ExportArtifacts(AzureSubscription targetSubscription) { VirtualNetworkGateways = new List<VirtualNetworkGateway>(); VirtualNetworkGatewayConnections = new List<VirtualNetworkGatewayConnection>(); LocalNetworkGateways = new List<LocalNetworkGateway>(); NetworkSecurityGroups = new List<NetworkSecurityGroup>(); RouteTables = new List<RouteTable>(); StorageAccounts = new List<StorageAccount>(); VirtualNetworks = new List<VirtualNetwork>(); AvailablitySets = new List<AvailabilitySet>(); VirtualMachines = new List<VirtualMachine>(); LoadBalancers = new List<LoadBalancer>(); PublicIPs = new List<PublicIp>(); Disks = new List<Disk>(); NetworkInterfaces = new List<NetworkInterface>(); RouteTables = new List<RouteTable>(); this.TargetSubscription = targetSubscription; } public ResourceGroup ResourceGroup { get; set; } public List<VirtualNetworkGateway> VirtualNetworkGateways { get; } public List<VirtualNetworkGatewayConnection> VirtualNetworkGatewayConnections { get; } public List<LocalNetworkGateway> LocalNetworkGateways { get; } public List<NetworkSecurityGroup> NetworkSecurityGroups { get; } public List<StorageAccount> StorageAccounts { get; } public List<VirtualNetwork> VirtualNetworks { get; } public List<AvailabilitySet> AvailablitySets { get; } public List<VirtualMachine> VirtualMachines { get; } public List<LoadBalancer> LoadBalancers { get; } public List<PublicIp> PublicIPs { get; } public List<Disk> Disks { get; } public List<NetworkInterface> NetworkInterfaces { get; } public List<RouteTable> RouteTables { get; } public List<MigAzGeneratorAlert> Alerts { get { return _Alerts; } } public AzureSubscription TargetSubscription { get; private set; } public NetworkSecurityGroup SeekNetworkSecurityGroup(string sourceName) { foreach (NetworkSecurityGroup networkSecurityGroup in NetworkSecurityGroups) { if (networkSecurityGroup.ToString() == sourceName) return networkSecurityGroup; } return null; } internal PublicIp SeekPublicIp(string sourceName) { foreach (PublicIp publicIp in PublicIPs) { if (publicIp.ToString() == sourceName) return publicIp; } return null; } internal bool ContainsLoadBalancer(LoadBalancer loadBalancer) { foreach (LoadBalancer exportArtifactLoadBalancer in LoadBalancers) { if (exportArtifactLoadBalancer.ToString() == loadBalancer.ToString()) return true; } return false; } public bool HasErrors { get { foreach (MigAzGeneratorAlert alert in this.Alerts) { if (alert.AlertType == AlertType.Error) return true; } return false; } } public MigAzGeneratorAlert SeekAlert(string alertMessage) { foreach (MigAzGeneratorAlert alert in this.Alerts) { if (alert.Message.Contains(alertMessage)) return alert; } return null; } public async Task ValidateAzureResources() { Alerts.Clear(); if (this.TargetSubscription == null) { this.AddAlert(AlertType.Error, "Target Azure Subscription must be provided for template generation.", this.ResourceGroup); } else { if (this.TargetSubscription.Locations == null || this.TargetSubscription.Locations.Count() == 0) { this.AddAlert(AlertType.Error, "Target Azure Subscription must have one or more Locations instantiated.", this.ResourceGroup); } } if (this.ResourceGroup == null) { this.AddAlert(AlertType.Error, "Target Resource Group must be provided for template generation.", this.ResourceGroup); } else { if (this.ResourceGroup.TargetLocation == null) { this.AddAlert(AlertType.Error, "Target Resource Group Location must be provided for template generation.", this.ResourceGroup); } else { // It is possible that the Target Location is no longer in the Target Subscription // Sample case, user first connected to Azure Commercial as source (and set as initial target) // but then logged into a different account for the target and target is now USGov. if (this.TargetSubscription != null && this.TargetSubscription.Locations != null) { if (!this.TargetSubscription.Locations.Contains(this.ResourceGroup.TargetLocation)) { this.AddAlert(AlertType.Error, "Target Resource Group Location '" + this.ResourceGroup.TargetLocation.ToString() + "' is not available in Subscription '" + this.TargetSubscription.ToString() + "'. Select a new Target Location.", this.ResourceGroup); } } } } foreach (MigrationTarget.StorageAccount targetStorageAccount in this.StorageAccounts) { ValidateTargetApiVersion(targetStorageAccount); await targetStorageAccount.CheckNameAvailability(this.TargetSubscription); if (!targetStorageAccount.IsNameAvailable) this.AddAlert(AlertType.Error, "Target Name for Storage Account '" + targetStorageAccount.ToString() + "' already exists within Azure Environment " + this.TargetSubscription.AzureEnvironment.ToString() + ". A new (available) target name must be specified.", targetStorageAccount); if (targetStorageAccount.BlobStorageNamespace == null || targetStorageAccount.BlobStorageNamespace.Trim().Length <= 0) this.AddAlert(AlertType.Error, "Blob Storage Namespace for Target Storage Account '" + targetStorageAccount.ToString() + "' must be specified.", targetStorageAccount); if (!this.IsStorageAccountVmDiskTarget(targetStorageAccount)) this.AddAlert(AlertType.Warning, "Target Storage Account '" + targetStorageAccount.ToString() + "' is not utilized within this Resource Group Deployment as a Virtual Machine Disk Target. Consider removing to avoid creation of a non-utilized Storage Account.", targetStorageAccount); } foreach (MigrationTarget.VirtualNetwork targetVirtualNetwork in this.VirtualNetworks) { ValidateTargetApiVersion(targetVirtualNetwork); foreach (MigrationTarget.Subnet targetSubnet in targetVirtualNetwork.TargetSubnets) { if (targetSubnet.NetworkSecurityGroup != null) { MigrationTarget.NetworkSecurityGroup networkSecurityGroupInMigration = this.SeekNetworkSecurityGroup(targetSubnet.NetworkSecurityGroup.ToString()); if (networkSecurityGroupInMigration == null) { this.AddAlert(AlertType.Error, "Virtual Network '" + targetVirtualNetwork.ToString() + "' Subnet '" + targetSubnet.ToString() + "' utilizes Network Security Group (NSG) '" + targetSubnet.NetworkSecurityGroup.ToString() + "', but the NSG resource is not added into the migration template.", targetSubnet); } } } } foreach (MigrationTarget.NetworkSecurityGroup targetNetworkSecurityGroup in this.NetworkSecurityGroups) { ValidateTargetApiVersion(targetNetworkSecurityGroup); if (targetNetworkSecurityGroup.TargetName == string.Empty) this.AddAlert(AlertType.Error, "Target Name for Network Security Group must be specified.", targetNetworkSecurityGroup); } foreach (MigrationTarget.LoadBalancer targetLoadBalancer in this.LoadBalancers) { ValidateTargetApiVersion(targetLoadBalancer); if (targetLoadBalancer.TargetName == string.Empty) this.AddAlert(AlertType.Error, "Target Name for Load Balancer must be specified.", targetLoadBalancer); if (targetLoadBalancer.FrontEndIpConfigurations.Count == 0) { this.AddAlert(AlertType.Error, "Load Balancer must have a FrontEndIpConfiguration.", targetLoadBalancer); } else { if (targetLoadBalancer.LoadBalancerType == MigrationTarget.LoadBalancerType.Internal) { if (targetLoadBalancer.FrontEndIpConfigurations.Count > 0) { if (targetLoadBalancer.FrontEndIpConfigurations[0].TargetSubnet == null) { this.AddAlert(AlertType.Error, "Internal Load Balancer must have an internal Subnet association.", targetLoadBalancer); } else { // russell if (targetLoadBalancer.FrontEndIpConfigurations[0].TargetPrivateIPAllocationMethod == IPAllocationMethodEnum.Static) { if (!IPv4CIDR.IsIpAddressInAddressPrefix(targetLoadBalancer.FrontEndIpConfigurations[0].TargetSubnet.AddressPrefix, targetLoadBalancer.FrontEndIpConfigurations[0].TargetPrivateIpAddress)) { this.AddAlert(AlertType.Error, "Load Balancer '" + targetLoadBalancer.ToString() + "' IP Address '" + targetLoadBalancer.FrontEndIpConfigurations[0].TargetPrivateIpAddress + "' is not valid within Subnet '" + targetLoadBalancer.FrontEndIpConfigurations[0].TargetSubnet.ToString() + "' Address Prefix '" + targetLoadBalancer.FrontEndIpConfigurations[0].TargetSubnet.AddressPrefix + "'.", targetLoadBalancer); } else { if (targetLoadBalancer.FrontEndIpConfigurations[0].TargetVirtualNetwork != null && targetLoadBalancer.FrontEndIpConfigurations[0].TargetVirtualNetwork.GetType() == typeof(Azure.Arm.VirtualNetwork) && IPv4CIDR.IsValidIpAddress(targetLoadBalancer.FrontEndIpConfigurations[0].TargetPrivateIpAddress) // Only worth passing to Azure for Availability validation if the IP address is valid. ) { Arm.VirtualNetwork armVirtualNetwork = (Arm.VirtualNetwork)targetLoadBalancer.FrontEndIpConfigurations[0].TargetVirtualNetwork; (bool isAvailable, List<String> availableIps) = await armVirtualNetwork.IsIpAddressAvailable(targetLoadBalancer.FrontEndIpConfigurations[0].TargetPrivateIpAddress); if (!isAvailable) { this.AddAlert(AlertType.Error, "Load Balancer '" + targetLoadBalancer.ToString() + "' IP Address '" + targetLoadBalancer.FrontEndIpConfigurations[0].TargetPrivateIpAddress + "' is not available within Virtual Network '" + targetLoadBalancer.FrontEndIpConfigurations[0].TargetVirtualNetwork.ToString() + "'.", targetLoadBalancer); } } } } } } } else { if (targetLoadBalancer.FrontEndIpConfigurations[0].PublicIp == null) { this.AddAlert(AlertType.Error, "Public Load Balancer must have a Public IP association.", targetLoadBalancer); } else { if (targetLoadBalancer.FrontEndIpConfigurations[0].PublicIp.GetType() == typeof(MigrationTarget.PublicIp)) { MigrationTarget.PublicIp migrationTargetPublicIp = (MigrationTarget.PublicIp)targetLoadBalancer.FrontEndIpConfigurations[0].PublicIp; // Ensure the selected Public IP Address is "in the migration" as a target new Public IP Object bool publicIpExistsInMigration = false; foreach (Azure.MigrationTarget.PublicIp publicIp in this.PublicIPs) { if (publicIp.TargetName == migrationTargetPublicIp.TargetName) { publicIpExistsInMigration = true; break; } } if (!publicIpExistsInMigration) this.AddAlert(AlertType.Error, "Load Balancer Public IP '" + migrationTargetPublicIp.TargetName + "' specified '" + targetLoadBalancer.ToString() + "' is not included in the migration template.", targetLoadBalancer); } else if (targetLoadBalancer.FrontEndIpConfigurations[0].PublicIp.GetType() == typeof(Arm.PublicIP)) { Arm.PublicIP armPublicIp = (Arm.PublicIP)targetLoadBalancer.FrontEndIpConfigurations[0].PublicIp; if (armPublicIp.IpConfigurationId != String.Empty) this.AddAlert(AlertType.Error, "Load Balancer referenced ARM Public IP '" + armPublicIp.Name + "' is already in use by ARM Resource '" + armPublicIp.IpConfigurationId + "'.", targetLoadBalancer); } } } } } foreach (Azure.MigrationTarget.AvailabilitySet availablitySet in this.AvailablitySets) { ValidateTargetApiVersion(availablitySet); if (availablitySet.TargetVirtualMachines.Count == 0) { this.AddAlert(AlertType.Error, "Availability Set '" + availablitySet.ToString() + "' does not contain any Virtual Machines. Remove the Availability Set from the Target Resources for export or associate Virtual Machines to the Availability Set.", availablitySet); } else if (availablitySet.TargetVirtualMachines.Count == 1) { this.AddAlert(AlertType.Warning, "Availability Set '" + availablitySet.ToString() + "' only contains a single VM. Only utilize an Availability Set if additional VMs will be added; otherwise, a single VM instance should not reside within an Availability Set.", availablitySet); } if (!availablitySet.IsManagedDisks && !availablitySet.IsUnmanagedDisks) { this.AddAlert(AlertType.Error, "All OS and Data Disks for Virtual Machines contained within Availablity Set '" + availablitySet.ToString() + "' should be either Unmanaged Disks or Managed Disks for consistent deployment.", availablitySet); } } foreach (Azure.MigrationTarget.VirtualMachine virtualMachine in this.VirtualMachines) { ValidateTargetApiVersion(virtualMachine); if (virtualMachine.TargetName == string.Empty) this.AddAlert(AlertType.Error, "Target Name for Virtual Machine '" + virtualMachine.ToString() + "' must be specified.", virtualMachine); if (virtualMachine.OSVirtualHardDisk == null) { this.AddAlert(AlertType.Error, "Virtual Machine '" + virtualMachine.ToString() + "' does not have an OS Disk.", virtualMachine); } if (virtualMachine.TargetAvailabilitySet == null) { if (virtualMachine.OSVirtualHardDisk != null && virtualMachine.OSVirtualHardDisk.TargetStorage != null && virtualMachine.OSVirtualHardDisk.TargetStorage.StorageAccountType != StorageAccountType.Premium_LRS) this.AddAlert(AlertType.Warning, "Virtual Machine '" + virtualMachine.ToString() + "' is not part of an Availability Set. OS Disk should be migrated to Azure Premium Storage to receive an Azure SLA for single server deployments. Existing configuration will receive no (0%) Service Level Agreement (SLA).", virtualMachine.OSVirtualHardDisk); foreach (Azure.MigrationTarget.Disk dataDisk in virtualMachine.DataDisks) { if (dataDisk.TargetStorage != null && dataDisk.TargetStorage.StorageAccountType != StorageAccountType.Premium_LRS) this.AddAlert(AlertType.Warning, "Virtual Machine '" + virtualMachine.ToString() + "' is not part of an Availability Set. Data Disk '" + dataDisk.ToString() + "' should be migrated to Azure Premium Storage to receive an Azure SLA for single server deployments. Existing configuration will receive no (0%) Service Level Agreement (SLA).", dataDisk); } } else { bool virtualMachineAvailabitySetExists = false; foreach (MigrationTarget.AvailabilitySet targetAvailabilitySet in this.AvailablitySets) { if (targetAvailabilitySet.ToString() == virtualMachine.TargetAvailabilitySet.ToString()) virtualMachineAvailabitySetExists = true; } if (!virtualMachineAvailabitySetExists) this.AddAlert(AlertType.Error, "Virtual Machine '" + virtualMachine.ToString() + "' utilizes Availability Set '" + virtualMachine.TargetAvailabilitySet.ToString() + "'; however, the Availability Set is not included in the Export.", virtualMachine); } if (virtualMachine.TargetSize == null) { this.AddAlert(AlertType.Error, "Target Size for Virtual Machine '" + virtualMachine.ToString() + "' must be specified.", virtualMachine); } else { // Ensure that the selected target size is available in the target Azure Location if (this.ResourceGroup != null && this.ResourceGroup.TargetLocation != null) { if (this.ResourceGroup.TargetLocation.VMSizes == null || this.ResourceGroup.TargetLocation.VMSizes.Count == 0) { this.AddAlert(AlertType.Error, "No ARM VM Sizes are available for Azure Location '" + this.ResourceGroup.TargetLocation.DisplayName + "'.", virtualMachine); } else { // Ensure selected target VM Size is available in the Target Azure Location Arm.VMSize matchedVmSize = this.ResourceGroup.TargetLocation.SeekVmSize(virtualMachine.TargetSize.Name); if (matchedVmSize == null) this.AddAlert(AlertType.Error, "Specified VM Size '" + virtualMachine.TargetSize.Name + "' for Virtual Machine '" + virtualMachine.ToString() + "' is invalid as it is not available in Azure Location '" + this.ResourceGroup.TargetLocation.DisplayName + "'.", virtualMachine); } } if (virtualMachine.OSVirtualHardDisk != null && virtualMachine.OSVirtualHardDisk.TargetStorage != null && virtualMachine.OSVirtualHardDisk.TargetStorage.StorageAccountType == StorageAccountType.Premium_LRS && !virtualMachine.TargetSize.IsStorageTypeSupported(virtualMachine.OSVirtualHardDisk.StorageAccountType)) { this.AddAlert(AlertType.Error, "Premium Disk based Virtual Machines must be of VM Series 'B', 'DS', 'DS v2', 'DS v3', 'GS', 'GS v2', 'Ls' or 'Fs'.", virtualMachine); } } foreach (Azure.MigrationTarget.NetworkInterface networkInterface in virtualMachine.NetworkInterfaces) { // Seek the inclusion of the Network Interface in the export object bool networkInterfaceExistsInExport = false; foreach (Azure.MigrationTarget.NetworkInterface targetNetworkInterface in this.NetworkInterfaces) { if (String.Compare(networkInterface.SourceName, targetNetworkInterface.SourceName, true) == 0) { networkInterfaceExistsInExport = true; break; } } if (!networkInterfaceExistsInExport) { this.AddAlert(AlertType.Error, "Network Interface Card (NIC) '" + networkInterface.ToString() + "' is used by Virtual Machine '" + virtualMachine.ToString() + "', but is not included in the exported resources.", virtualMachine); } if (virtualMachine.TargetSize != null) { if (networkInterface.EnableAcceleratedNetworking && !virtualMachine.TargetSize.IsAcceleratedNetworkingSupported) { this.AddAlert(AlertType.Error, "Network Interface Card (NIC) '" + networkInterface.ToString() + "' has Accelerated Networking enabled, but the Virtual Machine must be of VM Series 'D', 'DSv2', 'DSv3', 'E', 'ESv3', 'F', 'FS', 'FSv2', 'Ms' or 'Mms' to support Accelerated Networking.", networkInterface); } else if (!networkInterface.EnableAcceleratedNetworking && virtualMachine.TargetSize.IsAcceleratedNetworkingSupported) { this.AddAlert(AlertType.Recommendation, "Network Interface Card (NIC) '" + networkInterface.ToString() + "' has Accelerated Networking disabled and the Virtual Machine Size '" + virtualMachine.TargetSize.ToString() + "' can support Accelerated Networking. Consider enabling Accelerated Networking.", networkInterface); } } if (networkInterface.NetworkSecurityGroup != null) { MigrationTarget.NetworkSecurityGroup networkSecurityGroupInMigration = this.SeekNetworkSecurityGroup(networkInterface.NetworkSecurityGroup.ToString()); if (networkSecurityGroupInMigration == null) { this.AddAlert(AlertType.Error, "Network Interface Card (NIC) '" + networkInterface.ToString() + "' utilizes Network Security Group (NSG) '" + networkInterface.NetworkSecurityGroup.ToString() + "', but the NSG resource is not added into the migration template.", networkInterface); } } foreach (Azure.MigrationTarget.NetworkInterfaceIpConfiguration ipConfiguration in networkInterface.TargetNetworkInterfaceIpConfigurations) { if (ipConfiguration.TargetVirtualNetwork == null) this.AddAlert(AlertType.Error, "Target Virtual Network for Virtual Machine '" + virtualMachine.ToString() + "' Network Interface '" + networkInterface.ToString() + "' must be specified.", networkInterface); else { if (ipConfiguration.TargetVirtualNetwork.GetType() == typeof(MigrationTarget.VirtualNetwork)) { MigrationTarget.VirtualNetwork virtualMachineTargetVirtualNetwork = (MigrationTarget.VirtualNetwork)ipConfiguration.TargetVirtualNetwork; bool targetVNetExists = false; foreach (MigrationTarget.VirtualNetwork targetVirtualNetwork in this.VirtualNetworks) { if (targetVirtualNetwork.TargetName == virtualMachineTargetVirtualNetwork.TargetName) { targetVNetExists = true; break; } } if (!targetVNetExists) this.AddAlert(AlertType.Error, "Target Virtual Network '" + virtualMachineTargetVirtualNetwork.ToString() + "' for Virtual Machine '" + virtualMachine.ToString() + "' Network Interface '" + networkInterface.ToString() + "' is invalid, as it is not included in the migration / template. Either include the source Virtual Network in the Migration Template (if this is the first time migration needing a new ARM Virtual Network), or select an existing ARM Virtual Network and Subnet to migrate the Virtual Machine into.", networkInterface); } } if (ipConfiguration.TargetSubnet == null) this.AddAlert(AlertType.Error, "Target Subnet for Virtual Machine '" + virtualMachine.ToString() + "' Network Interface '" + networkInterface.ToString() + "' must be specified.", networkInterface); else { if (!IPv4CIDR.IsValidCIDR(ipConfiguration.TargetSubnet.AddressPrefix)) { this.AddAlert(AlertType.Error, "Target Subnet '" + ipConfiguration.TargetSubnet.ToString() + "' used by Virtual Machine '" + virtualMachine.ToString() + "' has an invalid IPv4 Address Prefix: " + ipConfiguration.TargetSubnet.AddressPrefix, ipConfiguration.TargetSubnet); } else { if (ipConfiguration.TargetPrivateIPAllocationMethod == IPAllocationMethodEnum.Static) { if (!IPv4CIDR.IsIpAddressInAddressPrefix(ipConfiguration.TargetSubnet.AddressPrefix, ipConfiguration.TargetPrivateIpAddress)) { this.AddAlert(AlertType.Error, "Target IP Address '" + ipConfiguration.TargetPrivateIpAddress + "' is not valid in Subnet '" + ipConfiguration.TargetSubnet.ToString() + "' Address Prefix '" + ipConfiguration.TargetSubnet.AddressPrefix + "'.", networkInterface); } } } } if (ipConfiguration.TargetPublicIp != null) { if (ipConfiguration.TargetPublicIp.GetType().UnderlyingSystemType == typeof(MigrationTarget.PublicIp)) { MigrationTarget.PublicIp publicIpInMigration = this.SeekPublicIp(ipConfiguration.TargetPublicIp.ToString()); if (publicIpInMigration == null) { this.AddAlert(AlertType.Error, "Network Interface Card (NIC) '" + networkInterface.ToString() + "' IP Configuration '" + ipConfiguration.ToString() + "' utilizes Public IP '" + ipConfiguration.TargetPublicIp.ToString() + "', but the Public IP resource is not added into the migration template.", networkInterface); } } else if (ipConfiguration.TargetPublicIp.GetType().UnderlyingSystemType == typeof(Arm.PublicIP)) { Arm.PublicIP existingArmPublicIp = (Arm.PublicIP)ipConfiguration.TargetPublicIp; if (existingArmPublicIp.IpConfigurationId != String.Empty) { this.AddAlert(AlertType.Error, "Network Interface Card (NIC) '" + networkInterface.ToString() + "' IP Configuration '" + ipConfiguration.ToString() + "' utilizes existing Public IP '" + ipConfiguration.TargetPublicIp.ToString() + "', but the Public IP resource is already used by existing ARM Resource '" + existingArmPublicIp.IpConfigurationId + "'.", networkInterface); } } } } } if (virtualMachine.OSVirtualHardDisk != null) ValidateVMDisk(virtualMachine.OSVirtualHardDisk); foreach (MigrationTarget.Disk dataDisk in virtualMachine.DataDisks) { ValidateVMDisk(dataDisk); if (!dataDisk.Lun.HasValue || dataDisk.Lun.Value == -1) { this.AddAlert(AlertType.Error, "Data Disk '" + dataDisk.ToString() + "' must have a valid LUN Index assigned.", dataDisk); } else { if (virtualMachine.TargetSize != null) { if (dataDisk.Lun > virtualMachine.TargetSize.maxDataDiskCount - 1) this.AddAlert(AlertType.Error, "Data Disk '" + dataDisk.ToString() + "' LUN index " + dataDisk.Lun.Value.ToString() + " exceeds the maximum LUN of " + (virtualMachine.TargetSize.maxDataDiskCount - 1).ToString() + " allowed by VM Size '" + virtualMachine.TargetSize.ToString() + "'.", dataDisk); } int lunCount = virtualMachine.DataDisks.Where(a => a.Lun == dataDisk.Lun).Count(); if (lunCount > 1) { this.AddAlert(AlertType.Error, "Multiple data disks are assigned to LUN " + dataDisk.Lun.ToString() + " on Virtual Machine '" + virtualMachine.ToString() + "'. Data Disk LUNs must be unique.", dataDisk); } } } if (!virtualMachine.IsManagedDisks && !virtualMachine.IsUnmanagedDisks) { this.AddAlert(AlertType.Error, "All OS and Data Disks for Virtual Machine '" + virtualMachine.ToString() + "' should be either Unmanaged Disks or Managed Disks for consistent deployment.", virtualMachine); } } foreach (Azure.MigrationTarget.Disk targetDisk in this.Disks) { ValidateTargetApiVersion(targetDisk); ValidateDiskStandards(targetDisk); } // todo now asap - Add test for NSGs being present in Migration //MigrationTarget.NetworkSecurityGroup targetNetworkSecurityGroup = (MigrationTarget.NetworkSecurityGroup)this.SeekNetworkSecurityGroup(targetSubnet.NetworkSecurityGroup.ToString()); //if (targetNetworkSecurityGroup == null) //{ // this.AddAlert(AlertType.Error, "Subnet '" + subnet.name + "' utilized ASM Network Security Group (NSG) '" + targetSubnet.NetworkSecurityGroup.ToString() + "', which has not been added to the ARM Subnet as the NSG was not included in the ARM Template (was not selected as an included resources for export).", targetNetworkSecurityGroup); //} // todo add error if existing target disk storage is not in the same data center / region as vm. if (AfterResourceValidation != null) await AfterResourceValidation.Invoke(); } private void ValidateTargetApiVersion(Core.MigrationTarget migrationTarget) { if (migrationTarget.ApiVersion == null || migrationTarget.ApiVersion == String.Empty) { if (this.TargetSubscription != null) { migrationTarget.DefaultApiVersion(this.TargetSubscription); } if (migrationTarget.ApiVersion == null || migrationTarget.ApiVersion.Length == 0) this.AddAlert(AlertType.Error, "Target Azure RM API Version must be specificed for " + migrationTarget.FriendlyObjectName + " '" + migrationTarget.TargetNameResult + "'.", migrationTarget); } } internal bool IsStorageAccountVmDiskTarget(StorageAccount targetStorageAccount) { foreach (VirtualMachine virtrualMachine in this.VirtualMachines) { if (virtrualMachine.OSVirtualHardDisk.TargetStorage != null && virtrualMachine.OSVirtualHardDisk.TargetStorage.GetType() == typeof(StorageAccount)) { StorageAccount osDiskStorageAccount = (StorageAccount)virtrualMachine.OSVirtualHardDisk.TargetStorage; if (osDiskStorageAccount == targetStorageAccount) { return true; } } foreach (Disk dataDisk in virtrualMachine.DataDisks) { if (dataDisk.TargetStorage != null && dataDisk.TargetStorage.GetType() == typeof(StorageAccount)) { StorageAccount dataDiskStorageAccount = (StorageAccount)dataDisk.TargetStorage; if (dataDiskStorageAccount == targetStorageAccount) { return true; } } } } return false; } private void ValidateVMDisk(MigrationTarget.Disk targetDisk) { if (targetDisk.IsManagedDisk) { // All Managed Disks are included in the Export Artifacts, so we aren't including a call here to ValidateDiskStandards for Managed Disks. // Only non Managed Disks are validated against Disk Standards below. // VM References a managed disk, ensure it is included in the Export Artifacts bool targetDiskInExport = false; foreach (Azure.MigrationTarget.Disk exportDisk in this.Disks) { if (targetDisk.SourceName == exportDisk.SourceName) targetDiskInExport = true; } if (!targetDiskInExport && targetDisk.ParentVirtualMachine != null) { this.AddAlert(AlertType.Error, "Virtual Machine '" + targetDisk.ParentVirtualMachine.SourceName + "' references Managed Disk '" + targetDisk.SourceName + "' which has not been added as an export resource.", targetDisk.ParentVirtualMachine); } } else { // We are calling Validate Disk Standards here (only for non-managed disks, as noted above) as all Managed Disks are validated for Disk Standards through the ExportArtifacts.Disks Collection ValidateDiskStandards(targetDisk); } } private void ValidateDiskStandards(MigrationTarget.Disk targetDisk) { if (targetDisk.DiskSizeInGB == 0) this.AddAlert(AlertType.Error, "Disk '" + targetDisk.ToString() + "' does not have a Disk Size defined. Disk Size (not to exceed 4095 GB) is required.", targetDisk); if (targetDisk.IsSmallerThanSourceDisk) this.AddAlert(AlertType.Error, "Disk '" + targetDisk.ToString() + "' Size of " + targetDisk.DiskSizeInGB.ToString() + " GB cannot be smaller than the source Disk Size of " + targetDisk.SourceDisk.DiskSizeGb.ToString() + " GB.", targetDisk); if (targetDisk.IsTargetLunDifferentThanSourceLun) this.AddAlert(AlertType.Warning, "Disk '" + targetDisk.ToString() + "' target LUN " + targetDisk.Lun.ToString() + " does not match the source LUN " + targetDisk.SourceDisk.Lun.ToString() + ".", targetDisk); if (targetDisk.SourceDisk != null && targetDisk.SourceDisk.GetType() == typeof(Azure.Arm.ClassicDisk)) { if (targetDisk.SourceDisk.IsEncrypted) { this.AddAlert(AlertType.Error, "Disk '" + targetDisk.ToString() + "' is encrypted. MigAz does not contain support for moving encrypted Azure Compute VMs.", targetDisk); } } if (targetDisk.TargetStorage == null) this.AddAlert(AlertType.Error, "Disk '" + targetDisk.ToString() + "' Target Storage must be specified.", targetDisk); else { if (targetDisk.TargetStorage.GetType() == typeof(Azure.Arm.StorageAccount)) { Arm.StorageAccount armStorageAccount = (Arm.StorageAccount)targetDisk.TargetStorage; if (armStorageAccount.Location.Name != this.ResourceGroup.TargetLocation.Name) { this.AddAlert(AlertType.Error, "Target Storage Account '" + armStorageAccount.Name + "' is not in the same region (" + armStorageAccount.Location.Name + ") as the Target Resource Group '" + this.ResourceGroup.ToString() + "' (" + this.ResourceGroup.TargetLocation.Name + ").", targetDisk); } } //else if (targetDisk.TargetStorage.GetType() == typeof(Azure.MigrationTarget.StorageAccount)) //{ // Azure.MigrationTarget.StorageAccount targetStorageAccount = (Azure.MigrationTarget.StorageAccount)targetDisk.TargetStorage; // bool targetStorageExists = false; // foreach (Azure.MigrationTarget.StorageAccount storageAccount in this.StorageAccounts) // { // if (storageAccount.ToString() == targetStorageAccount.ToString()) // { // targetStorageExists = true; // break; // } // } // if (!targetStorageExists) // this.AddAlert(AlertType.Error, "Target Storage Account '" + targetStorageAccount.ToString() + "' for Disk '" + targetDisk.ToString() + "' is invalid, as it is not included in the migration / template.", targetDisk); //} if (targetDisk.TargetStorage.GetType() == typeof(Azure.MigrationTarget.StorageAccount) || targetDisk.TargetStorage.GetType() == typeof(Azure.Arm.StorageAccount)) { if (targetDisk.TargetStorageAccountBlob == null || targetDisk.TargetStorageAccountBlob.Trim().Length == 0) this.AddAlert(AlertType.Error, "Target Storage Blob Name is required.", targetDisk); else if (!targetDisk.TargetStorageAccountBlob.ToLower().EndsWith(".vhd")) this.AddAlert(AlertType.Error, "Target Storage Blob Name '" + targetDisk.TargetStorageAccountBlob + "' for Disk is invalid, as it must end with '.vhd'.", targetDisk); } if (targetDisk.TargetStorage.StorageAccountType == StorageAccountType.Premium_LRS) { if (targetDisk.DiskSizeInGB > 0 && targetDisk.DiskSizeInGB < 32) this.AddAlert(AlertType.Recommendation, "Consider using disk size 32GB (P4), as this disk will be billed at that capacity per Azure Premium Storage billing sizes.", targetDisk); else if (targetDisk.DiskSizeInGB > 32 && targetDisk.DiskSizeInGB < 64) this.AddAlert(AlertType.Recommendation, "Consider using disk size 64GB (P6), as this disk will be billed at that capacity per Azure Premium Storage billing sizes.", targetDisk); else if (targetDisk.DiskSizeInGB > 64 && targetDisk.DiskSizeInGB < 128) this.AddAlert(AlertType.Recommendation, "Consider using disk size 128GB (P10), as this disk will be billed at that capacity per Azure Premium Storage billing sizes.", targetDisk); else if (targetDisk.DiskSizeInGB > 128 && targetDisk.DiskSizeInGB < 512) this.AddAlert(AlertType.Recommendation, "Consider using disk size 512GB (P20), as this disk will be billed at that capacity per Azure Premium Storage billing sizes.", targetDisk); else if (targetDisk.DiskSizeInGB > 512 && targetDisk.DiskSizeInGB < 1023) this.AddAlert(AlertType.Recommendation, "Consider using disk size 1023GB (P30), as this disk will be billed at that capacity per Azure Premium Storage billing sizes.", targetDisk); else if (targetDisk.DiskSizeInGB > 1023 && targetDisk.DiskSizeInGB < 2047) this.AddAlert(AlertType.Recommendation, "Consider using disk size 2047GB (P40), as this disk will be billed at that capacity per Azure Premium Storage billing sizes.", targetDisk); else if (targetDisk.DiskSizeInGB > 2047 && targetDisk.DiskSizeInGB < 4095) this.AddAlert(AlertType.Recommendation, "Consider using disk size 4095GB (P50), as this disk will be billed at that capacity per Azure Premium Storage billing sizes.", targetDisk); } } } private void AddAlert(AlertType alertType, string message, object sourceObject) { this.Alerts.Add(new MigAzGeneratorAlert(alertType, message, sourceObject)); } } }
// ReSharper disable All using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.Config.Api.Fakes; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Xunit; namespace Frapid.Config.Api.Tests { public class AppTests { public static AppController Fixture() { AppController controller = new AppController(new AppRepository(), "", new LoginView()); return controller; } [Fact] [Conditional("Debug")] public void CountEntityColumns() { EntityView entityView = Fixture().GetEntityView(); Assert.Null(entityView.Columns); } [Fact] [Conditional("Debug")] public void Count() { long count = Fixture().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetAll() { int count = Fixture().GetAll().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Export() { int count = Fixture().Export().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Get() { Frapid.Config.Entities.App app = Fixture().Get(string.Empty); Assert.NotNull(app); } [Fact] [Conditional("Debug")] public void First() { Frapid.Config.Entities.App app = Fixture().GetFirst(); Assert.NotNull(app); } [Fact] [Conditional("Debug")] public void Previous() { Frapid.Config.Entities.App app = Fixture().GetPrevious(string.Empty); Assert.NotNull(app); } [Fact] [Conditional("Debug")] public void Next() { Frapid.Config.Entities.App app = Fixture().GetNext(string.Empty); Assert.NotNull(app); } [Fact] [Conditional("Debug")] public void Last() { Frapid.Config.Entities.App app = Fixture().GetLast(); Assert.NotNull(app); } [Fact] [Conditional("Debug")] public void GetMultiple() { IEnumerable<Frapid.Config.Entities.App> apps = Fixture().Get(new string[] { }); Assert.NotNull(apps); } [Fact] [Conditional("Debug")] public void GetPaginatedResult() { int count = Fixture().GetPaginatedResult().Count(); Assert.Equal(1, count); count = Fixture().GetPaginatedResult(1).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountWhere() { long count = Fixture().CountWhere(new JArray()); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetWhere() { int count = Fixture().GetWhere(1, new JArray()).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountFiltered() { long count = Fixture().CountFiltered(""); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetFiltered() { int count = Fixture().GetFiltered(1, "").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetDisplayFields() { int count = Fixture().GetDisplayFields().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetCustomFields() { int count = Fixture().GetCustomFields().Count(); Assert.Equal(1, count); count = Fixture().GetCustomFields("").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void AddOrEdit() { try { var form = new JArray { null, null }; Fixture().AddOrEdit(form); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Add() { try { Fixture().Add(null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Edit() { try { Fixture().Edit(string.Empty, null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void BulkImport() { var collection = new JArray { null, null, null, null }; var actual = Fixture().BulkImport(collection); Assert.NotNull(actual); } [Fact] [Conditional("Debug")] public void Delete() { try { Fixture().Delete(string.Empty); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// NetworkInterfaceLoadBalancersOperations operations. /// </summary> internal partial class NetworkInterfaceLoadBalancersOperations : IServiceOperations<NetworkManagementClient>, INetworkInterfaceLoadBalancersOperations { /// <summary> /// Initializes a new instance of the NetworkInterfaceLoadBalancersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal NetworkInterfaceLoadBalancersOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// List all load balancers in a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkInterfaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkInterfaceName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/loadBalancers").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkInterfaceName}", System.Uri.EscapeDataString(networkInterfaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List all load balancers in a network interface. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoadBalancer>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ICommands.cs"> // Copyright (c) 2017. All rights reserved. Licensed under the MIT license. See LICENSE file in // the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Spritely.ReadModel { using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; /// <summary> /// Represents an object for executing commands with simple models. Useful for dependency injection. /// </summary> /// <typeparam name="TId">The type of the identifier.</typeparam> /// <typeparam name="TModel">The type of the model.</typeparam> public interface ICommands<TId, TModel> { /// <summary> /// Executes the command to remove one model from the database. /// </summary> /// <param name="model">The model to remove.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task RemoveOneAsync( TModel model, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to remove a set of models matching the specified filter from the database. /// </summary> /// <param name="where">The where filter indicating which models to remove.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task RemoveManyAsync( Expression<Func<TModel, bool>> where, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to remove all models from the database. /// </summary> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task RemoveAllAsync( string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to add one model to the database. Throws if model is already present. /// </summary> /// <param name="model">The model to add.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task AddOneAsync( TModel model, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to add a set of models to the database. Throws if any models are /// already present. /// </summary> /// <param name="models">The models to add.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task AddManyAsync( IEnumerable<TModel> models, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to update a model in the database. Throws if model with matching /// identifier cannot be found. /// </summary> /// <param name="model">The model to update.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task UpdateOneAsync( TModel model, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to update a set of models in the database. Throws if any models /// cannot be found by their identifiers. /// </summary> /// <param name="models">The models to update.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task UpdateManyAsync( IDictionary<TId, TModel> models, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to add or update a model in the database. /// </summary> /// <param name="model">The model.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task AddOrUpdateOneAsync( TModel model, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to add or update a set of models in the database. /// </summary> /// <param name="models">The models.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task AddOrUpdateManyAsync( IDictionary<TId, TModel> models, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command that assumes a complete set of models is provided and proceeds to /// add, update, or remove models in the database to bring it in sync. /// </summary> /// <param name="models">The models.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task MergeCompleteSetAsync( IDictionary<TId, TModel> models, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); } /// <summary> /// Represents an object for executing commands with storage models. Useful for dependency injection. /// </summary> /// <typeparam name="TId">The type of the identifier.</typeparam> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TMetadata">The type of the metadata.</typeparam> public interface ICommands<TId, TModel, TMetadata> { /// <summary> /// Executes the command to remove one model from the database. /// </summary> /// <param name="model">The model to remove.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task RemoveOneAsync( TModel model, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to remove a set of storage models matching the specified filter /// from the database. /// </summary> /// <param name="where">The where filter indicating which storage models to remove.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task RemoveManyAsync( Expression<Func<StorageModel<TModel, TMetadata>, bool>> where, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to remove all storage models from the database. /// </summary> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task RemoveAllAsync( string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to add one model to the database. Throws if model is already present. /// </summary> /// <param name="model">The model to add.</param> /// <param name="metadata">The metadata to include.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task AddOneAsync( TModel model, TMetadata metadata = default(TMetadata), string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to add a set of storage models to the database. Throws if any /// storage models are already present. /// </summary> /// <param name="storageModels">The storage models to add.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task AddManyAsync( IEnumerable<StorageModel<TModel, TMetadata>> storageModels, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to update a model and its metadata in the database. Throws if /// storage model with matching identifier cannot be found. /// </summary> /// <param name="model">The model to update.</param> /// <param name="metadata">The metadata to include.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task UpdateOneAsync( TModel model, TMetadata metadata = default(TMetadata), string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to update a set of storage models in the database. Throws if any /// storage models cannot be found by their identifiers. /// </summary> /// <param name="storageModels">The storage models to update.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task UpdateManyAsync( IDictionary<TId, StorageModel<TModel, TMetadata>> storageModels, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to add or update a model and its metadata in the database. /// </summary> /// <param name="model">The model.</param> /// <param name="metadata">The metadata.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task AddOrUpdateOneAsync( TModel model, TMetadata metadata = default(TMetadata), string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command to add or update a set of storage models in the database. /// </summary> /// <param name="storageModels">The storage models.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task AddOrUpdateManyAsync( IDictionary<TId, StorageModel<TModel, TMetadata>> storageModels, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Executes the command that assumes a complete set of storage models is provided and /// proceeds to add, update, or remove storage models in the database to bring it in sync. /// </summary> /// <param name="storageModels">The storage models.</param> /// <param name="collectionName"> /// Name of the collection. If null will use {TModel} to generate a collection name. /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task for tracking operation completion.</returns> Task MergeCompleteSetAsync( IDictionary<TId, StorageModel<TModel, TMetadata>> storageModels, string collectionName = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// /* // * Copyright (c) 2016, Alachisoft. 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. // */ #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Alachisoft.NosDB.Common.Protobuf { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class AuthenticationResponse { #region EXTENSION registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationResponse__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse, global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationResponse__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static AuthenticationResponse() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChxBdXRoZW50aWNhdGlvblJlc3BvbnNlLnByb3RvEiBBbGFjaGlzb2Z0Lk5v", "c0RCLkNvbW1vbi5Qcm90b2J1ZhohUmVzcG9uc2VBdXRoZW50aWNhdGlvblRv", "a2VuLnByb3RvInQKFkF1dGhlbnRpY2F0aW9uUmVzcG9uc2USWgoTYXV0aGVu", "dGljYXRpb25Ub2tlbhgBIAEoCzI9LkFsYWNoaXNvZnQuTm9zREIuQ29tbW9u", "LlByb3RvYnVmLlJlc3BvbnNlQXV0aGVudGljYXRpb25Ub2tlbkJGCiRjb20u", "YWxhY2hpc29mdC5ub3NkYi5jb21tb24ucHJvdG9idWZCHkF1dGhlbnRpY2F0", "aW9uUmVzcG9uc2VQcm90b2NvbA==")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationResponse__Descriptor = Descriptor.MessageTypes[0]; internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationResponse__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse, global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationResponse__Descriptor, new string[] { "AuthenticationToken", }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Alachisoft.NosDB.Common.Protobuf.Proto.ResponseAuthenticationToken.Descriptor, }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class AuthenticationResponse : pb::GeneratedMessage<AuthenticationResponse, AuthenticationResponse.Builder> { private AuthenticationResponse() { } private static readonly AuthenticationResponse defaultInstance = new AuthenticationResponse().MakeReadOnly(); private static readonly string[] _authenticationResponseFieldNames = new string[] { "authenticationToken" }; private static readonly uint[] _authenticationResponseFieldTags = new uint[] { 10 }; public static AuthenticationResponse DefaultInstance { get { return defaultInstance; } } public override AuthenticationResponse DefaultInstanceForType { get { return DefaultInstance; } } protected override AuthenticationResponse ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.AuthenticationResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationResponse__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<AuthenticationResponse, AuthenticationResponse.Builder> InternalFieldAccessors { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.AuthenticationResponse.internal__static_Alachisoft_NosDB_Common_Protobuf_AuthenticationResponse__FieldAccessorTable; } } public const int AuthenticationTokenFieldNumber = 1; private bool hasAuthenticationToken; private global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken authenticationToken_; public bool HasAuthenticationToken { get { return hasAuthenticationToken; } } public global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken AuthenticationToken { get { return authenticationToken_ ?? global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken.DefaultInstance; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _authenticationResponseFieldNames; if (hasAuthenticationToken) { output.WriteMessage(1, field_names[0], AuthenticationToken); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasAuthenticationToken) { size += pb::CodedOutputStream.ComputeMessageSize(1, AuthenticationToken); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static AuthenticationResponse ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static AuthenticationResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static AuthenticationResponse ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static AuthenticationResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static AuthenticationResponse ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static AuthenticationResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static AuthenticationResponse ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static AuthenticationResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static AuthenticationResponse ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static AuthenticationResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private AuthenticationResponse MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(AuthenticationResponse prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<AuthenticationResponse, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(AuthenticationResponse cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private AuthenticationResponse result; private AuthenticationResponse PrepareBuilder() { if (resultIsReadOnly) { AuthenticationResponse original = result; result = new AuthenticationResponse(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override AuthenticationResponse MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.Descriptor; } } public override AuthenticationResponse DefaultInstanceForType { get { return global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.DefaultInstance; } } public override AuthenticationResponse BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is AuthenticationResponse) { return MergeFrom((AuthenticationResponse) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(AuthenticationResponse other) { if (other == global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.DefaultInstance) return this; PrepareBuilder(); if (other.HasAuthenticationToken) { MergeAuthenticationToken(other.AuthenticationToken); } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_authenticationResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _authenticationResponseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken.CreateBuilder(); if (result.hasAuthenticationToken) { subBuilder.MergeFrom(AuthenticationToken); } input.ReadMessage(subBuilder, extensionRegistry); AuthenticationToken = subBuilder.BuildPartial(); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasAuthenticationToken { get { return result.hasAuthenticationToken; } } public global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken AuthenticationToken { get { return result.AuthenticationToken; } set { SetAuthenticationToken(value); } } public Builder SetAuthenticationToken(global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasAuthenticationToken = true; result.authenticationToken_ = value; return this; } public Builder SetAuthenticationToken(global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasAuthenticationToken = true; result.authenticationToken_ = builderForValue.Build(); return this; } public Builder MergeAuthenticationToken(global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasAuthenticationToken && result.authenticationToken_ != global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken.DefaultInstance) { result.authenticationToken_ = global::Alachisoft.NosDB.Common.Protobuf.ResponseAuthenticationToken.CreateBuilder(result.authenticationToken_).MergeFrom(value).BuildPartial(); } else { result.authenticationToken_ = value; } result.hasAuthenticationToken = true; return this; } public Builder ClearAuthenticationToken() { PrepareBuilder(); result.hasAuthenticationToken = false; result.authenticationToken_ = null; return this; } } static AuthenticationResponse() { object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.AuthenticationResponse.Descriptor, null); } } #endregion } #endregion Designer generated code
using System; using Acquaint.Abstractions; using Acquaint.Models; using Acquaint.Util; using CoreAnimation; using CoreGraphics; using CoreLocation; using FFImageLoading; using FFImageLoading.Transformations; using MapKit; //using Microsoft.Practices.ServiceLocation; using CommonServiceLocator; using ObjCRuntime; using Plugin.ExternalMaps; using Plugin.ExternalMaps.Abstractions; using Plugin.Messaging; using UIKit; namespace Acquaint.Native.iOS { /// <summary> /// Acquaintance detail view controller. The layout for this view controller is defined almost entirely in Main.storyboard. /// </summary> public partial class AcquaintanceDetailViewController : UIViewController { /// <summary> /// The data source. /// </summary> IDataSource<Acquaintance> _DataSource; public Acquaintance Acquaintance { get; set; } UIBarButtonItem DeleteBarButtonItem; readonly CLGeocoder _Geocoder; // This constructor signature is required, for marshalling between the managed and native instances of this class. public AcquaintanceDetailViewController( IntPtr handle ) : base( handle ) { _DataSource = ServiceLocator.Current.GetInstance<IDataSource<Acquaintance>>(); _Geocoder = new CLGeocoder(); } // This overridden method will be called after the AcquaintanceDetailViewController has been instantiated and loaded into memory, // but before the view hierarchy is rendered to the device screen. // The "async" keyword is added here to the override in order to allow other awaited async method calls inside the override to be called ascynchronously. public override async void ViewWillAppear( bool animated ) { if( Acquaintance != null ) { // set the title and label text properties Title = Acquaintance.DisplayName; CompanyNameLabel.Text = Acquaintance.Company; JobTitleLabel.Text = Acquaintance.JobTitle; StreetLabel.Text = Acquaintance.Street; CityLabel.Text = Acquaintance.City; StateAndPostalLabel.Text = Acquaintance.StatePostal; PhoneLabel.Text = Acquaintance.Phone; EmailLabel.Text = Acquaintance.Email; // Set image views for user actions. // The action for getting navigation directions is setup further down in this method, after the geocoding occurs. SetupSendMessageAction(); SetupDialNumberAction(); SetupSendEmailAction(); // use FFImageLoading library to asynchronously: await ImageService .Instance .LoadUrl( Acquaintance.PhotoUrl, TimeSpan.FromHours( Util.Settings.ImageCacheDurationHours ) ) // get the image from a URL .LoadingPlaceholder( "placeholderProfileImage.png" ) // specify a placeholder image .Transform( new CircleTransformation() ) // transform the image to a circle .Error( e => System.Diagnostics.Debug.WriteLine( e.Message ) ) .IntoAsync( ProfilePhotoImageView ); // load the image into the UIImageView try { // asynchronously geocode the address var locations = await _Geocoder.GeocodeAddressAsync( Acquaintance.AddressString ); // if we have at least one location if( locations != null && locations.Length > 0 ) { var coord = locations[ 0 ].Location.Coordinate; var span = new MKCoordinateSpan( MilesToLatitudeDegrees( 20 ), MilesToLongitudeDegrees( 20, coord.Latitude ) ); // set the region that the map should display MapView.Region = new MKCoordinateRegion( coord, span ); // create a new pin for the map var pin = new MKPointAnnotation() { Title = Acquaintance.DisplayName, Coordinate = new CLLocationCoordinate2D() { Latitude = coord.Latitude, Longitude = coord.Longitude } }; // add the pin to the map MapView.AddAnnotation( pin ); // add a top border to the MapView MapView.Layer.AddSublayer( new CALayer() { BackgroundColor = UIColor.LightGray.CGColor, Frame = new CGRect( 0, 0, MapView.Frame.Width, 1 ) } ); // setup fhe action for getting navigation directions SetupGetDirectionsAction( coord.Latitude, coord.Longitude ); } } catch { DisplayErrorAlertView( "Geocoding Error", "Please make sure the address is valid and that you have a network connection." ); } } } public override void ViewDidLoad() { base.ViewDidLoad(); // override the back button text for AcquaintanceEditViewController (the navigated-to view controller) NavigationItem.BackBarButtonItem = new UIBarButtonItem( "Details", UIBarButtonItemStyle.Plain, null ); DeleteBarButtonItem = NavigationItem.RightBarButtonItems[ 1 ]; DeleteBarButtonItem.Clicked += DeleteBarButtonItemClicked; } void DeleteBarButtonItemClicked( object sender, EventArgs ea ) { UIAlertController alert = UIAlertController.Create( "Delete?", $"Are you sure you want to delete {Acquaintance.FirstName} {Acquaintance.LastName}?", UIAlertControllerStyle.Alert ); // cancel button alert.AddAction( UIAlertAction.Create( "Cancel", UIAlertActionStyle.Cancel, null ) ); // delete button alert.AddAction( UIAlertAction.Create( "Delete", UIAlertActionStyle.Destructive, async ( action ) => { if( action != null ) { await _DataSource.RemoveItem( Acquaintance ); NavigationController.PopViewController( true ); } } ) ); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController( alert, true, null ); } public override void PrepareForSegue( UIStoryboardSegue segue, Foundation.NSObject sender ) { // get the destination viewcontroller from the segue var acquaintanceEditViewController = segue.DestinationViewController as AcquaintanceEditViewController; acquaintanceEditViewController.Acquaintance = Acquaintance; } void SetupGetDirectionsAction( double lat, double lon ) { GetDirectionsImageView.Image = UIImage.FromBundle( "directions" ); // UIImageView doesn't accept touch events by default, so we have to explcitly enable user interaction GetDirectionsImageView.UserInteractionEnabled = true; GetDirectionsImageView.AddGestureRecognizer( new UITapGestureRecognizer( async () => { // we're using the External Maps plugin from James Montemagno here (included as a NuGet) await CrossExternalMaps.Current.NavigateTo( Acquaintance.DisplayName, lat, lon, NavigationType.Driving ); } ) ); } void SetupSendMessageAction() { SendMessageImageView.Image = UIImage.FromBundle( "message" ); // UIImageView doesn't accept touch events by default, so we have to explcitly enable user interaction SendMessageImageView.UserInteractionEnabled = true; SendMessageImageView.AddGestureRecognizer( new UITapGestureRecognizer( () => { // we're using the Messaging plugin from Carel Lotz here (included as a NuGet) var smsTask = CrossMessaging.Current.SmsMessenger; if( smsTask.CanSendSms && IsRealDevice ) smsTask.SendSms( Acquaintance.Phone, "" ); else DisplaySimulatorNotSupportedErrorAlertView( "Messaging is not supported in the iOS simulator." ); } ) ); } void SetupDialNumberAction() { DialNumberImageView.Image = UIImage.FromBundle( "phone" ); // UIImageView doesn't accept touch events by default, so we have to explcitly enable user interaction DialNumberImageView.UserInteractionEnabled = true; DialNumberImageView.AddGestureRecognizer( new UITapGestureRecognizer( () => { // we're using the Messaging plugin from Carel Lotz here (included as a NuGet) var phoneCallTask = CrossMessaging.Current.PhoneDialer; if( phoneCallTask.CanMakePhoneCall && IsRealDevice ) phoneCallTask.MakePhoneCall( Acquaintance.Phone ); else DisplaySimulatorNotSupportedErrorAlertView( "Phone calls are not supported in the iOS simulator." ); } ) ); } void SetupSendEmailAction() { SendEmailImageView.Image = UIImage.FromBundle( "email" ); // UIImageView doesn't accept touch events by default, so we have to explcitly enable user interaction SendEmailImageView.UserInteractionEnabled = true; SendEmailImageView.AddGestureRecognizer( new UITapGestureRecognizer( () => { // we're using the Messaging plugin from Carel Lotz here (included as a NuGet) var emailTask = CrossMessaging.Current.EmailMessenger; if( emailTask.CanSendEmail && IsRealDevice ) emailTask.SendEmail( Acquaintance.Email, "" ); else DisplaySimulatorNotSupportedErrorAlertView( "Email composition is not supported in the iOS simulator." ); } ) ); } void DisplaySimulatorNotSupportedErrorAlertView( string message ) { DisplayErrorAlertView( "Simulator Not Supported", message ); } void DisplayErrorAlertView( string title, string message ) { //Create Alert var okAlertController = UIAlertController.Create( title, message, UIAlertControllerStyle.Alert ); //Add Action okAlertController.AddAction( UIAlertAction.Create( "OK", UIAlertActionStyle.Default, null ) ); // Present Alert PresentViewController( okAlertController, true, null ); } /// <summary> /// Convert miles to latitude degrees. /// </summary> /// <returns>The latitude in degrees.</returns> /// <param name="miles">Miles.</param> static double MilesToLatitudeDegrees( double miles ) { const double earthRadius = 3960.0; // In miles. Wow! const double radiansToDegrees = 180.0 / Math.PI; return miles / earthRadius * radiansToDegrees; } /// <summary> /// Convert miles to longitude degrees. /// </summary> /// <returns>The longitude in degrees.</returns> /// <param name="miles">Miles.</param> /// <param name="atLatitude">At latitude.</param> static double MilesToLongitudeDegrees( double miles, double atLatitude ) { const double earthRadius = 3960.0; // In miles. Wow! const double degreesToRadians = Math.PI / 180.0; const double radiansToDegrees = 180.0 / Math.PI; // derive the earth's radius at that point in latitude double radiusAtLatitude = earthRadius * Math.Cos( atLatitude * degreesToRadians ); return miles / radiusAtLatitude * radiansToDegrees; } bool IsRealDevice => Runtime.Arch == Arch.DEVICE; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias Scripting; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver; internal partial class InteractiveHost { /// <summary> /// A remote singleton server-activated object that lives in the interactive host process and controls it. /// </summary> internal sealed class Service : MarshalByRefObject, IDisposable { private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false); private static Control s_control; private InteractiveAssemblyLoader _assemblyLoader; private MetadataShadowCopyProvider _metadataFileProvider; private ReplServiceProvider _replServiceProvider; private InteractiveScriptGlobals _globals; // Session is not thread-safe by itself, and the compilation // and execution of scripts are asynchronous operations. // However since the operations are executed serially, it // is sufficient to lock when creating the async tasks. private readonly object _lastTaskGuard = new object(); private Task<EvaluationState> _lastTask; private struct EvaluationState { internal ImmutableArray<string> SourceSearchPaths; internal ImmutableArray<string> ReferenceSearchPaths; internal string WorkingDirectory; internal readonly ScriptState<object> ScriptStateOpt; internal readonly ScriptOptions ScriptOptions; internal EvaluationState( ScriptState<object> scriptState, ScriptOptions scriptOptions, ImmutableArray<string> sourceSearchPaths, ImmutableArray<string> referenceSearchPaths, string workingDirectory) { ScriptStateOpt = scriptState; ScriptOptions = scriptOptions; SourceSearchPaths = sourceSearchPaths; ReferenceSearchPaths = referenceSearchPaths; WorkingDirectory = workingDirectory; } internal EvaluationState WithScriptState(ScriptState<object> state) { return new EvaluationState( state, ScriptOptions, SourceSearchPaths, ReferenceSearchPaths, WorkingDirectory); } internal EvaluationState WithOptions(ScriptOptions options) { return new EvaluationState( ScriptStateOpt, options, SourceSearchPaths, ReferenceSearchPaths, WorkingDirectory); } } private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create( FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)), FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory())); #region Setup public Service() { var initialState = new EvaluationState( scriptState: null, scriptOptions: ScriptOptions.Default, sourceSearchPaths: ImmutableArray<string>.Empty, referenceSearchPaths: ImmutableArray<string>.Empty, workingDirectory: Directory.GetCurrentDirectory()); _lastTask = Task.FromResult(initialState); Console.OutputEncoding = Encoding.UTF8; // We want to be sure to delete the shadow-copied files when the process goes away. Frankly // there's nothing we can do if the process is forcefully quit or goes down in a completely // uncontrolled manner (like a stack overflow). When the process goes down in a controlled // manned, we should generally expect this event to be called. AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; } private void HandleProcessExit(object sender, EventArgs e) { Dispose(); AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit; } public void Dispose() { _metadataFileProvider.Dispose(); } public override object InitializeLifetimeService() { return null; } public void Initialize(Type replServiceProviderType, string cultureName) { Debug.Assert(replServiceProviderType != null); Debug.Assert(cultureName != null); Debug.Assert(_metadataFileProvider == null); Debug.Assert(_assemblyLoader == null); Debug.Assert(_replServiceProvider == null); // TODO (tomat): we should share the copied files with the host _metadataFileProvider = new MetadataShadowCopyProvider( Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"), noShadowCopyDirectories: s_systemNoShadowCopyDirectories, documentationCommentsCulture: new CultureInfo(cultureName)); _assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider); _replServiceProvider = (ReplServiceProvider)Activator.CreateInstance(replServiceProviderType); _globals = new InteractiveScriptGlobals(Console.Out, _replServiceProvider.ObjectFormatter); } private MetadataReferenceResolver CreateMetadataReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new RuntimeMetadataReferenceResolver( new RelativePathResolver(searchPaths, baseDirectory), null, GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null, (path, properties) => new ShadowCopyReference(_metadataFileProvider, path, properties)); } private SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new SourceFileResolver(searchPaths, baseDirectory); } private static bool AttachToClientProcess(int clientProcessId) { Process clientProcess; try { clientProcess = Process.GetProcessById(clientProcessId); } catch (ArgumentException) { return false; } clientProcess.EnableRaisingEvents = true; clientProcess.Exited += new EventHandler((_, __) => { s_clientExited.Set(); }); return clientProcess.IsAlive(); } // for testing purposes public void EmulateClientExit() { s_clientExited.Set(); } internal static void RunServer(string[] args) { if (args.Length != 3) { throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>"); } RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture)); } /// <summary> /// Implements remote server. /// </summary> private static void RunServer(string serverPort, string semaphoreName, int clientProcessId) { if (!AttachToClientProcess(clientProcessId)) { return; } // Disables Windows Error Reporting for the process, so that the process fails fast. // Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) // Note that GetErrorMode is not available on XP at all. if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0)) { SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); } IpcServerChannel serverChannel = null; IpcClientChannel clientChannel = null; try { using (var semaphore = Semaphore.OpenExisting(semaphoreName)) { // DEBUG: semaphore.WaitOne(); var serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; var clientProvider = new BinaryClientFormatterSinkProvider(); clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider); ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false); serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider); ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Service), ServiceName, WellKnownObjectMode.Singleton); using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { s_control = new Control(); s_control.CreateControl(); resetEvent.Set(); Application.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } // the client can instantiate interactive host now: semaphore.Release(); } s_clientExited.Wait(); } finally { if (serverChannel != null) { ChannelServices.UnregisterChannel(serverChannel); } if (clientChannel != null) { ChannelServices.UnregisterChannel(clientChannel); } } // force exit even if there are foreground threads running: Environment.Exit(0); } internal static string ServiceName { get { return typeof(Service).Name; } } private static string GenerateUniqueChannelLocalName() { return typeof(Service).FullName + Guid.NewGuid(); } #endregion #region Remote Async Entry Points // Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.) [OneWay] public void SetPathsAsync( RemoteAsyncOperation<RemoteExecutionResult> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { Debug.Assert(operation != null); Debug.Assert(referenceSearchPaths != null); Debug.Assert(sourceSearchPaths != null); Debug.Assert(baseDirectory != null); lock (_lastTaskGuard) { _lastTask = SetPathsAsync(_lastTask, operation, referenceSearchPaths, sourceSearchPaths, baseDirectory); } } private async Task<EvaluationState> SetPathsAsync( Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { Directory.SetCurrentDirectory(baseDirectory); _globals.ReferencePaths.Clear(); _globals.ReferencePaths.AddRange(referenceSearchPaths); _globals.SourcePaths.Clear(); _globals.SourcePaths.AddRange(sourceSearchPaths); } finally { state = CompleteExecution(state, operation, success: true); } return state; } /// <summary> /// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it. /// Execution is performed on the UI thread. /// </summary> [OneWay] public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting) { Debug.Assert(operation != null); lock (_lastTaskGuard) { _lastTask = InitializeContextAsync(_lastTask, operation, initializationFile, isRestarting); } } /// <summary> /// Adds an assembly reference to the current session. /// </summary> [OneWay] public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference) { Debug.Assert(operation != null); Debug.Assert(reference != null); lock (_lastTaskGuard) { _lastTask = AddReferenceAsync(_lastTask, operation, reference); } } private async Task<EvaluationState> AddReferenceAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<bool> operation, string reference) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); bool success = false; try { var resolvedReferences = state.ScriptOptions.MetadataResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { state = state.WithOptions(state.ScriptOptions.AddReferences(resolvedReferences)); success = true; } else { Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference)); } } catch (Exception e) { ReportUnhandledException(e); } finally { operation.Completed(success); } return state; } /// <summary> /// Executes given script snippet on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { Debug.Assert(operation != null); Debug.Assert(text != null); lock (_lastTaskGuard) { _lastTask = ExecuteAsync(_lastTask, operation, text); } } private async Task<EvaluationState> ExecuteAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); bool success = false; try { Script<object> script = TryCompile(state.ScriptStateOpt?.Script, text, null, state.ScriptOptions); if (script != null) { // successful if compiled success = true; // remove references and imports from the options, they have been applied and will be inherited from now on: state = state.WithOptions(state.ScriptOptions.RemoveImportsAndReferences()); var newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false); if (newScriptState != null) { DisplaySubmissionResult(newScriptState); state = state.WithScriptState(newScriptState); } } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success); } return state; } private void DisplaySubmissionResult(ScriptState<object> state) { if (state.Script.HasReturnValue()) { _globals.Print(state.ReturnValue); } } /// <summary> /// Executes given script file on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path) { Debug.Assert(operation != null); Debug.Assert(path != null); lock (_lastTaskGuard) { _lastTask = ExecuteFileAsync(operation, _lastTask, path); } } private EvaluationState CompleteExecution(EvaluationState state, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success) { // send any updates to the host object and current directory back to the client: var currentSourcePaths = _globals.SourcePaths.ToArray(); var currentReferencePaths = _globals.ReferencePaths.ToArray(); var currentWorkingDirectory = Directory.GetCurrentDirectory(); var changedSourcePaths = currentSourcePaths.SequenceEqual(state.SourceSearchPaths) ? null : currentSourcePaths; var changedReferencePaths = currentReferencePaths.SequenceEqual(state.ReferenceSearchPaths) ? null : currentReferencePaths; var changedWorkingDirectory = currentWorkingDirectory == state.WorkingDirectory ? null : currentWorkingDirectory; operation.Completed(new RemoteExecutionResult(success, changedSourcePaths, changedReferencePaths, changedWorkingDirectory)); // no changes in resolvers: if (changedReferencePaths == null && changedSourcePaths == null && changedWorkingDirectory == null) { return state; } var newSourcePaths = ImmutableArray.CreateRange(currentSourcePaths); var newReferencePaths = ImmutableArray.CreateRange(currentReferencePaths); var newWorkingDirectory = currentWorkingDirectory; ScriptOptions newOptions = state.ScriptOptions; if (changedReferencePaths != null || changedWorkingDirectory != null) { newOptions = newOptions.WithMetadataResolver(CreateMetadataReferenceResolver(newReferencePaths, newWorkingDirectory)); } if (changedSourcePaths != null || changedWorkingDirectory != null) { newOptions = newOptions.WithSourceResolver(CreateSourceReferenceResolver(newSourcePaths, newWorkingDirectory)); } return new EvaluationState( state.ScriptStateOpt, newOptions, newSourcePaths, newReferencePaths, workingDirectory: newWorkingDirectory); } private static async Task<EvaluationState> ReportUnhandledExceptionIfAny(Task<EvaluationState> lastTask) { try { return await lastTask.ConfigureAwait(false); } catch (Exception e) { ReportUnhandledException(e); return lastTask.Result; } } private static void ReportUnhandledException(Exception e) { Console.Error.WriteLine("Unexpected error:"); Console.Error.WriteLine(e); Debug.Fail("Unexpected error"); Debug.WriteLine(e); } #endregion #region Operations /// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private async Task<EvaluationState> InitializeContextAsync( Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_replServiceProvider.Logo); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _replServiceProvider.CommandLineParser; // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspDirectory = Path.GetDirectoryName(initializationFileOpt); var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory); var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, rspDirectory); var metadataReferences = new List<PortableExecutableReference>(); foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { metadataReferences.AddRange(resolvedReferences); } } var scriptPathOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path; var rspState = new EvaluationState( state.ScriptStateOpt, state.ScriptOptions. WithFilePath(scriptPathOpt). WithReferences(metadataReferences). WithImports(CommandLineHelpers.GetImports(args)). WithMetadataResolver(metadataResolver). WithSourceResolver(sourceResolver), args.SourcePaths, args.ReferencePaths, rspDirectory); _globals.ReferencePaths.Clear(); _globals.ReferencePaths.AddRange(args.ReferencePaths); _globals.SourcePaths.Clear(); _globals.SourcePaths.AddRange(args.SourcePaths); _globals.Args.AddRange(args.ScriptArguments); if (scriptPathOpt != null) { var newScriptState = await ExecuteFileAsync(rspState, scriptPathOpt).ConfigureAwait(false); if (newScriptState != null) { // remove references and imports from the options, they have been applied and will be inherited from now on: rspState = rspState. WithScriptState(newScriptState). WithOptions(rspState.ScriptOptions.RemoveImportsAndReferences()); } } state = rspState; } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success: true); } return state; } private string ResolveRelativePath(string path, string baseDirectory, ImmutableArray<string> searchPaths, bool displayPath) { List<string> attempts = new List<string>(); Func<string, bool> fileExists = file => { attempts.Add(file); return File.Exists(file); }; string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, searchPaths, fileExists); if (fullPath == null) { if (displayPath) { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path); } else { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound); } if (attempts.Count > 0) { DisplaySearchPaths(Console.Error, attempts); } } return fullPath; } private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options) { Script script; var scriptOptions = options.WithFilePath(path); if (previousScript != null) { script = previousScript.ContinueWith(code, scriptOptions); } else { script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _globals.GetType(), _assemblyLoader); } var diagnostics = script.Compile(); if (diagnostics.HasAnyErrors()) { DisplayInteractiveErrors(diagnostics, Console.Error); return null; } return (Script<object>)script; } private async Task<EvaluationState> ExecuteFileAsync( RemoteAsyncOperation<RemoteExecutionResult> operation, Task<EvaluationState> lastTask, string path) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); var success = false; try { var fullPath = ResolveRelativePath(path, state.WorkingDirectory, state.SourceSearchPaths, displayPath: false); var newScriptState = await ExecuteFileAsync(state, fullPath).ConfigureAwait(false); if (newScriptState != null) { success = true; state = state.WithScriptState(newScriptState); } } finally { state = CompleteExecution(state, operation, success); } return state; } /// <summary> /// Executes specified script file as a submission. /// </summary> /// <returns>True if the code has been executed. False if the code doesn't compile.</returns> /// <remarks> /// All errors are written to the error output stream. /// Uses source search paths to resolve unrooted paths. /// </remarks> private async Task<ScriptState<object>> ExecuteFileAsync(EvaluationState state, string fullPath) { string content = null; if (fullPath != null) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); try { content = File.ReadAllText(fullPath); } catch (Exception e) { Console.Error.WriteLine(e.Message); } } ScriptState<object> newScriptState = null; if (content != null) { Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions); if (script != null) { newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false); } } return newScriptState; } private static void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths) { var directories = attemptedFilePaths.Select(path => Path.GetDirectoryName(path)).ToArray(); var uniqueDirectories = new HashSet<string>(directories); writer.WriteLine(uniqueDirectories.Count == 1 ? FeaturesResources.SearchedInDirectory : FeaturesResources.SearchedInDirectories); foreach (string directory in directories) { if (uniqueDirectories.Remove(directory)) { writer.Write(" "); writer.WriteLine(directory); } } } private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt) { return await ((Task<ScriptState<object>>)s_control.Invoke( (Func<Task<ScriptState<object>>>)(async () => { try { var task = (stateOpt == null) ? script.RunAsync(_globals, CancellationToken.None) : script.ContinueAsync(stateOpt, CancellationToken.None); return await task.ConfigureAwait(false); } catch (FileLoadException e) when (e.InnerException is InteractiveAssemblyLoaderException) { Console.Error.WriteLine(e.InnerException.Message); return null; } catch (Exception e) { Console.Error.WriteLine(_replServiceProvider.ObjectFormatter.FormatUnhandledException(e)); return null; } }))).ConfigureAwait(false); } private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output) { var displayedDiagnostics = new List<Diagnostic>(); const int MaxErrorCount = 5; for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++) { displayedDiagnostics.Add(diagnostics[i]); } displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start); var formatter = _replServiceProvider.DiagnosticFormatter; foreach (var diagnostic in displayedDiagnostics) { output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo)); } if (diagnostics.Length > MaxErrorCount) { int notShown = diagnostics.Length - MaxErrorCount; output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors")); } } #endregion #region Win32 API [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode SetErrorMode(ErrorMode mode); [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode GetErrorMode(); [Flags] internal enum ErrorMode : int { /// <summary> /// Use the system default, which is to display all error dialog boxes. /// </summary> SEM_FAILCRITICALERRORS = 0x0001, /// <summary> /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup. /// This is to prevent error mode dialogs from hanging the application. /// </summary> SEM_NOGPFAULTERRORBOX = 0x0002, /// <summary> /// The system automatically fixes memory alignment faults and makes them invisible to the application. /// It does this for the calling process and any descendant processes. This feature is only supported by /// certain processor architectures. For more information, see the Remarks section. /// After this value is set for a process, subsequent attempts to clear the value are ignored. /// </summary> SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, /// <summary> /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// </summary> SEM_NOOPENFILEERRORBOX = 0x8000, } #endregion #region Testing // TODO(tomat): remove when the compiler supports events // For testing purposes only! public void HookMaliciousAssemblyResolve() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) => { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { Console.Error.WriteLine("in the loop"); i = i + 1; } } }); } public void RemoteConsoleWrite(byte[] data, bool isError) { using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput()) { stream.Write(data, 0, data.Length); stream.Flush(); } } public bool IsShadowCopy(string path) { return _metadataFileProvider.IsShadowCopy(path); } #endregion } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Build.BackEnd; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Internal; using Microsoft.Build.Shared; using Microsoft.Build.UnitTests.BackEnd; using Xunit; namespace Microsoft.Build.UnitTests.Definition { public class Toolset_Tests { [Fact] public void ToolsetCtorErrors1() { Assert.Throws<ArgumentNullException>(() => { Toolset t = new Toolset(null, "x", new ProjectCollection(), null); } ); } [Fact] public void ToolsetCtorErrors2() { Assert.Throws<ArgumentNullException>(() => { Toolset t = new Toolset("x", null, new ProjectCollection(), null); } ); } [Fact] public void ToolsetCtorErrors3() { Assert.Throws<ArgumentException>(() => { Toolset t = new Toolset(String.Empty, "x", new ProjectCollection(), null); } ); } [Fact] public void Regress27993_TrailingSlashTrimmedFromMSBuildToolsPath() { Toolset t; if (NativeMethodsShared.IsWindows) { t = new Toolset("x", "C:", new ProjectCollection(), null); Assert.Equal(@"C:", t.ToolsPath); t = new Toolset("x", @"C:\", new ProjectCollection(), null); Assert.Equal(@"C:\", t.ToolsPath); t = new Toolset("x", @"C:\\", new ProjectCollection(), null); Assert.Equal(@"C:\", t.ToolsPath); t = new Toolset("x", @"C:\foo", new ProjectCollection(), null); Assert.Equal(@"C:\foo", t.ToolsPath); t = new Toolset("x", @"C:\foo\", new ProjectCollection(), null); Assert.Equal(@"C:\foo", t.ToolsPath); t = new Toolset("x", @"C:\foo\\", new ProjectCollection(), null); Assert.Equal(@"C:\foo\", t.ToolsPath); // trim at most one slash t = new Toolset("x", @"\\foo\share", new ProjectCollection(), null); Assert.Equal(@"\\foo\share", t.ToolsPath); t = new Toolset("x", @"\\foo\share\", new ProjectCollection(), null); Assert.Equal(@"\\foo\share", t.ToolsPath); t = new Toolset("x", @"\\foo\share\\", new ProjectCollection(), null); Assert.Equal(@"\\foo\share\", t.ToolsPath); // trim at most one slash } else { t = new Toolset("x", "/", new ProjectCollection(), null); Assert.Equal("/", t.ToolsPath); t = new Toolset("x", "/foo", new ProjectCollection(), null); Assert.Equal("/foo", t.ToolsPath); t = new Toolset("x", "/foo/", new ProjectCollection(), null); Assert.Equal(@"/foo", t.ToolsPath); t = new Toolset("x", "/foo//", new ProjectCollection(), null); Assert.Equal("/foo/", t.ToolsPath); // trim at most one slash t = new Toolset("x", @"\\foo\share", new ProjectCollection(), null); Assert.Equal(@"\\foo\share", t.ToolsPath); t = new Toolset("x", @"\\foo\share/", new ProjectCollection(), null); Assert.Equal(@"\\foo\share", t.ToolsPath); t = new Toolset("x", @"\\foo\share//", new ProjectCollection(), null); Assert.Equal(@"\\foo\share/", t.ToolsPath); // trim at most one slash } } [Fact] public void ValidateToolsetTranslation() { PropertyDictionary<ProjectPropertyInstance> buildProperties = new PropertyDictionary<ProjectPropertyInstance>(); buildProperties.Set(ProjectPropertyInstance.Create("a", "a1")); PropertyDictionary<ProjectPropertyInstance> environmentProperties = new PropertyDictionary<ProjectPropertyInstance>(); environmentProperties.Set(ProjectPropertyInstance.Create("b", "b1")); PropertyDictionary<ProjectPropertyInstance> globalProperties = new PropertyDictionary<ProjectPropertyInstance>(); globalProperties.Set(ProjectPropertyInstance.Create("c", "c1")); PropertyDictionary<ProjectPropertyInstance> subToolsetProperties = new PropertyDictionary<ProjectPropertyInstance>(); subToolsetProperties.Set(ProjectPropertyInstance.Create("d", "d1")); Dictionary<string, SubToolset> subToolsets = new Dictionary<string, SubToolset>(StringComparer.OrdinalIgnoreCase); subToolsets.Add("dogfood", new SubToolset("dogfood", subToolsetProperties)); Toolset t = new Toolset("4.0", "c:\\bar", buildProperties, environmentProperties, globalProperties, subToolsets, "c:\\foo", "4.0", new Dictionary<string, ProjectImportPathMatch> { ["MSBuildExtensionsPath"] = new ProjectImportPathMatch("MSBuildExtensionsPath", new List<string> {@"c:\foo"}) }); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); Toolset t2 = Toolset.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(t.ToolsVersion, t2.ToolsVersion); Assert.Equal(t.ToolsPath, t2.ToolsPath); Assert.Equal(t.OverrideTasksPath, t2.OverrideTasksPath); Assert.Equal(t.Properties.Count, t2.Properties.Count); foreach (string key in t.Properties.Values.Select(p => p.Name)) { Assert.Equal(t.Properties[key].Name, t2.Properties[key].Name); Assert.Equal(t.Properties[key].EvaluatedValue, t2.Properties[key].EvaluatedValue); } Assert.Equal(t.SubToolsets.Count, t2.SubToolsets.Count); foreach (string key in t.SubToolsets.Keys) { SubToolset subToolset1 = t.SubToolsets[key]; SubToolset subToolset2 = null; if (t2.SubToolsets.TryGetValue(key, out subToolset2)) { Assert.Equal(subToolset1.SubToolsetVersion, subToolset2.SubToolsetVersion); Assert.Equal(subToolset1.Properties.Count, subToolset2.Properties.Count); foreach (string subToolsetPropertyKey in subToolset1.Properties.Values.Select(p => p.Name)) { Assert.Equal(subToolset1.Properties[subToolsetPropertyKey].Name, subToolset2.Properties[subToolsetPropertyKey].Name); Assert.Equal(subToolset1.Properties[subToolsetPropertyKey].EvaluatedValue, subToolset2.Properties[subToolsetPropertyKey].EvaluatedValue); } } else { Assert.True(false, $"Sub-toolset {key} was lost in translation."); } } Assert.Equal(t.DefaultOverrideToolsVersion, t2.DefaultOverrideToolsVersion); Assert.NotNull(t2.ImportPropertySearchPathsTable); Assert.Single(t2.ImportPropertySearchPathsTable); Assert.Equal(@"c:\foo", t2.ImportPropertySearchPathsTable["MSBuildExtensionsPath"].SearchPaths[0]); } [Fact] public void TestDefaultSubToolset() { Toolset t = GetFakeToolset(null /* no global properties */); // The highest one numerically -- in this case, v13. Assert.Equal("v13.0", t.DefaultSubToolsetVersion); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestDefaultSubToolsetFor40() { Toolset t = ProjectCollection.GlobalProjectCollection.GetToolset("4.0"); if (t != null) { if (Toolset.Dev10IsInstalled) { // If Dev10 is installed, the default sub-toolset = no sub-toolset Assert.Equal(Constants.Dev10SubToolsetValue, t.DefaultSubToolsetVersion); } else { // Otherwise, it's the highest one numerically. Since by definition if Dev10 isn't // installed and subtoolsets exists we must be at least Dev11, it should be "11.0" Assert.Equal("11.0", t.DefaultSubToolsetVersion); } } } [Fact] public void TestDefaultWhenNoSubToolset() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); ProjectCollection projectCollection = new ProjectCollection(); Toolset parentToolset = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion); Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath); if (Toolset.Dev10IsInstalled) { Assert.Equal(Constants.Dev10SubToolsetValue, t.DefaultSubToolsetVersion); } else { Assert.Null(t.DefaultSubToolsetVersion); } } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestGenerateSubToolsetVersionWhenNoSubToolset() { if (NativeMethodsShared.IsUnixLike) { return; // "TODO: Under Unix this test throws. Investigate" } string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); ProjectCollection projectCollection = new ProjectCollection(); Toolset parentToolset = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion); Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath); string subToolsetVersion = t.GenerateSubToolsetVersion(); if (Toolset.Dev10IsInstalled) { Assert.Equal(Constants.Dev10SubToolsetValue, subToolsetVersion); } else { Assert.Null(subToolsetVersion); } } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestNoSubToolset_GlobalPropertyOverrides() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); IDictionary<string, string> globalProperties = new Dictionary<string, string>(); globalProperties.Add("VisualStudioVersion", "99.0"); ProjectCollection projectCollection = new ProjectCollection(globalProperties); Toolset parentToolset = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion); Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath); Assert.Equal("99.0", t.GenerateSubToolsetVersion()); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestNoSubToolset_EnvironmentOverrides() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", "foo"); ProjectCollection projectCollection = new ProjectCollection(); Toolset parentToolset = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion); Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath); Assert.Equal("foo", t.GenerateSubToolsetVersion()); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestNoSubToolset_ExplicitlyPassedGlobalPropertyOverrides() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); ProjectCollection projectCollection = new ProjectCollection(); Toolset parentToolset = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion); Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath); IDictionary<string, string> globalProperties = new Dictionary<string, string>(); globalProperties.Add("VisualStudioVersion", "v14.0"); Assert.Equal("v14.0", t.GenerateSubToolsetVersion(globalProperties, 0)); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestNoSubToolset_ExplicitlyPassedGlobalPropertyWins() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", "foo"); IDictionary<string, string> globalProperties = new Dictionary<string, string>(); globalProperties.Add("VisualStudioVersion", "v13.0"); ProjectCollection projectCollection = new ProjectCollection(globalProperties); Toolset parentToolset = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion); Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath); IDictionary<string, string> explicitGlobalProperties = new Dictionary<string, string>(); explicitGlobalProperties.Add("VisualStudioVersion", "baz"); Assert.Equal("baz", t.GenerateSubToolsetVersion(explicitGlobalProperties, 0)); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestGenerateSubToolsetVersion_GlobalPropertyOverrides() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); IDictionary<string, string> globalProperties = new Dictionary<string, string>(); globalProperties.Add("VisualStudioVersion", ObjectModelHelpers.CurrentVisualStudioVersion); Toolset t = GetFakeToolset(globalProperties); Assert.Equal(ObjectModelHelpers.CurrentVisualStudioVersion, t.GenerateSubToolsetVersion()); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestGenerateSubToolsetVersion_EnvironmentOverrides() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", "FakeSubToolset"); Toolset t = GetFakeToolset(null); Assert.Equal("FakeSubToolset", t.GenerateSubToolsetVersion()); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestGenerateSubToolsetVersion_ExplicitlyPassedGlobalPropertyOverrides() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); Toolset t = GetFakeToolset(null); IDictionary<string, string> globalProperties = new Dictionary<string, string>(); globalProperties.Add("VisualStudioVersion", "v13.0"); Assert.Equal("v13.0", t.GenerateSubToolsetVersion(globalProperties, 0)); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestGenerateSubToolsetVersion_SolutionVersionOverrides() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); Toolset t = GetFakeToolset(null); // VisualStudioVersion = SolutionVersion - 1 Assert.Equal("12.0", t.GenerateSubToolsetVersion(null, 13)); Assert.Equal("v13.0", t.GenerateSubToolsetVersion(null, 14)); // however, if there is no matching solution version, we just fall back to the // default sub-toolset. Assert.Equal(t.DefaultSubToolsetVersion, t.GenerateSubToolsetVersion(null, 55)); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestGenerateSubToolsetVersion_ExplicitlyPassedGlobalPropertyWins() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", ObjectModelHelpers.CurrentVisualStudioVersion); IDictionary<string, string> globalProperties = new Dictionary<string, string>(); globalProperties.Add("VisualStudioVersion", "v13.0"); ProjectCollection projectCollection = new ProjectCollection(globalProperties); Toolset parentToolset = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion); Toolset t = new Toolset("Fake", parentToolset.ToolsPath, null, projectCollection, null, parentToolset.OverrideTasksPath); IDictionary<string, string> explicitGlobalProperties = new Dictionary<string, string>(); explicitGlobalProperties.Add("VisualStudioVersion", "FakeSubToolset"); Assert.Equal("FakeSubToolset", t.GenerateSubToolsetVersion(explicitGlobalProperties, 0)); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } [Fact] public void TestGetPropertyFromSubToolset() { Toolset t = GetFakeToolset(null); Assert.Equal("a1", t.GetProperty("a", "v11.0").EvaluatedValue); // property in base toolset Assert.Equal("c2", t.GetProperty("c", "v11.0").EvaluatedValue); // property in sub-toolset Assert.Equal("b2", t.GetProperty("b", "v11.0").EvaluatedValue); // property in sub-toolset that overrides base toolset Assert.Null(t.GetProperty("d", "v11.0")); // property in a different sub-toolset } /// <summary> /// Creates a standard ProjectCollection and adds a fake toolset with the following contents to it: /// /// ToolsVersion = Fake /// Base Properties: /// a = a1 /// b = b1 /// /// SubToolset "12.0": /// d = d4 /// e = e5 /// /// SubToolset "v11.0": /// b = b2 /// c = c2 /// /// SubToolset "FakeSubToolset": /// a = a3 /// c = c3 /// /// SubToolset "v13.0": /// f = f6 /// g = g7 /// </summary> private Toolset GetFakeToolset(IDictionary<string, string> globalPropertiesForProjectCollection) { ProjectCollection projectCollection = new ProjectCollection(globalPropertiesForProjectCollection); IDictionary<string, string> properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); properties.Add("a", "a1"); properties.Add("b", "b1"); Dictionary<string, SubToolset> subToolsets = new Dictionary<string, SubToolset>(StringComparer.OrdinalIgnoreCase); // SubToolset 12.0 properties PropertyDictionary<ProjectPropertyInstance> subToolset12Properties = new PropertyDictionary<ProjectPropertyInstance>(); subToolset12Properties.Set(ProjectPropertyInstance.Create("d", "d4")); subToolset12Properties.Set(ProjectPropertyInstance.Create("e", "e5")); // SubToolset v11.0 properties PropertyDictionary<ProjectPropertyInstance> subToolset11Properties = new PropertyDictionary<ProjectPropertyInstance>(); subToolset11Properties.Set(ProjectPropertyInstance.Create("b", "b2")); subToolset11Properties.Set(ProjectPropertyInstance.Create("c", "c2")); // FakeSubToolset properties PropertyDictionary<ProjectPropertyInstance> fakeSubToolsetProperties = new PropertyDictionary<ProjectPropertyInstance>(); fakeSubToolsetProperties.Set(ProjectPropertyInstance.Create("a", "a3")); fakeSubToolsetProperties.Set(ProjectPropertyInstance.Create("c", "c3")); // SubToolset v13.0 properties PropertyDictionary<ProjectPropertyInstance> subToolset13Properties = new PropertyDictionary<ProjectPropertyInstance>(); subToolset13Properties.Set(ProjectPropertyInstance.Create("f", "f6")); subToolset13Properties.Set(ProjectPropertyInstance.Create("g", "g7")); subToolsets.Add("12.0", new SubToolset("12.0", subToolset12Properties)); subToolsets.Add("v11.0", new SubToolset("v11.0", subToolset11Properties)); subToolsets.Add("FakeSubToolset", new SubToolset("FakeSubToolset", fakeSubToolsetProperties)); subToolsets.Add("v13.0", new SubToolset("v13.0", subToolset13Properties)); Toolset parentToolset = projectCollection.GetToolset(ObjectModelHelpers.MSBuildDefaultToolsVersion); Toolset fakeToolset = new Toolset("Fake", parentToolset.ToolsPath, properties, projectCollection, subToolsets, parentToolset.OverrideTasksPath); projectCollection.AddToolset(fakeToolset); return fakeToolset; } } }
#region License /* * Copyright 2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using NUnit.Framework; using Spring.Core; using Spring.Objects; using Spring.Objects.Factory; using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Xml; namespace Spring.Context.Support { /// <summary> /// Test creation of application context from XML. /// </summary> /// <author>Mark Pollack</author> [TestFixture] public sealed class XmlApplicationContextTests { [Test(Description = "http://jira.springframework.org/browse/SPRNET-1231")] public void SPRNET1231_DoesNotInvokeFactoryMethodDuringObjectFactoryPostProcessing() { string configLocation = TestResourceLoader.GetAssemblyResourceUri(this.GetType(), "XmlApplicationContextTests-SPRNET1231.xml"); XmlApplicationContext ctx = new XmlApplicationContext(configLocation); } private class SPRNET1231ObjectFactoryPostProcessor : IObjectFactoryPostProcessor { public void PostProcessObjectFactory(IConfigurableListableObjectFactory factory) { SPRNET1231FactoryObject testFactory = (SPRNET1231FactoryObject)factory.GetObject("testFactory"); Assert.AreEqual(0, testFactory.count); } } private class SPRNET1231FactoryObject { public int count; public ITestObject GetProduct() { count++; return new TestObject("test" + count, count); } } [Test] public void InnerObjectWithPostProcessing() { try { XmlApplicationContext ctx = new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/innerObjectsWithPostProcessor.xml"); ctx.GetObject("hasInnerObjects"); Assert.Fail("should throw ObjectCreationException"); } catch (ObjectCreationException e) { NoSuchObjectDefinitionException ex = e.InnerException as NoSuchObjectDefinitionException; Assert.IsNotNull(ex); //Pass } } [Test] [ExpectedException(typeof(ArgumentException))] public void NoConfigLocation() { new XmlApplicationContext(); } [Test] public void SingleConfigLocation() { XmlApplicationContext ctx = new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/simpleContext.xml"); Assert.IsTrue(ctx.ContainsObject("someMessageSource")); ctx.Dispose(); } [Test] public void MultipleConfigLocations() { XmlApplicationContext ctx = new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/contextB.xml", "assembly://Spring.Core.Tests/Spring.Context.Support/contextC.xml", "assembly://Spring.Core.Tests/Spring.Context.Support/contextA.xml"); Assert.IsTrue(ctx.ContainsObject("service")); Assert.IsTrue(ctx.ContainsObject("logicOne")); Assert.IsTrue(ctx.ContainsObject("logicTwo")); Service service = (Service) ctx.GetObject("service"); ctx.Refresh(); Assert.IsTrue(service.ProperlyDestroyed); service = (Service) ctx.GetObject("service"); ctx.Dispose(); Assert.IsTrue(service.ProperlyDestroyed); } [Test] public void ContextWithInvalidValueType() { try { XmlApplicationContext ctx = new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/invalidValueType.xml"); Assert.Fail("Should have thrown ObjectCreationException for context", ctx); } catch (ObjectCreationException ex) { Assert.IsTrue(ex.Message.IndexOf((typeof (TypeMismatchException).Name)) != -1); Assert.IsTrue(ex.Message.IndexOf(("UseCodeAsDefaultMessage")) != -1); } } [Test] [Ignore("Need to add Spring.TypeLoadException")] public void ContextWithInvalidLazyType() { XmlApplicationContext ctx = new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/invalidType.xml"); Assert.IsTrue(ctx.ContainsObject("someMessageSource")); ctx.GetObject("someMessageSource"); } [Test] public void CaseInsensitiveContext() { XmlApplicationContext ctx = new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml"); Assert.IsTrue(ctx.ContainsObject("goran")); Assert.IsTrue(ctx.ContainsObject("Goran")); Assert.IsTrue(ctx.ContainsObject("GORAN")); Assert.AreEqual(ctx.GetObject("goran"), ctx.GetObject("GORAN")); } [Test] [ExpectedException(typeof(NoSuchObjectDefinitionException))] public void GetObjectOnUnknownIdThrowsNoSuchObjectDefinition() { XmlApplicationContext ctx = new XmlApplicationContext(false, "assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml"); string DOES_NOT_EXIST = "does_not_exist"; Assert.IsFalse(ctx.ContainsObject(DOES_NOT_EXIST)); Assert.IsNull(ctx.GetObject(DOES_NOT_EXIST)); } [Test] public void FactoryObjectsAreNotInstantiatedBeforeObjectFactoryPostProcessorsAreApplied() { XmlApplicationContext ctx = new XmlApplicationContext("Spring/Context/Support/SPRNET-192.xml"); LogFactoryObject logFactory = (LogFactoryObject) ctx["&log"]; Assert.AreEqual("foo", logFactory.LogName); } /// <summary> /// Make sure that if an IObjectPostProcessor is defined as abstract /// the creation of an IApplicationContext will not try to instantiate it. /// </summary> [Test] public void ContextWithPostProcessors() { CountingObjectPostProcessor.Count = 0; CoutingObjectFactoryPostProcessor.Count = 0; IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml"); Assert.IsTrue(ctx.ContainsObject("abstractObjectProcessorPrototype")); Assert.IsTrue(ctx.ContainsObject("abstractFactoryProcessorPrototype")); Assert.AreEqual(0, CountingObjectPostProcessor.Count); Assert.AreEqual(0, CoutingObjectFactoryPostProcessor.Count); } /// <summary> /// Make sure that ConfigureObject() completly configures target /// object (goes through whole lifecycle of object creation and /// applies all processors). /// </summary> [Test] public void ConfigureObject() { const string objDefLocation = "assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml"; XmlApplicationContext xmlContext = new XmlApplicationContext(new string[] {objDefLocation}); object objGoran = xmlContext.GetObject("goran"); Assert.IsTrue(objGoran is TestObject); TestObject fooGet = objGoran as TestObject; TestObject fooConfigure = new TestObject(); xmlContext.ConfigureObject(fooConfigure, "goran"); Assert.IsNotNull(fooGet); Assert.AreEqual(fooGet.Name, fooConfigure.Name); Assert.AreEqual(fooGet.Age, fooConfigure.Age); Assert.AreEqual(fooGet.ObjectName, fooConfigure.ObjectName); Assert.IsNotNull(fooGet.ObjectName); Assert.AreEqual(xmlContext, fooGet.ApplicationContext); Assert.AreEqual(xmlContext, fooConfigure.ApplicationContext); } [Test] public void ContextLifeCycle() { IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Core.Tests/Spring.Context/contextlifecycle.xml"); IConfigurableApplicationContext configCtx = ctx as IConfigurableApplicationContext; Assert.IsNotNull(configCtx); ContextListenerObject clo; using (configCtx) { clo = configCtx["contextListenerObject"] as ContextListenerObject; Assert.IsNotNull(clo); Assert.IsTrue(clo.AppListenerContextRefreshed, "Object did not receive context refreshed event via IApplicationListener"); Assert.IsTrue(clo.CtxRefreshed, "Object did not receive context refreshed event via direct wiring"); } Assert.IsTrue(clo.AppListenerContextClosed, "Object did not receive context closed event via IApplicationContextListener"); Assert.IsTrue(clo.CtxClosed, "Object did not receive context closed event via direct wiring."); } [Test] public void RefreshDisposesExistingObjectFactory_SPRNET479() { string tmp = typeof (DestroyTester).FullName; Console.WriteLine(tmp); IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Core.Tests/Spring.Context.Support/objects.xml"); DestroyTester destroyTester = (DestroyTester) ctx.GetObject("destroyTester"); DisposeTester disposeTester = (DisposeTester) ctx.GetObject("disposeTester"); Assert.IsFalse(destroyTester.IsDestroyed); Assert.IsFalse(disposeTester.IsDisposed); ((IConfigurableApplicationContext) ctx).Refresh(); Assert.IsTrue(destroyTester.IsDestroyed); Assert.IsTrue(disposeTester.IsDisposed); } [Test] public void GenericApplicationContextWithXmlObjectDefinitions() { GenericApplicationContext ctx = new GenericApplicationContext(); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(ctx); reader.LoadObjectDefinitions("assembly://Spring.Core.Tests/Spring.Context.Support/contextB.xml"); reader.LoadObjectDefinitions("assembly://Spring.Core.Tests/Spring.Context.Support/contextC.xml"); reader.LoadObjectDefinitions("assembly://Spring.Core.Tests/Spring.Context.Support/contextA.xml"); ctx.Refresh(); Assert.IsTrue(ctx.ContainsObject("service")); Assert.IsTrue(ctx.ContainsObject("logicOne")); Assert.IsTrue(ctx.ContainsObject("logicTwo")); ctx.Dispose(); } [Test] public void GenericApplicationContextConstructorTests() { IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Core.Tests/Spring.Context/contextlifecycle.xml"); GenericApplicationContext genericCtx = new GenericApplicationContext(ctx); genericCtx = new GenericApplicationContext("test", true, ctx); } #region Helper classes public class DisposeTester : IDisposable { private bool isDisposed = false; public bool IsDisposed { get { return isDisposed; } } public void Dispose() { if (isDisposed) throw new InvalidOperationException("must not be disposed twice"); isDisposed = true; } } public class DestroyTester { private bool isDestroyed = false; public bool IsDestroyed { get { return isDestroyed; } } public void DestroyMe() { if (isDestroyed) throw new InvalidOperationException("must not be destroyed twice"); isDestroyed = true; } } /// <summary> /// Utility class to keep track of object construction. /// </summary> public class CountingObjectPostProcessor : IObjectPostProcessor { private static int count; /// <summary> /// Property Count (int) /// </summary> public static int Count { get { return count; } set { count = value; } } /// <summary> /// Create an instance and increment the counter /// </summary> public CountingObjectPostProcessor() { count++; } #region IObjectPostProcessor Members /// <summary> /// No op implementation /// </summary> /// <param name="obj">object to process</param> /// <param name="objectName">name of object</param> /// <returns>processed object</returns> public object PostProcessAfterInitialization(object obj, string objectName) { return obj; } /// <summary> /// No op implementation /// </summary> /// <param name="obj">object to process</param> /// <param name="name">name of object</param> /// <returns>processed object</returns> public object PostProcessBeforeInitialization(object obj, string name) { return obj; } #endregion } /// <summary> /// Utility class to keep track of object construction. /// </summary> public class CoutingObjectFactoryPostProcessor : IObjectFactoryPostProcessor { private static int count; /// <summary> /// Property Count (int) /// </summary> public static int Count { get { return count; } set { count = value; } } /// <summary> /// Create an instance and increment the counter /// </summary> public CoutingObjectFactoryPostProcessor() { count++; } #region IObjectFactoryPostProcessor Members /// <summary> /// no op /// </summary> /// <param name="factory">factory to post process</param> public void PostProcessObjectFactory(IConfigurableListableObjectFactory factory) { } #endregion } #endregion } public class SingletonTestingObjectPostProcessor : IObjectPostProcessor, IApplicationContextAware { private IApplicationContext applicationContext; #region IObjectPostProcessor Members public object PostProcessBeforeInitialization(object instance, string name) { return instance; } public object PostProcessAfterInitialization(object instance, string objectName) { Console.WriteLine("post process " + objectName); if (this.applicationContext.IsSingleton(objectName)) { return instance; } return instance; } #endregion #region IApplicationContextAware Members public IApplicationContext ApplicationContext { set { this.applicationContext = value; } } #endregion } }
using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Text.RegularExpressions; namespace io { public class IoMessage : IoObject { public bool async = false; public override string name { get { return "Message"; } } public IoSeq messageName; public IoObjectArrayList args; public IoMessage next; public IoObject cachedResult; public int lineNumber; public IoSeq label; public new static IoMessage createProto(IoState state) { IoMessage m = new IoMessage(); return m.proto(state) as IoMessage; } public new static IoMessage createObject(IoState state) { IoMessage pro = new IoMessage(); return pro.clone(state) as IoMessage; } public override IoObject proto(IoState state) { IoMessage pro = new IoMessage(); pro.state = state; // pro.tag.cloneFunc = new IoTagCloneFunc(this.clone); //pro.tag.activateFunc = new IoTagActivateFunc(this.activate); pro.createSlots(); pro.createProtos(); pro.uniqueId = 0; pro.messageName = IoSeq.createSymbolInMachine(state, "anonymous"); pro.label = IoSeq.createSymbolInMachine(state, "unlabeled"); pro.args = new IoObjectArrayList(); state.registerProtoWithFunc(name, new IoStateProto(name, pro, new IoStateProtoFunc(this.proto))); pro.protos.Add(state.protoWithInitFunc("Object")); IoCFunction[] methodTable = new IoCFunction[] { new IoCFunction("name", new IoMethodFunc(IoMessage.slotName)), new IoCFunction("setName", new IoMethodFunc(IoMessage.slotSetName)), new IoCFunction("next", new IoMethodFunc(IoMessage.slotNext)), new IoCFunction("setNext", new IoMethodFunc(IoMessage.slotSetNext)), new IoCFunction("code", new IoMethodFunc(IoMessage.slotCode)), new IoCFunction("arguments", new IoMethodFunc(IoMessage.slotArguments)), new IoCFunction("appendArg", new IoMethodFunc(IoMessage.slotAppendArg)), new IoCFunction("argAt", new IoMethodFunc(IoMessage.slotArgAt)), new IoCFunction("argCount", new IoMethodFunc(IoMessage.slotArgCount)), new IoCFunction("asString", new IoMethodFunc(IoMessage.slotCode)), new IoCFunction("cachedResult", new IoMethodFunc(IoMessage.slotCachedResult)), new IoCFunction("setCachedResult", new IoMethodFunc(IoMessage.slotSetCachedResult)), new IoCFunction("removeCachedResult", new IoMethodFunc(IoMessage.slotRemoveCachedResult)), new IoCFunction("hasCachedResult", new IoMethodFunc(IoMessage.slotHasCachedResult)), }; pro.addTaglessMethodTable(state, methodTable); return pro; } public override void cloneSpecific(IoObject _from, IoObject _to) { IoMessage from = _from as IoMessage; IoMessage to = _to as IoMessage; to.messageName = from.messageName; to.label = from.label; to.args = new IoObjectArrayList(); } // Published Slots public static IoObject slotName(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; return self.messageName; } public static IoObject slotSetName(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; IoMessage msg = message as IoMessage; IoSeq s = msg.localsSymbolArgAt(locals, 0); self.messageName = s; return self; } public static IoObject slotNext(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; return self.next == null ? target.state.ioNil : self.next; } public static IoObject slotSetNext(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; IoMessage msg = message as IoMessage; IoObject m = msg.localsMessageArgAt(locals, 0) as IoObject; IoMessage mmm = null; if (m == target.state.ioNil) { mmm = null; } else if (m.name.Equals("Message")) { mmm = m as IoMessage; } else { Console.WriteLine("argument must be Message or Nil"); } self.next = mmm; return self; } public static IoObject slotCode(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; string s = ""; s = self.descriptionToFollow(true); return IoSeq.createObject(self.state, s); } public static IoObject slotArguments(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; IoList list = IoList.createObject(target.state); foreach (IoObject o in self.args) { list.append(o); } return list; } public static IoObject slotAppendArg(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; IoMessage msg = message as IoMessage; IoMessage m = msg.localsMessageArgAt(locals, 0) as IoMessage; self.args.Add(m); return self; } public static IoObject slotArgCount(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; return IoNumber.newWithDouble(target.state, Convert.ToDouble(self.args.Count)); } public static IoObject slotArgAt(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; IoMessage m = message as IoMessage; int index = m.localsNumberArgAt(locals, 0).asInt(); IoObject v = self.args[index] as IoObject; return v != null ? v : self.state.ioNil; } public static IoObject slotCachedResult(IoObject target, IoObject locals, IoObject message) { IoMessage m = target as IoMessage; return m.cachedResult == null ? target.state.ioNil : m.cachedResult; } public static IoObject slotSetCachedResult(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; IoMessage msg = message as IoMessage; self.cachedResult = msg.localsValueArgAt(locals, 0); return self; } public static IoObject slotRemoveCachedResult(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; self.cachedResult = null; return self; } public static IoObject slotHasCachedResult(IoObject target, IoObject locals, IoObject message) { IoMessage self = target as IoMessage; return self.cachedResult == null ? target.state.ioFalse : target.state.ioTrue; } // Message Public Raw Methods public static IoMessage newWithName(IoState state, IoSeq ioSymbol) { IoMessage msg = IoMessage.createObject(state); msg.messageName = ioSymbol; return msg; } public IoMessage newFromTextLabel(IoState state, string code, string label) { IoSeq labelSymbol = IoSeq.createSymbolInMachine(state, label); return newFromTextLabelSymbol(state, code, labelSymbol); } public string descriptionToFollow(bool follow) { IoMessage m = this; string s = ""; do { s += m.messageName; if (m.args.Count > 0) { s += "("; for (int i = 0; i < m.args.Count; i++) { IoMessage arg = m.args[i] as IoMessage; s += arg.descriptionToFollow(true); if (i != m.args.Count - 1) { s += ", "; } } s += ")"; } if (!follow) { return s; } if (m.next != null && !m.messageName.value.Equals(";")) { s += " "; } if (m.messageName.value.Equals(";")) { s += "\n"; } } while ((m = m.next) != null); return s; } public static IEnumerator asyncCall(IoContext ctx, IoObject future) { IoObject target = ctx.target; IoObject locals = ctx.locals; IoObject result = target; IoObject cachedTarget = target; IoMessage msg = ctx.message; IoObject savedPrevResultAsYieldResult = null; do { if (msg.messageName.Equals(msg.state.semicolonSymbol)) { target = cachedTarget; } else { result = msg.cachedResult; if (result == null) { if (msg.messageName.value.Equals("yield")) { yield return result; } else { result = target.perform(target, locals, msg); } } if (result == null) { result = savedPrevResultAsYieldResult; } target = result; savedPrevResultAsYieldResult = result; } } while ((msg = msg.next) != null); future.slots["future"] = result; yield return null; //yield return result; } public IoObject localsPerformOn(IoObject target, IoObject locals) { if (async) { IoContext ctx = new IoContext(); ctx.target = target; ctx.locals = locals; ctx.message = this; IoState state = target.state; IoObject future = IoObject.createObject(state); IEnumerator e = IoMessage.asyncCall(ctx, future); state.contextList.Add(e); return future; } IoObject result = target; IoObject cachedTarget = target; IoMessage msg = this; do { if (msg.messageName.Equals(msg.state.semicolonSymbol)) { target = cachedTarget; } else { result = msg.cachedResult; if (result == null) { //if (target.tag.performFunc == null) result = target.perform(target, locals, msg); //else // result = target.tag.performFunc(target, locals, msg); } if (result == null) { Console.WriteLine("Message chains intermediate mustn't be null"); } target = result; } } while ((msg = msg.next) != null); return result; } public override string ToString() { return messageName.ToString();// +args.ToString(); } public override void print() { string code = this.descriptionToFollow(true); Console.Write(code); //Console.Write(ToString()); } public IoMessage rawArgAt(int p) { IoMessage argIsMessage = args[p] as IoMessage; return argIsMessage; } public IoObject localsValueArgAt(IoObject locals, int i) { IoMessage m = i < args.Count ? args[i] as IoMessage : null; //m.async = async; if (m != null) { if (m.cachedResult != null && m.next == null) { return m.cachedResult; } return m.localsPerformOn(locals, locals); } return this.state.ioNil; } // TODO: possible folding of following functions public IoSeq localsSymbolArgAt(IoObject locals, int i) { IoObject o = localsValueArgAt(locals, i); if (!o.name.Equals("Sequence")) { localsNumberArgAtErrorForType(locals, i, "Sequence"); } return o as IoSeq; } public IoObject localsMessageArgAt(IoObject locals, int n) { IoObject v = localsValueArgAt(locals, n); if (!v.name.Equals("Message") && v != state.ioNil) { localsNumberArgAtErrorForType(locals, n, "Message"); } return v; } public IoNumber localsNumberArgAt(IoObject locals, int i) { IoObject o = localsValueArgAt(locals, i); if (o == null || !o.name.Equals("Number")) { localsNumberArgAtErrorForType(locals, i, "Number"); } return o as IoNumber; } // Private Methods void localsNumberArgAtErrorForType(IoObject locals, int i, string p) { IoObject v = localsValueArgAt(locals, i); Console.WriteLine("argument {0} to method '{1}' must be a {2}, not a '{3}'", i, this.messageName, p, v.name); } IoMessage newParse(IoState state, IoLexer lexer) { if (lexer.errorToken != null) { } if (lexer.topType() == IoTokenType.TERMINATOR_TOKEN) { lexer.pop(); } if (lexer.top() != null && lexer.top().isValidMessageName()) { IoMessage self = newParseNextMessageChain(state, lexer); if (lexer.topType() != IoTokenType.NO_TOKEN) { state.error(self, "compile error: %s", "unused tokens"); } return self; } return newWithNameReturnsValue(state, IoSeq.createSymbolInMachine(state, "nil"), state.ioNil); } IoMessage newWithNameReturnsValue(IoState state, IoSeq symbol, IoObject v) { IoMessage self = clone(state) as IoMessage; self.messageName = symbol; self.cachedResult = v; return self; } IoMessage newParseNextMessageChain(IoState state, IoLexer lexer) { IoMessage msg = clone(state) as IoMessage; if (lexer.top() != null && lexer.top().isValidMessageName()) { msg.parseName(state, lexer); } if (lexer.topType() == IoTokenType.OPENPAREN_TOKEN) { msg.parseArgs(lexer); } if (lexer.top() != null && lexer.top().isValidMessageName()) { msg.parseNext(lexer); } while (lexer.topType() == IoTokenType.TERMINATOR_TOKEN) { lexer.pop(); if (lexer.top() != null && lexer.top().isValidMessageName()) { IoMessage eol = IoMessage.newWithName(state, state.semicolonSymbol); msg.next = eol; eol.parseNext(lexer); } } return msg; } void parseName(IoState state, IoLexer lexer) { IoToken token = lexer.pop(); messageName = IoSeq.createSymbolInMachine(state, token.name); ifPossibleCacheToken(token); //rawSetLineNumber(token.lineNumber); //rawSetCharNumber(token.charNumber); } void ifPossibleCacheToken(IoToken token) { IoSeq method = this.messageName; IoObject r = null; switch (token.type) { case IoTokenType.TRIQUOTE_TOKEN: break; case IoTokenType.MONOQUOTE_TOKEN: r = IoSeq.createSymbolInMachine( method.state, IoSeq.rawAsUnescapedSymbol( IoSeq.rawAsUnquotedSymbol( IoSeq.createObject(method.state, method.value) ) ).value ); break; case IoTokenType.NUMBER_TOKEN: r = IoNumber.newWithDouble(this.state, Convert.ToDouble(method.value, CultureInfo.InvariantCulture)); break; default: if (method.value.Equals("nil")) { r = state.ioNil; } else if (method.value.Equals("true")) { r = state.ioTrue; } else if (method.value.Equals("false")) { r = state.ioFalse; } break; } this.cachedResult = r; } void parseNext(IoLexer lexer) { IoMessage nextMessage = newParseNextMessageChain(this.state, lexer); this.next = nextMessage; } void parseArgs(IoLexer lexer) { lexer.pop(); if (lexer.top() != null && lexer.top().isValidMessageName()) { IoMessage arg = newParseNextMessageChain(this.state, lexer); addArg(arg); while (lexer.topType() == IoTokenType.COMMA_TOKEN) { lexer.pop(); if (lexer.top() != null && lexer.top().isValidMessageName()) { IoMessage arg2 = newParseNextMessageChain(this.state, lexer); addArg(arg2); } else { } } } if (lexer.topType() != IoTokenType.CLOSEPAREN_TOKEN) { // TODO: Exception, missing close paren } lexer.pop(); } void addArg(IoMessage arg) { args.Add(arg); } IoMessage newFromTextLabelSymbol(IoState state, string code, IoSeq labelSymbol) { IoLexer lexer = new IoLexer(); IoMessage msg = new IoMessage(); msg = msg.clone(state) as IoMessage; lexer.s = code; lexer.lex(); msg = this.newParse(state, lexer); msg.opShuffle(); msg.label = labelSymbol; return msg; } IoObject opShuffle() { IoObject context = null; IoObject m = this.rawGetSlotContext(state.opShuffleMessage.messageName, out context); if (m != null) { state.opShuffleMessage.localsPerformOn(this, state.lobby); } return this; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; using Microsoft.Xunit.Performance; namespace System.Linq.Tests { public class Perf_Linq { #region Helper Methods /// <summary> /// Provides TestInfo data to xunit performance tests /// </summary> public static IEnumerable<object[]> IterationSizeWrapperData() { int[] iterations = { 1000 }; int[] sizes = { 100 }; foreach (int iteration in iterations) foreach (int size in sizes) { yield return new object[] { size, iteration, Perf_LinqTestBase.WrapperType.NoWrap }; yield return new object[] { size, iteration, Perf_LinqTestBase.WrapperType.IEnumerable }; yield return new object[] { size, iteration, Perf_LinqTestBase.WrapperType.IReadOnlyCollection }; yield return new object[] { size, iteration, Perf_LinqTestBase.WrapperType.ICollection }; } } /// <summary> /// Provides TestInfo data to xunit performance tests /// </summary> public static IEnumerable<object[]> IterationSizeWrapperDataNoWrapper() { int[] iterations = { 1000 }; int[] sizes = { 100 }; foreach (int iteration in iterations) foreach (int size in sizes) yield return new object[] { size, iteration }; } private class BaseClass { public int Value; } private class ChildClass : BaseClass { public int ChildValue; } #endregion #region Perf Tests [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Select(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Select(o => o + 1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void SelectSelect(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Select(o => o + 1).Select(o => o - 1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Where(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Where(o => o >= 0)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void WhereWhere(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Where(o => o >= 0).Where(o => o >= -1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void WhereSelect(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Where(o => o >= 0).Select(o => o + 1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Cast_ToBaseClass(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Func<IEnumerable<ChildClass>, IEnumerable<BaseClass>> linqApply = col => col.Cast<BaseClass>(); ChildClass val = new ChildClass() { Value = 1, ChildValue = 2 }; Perf_LinqTestBase.Measure<ChildClass, BaseClass>(10, 5, val, wrapType, linqApply); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Cast_SameType(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Func<IEnumerable<int>, IEnumerable<int>> linqApply = col => col.Cast<int>(); int val = 1; Perf_LinqTestBase.Measure<int, int>(10, 5, val, wrapType, linqApply); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void OrderBy(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.OrderBy(o => -o)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void OrderByDescending(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.OrderByDescending(o => -o)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void OrderByThenBy(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.OrderBy(o => -o).ThenBy(o => o)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperDataNoWrapper))] public void Range(int size, int iteration) { Perf_LinqTestBase.Measure<int>(1, iteration, Perf_LinqTestBase.WrapperType.NoWrap, col => Enumerable.Range(0, size)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperDataNoWrapper))] public void Repeat(int size, int iteration) { Perf_LinqTestBase.Measure<int>(1, iteration, Perf_LinqTestBase.WrapperType.NoWrap, col => Enumerable.Repeat(0, size)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Reverse(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Reverse()); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Skip(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Skip(1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Take(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Take(size - 1)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void SkipTake(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { Perf_LinqTestBase.Measure<int>(size, iteration, wrapType, col => col.Skip(1).Take(size - 2)); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void ToArray(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { int[] array = Enumerable.Range(0, size).ToArray(); Perf_LinqTestBase.MeasureMaterializationToArray<int>(Perf_LinqTestBase.Wrap(array, wrapType), iteration); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void ToList(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { int[] array = Enumerable.Range(0, size).ToArray(); Perf_LinqTestBase.MeasureMaterializationToList<int>(Perf_LinqTestBase.Wrap(array, wrapType), iteration); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void ToDictionary(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType) { int[] array = Enumerable.Range(0, size).ToArray(); Perf_LinqTestBase.MeasureMaterializationToDictionary<int>(Perf_LinqTestBase.Wrap(array, wrapType), iteration); } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Contains_ElementNotFound(int size, int iterationCount, Perf_LinqTestBase.WrapperType wrapType) { IEnumerable<int> source = Perf_LinqTestBase.Wrap(Enumerable.Range(0, size).ToArray(), wrapType); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < iterationCount; i++) { source.Contains(size + 1); } } } } [Benchmark] [MemberData(nameof(IterationSizeWrapperData))] public void Contains_FirstElementMatches(int size, int iterationCount, Perf_LinqTestBase.WrapperType wrapType) { IEnumerable<int> source = Perf_LinqTestBase.Wrap(Enumerable.Range(0, size).ToArray(), wrapType); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < iterationCount; i++) { source.Contains(0); } } } } #endregion } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using System.Windows.Markup; using Fluent.Collections; using Fluent.Extensions; using Fluent.Helpers; using Fluent.Internal.KnownBoxes; using Fluent.Localization; using JetBrains.Annotations; using WindowChrome = ControlzEx.Windows.Shell.WindowChrome; // TODO: improve style parts naming & using /// <summary> /// Represents the main Ribbon control which consists of multiple tabs, each of which /// containing groups of controls. The Ribbon also provides improved context /// menus, enhanced screen tips, and keyboard shortcuts. /// </summary> [ContentProperty(nameof(Tabs))] [DefaultProperty(nameof(Tabs))] [TemplatePart(Name = "PART_LayoutRoot", Type = typeof(Panel))] [TemplatePart(Name = "PART_RibbonTabControl", Type = typeof(RibbonTabControl))] [TemplatePart(Name = "PART_QuickAccessToolBar", Type = typeof(QuickAccessToolBar))] public class Ribbon : Control, ILogicalChildSupport { private IRibbonStateStorage ribbonStateStorage; /// <summary> /// Gets the current instance for storing the state of this control. /// </summary> public IRibbonStateStorage RibbonStateStorage => this.ribbonStateStorage ?? (this.ribbonStateStorage = this.CreateRibbonStateStorage()); /// <summary> /// Create a new instance for storing the state of this control. /// </summary> /// <returns>Instance of a state storage class.</returns> protected virtual IRibbonStateStorage CreateRibbonStateStorage() { return new RibbonStateStorage(this); } #region Constants /// <summary> /// Minimal width of ribbon parent window /// </summary> public const double MinimalVisibleWidth = 300; /// <summary> /// Minimal height of ribbon parent window /// </summary> public const double MinimalVisibleHeight = 250; #endregion #region ContextMenu /// <summary>Identifies the <see cref="IsDefaultContextMenuEnabled"/> dependency property.</summary> public static readonly DependencyProperty IsDefaultContextMenuEnabledProperty = DependencyProperty.Register(nameof(IsDefaultContextMenuEnabled), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets whether the default context menu should be enabled/used. /// </summary> public bool IsDefaultContextMenuEnabled { get { return (bool)this.GetValue(IsDefaultContextMenuEnabledProperty); } set { this.SetValue(IsDefaultContextMenuEnabledProperty, value); } } private static readonly Dictionary<int, System.Windows.Controls.ContextMenu> contextMenus = new Dictionary<int, System.Windows.Controls.ContextMenu>(); /// <summary> /// Context menu for ribbon in current thread /// </summary> public static System.Windows.Controls.ContextMenu RibbonContextMenu { get { if (!contextMenus.ContainsKey(Thread.CurrentThread.ManagedThreadId)) { InitRibbonContextMenu(); } return contextMenus[Thread.CurrentThread.ManagedThreadId]; } } // Context menu owner ribbon private static Ribbon contextMenuOwner; // Context menu items private static readonly Dictionary<int, System.Windows.Controls.MenuItem> addToQuickAccessMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem AddToQuickAccessMenuItem { get { return addToQuickAccessMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, System.Windows.Controls.MenuItem> addGroupToQuickAccessMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem AddGroupToQuickAccessMenuItem { get { return addGroupToQuickAccessMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, System.Windows.Controls.MenuItem> addMenuToQuickAccessMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem AddMenuToQuickAccessMenuItem { get { return addMenuToQuickAccessMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, System.Windows.Controls.MenuItem> addGalleryToQuickAccessMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem AddGalleryToQuickAccessMenuItem { get { return addGalleryToQuickAccessMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, System.Windows.Controls.MenuItem> removeFromQuickAccessMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem RemoveFromQuickAccessMenuItem { get { return removeFromQuickAccessMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, System.Windows.Controls.MenuItem> showQuickAccessToolbarBelowTheRibbonMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem ShowQuickAccessToolbarBelowTheRibbonMenuItem { get { return showQuickAccessToolbarBelowTheRibbonMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, System.Windows.Controls.MenuItem> showQuickAccessToolbarAboveTheRibbonMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem ShowQuickAccessToolbarAboveTheRibbonMenuItem { get { return showQuickAccessToolbarAboveTheRibbonMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, System.Windows.Controls.MenuItem> minimizeTheRibbonMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem MinimizeTheRibbonMenuItem { get { return minimizeTheRibbonMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, System.Windows.Controls.MenuItem> customizeQuickAccessToolbarMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem CustomizeQuickAccessToolbarMenuItem { get { return customizeQuickAccessToolbarMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, System.Windows.Controls.MenuItem> customizeTheRibbonMenuItemDictionary = new Dictionary<int, System.Windows.Controls.MenuItem>(); private static System.Windows.Controls.MenuItem CustomizeTheRibbonMenuItem { get { return customizeTheRibbonMenuItemDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, Separator> firstSeparatorDictionary = new Dictionary<int, Separator>(); private static Separator FirstSeparator { get { return firstSeparatorDictionary[Thread.CurrentThread.ManagedThreadId]; } } private static readonly Dictionary<int, Separator> secondSeparatorDictionary = new Dictionary<int, Separator>(); private static Separator SecondSeparator { get { return secondSeparatorDictionary[Thread.CurrentThread.ManagedThreadId]; } } // Initialize ribbon context menu private static void InitRibbonContextMenu() { contextMenus.Add(Thread.CurrentThread.ManagedThreadId, new ContextMenu()); RibbonContextMenu.Opened += OnContextMenuOpened; } private static void InitRibbonContextMenuItems() { // Add to quick access toolbar addToQuickAccessMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(AddToQuickAccessCommand)); RibbonContextMenu.Items.Add(AddToQuickAccessMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, AddToQuickAccessMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuAddItem), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, AddToQuickAccessMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); // Add group to quick access toolbar addGroupToQuickAccessMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(AddToQuickAccessCommand)); RibbonContextMenu.Items.Add(AddGroupToQuickAccessMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, AddGroupToQuickAccessMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuAddGroup), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, AddGroupToQuickAccessMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); // Add menu item to quick access toolbar addMenuToQuickAccessMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(AddToQuickAccessCommand)); RibbonContextMenu.Items.Add(AddMenuToQuickAccessMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, AddMenuToQuickAccessMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuAddMenu), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, AddMenuToQuickAccessMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); // Add gallery to quick access toolbar addGalleryToQuickAccessMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(AddToQuickAccessCommand)); RibbonContextMenu.Items.Add(AddGalleryToQuickAccessMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, AddGalleryToQuickAccessMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuAddGallery), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, AddGalleryToQuickAccessMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); // Remove from quick access toolbar removeFromQuickAccessMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(RemoveFromQuickAccessCommand)); RibbonContextMenu.Items.Add(RemoveFromQuickAccessMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, RemoveFromQuickAccessMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuRemoveItem), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, RemoveFromQuickAccessMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); // Separator firstSeparatorDictionary.Add(Thread.CurrentThread.ManagedThreadId, new Separator()); RibbonContextMenu.Items.Add(FirstSeparator); // Customize quick access toolbar customizeQuickAccessToolbarMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(CustomizeQuickAccessToolbarCommand)); RibbonContextMenu.Items.Add(CustomizeQuickAccessToolbarMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, CustomizeQuickAccessToolbarMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuCustomizeQuickAccessToolBar), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, CustomizeQuickAccessToolbarMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); // Show quick access below the ribbon showQuickAccessToolbarBelowTheRibbonMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(ShowQuickAccessBelowCommand)); RibbonContextMenu.Items.Add(ShowQuickAccessToolbarBelowTheRibbonMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, ShowQuickAccessToolbarBelowTheRibbonMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuShowBelow), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, ShowQuickAccessToolbarBelowTheRibbonMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); // Show quick access above the ribbon showQuickAccessToolbarAboveTheRibbonMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(ShowQuickAccessAboveCommand)); RibbonContextMenu.Items.Add(ShowQuickAccessToolbarAboveTheRibbonMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, ShowQuickAccessToolbarAboveTheRibbonMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuShowAbove), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, ShowQuickAccessToolbarAboveTheRibbonMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); // Separator secondSeparatorDictionary.Add(Thread.CurrentThread.ManagedThreadId, new Separator()); RibbonContextMenu.Items.Add(SecondSeparator); // Customize the ribbon customizeTheRibbonMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(CustomizeTheRibbonCommand)); RibbonContextMenu.Items.Add(CustomizeTheRibbonMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, CustomizeTheRibbonMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuCustomizeRibbon), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, CustomizeTheRibbonMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); // Minimize the ribbon minimizeTheRibbonMenuItemDictionary.Add(Thread.CurrentThread.ManagedThreadId, CreateMenuItemForContextMenu(ToggleMinimizeTheRibbonCommand)); RibbonContextMenu.Items.Add(MinimizeTheRibbonMenuItem); RibbonControl.Bind(RibbonLocalization.Current.Localization, MinimizeTheRibbonMenuItem, nameof(RibbonLocalizationBase.RibbonContextMenuMinimizeRibbon), HeaderedItemsControl.HeaderProperty, BindingMode.OneWay); RibbonControl.Bind(RibbonContextMenu, MinimizeTheRibbonMenuItem, nameof(System.Windows.Controls.ContextMenu.PlacementTarget), System.Windows.Controls.MenuItem.CommandParameterProperty, BindingMode.OneWay); } private static MenuItem CreateMenuItemForContextMenu(ICommand command) { return new MenuItem { Command = command, CanAddToQuickAccessToolBar = false, ContextMenu = null }; } /// <inheritdoc /> protected override void OnContextMenuOpening(ContextMenuEventArgs e) { contextMenuOwner = this; base.OnContextMenuOpening(e); } /// <inheritdoc /> protected override void OnContextMenuClosing(ContextMenuEventArgs e) { contextMenuOwner = null; base.OnContextMenuClosing(e); } private void OnQuickAccessContextMenuOpening(object sender, ContextMenuEventArgs e) { this.OnContextMenuOpening(e); } private void OnQuickAccessContextMenuClosing(object sender, ContextMenuEventArgs e) { this.OnContextMenuClosing(e); } // Occurs when context menu is opening private static void OnContextMenuOpened(object sender, RoutedEventArgs e) { var ribbon = contextMenuOwner; if (RibbonContextMenu is null || ribbon is null) { return; } if (ribbon.IsDefaultContextMenuEnabled && RibbonContextMenu.Items.Count == 0) { InitRibbonContextMenuItems(); } if (ribbon.IsDefaultContextMenuEnabled == false) { foreach (UIElement item in RibbonContextMenu.Items) { item.Visibility = Visibility.Collapsed; } RibbonContextMenu.IsOpen = false; return; } AddToQuickAccessMenuItem.CommandTarget = ribbon; AddGroupToQuickAccessMenuItem.CommandTarget = ribbon; AddMenuToQuickAccessMenuItem.CommandTarget = ribbon; AddGalleryToQuickAccessMenuItem.CommandTarget = ribbon; RemoveFromQuickAccessMenuItem.CommandTarget = ribbon; CustomizeQuickAccessToolbarMenuItem.CommandTarget = ribbon; CustomizeTheRibbonMenuItem.CommandTarget = ribbon; MinimizeTheRibbonMenuItem.CommandTarget = ribbon; ShowQuickAccessToolbarBelowTheRibbonMenuItem.CommandTarget = ribbon; ShowQuickAccessToolbarAboveTheRibbonMenuItem.CommandTarget = ribbon; // Hide items for ribbon controls AddToQuickAccessMenuItem.Visibility = Visibility.Collapsed; AddGroupToQuickAccessMenuItem.Visibility = Visibility.Collapsed; AddMenuToQuickAccessMenuItem.Visibility = Visibility.Collapsed; AddGalleryToQuickAccessMenuItem.Visibility = Visibility.Collapsed; RemoveFromQuickAccessMenuItem.Visibility = Visibility.Collapsed; FirstSeparator.Visibility = Visibility.Collapsed; // Hide customize quick access menu item CustomizeQuickAccessToolbarMenuItem.Visibility = Visibility.Collapsed; SecondSeparator.Visibility = Visibility.Collapsed; // Set minimize the ribbon menu item state MinimizeTheRibbonMenuItem.IsChecked = ribbon.IsMinimized; // Set minimize the ribbon menu item visibility MinimizeTheRibbonMenuItem.Visibility = ribbon.CanMinimize ? Visibility.Visible : Visibility.Collapsed; // Set customize the ribbon menu item visibility CustomizeTheRibbonMenuItem.Visibility = ribbon.CanCustomizeRibbon ? Visibility.Visible : Visibility.Collapsed; // Hide quick access position menu items ShowQuickAccessToolbarBelowTheRibbonMenuItem.Visibility = Visibility.Collapsed; ShowQuickAccessToolbarAboveTheRibbonMenuItem.Visibility = Visibility.Collapsed; // If quick access toolbar is visible show if (ribbon.IsQuickAccessToolBarVisible) { // Set quick access position menu items visibility if (ribbon.CanQuickAccessLocationChanging) { if (ribbon.ShowQuickAccessToolBarAboveRibbon) { ShowQuickAccessToolbarBelowTheRibbonMenuItem.Visibility = Visibility.Visible; } else { ShowQuickAccessToolbarAboveTheRibbonMenuItem.Visibility = Visibility.Visible; } } if (ribbon.CanCustomizeQuickAccessToolBar) { CustomizeQuickAccessToolbarMenuItem.Visibility = Visibility.Visible; } if (ribbon.CanQuickAccessLocationChanging || ribbon.CanCustomizeQuickAccessToolBar) { SecondSeparator.Visibility = Visibility.Visible; } else { SecondSeparator.Visibility = Visibility.Collapsed; } if (ribbon.CanCustomizeQuickAccessToolBarItems) { // Gets control that raise menu opened var control = RibbonContextMenu.PlacementTarget; AddToQuickAccessCommand.CanExecute(null, control); RemoveFromQuickAccessCommand.CanExecute(null, control); //Debug.WriteLine("Menu opened on "+control); if (control != null) { FirstSeparator.Visibility = Visibility.Visible; // Check for value because remove is only possible in the context menu of items in QA which represent the value for QA-items if (ribbon.QuickAccessElements.ContainsValue(control)) { // Control is on quick access RemoveFromQuickAccessMenuItem.Visibility = Visibility.Visible; } else if (control is System.Windows.Controls.MenuItem) { // Control is menu item AddMenuToQuickAccessMenuItem.Visibility = Visibility.Visible; } else if (control is Gallery || control is InRibbonGallery) { // Control is gallery AddGalleryToQuickAccessMenuItem.Visibility = Visibility.Visible; } else if (control is RibbonGroupBox) { // Control is group box AddGroupToQuickAccessMenuItem.Visibility = Visibility.Visible; } else if (control is IQuickAccessItemProvider) { // Its other control AddToQuickAccessMenuItem.Visibility = Visibility.Visible; } else { FirstSeparator.Visibility = Visibility.Collapsed; } } } } // We have to close the context menu if no items are visible if (RibbonContextMenu.Items.OfType<System.Windows.Controls.MenuItem>().All(x => x.Visibility == Visibility.Collapsed)) { RibbonContextMenu.IsOpen = false; } } #endregion #region Events /// <summary> /// Occurs when selected tab has been changed (be aware that SelectedTab can be null) /// </summary> public event SelectionChangedEventHandler SelectedTabChanged; /// <summary> /// Occurs when customize the ribbon /// </summary> public event EventHandler CustomizeTheRibbon; /// <summary> /// Occurs when customize quick access toolbar /// </summary> public event EventHandler CustomizeQuickAccessToolbar; /// <summary> /// Occurs when IsMinimized property is changing /// </summary> public event DependencyPropertyChangedEventHandler IsMinimizedChanged; /// <summary> /// Occurs when IsCollapsed property is changing /// </summary> public event DependencyPropertyChangedEventHandler IsCollapsedChanged; #endregion #region Fields private ObservableCollection<Key> keyTipKeys; // Collection of contextual tab groups private ObservableCollection<RibbonContextualTabGroup> contextualGroups; // Collection of tabs private ObservableCollection<RibbonTabItem> tabs; private CollectionSyncHelper<RibbonTabItem> tabsSync; // Collection of toolbar items private ObservableCollection<UIElement> toolBarItems; private CollectionSyncHelper<UIElement> toolBarItemsSync; // Ribbon quick access toolbar // Ribbon layout root private Panel layoutRoot; // Handles F10, Alt and so on private readonly KeyTipService keyTipService; // Collection of quickaccess menu items private ObservableCollection<QuickAccessMenuItem> quickAccessItems; private CollectionSyncHelper<QuickAccessMenuItem> quickAccessItemsSync; // Currently added in QAT items private Window ownerWindow; #endregion #region Properties #region Menu /// <summary> /// Gets or sets file menu control (can be application menu button, backstage button and so on) /// </summary> public FrameworkElement Menu { get { return (FrameworkElement)this.GetValue(MenuProperty); } set { this.SetValue(MenuProperty, value); } } /// <summary>Identifies the <see cref="Menu"/> dependency property.</summary> public static readonly DependencyProperty MenuProperty = DependencyProperty.Register(nameof(Menu), typeof(FrameworkElement), typeof(Ribbon), new FrameworkPropertyMetadata(default(FrameworkElement), FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure, OnMenuChanged)); private static void OnMenuChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AddOrRemoveLogicalChildOnPropertyChanged(d, e); } #endregion #region StartScreen /// <summary> /// Property for defining the start screen. /// </summary> public StartScreen StartScreen { get { return (StartScreen)this.GetValue(StartScreenProperty); } set { this.SetValue(StartScreenProperty, value); } } /// <summary>Identifies the <see cref="StartScreen"/> dependency property.</summary> public static readonly DependencyProperty StartScreenProperty = DependencyProperty.Register(nameof(StartScreen), typeof(StartScreen), typeof(Ribbon), new FrameworkPropertyMetadata(default(StartScreen), FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure, OnStartScreenChanged)); private static void OnStartScreenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AddOrRemoveLogicalChildOnPropertyChanged(d, e); } #endregion #region QuickAccessToolBar /// <summary> /// Property for defining the QuickAccessToolBar. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public QuickAccessToolBar QuickAccessToolBar { get { return (QuickAccessToolBar)this.GetValue(QuickAccessToolBarProperty); } private set { this.SetValue(QuickAccessToolBarPropertyKey, value); } } // ReSharper disable once InconsistentNaming private static readonly DependencyPropertyKey QuickAccessToolBarPropertyKey = DependencyProperty.RegisterReadOnly(nameof(QuickAccessToolBar), typeof(QuickAccessToolBar), typeof(Ribbon), new FrameworkPropertyMetadata(default(QuickAccessToolBar), FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure, OnQuickAccessToolBarChanged)); private static void OnQuickAccessToolBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AddOrRemoveLogicalChildOnPropertyChanged(d, e); } /// <summary>Identifies the <see cref="QuickAccessToolBar"/> dependency property.</summary> public static readonly DependencyProperty QuickAccessToolBarProperty = QuickAccessToolBarPropertyKey.DependencyProperty; #endregion #region TabControl /// <summary> /// Property for defining the TabControl. /// </summary> [CanBeNull] [EditorBrowsable(EditorBrowsableState.Never)] public RibbonTabControl TabControl { get { return (RibbonTabControl)this.GetValue(TabControlProperty); } private set { this.SetValue(TabControlPropertyKey, value); } } // ReSharper disable once InconsistentNaming private static readonly DependencyPropertyKey TabControlPropertyKey = DependencyProperty.RegisterReadOnly(nameof(TabControl), typeof(RibbonTabControl), typeof(Ribbon), new FrameworkPropertyMetadata(default(RibbonTabControl), FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure, LogicalChildSupportHelper.OnLogicalChildPropertyChanged)); /// <summary>Identifies the <see cref="TabControl"/> dependency property.</summary> public static readonly DependencyProperty TabControlProperty = TabControlPropertyKey.DependencyProperty; #endregion /// <summary> /// Gets or sets selected tab item /// </summary> public RibbonTabItem SelectedTabItem { get { return (RibbonTabItem)this.GetValue(SelectedTabItemProperty); } set { this.SetValue(SelectedTabItemProperty, value); } } /// <summary>Identifies the <see cref="SelectedTabItem"/> dependency property.</summary> public static readonly DependencyProperty SelectedTabItemProperty = DependencyProperty.Register(nameof(SelectedTabItem), typeof(RibbonTabItem), typeof(Ribbon), new PropertyMetadata(OnSelectedTabItemChanged)); private static void OnSelectedTabItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = (Ribbon)d; if (ribbon.TabControl != null) { ribbon.TabControl.SelectedItem = e.NewValue; } if (e.NewValue is RibbonTabItem selectedItem && ribbon.Tabs.Contains(selectedItem)) { ribbon.SelectedTabIndex = ribbon.Tabs.IndexOf(selectedItem); } else { ribbon.SelectedTabIndex = -1; } } /// <summary> /// Gets or sets selected tab index /// </summary> public int SelectedTabIndex { get { return (int)this.GetValue(SelectedTabIndexProperty); } set { this.SetValue(SelectedTabIndexProperty, value); } } /// <summary>Identifies the <see cref="SelectedTabIndex"/> dependency property.</summary> public static readonly DependencyProperty SelectedTabIndexProperty = DependencyProperty.Register(nameof(SelectedTabIndex), typeof(int), typeof(Ribbon), new PropertyMetadata(-1, OnSelectedTabIndexChanged)); private static void OnSelectedTabIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = (Ribbon)d; var selectedIndex = (int)e.NewValue; if (ribbon.TabControl != null) { ribbon.TabControl.SelectedIndex = selectedIndex; } if (selectedIndex >= 0 && selectedIndex < ribbon.Tabs.Count) { ribbon.SelectedTabItem = ribbon.Tabs[selectedIndex]; } else { ribbon.SelectedTabItem = null; } } private static void AddOrRemoveLogicalChildOnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = (Ribbon)d; if (e.OldValue != null) { ribbon.RemoveLogicalChild(e.OldValue); } if (e.NewValue != null) { ribbon.AddLogicalChild(e.NewValue); } } /// <summary> /// Gets the first visible TabItem /// </summary> public RibbonTabItem FirstVisibleItem => this.GetFirstVisibleItem(); /// <summary> /// Gets the last visible TabItem /// </summary> public RibbonTabItem LastVisibleItem => this.GetLastVisibleItem(); /// <summary> /// Gets currently active quick access elements. /// </summary> protected Dictionary<UIElement, UIElement> QuickAccessElements { get; } = new Dictionary<UIElement, UIElement>(); /// <summary> /// Gets a copy of currently active quick access elements. /// </summary> public IDictionary<UIElement, UIElement> GetQuickAccessElements() => this.QuickAccessElements.ToDictionary(x => x.Key, y => y.Value); #region TitelBar /// <summary> /// Gets ribbon titlebar /// </summary> public RibbonTitleBar TitleBar { get { return (RibbonTitleBar)this.GetValue(TitleBarProperty); } set { this.SetValue(TitleBarProperty, value); } } /// <summary>Identifies the <see cref="TitleBar"/> dependency property.</summary> public static readonly DependencyProperty TitleBarProperty = DependencyProperty.Register(nameof(TitleBar), typeof(RibbonTitleBar), typeof(Ribbon), new PropertyMetadata(OnTitleBarChanged)); private static void OnTitleBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = (Ribbon)d; if (e.OldValue is RibbonTitleBar oldValue) { oldValue.ItemsSource = null; ribbon.RemoveQuickAccessToolBarFromTitleBar(oldValue); } if (e.NewValue is RibbonTitleBar newValue) { newValue.ItemsSource = ribbon.ContextualGroups; if (ribbon.ShowQuickAccessToolBarAboveRibbon) { ribbon.MoveQuickAccessToolBarToTitleBar(newValue); } } } #endregion /// <summary> /// Gets or sets whether quick access toolbar showes above ribbon /// </summary> public bool ShowQuickAccessToolBarAboveRibbon { get { return (bool)this.GetValue(ShowQuickAccessToolBarAboveRibbonProperty); } set { this.SetValue(ShowQuickAccessToolBarAboveRibbonProperty, value); } } /// <summary>Identifies the <see cref="ShowQuickAccessToolBarAboveRibbon"/> dependency property.</summary> public static readonly DependencyProperty ShowQuickAccessToolBarAboveRibbonProperty = DependencyProperty.Register(nameof(ShowQuickAccessToolBarAboveRibbon), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox, OnShowQuickAccessToolBarAboveRibbonChanged)); /// <summary> /// Handles ShowQuickAccessToolBarAboveRibbon property changed /// </summary> /// <param name="d">Object</param> /// <param name="e">The event data</param> private static void OnShowQuickAccessToolBarAboveRibbonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = (Ribbon)d; if (ribbon.TitleBar != null) { if ((bool)e.NewValue) { ribbon.MoveQuickAccessToolBarToTitleBar(ribbon.TitleBar); } else { ribbon.RemoveQuickAccessToolBarFromTitleBar(ribbon.TitleBar); } ribbon.TitleBar.InvalidateMeasure(); } ribbon.RibbonStateStorage.SaveTemporary(); } /// <summary> /// Gets or sets the height which is used to render the window title. /// </summary> public double QuickAccessToolBarHeight { get { return (double)this.GetValue(QuickAccessToolBarHeightProperty); } set { this.SetValue(QuickAccessToolBarHeightProperty, value); } } /// <summary>Identifies the <see cref="QuickAccessToolBarHeight"/> dependency property.</summary> public static readonly DependencyProperty QuickAccessToolBarHeightProperty = DependencyProperty.Register(nameof(QuickAccessToolBarHeight), typeof(double), typeof(Ribbon), new PropertyMetadata(23D)); /// <summary> /// Gets collection of contextual tab groups /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ObservableCollection<RibbonContextualTabGroup> ContextualGroups => this.contextualGroups ??= new ObservableCollection<RibbonContextualTabGroup>(); /// <summary> /// gets collection of ribbon tabs /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ObservableCollection<RibbonTabItem> Tabs => this.tabs ??= new ObservableCollection<RibbonTabItem>(); /// <summary> /// Gets collection of toolbar items /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ObservableCollection<UIElement> ToolBarItems => this.toolBarItems ??= new ObservableCollection<UIElement>(); /// <summary> /// Gets collection of quick access menu items /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ObservableCollection<QuickAccessMenuItem> QuickAccessItems { get { if (this.quickAccessItems is null) { this.quickAccessItems = new ObservableCollection<QuickAccessMenuItem>(); this.quickAccessItems.CollectionChanged += this.OnQuickAccessItemsCollectionChanged; } return this.quickAccessItems; } } /// <summary> /// Handles collection of quick access menu items changes /// </summary> /// <param name="sender">Sender</param> /// <param name="e">The event data</param> private void OnQuickAccessItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (var item in e.NewItems.OfType<QuickAccessMenuItem>()) { item.Ribbon = this; } break; case NotifyCollectionChangedAction.Remove: foreach (var item in e.OldItems.OfType<QuickAccessMenuItem>()) { item.Ribbon = null; } break; case NotifyCollectionChangedAction.Replace: foreach (var item in e.OldItems.OfType<QuickAccessMenuItem>()) { item.Ribbon = null; } foreach (var item in e.NewItems.OfType<QuickAccessMenuItem>()) { item.Ribbon = this; } break; } } /// <summary> /// Gets or sets whether Customize Quick Access Toolbar menu item is shown /// </summary> public bool CanCustomizeQuickAccessToolBar { get { return (bool)this.GetValue(CanCustomizeQuickAccessToolBarProperty); } set { this.SetValue(CanCustomizeQuickAccessToolBarProperty, value); } } /// <summary>Identifies the <see cref="CanCustomizeQuickAccessToolBar"/> dependency property.</summary> public static readonly DependencyProperty CanCustomizeQuickAccessToolBarProperty = DependencyProperty.Register(nameof(CanCustomizeQuickAccessToolBar), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets whether items can be added or removed from the quick access toolbar by users. /// </summary> public bool CanCustomizeQuickAccessToolBarItems { get { return (bool)this.GetValue(CanCustomizeQuickAccessToolBarItemsProperty); } set { this.SetValue(CanCustomizeQuickAccessToolBarItemsProperty, value); } } /// <summary>Identifies the <see cref="CanCustomizeQuickAccessToolBarItems"/> dependency property.</summary> public static readonly DependencyProperty CanCustomizeQuickAccessToolBarItemsProperty = DependencyProperty.Register(nameof(CanCustomizeQuickAccessToolBarItems), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets whether the QAT Menu-DropDown is visible or not. /// </summary> public bool IsQuickAccessToolBarMenuDropDownVisible { get { return (bool)this.GetValue(IsQuickAccessToolBarMenuDropDownVisibleProperty); } set { this.SetValue(IsQuickAccessToolBarMenuDropDownVisibleProperty, value); } } /// <summary>Identifies the <see cref="IsQuickAccessToolBarMenuDropDownVisible"/> dependency property.</summary> public static readonly DependencyProperty IsQuickAccessToolBarMenuDropDownVisibleProperty = DependencyProperty.Register(nameof(IsQuickAccessToolBarMenuDropDownVisible), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets whether Customize Ribbon menu item is shown /// </summary> public bool CanCustomizeRibbon { get { return (bool)this.GetValue(CanCustomizeRibbonProperty); } set { this.SetValue(CanCustomizeRibbonProperty, value); } } /// <summary>Identifies the <see cref="CanCustomizeRibbon"/> dependency property.</summary> public static readonly DependencyProperty CanCustomizeRibbonProperty = DependencyProperty.Register(nameof(CanCustomizeRibbon), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets whether ribbon can be minimized /// </summary> public bool CanMinimize { get { return (bool)this.GetValue(CanMinimizeProperty); } set { this.SetValue(CanMinimizeProperty, value); } } /// <summary> /// Gets or sets whether ribbon is minimized /// </summary> public bool IsMinimized { get { return (bool)this.GetValue(IsMinimizedProperty); } set { this.SetValue(IsMinimizedProperty, value); } } /// <summary>Identifies the <see cref="IsMinimized"/> dependency property.</summary> public static readonly DependencyProperty IsMinimizedProperty = DependencyProperty.Register(nameof(IsMinimized), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.FalseBox, OnIsMinimizedChanged)); /// <summary>Identifies the <see cref="CanMinimize"/> dependency property.</summary> public static readonly DependencyProperty CanMinimizeProperty = DependencyProperty.Register(nameof(CanMinimize), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); private static void OnIsMinimizedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = (Ribbon)d; var oldValue = (bool)e.OldValue; var newValue = (bool)e.NewValue; ribbon.IsMinimizedChanged?.Invoke(ribbon, e); // Invert values of arguments for RaiseExpandCollapseAutomationEvent because IsMinimized means the negative for expand/collapsed (UIElementAutomationPeer.FromElement(ribbon) as Fluent.Automation.Peers.RibbonAutomationPeer)?.RaiseExpandCollapseAutomationEvent(!oldValue, !newValue); } /// <summary> /// Gets or sets the height of the gap between the ribbon and the regular window content /// </summary> public double ContentGapHeight { get { return (double)this.GetValue(ContentGapHeightProperty); } set { this.SetValue(ContentGapHeightProperty, value); } } /// <summary>Identifies the <see cref="ContentGapHeight"/> dependency property.</summary> public static readonly DependencyProperty ContentGapHeightProperty = DependencyProperty.Register(nameof(ContentGapHeight), typeof(double), typeof(Ribbon), new PropertyMetadata(RibbonTabControl.DefaultContentGapHeight)); /// <summary> /// Gets or sets the height of the ribbon content area /// </summary> public double ContentHeight { get { return (double)this.GetValue(ContentHeightProperty); } set { this.SetValue(ContentHeightProperty, value); } } /// <summary>Identifies the <see cref="ContentHeight"/> dependency property.</summary> public static readonly DependencyProperty ContentHeightProperty = DependencyProperty.Register(nameof(ContentHeight), typeof(double), typeof(Ribbon), new PropertyMetadata(RibbonTabControl.DefaultContentHeight)); // todo check if IsCollapsed and IsAutomaticCollapseEnabled should be reduced to one shared property for RibbonWindow and Ribbon /// <summary> /// Gets whether ribbon is collapsed /// </summary> public bool IsCollapsed { get { return (bool)this.GetValue(IsCollapsedProperty); } set { this.SetValue(IsCollapsedProperty, value); } } /// <summary>Identifies the <see cref="IsCollapsed"/> dependency property.</summary> public static readonly DependencyProperty IsCollapsedProperty = DependencyProperty.Register(nameof(IsCollapsed), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.FalseBox, OnIsCollapsedChanged)); private static void OnIsCollapsedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = (Ribbon)d; ribbon.IsCollapsedChanged?.Invoke(ribbon, e); } /// <summary> /// Defines if the Ribbon should automatically set <see cref="IsCollapsed"/> when the width or height of the owner window drop under <see cref="MinimalVisibleWidth"/> or <see cref="MinimalVisibleHeight"/> /// </summary> public bool IsAutomaticCollapseEnabled { get { return (bool)this.GetValue(IsAutomaticCollapseEnabledProperty); } set { this.SetValue(IsAutomaticCollapseEnabledProperty, value); } } /// <summary>Identifies the <see cref="IsAutomaticCollapseEnabled"/> dependency property.</summary> public static readonly DependencyProperty IsAutomaticCollapseEnabledProperty = DependencyProperty.Register(nameof(IsAutomaticCollapseEnabled), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets whether QAT is visible /// </summary> public bool IsQuickAccessToolBarVisible { get { return (bool)this.GetValue(IsQuickAccessToolBarVisibleProperty); } set { this.SetValue(IsQuickAccessToolBarVisibleProperty, value); } } /// <summary>Identifies the <see cref="IsQuickAccessToolBarVisible"/> dependency property.</summary> public static readonly DependencyProperty IsQuickAccessToolBarVisibleProperty = DependencyProperty.Register(nameof(IsQuickAccessToolBarVisible), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets whether user can change location of QAT /// </summary> public bool CanQuickAccessLocationChanging { get { return (bool)this.GetValue(CanQuickAccessLocationChangingProperty); } set { this.SetValue(CanQuickAccessLocationChangingProperty, value); } } /// <summary>Identifies the <see cref="CanQuickAccessLocationChanging"/> dependency property.</summary> public static readonly DependencyProperty CanQuickAccessLocationChangingProperty = DependencyProperty.Register(nameof(CanQuickAccessLocationChanging), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary>Identifies the <see cref="AreTabHeadersVisible"/> dependency property.</summary> public static readonly DependencyProperty AreTabHeadersVisibleProperty = DependencyProperty.Register(nameof(AreTabHeadersVisible), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Defines whether tab headers are visible or not. /// </summary> public bool AreTabHeadersVisible { get { return (bool)this.GetValue(AreTabHeadersVisibleProperty); } set { this.SetValue(AreTabHeadersVisibleProperty, value); } } /// <summary>Identifies the <see cref="IsToolBarVisible"/> dependency property.</summary> public static readonly DependencyProperty IsToolBarVisibleProperty = DependencyProperty.Register(nameof(IsToolBarVisible), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Defines whether tab headers are visible or not. /// </summary> public bool IsToolBarVisible { get { return (bool)this.GetValue(IsToolBarVisibleProperty); } set { this.SetValue(IsToolBarVisibleProperty, value); } } /// <summary>Identifies the <see cref="IsMouseWheelScrollingEnabled"/> dependency property.</summary> public static readonly DependencyProperty IsMouseWheelScrollingEnabledProperty = DependencyProperty.Register(nameof(IsMouseWheelScrollingEnabled), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Defines whether scrolling by mouse wheel is enabled or not. /// </summary> public bool IsMouseWheelScrollingEnabled { get { return (bool)this.GetValue(IsMouseWheelScrollingEnabledProperty); } set { this.SetValue(IsMouseWheelScrollingEnabledProperty, value); } } /// <summary> /// Checks if any keytips are visible. /// </summary> public bool AreAnyKeyTipsVisible => this.keyTipService?.AreAnyKeyTipsVisible == true; /// <summary>Identifies the <see cref="IsKeyTipHandlingEnabled"/> dependency property.</summary> public static readonly DependencyProperty IsKeyTipHandlingEnabledProperty = DependencyProperty.Register(nameof(IsKeyTipHandlingEnabled), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox, OnIsKeyTipHandlingEnabledChanged)); /// <summary> /// Defines whether handling of key tips is enabled or not. /// </summary> public bool IsKeyTipHandlingEnabled { get { return (bool)this.GetValue(IsKeyTipHandlingEnabledProperty); } set { this.SetValue(IsKeyTipHandlingEnabledProperty, value); } } private static void OnIsKeyTipHandlingEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = (Ribbon)d; if ((bool)e.NewValue) { ribbon.keyTipService?.Attach(); } else { ribbon.keyTipService?.Detach(); } } /// <summary> /// Defines the keys that are used to activate the key tips. /// </summary> public ObservableCollection<Key> KeyTipKeys { get { if (this.keyTipKeys is null) { this.keyTipKeys = new ObservableCollection<Key>(); this.keyTipKeys.CollectionChanged += this.HandleKeyTipKeys_CollectionChanged; } return this.keyTipKeys; } } private void HandleKeyTipKeys_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { this.keyTipService.KeyTipKeys.Clear(); foreach (var keyTipKey in this.KeyTipKeys) { this.keyTipService.KeyTipKeys.Add(keyTipKey); } } #endregion #region Commands /// <summary> /// Gets add to quick access toolbar command /// </summary> public static readonly RoutedCommand AddToQuickAccessCommand = new RoutedCommand(nameof(AddToQuickAccessCommand), typeof(Ribbon)); /// <summary> /// Gets remove from quick access command /// </summary> public static readonly RoutedCommand RemoveFromQuickAccessCommand = new RoutedCommand(nameof(RemoveFromQuickAccessCommand), typeof(Ribbon)); /// <summary> /// Gets show quick access above command /// </summary> public static readonly RoutedCommand ShowQuickAccessAboveCommand = new RoutedCommand(nameof(ShowQuickAccessAboveCommand), typeof(Ribbon)); /// <summary> /// Gets show quick access below command /// </summary> public static readonly RoutedCommand ShowQuickAccessBelowCommand = new RoutedCommand(nameof(ShowQuickAccessBelowCommand), typeof(Ribbon)); /// <summary> /// Gets toggle ribbon minimize command /// </summary> public static readonly RoutedCommand ToggleMinimizeTheRibbonCommand = new RoutedCommand(nameof(ToggleMinimizeTheRibbonCommand), typeof(Ribbon)); /// <summary> /// Gets customize quick access toolbar command /// </summary> public static readonly RoutedCommand CustomizeQuickAccessToolbarCommand = new RoutedCommand(nameof(CustomizeQuickAccessToolbarCommand), typeof(Ribbon)); /// <summary> /// Gets customize the ribbon command /// </summary> public static readonly RoutedCommand CustomizeTheRibbonCommand = new RoutedCommand(nameof(CustomizeTheRibbonCommand), typeof(Ribbon)); // Occurs when customize toggle minimize command can execute handles private static void OnToggleMinimizeTheRibbonCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { if (sender is Ribbon ribbon) { e.CanExecute = ribbon.CanMinimize; } } // Occurs when toggle minimize command executed private static void OnToggleMinimizeTheRibbonCommandExecuted(object sender, ExecutedRoutedEventArgs e) { if (sender is Ribbon ribbon) { ribbon.IsMinimized = !ribbon.IsMinimized; } } // Occurs when show quick access below command executed private static void OnShowQuickAccessBelowCommandExecuted(object sender, ExecutedRoutedEventArgs e) { var ribbon = sender as Ribbon; if (ribbon is null) { return; } ribbon.ShowQuickAccessToolBarAboveRibbon = false; } // Occurs when show quick access above command executed private static void OnShowQuickAccessAboveCommandExecuted(object sender, ExecutedRoutedEventArgs e) { var ribbon = sender as Ribbon; if (ribbon is null) { return; } ribbon.ShowQuickAccessToolBarAboveRibbon = true; } // Occurs when remove from quick access command executed private static void OnRemoveFromQuickAccessCommandExecuted(object sender, ExecutedRoutedEventArgs e) { var ribbon = sender as Ribbon; if (ribbon?.QuickAccessToolBar != null) { var element = ribbon.QuickAccessElements.First(x => ReferenceEquals(x.Value, e.Parameter)).Key; ribbon.RemoveFromQuickAccessToolBar(element); } } // Occurs when add to quick access command executed private static void OnAddToQuickAccessCommandExecuted(object sender, ExecutedRoutedEventArgs e) { var ribbon = sender as Ribbon; if (ribbon?.QuickAccessToolBar != null) { ribbon.AddToQuickAccessToolBar(e.Parameter as UIElement); } } // Occurs when customize quick access command executed private static void OnCustomizeQuickAccessToolbarCommandExecuted(object sender, ExecutedRoutedEventArgs e) { var ribbon = sender as Ribbon; ribbon?.CustomizeQuickAccessToolbar?.Invoke(sender, EventArgs.Empty); } // Occurs when customize the ribbon command executed private static void OnCustomizeTheRibbonCommandExecuted(object sender, ExecutedRoutedEventArgs e) { var ribbon = sender as Ribbon; ribbon?.CustomizeTheRibbon?.Invoke(sender, EventArgs.Empty); } // Occurs when customize quick access command can execute handles private static void OnCustomizeQuickAccessToolbarCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { var ribbon = sender as Ribbon; if (ribbon is null) { return; } e.CanExecute = ribbon.CanCustomizeQuickAccessToolBar; } // Occurs when customize the ribbon command can execute handles private static void OnCustomizeTheRibbonCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { var ribbon = sender as Ribbon; if (ribbon is null) { return; } e.CanExecute = ribbon.CanCustomizeRibbon; } // Occurs when remove from quick access command can execute handles private static void OnRemoveFromQuickAccessCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { if (sender is Ribbon ribbon && ribbon.IsQuickAccessToolBarVisible) { e.CanExecute = ribbon.QuickAccessElements.ContainsValue(e.Parameter as UIElement); } else { e.CanExecute = false; } } // Occurs when add to quick access command can execute handles private static void OnAddToQuickAccessCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { if (sender is Ribbon ribbon && ribbon.IsQuickAccessToolBarVisible && QuickAccessItemsProvider.IsSupported(e.Parameter as UIElement) && ribbon.IsInQuickAccessToolBar(e.Parameter as UIElement) == false) { if (e.Parameter is Gallery gallery) { e.CanExecute = ribbon.IsInQuickAccessToolBar(FindParentRibbonControl(gallery) as UIElement) == false; } else { e.CanExecute = ribbon.IsInQuickAccessToolBar(e.Parameter as UIElement) == false; } } else { e.CanExecute = false; } } #endregion #region Constructors /// <summary> /// Initializes static members of the <see cref="Ribbon"/> class. /// </summary> static Ribbon() { DefaultStyleKeyProperty.OverrideMetadata(typeof(Ribbon), new FrameworkPropertyMetadata(typeof(Ribbon))); // Subscribe to menu commands CommandManager.RegisterClassCommandBinding(typeof(Ribbon), new CommandBinding(AddToQuickAccessCommand, OnAddToQuickAccessCommandExecuted, OnAddToQuickAccessCommandCanExecute)); CommandManager.RegisterClassCommandBinding(typeof(Ribbon), new CommandBinding(RemoveFromQuickAccessCommand, OnRemoveFromQuickAccessCommandExecuted, OnRemoveFromQuickAccessCommandCanExecute)); CommandManager.RegisterClassCommandBinding(typeof(Ribbon), new CommandBinding(ShowQuickAccessAboveCommand, OnShowQuickAccessAboveCommandExecuted)); CommandManager.RegisterClassCommandBinding(typeof(Ribbon), new CommandBinding(ShowQuickAccessBelowCommand, OnShowQuickAccessBelowCommandExecuted)); CommandManager.RegisterClassCommandBinding(typeof(Ribbon), new CommandBinding(ToggleMinimizeTheRibbonCommand, OnToggleMinimizeTheRibbonCommandExecuted, OnToggleMinimizeTheRibbonCommandCanExecute)); CommandManager.RegisterClassCommandBinding(typeof(Ribbon), new CommandBinding(CustomizeTheRibbonCommand, OnCustomizeTheRibbonCommandExecuted, OnCustomizeTheRibbonCommandCanExecute)); CommandManager.RegisterClassCommandBinding(typeof(Ribbon), new CommandBinding(CustomizeQuickAccessToolbarCommand, OnCustomizeQuickAccessToolbarCommandExecuted, OnCustomizeQuickAccessToolbarCommandCanExecute)); } /// <summary> /// Default constructor /// </summary> public Ribbon() { this.VerticalAlignment = VerticalAlignment.Top; KeyboardNavigation.SetDirectionalNavigation(this, KeyboardNavigationMode.Contained); WindowChrome.SetIsHitTestVisibleInChrome(this, true); this.keyTipService = new KeyTipService(this); this.Loaded += this.OnLoaded; this.Unloaded += this.OnUnloaded; } #endregion #region Overrides private void OnSizeChanged(object sender, SizeChangedEventArgs e) { this.MaintainIsCollapsed(); } private void MaintainIsCollapsed() { if (this.IsAutomaticCollapseEnabled == false || this.ownerWindow is null) { return; } if (this.ownerWindow.ActualWidth < MinimalVisibleWidth || this.ownerWindow.ActualHeight < MinimalVisibleHeight) { this.IsCollapsed = true; } else { this.IsCollapsed = false; } } /// <inheritdoc /> protected override void OnGotFocus(RoutedEventArgs e) { var ribbonTabItem = (RibbonTabItem)this.TabControl?.SelectedItem; ribbonTabItem?.Focus(); } /// <inheritdoc /> public override void OnApplyTemplate() { this.layoutRoot = this.GetTemplateChild("PART_LayoutRoot") as Panel; var selectedTab = this.SelectedTabItem; if (this.TabControl != null) { this.TabControl.SelectionChanged -= this.OnTabControlSelectionChanged; selectedTab = this.TabControl.SelectedItem as RibbonTabItem; this.tabsSync?.Target.Clear(); this.toolBarItemsSync?.Target.Clear(); } this.TabControl = this.GetTemplateChild("PART_RibbonTabControl") as RibbonTabControl; if (this.TabControl != null) { this.TabControl.SelectionChanged += this.OnTabControlSelectionChanged; this.tabsSync = new CollectionSyncHelper<RibbonTabItem>(this.Tabs, this.TabControl.Items); this.TabControl.SelectedItem = selectedTab; this.toolBarItemsSync = new CollectionSyncHelper<UIElement>(this.ToolBarItems, this.TabControl.ToolBarItems); } if (this.QuickAccessToolBar != null) { this.ClearQuickAccessToolBar(); this.quickAccessItemsSync?.Target.Clear(); } this.QuickAccessToolBar = this.GetTemplateChild("PART_QuickAccessToolBar") as QuickAccessToolBar; if (this.QuickAccessToolBar != null) { this.quickAccessItemsSync = new CollectionSyncHelper<QuickAccessMenuItem>(this.QuickAccessItems, this.QuickAccessToolBar.QuickAccessItems); { var binding = new Binding(nameof(this.CanQuickAccessLocationChanging)) { Source = this, Mode = BindingMode.OneWay }; this.QuickAccessToolBar.SetBinding(QuickAccessToolBar.CanQuickAccessLocationChangingProperty, binding); } } if (this.ShowQuickAccessToolBarAboveRibbon) { this.MoveQuickAccessToolBarToTitleBar(this.TitleBar); } } /// <inheritdoc /> protected override AutomationPeer OnCreateAutomationPeer() => new Fluent.Automation.Peers.RibbonAutomationPeer(this); private void MoveQuickAccessToolBarToTitleBar(RibbonTitleBar titleBar) { if (titleBar != null) { titleBar.QuickAccessToolBar = this.QuickAccessToolBar; } if (this.QuickAccessToolBar != null) { // Prevent double add for handler if this method is called multiple times this.QuickAccessToolBar.ContextMenuOpening -= this.OnQuickAccessContextMenuOpening; this.QuickAccessToolBar.ContextMenuClosing -= this.OnQuickAccessContextMenuClosing; this.QuickAccessToolBar.ContextMenuOpening += this.OnQuickAccessContextMenuOpening; this.QuickAccessToolBar.ContextMenuClosing += this.OnQuickAccessContextMenuClosing; } } private void RemoveQuickAccessToolBarFromTitleBar(RibbonTitleBar titleBar) { if (titleBar != null) { titleBar.QuickAccessToolBar = null; } if (this.QuickAccessToolBar != null) { this.QuickAccessToolBar.ContextMenuOpening -= this.OnQuickAccessContextMenuOpening; this.QuickAccessToolBar.ContextMenuClosing -= this.OnQuickAccessContextMenuClosing; } } /// <summary> /// Called when the <see cref="ownerWindow"/> is closed, so that we set it to null. /// </summary> private void OnOwnerWindowClosed(object sender, EventArgs e) { this.DetachFromWindow(); } private void AttachToWindow() { this.DetachFromWindow(); this.ownerWindow = Window.GetWindow(this); if (this.ownerWindow != null) { this.ownerWindow.Closed += this.OnOwnerWindowClosed; this.ownerWindow.SizeChanged += this.OnSizeChanged; this.ownerWindow.KeyDown += this.OnKeyDown; } } private void DetachFromWindow() { if (this.ownerWindow != null) { this.RibbonStateStorage.Save(); this.RibbonStateStorage.Dispose(); this.ribbonStateStorage = null; this.ownerWindow.Closed -= this.OnOwnerWindowClosed; this.ownerWindow.SizeChanged -= this.OnSizeChanged; this.ownerWindow.KeyDown -= this.OnKeyDown; } this.ownerWindow = null; } #endregion #region Quick Access Items Managment /// <summary> /// Determines whether the given element is in quick access toolbar /// </summary> /// <param name="element">Element</param> /// <returns>True if element in quick access toolbar</returns> public bool IsInQuickAccessToolBar(UIElement element) { if (element is null) { return false; } return this.QuickAccessElements.ContainsKey(element); } /// <summary> /// Adds the given element to quick access toolbar /// </summary> /// <param name="element">Element</param> public void AddToQuickAccessToolBar(UIElement element) { if (element is null) { return; } if (element is Gallery) { element = FindParentRibbonControl(element) as UIElement; } // Do not add menu items without icon. if (element is System.Windows.Controls.MenuItem menuItem && menuItem.Icon is null) { element = FindParentRibbonControl(element) as UIElement; } if (element is null) { return; } if (QuickAccessItemsProvider.IsSupported(element) == false) { return; } if (this.IsInQuickAccessToolBar(element) == false) { Debug.WriteLine($"Adding \"{element}\" to QuickAccessToolBar."); var control = QuickAccessItemsProvider.GetQuickAccessItem(element); this.QuickAccessElements.Add(element, control); this.QuickAccessToolBar.Items.Add(control); } } private static IRibbonControl FindParentRibbonControl(DependencyObject element) { var parent = LogicalTreeHelper.GetParent(element); while (parent != null) { if (parent is IRibbonControl control) { return control; } parent = LogicalTreeHelper.GetParent(parent); } return null; } /// <summary> /// Removes the given elements from quick access toolbar /// </summary> /// <param name="element">Element</param> public void RemoveFromQuickAccessToolBar(UIElement element) { Debug.WriteLine("Removing \"{0}\" from QuickAccessToolBar.", element); if (this.IsInQuickAccessToolBar(element)) { var quickAccessItem = this.QuickAccessElements[element]; this.QuickAccessElements.Remove(element); this.QuickAccessToolBar.Items.Remove(quickAccessItem); } } /// <summary> /// Clears quick access toolbar /// </summary> public void ClearQuickAccessToolBar() { this.QuickAccessElements.Clear(); this.QuickAccessToolBar?.Items.Clear(); } #endregion #region Event Handling // Handles tab control selection changed private void OnTabControlSelectionChanged(object sender, SelectionChangedEventArgs e) { if (ReferenceEquals(e.OriginalSource, this.TabControl) == false) { return; } this.SelectedTabItem = this.TabControl?.SelectedItem as RibbonTabItem; this.SelectedTabIndex = this.TabControl?.SelectedIndex ?? -1; this.SelectedTabChanged?.Invoke(this, e); } private void OnLoaded(object sender, RoutedEventArgs e) { this.keyTipService.Attach(); this.AttachToWindow(); this.LoadInitialState(); this.TitleBar?.ForceMeasureAndArrange(); } private void OnKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.F1 && Keyboard.Modifiers.HasFlag(ModifierKeys.Control)) { if (this.TabControl?.HasItems == true) { if (this.CanMinimize) { this.IsMinimized = !this.IsMinimized; } } } } private void OnUnloaded(object sender, RoutedEventArgs e) { this.RibbonStateStorage.Save(); this.keyTipService.Detach(); if (this.ownerWindow != null) { this.ownerWindow.SizeChanged -= this.OnSizeChanged; this.ownerWindow.KeyDown -= this.OnKeyDown; } } #endregion #region Private methods private RibbonTabItem GetFirstVisibleItem() { return this.Tabs.FirstOrDefault(item => item.Visibility == Visibility.Visible); } private RibbonTabItem GetLastVisibleItem() { return this.Tabs.LastOrDefault(item => item.Visibility == Visibility.Visible); } #endregion #region State Management private void LoadInitialState() { if (this.RibbonStateStorage.IsLoaded) { return; } this.RibbonStateStorage.Load(); this.TabControl?.SelectFirstTab(); } #endregion #region AutomaticStateManagement Property /// <summary> /// Gets or sets whether Quick Access ToolBar can /// save and load its state automatically /// </summary> public bool AutomaticStateManagement { get { return (bool)this.GetValue(AutomaticStateManagementProperty); } set { this.SetValue(AutomaticStateManagementProperty, value); } } /// <summary>Identifies the <see cref="AutomaticStateManagement"/> dependency property.</summary> public static readonly DependencyProperty AutomaticStateManagementProperty = DependencyProperty.Register(nameof(AutomaticStateManagement), typeof(bool), typeof(Ribbon), new PropertyMetadata(BooleanBoxes.TrueBox, OnAutomaticStateManagementChanged, CoerceAutomaticStateManagement)); private static object CoerceAutomaticStateManagement(DependencyObject d, object basevalue) { var ribbon = (Ribbon)d; if (ribbon.RibbonStateStorage.IsLoading) { return false; } return basevalue; } private static void OnAutomaticStateManagementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ribbon = (Ribbon)d; if ((bool)e.NewValue) { ribbon.LoadInitialState(); } } #endregion /// <inheritdoc /> void ILogicalChildSupport.AddLogicalChild(object child) { this.AddLogicalChild(child); } /// <inheritdoc /> void ILogicalChildSupport.RemoveLogicalChild(object child) { this.RemoveLogicalChild(child); } /// <inheritdoc /> protected override IEnumerator LogicalChildren { get { var baseEnumerator = base.LogicalChildren; while (baseEnumerator?.MoveNext() == true) { yield return baseEnumerator.Current; } if (this.Menu != null) { yield return this.Menu; } if (this.StartScreen != null) { yield return this.StartScreen; } if (this.QuickAccessToolBar != null) { yield return this.QuickAccessToolBar; } if (this.TabControl?.ToolbarPanel != null) { yield return this.TabControl.ToolbarPanel; } if (this.layoutRoot != null) { yield return this.layoutRoot; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using Xunit; namespace System.Tests { public class TupleTests { private class TupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> { private int _nItems; private readonly object Tuple; private readonly Tuple<T1> Tuple1; private readonly Tuple<T1, T2> Tuple2; private readonly Tuple<T1, T2, T3> Tuple3; private readonly Tuple<T1, T2, T3, T4> Tuple4; private readonly Tuple<T1, T2, T3, T4, T5> Tuple5; private readonly Tuple<T1, T2, T3, T4, T5, T6> Tuple6; private readonly Tuple<T1, T2, T3, T4, T5, T6, T7> Tuple7; private readonly Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Tuple8; private readonly Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> Tuple9; private readonly Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> Tuple10; internal TupleTestDriver(params object[] values) { if (values.Length == 0) throw new ArgumentOutOfRangeException(nameof(values), "You must provide at least one value"); if (values.Length > 10) throw new ArgumentOutOfRangeException(nameof(values), "You must provide at most 10 values"); _nItems = values.Length; switch (_nItems) { case 1: Tuple1 = new Tuple<T1>((T1)values[0]); Tuple = Tuple1; break; case 2: Tuple2 = new Tuple<T1, T2>((T1)values[0], (T2)values[1]); Tuple = Tuple2; break; case 3: Tuple3 = new Tuple<T1, T2, T3>((T1)values[0], (T2)values[1], (T3)values[2]); Tuple = Tuple3; break; case 4: Tuple4 = new Tuple<T1, T2, T3, T4>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3]); Tuple = Tuple4; break; case 5: Tuple5 = new Tuple<T1, T2, T3, T4, T5>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4]); Tuple = Tuple5; break; case 6: Tuple6 = new Tuple<T1, T2, T3, T4, T5, T6>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5]); Tuple = Tuple6; break; case 7: Tuple7 = new Tuple<T1, T2, T3, T4, T5, T6, T7>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6]); Tuple = Tuple7; break; case 8: Tuple8 = new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new Tuple<T8>((T8)values[7])); Tuple = Tuple8; break; case 9: Tuple9 = new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new Tuple<T8, T9>((T8)values[7], (T9)values[8])); Tuple = Tuple9; break; case 10: Tuple10 = new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4], (T6)values[5], (T7)values[6], new Tuple<T8, T9, T10>((T8)values[7], (T9)values[8], (T10)values[9])); Tuple = Tuple10; break; } } private void VerifyItem(int itemPos, object Item1, object Item2) { Assert.True(object.Equals(Item1, Item2)); } public void Ctor(params object[] expectedValue) { Assert.Equal(_nItems, expectedValue.Length); switch (_nItems) { case 1: VerifyItem(1, Tuple1.Item1, expectedValue[0]); break; case 2: VerifyItem(1, Tuple2.Item1, expectedValue[0]); VerifyItem(2, Tuple2.Item2, expectedValue[1]); break; case 3: VerifyItem(1, Tuple3.Item1, expectedValue[0]); VerifyItem(2, Tuple3.Item2, expectedValue[1]); VerifyItem(3, Tuple3.Item3, expectedValue[2]); break; case 4: VerifyItem(1, Tuple4.Item1, expectedValue[0]); VerifyItem(2, Tuple4.Item2, expectedValue[1]); VerifyItem(3, Tuple4.Item3, expectedValue[2]); VerifyItem(4, Tuple4.Item4, expectedValue[3]); break; case 5: VerifyItem(1, Tuple5.Item1, expectedValue[0]); VerifyItem(2, Tuple5.Item2, expectedValue[1]); VerifyItem(3, Tuple5.Item3, expectedValue[2]); VerifyItem(4, Tuple5.Item4, expectedValue[3]); VerifyItem(5, Tuple5.Item5, expectedValue[4]); break; case 6: VerifyItem(1, Tuple6.Item1, expectedValue[0]); VerifyItem(2, Tuple6.Item2, expectedValue[1]); VerifyItem(3, Tuple6.Item3, expectedValue[2]); VerifyItem(4, Tuple6.Item4, expectedValue[3]); VerifyItem(5, Tuple6.Item5, expectedValue[4]); VerifyItem(6, Tuple6.Item6, expectedValue[5]); break; case 7: VerifyItem(1, Tuple7.Item1, expectedValue[0]); VerifyItem(2, Tuple7.Item2, expectedValue[1]); VerifyItem(3, Tuple7.Item3, expectedValue[2]); VerifyItem(4, Tuple7.Item4, expectedValue[3]); VerifyItem(5, Tuple7.Item5, expectedValue[4]); VerifyItem(6, Tuple7.Item6, expectedValue[5]); VerifyItem(7, Tuple7.Item7, expectedValue[6]); break; case 8: // Extended Tuple VerifyItem(1, Tuple8.Item1, expectedValue[0]); VerifyItem(2, Tuple8.Item2, expectedValue[1]); VerifyItem(3, Tuple8.Item3, expectedValue[2]); VerifyItem(4, Tuple8.Item4, expectedValue[3]); VerifyItem(5, Tuple8.Item5, expectedValue[4]); VerifyItem(6, Tuple8.Item6, expectedValue[5]); VerifyItem(7, Tuple8.Item7, expectedValue[6]); VerifyItem(8, Tuple8.Rest.Item1, expectedValue[7]); break; case 9: // Extended Tuple VerifyItem(1, Tuple9.Item1, expectedValue[0]); VerifyItem(2, Tuple9.Item2, expectedValue[1]); VerifyItem(3, Tuple9.Item3, expectedValue[2]); VerifyItem(4, Tuple9.Item4, expectedValue[3]); VerifyItem(5, Tuple9.Item5, expectedValue[4]); VerifyItem(6, Tuple9.Item6, expectedValue[5]); VerifyItem(7, Tuple9.Item7, expectedValue[6]); VerifyItem(8, Tuple9.Rest.Item1, expectedValue[7]); VerifyItem(9, Tuple9.Rest.Item2, expectedValue[8]); break; case 10: // Extended Tuple VerifyItem(1, Tuple10.Item1, expectedValue[0]); VerifyItem(2, Tuple10.Item2, expectedValue[1]); VerifyItem(3, Tuple10.Item3, expectedValue[2]); VerifyItem(4, Tuple10.Item4, expectedValue[3]); VerifyItem(5, Tuple10.Item5, expectedValue[4]); VerifyItem(6, Tuple10.Item6, expectedValue[5]); VerifyItem(7, Tuple10.Item7, expectedValue[6]); VerifyItem(8, Tuple10.Rest.Item1, expectedValue[7]); VerifyItem(9, Tuple10.Rest.Item2, expectedValue[8]); VerifyItem(10, Tuple10.Rest.Item3, expectedValue[9]); break; default: throw new ArgumentException("Must specify between 1 and 10 expected values (inclusive)."); } } public void ToString(string expected) { Assert.Equal(expected, Tuple.ToString()); } public void Equals_GetHashCode(TupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, bool expectEqual, bool expectStructuallyEqual) { if (expectEqual) { Assert.True(Tuple.Equals(other.Tuple)); Assert.Equal(Tuple.GetHashCode(), other.Tuple.GetHashCode()); } else { Assert.False(Tuple.Equals(other.Tuple)); Assert.NotEqual(Tuple.GetHashCode(), other.Tuple.GetHashCode()); } if (expectStructuallyEqual) { var equatable = ((IStructuralEquatable)Tuple); var otherEquatable = ((IStructuralEquatable)other.Tuple); Assert.True(equatable.Equals(other.Tuple, TestEqualityComparer.Instance)); Assert.Equal(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance)); } else { var equatable = ((IStructuralEquatable)Tuple); var otherEquatable = ((IStructuralEquatable)other.Tuple); Assert.False(equatable.Equals(other.Tuple, TestEqualityComparer.Instance)); Assert.NotEqual(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance)); } Assert.False(Tuple.Equals(null)); Assert.False(((IStructuralEquatable)Tuple).Equals(null)); IStructuralEquatable_Equals_NullComparer_ThrowsNullReferenceException(); IStructuralEquatable_GetHashCode_NullComparer_ThrowsNullReferenceException(); } public void IStructuralEquatable_Equals_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the full .NET framework and Xamarin. See #13410 IStructuralEquatable equatable = (IStructuralEquatable)Tuple; Assert.Throws<NullReferenceException>(() => equatable.Equals(Tuple, null)); } public void IStructuralEquatable_GetHashCode_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the full .NET framework and Xamarin. See #13410 IStructuralEquatable equatable = (IStructuralEquatable)Tuple; Assert.Throws<NullReferenceException>(() => equatable.GetHashCode(null)); } public void CompareTo(TupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, int expectedResult, int expectedStructuralResult) { Assert.Equal(expectedResult, ((IComparable)Tuple).CompareTo(other.Tuple)); Assert.Equal(expectedStructuralResult, ((IStructuralComparable)Tuple).CompareTo(other.Tuple, TestComparer.Instance)); Assert.Equal(1, ((IComparable)Tuple).CompareTo(null)); IStructuralComparable_NullComparer_ThrowsNullReferenceException(); } public void IStructuralComparable_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the full .NET framework and Xamarin. See #13410 IStructuralComparable comparable = (IStructuralComparable)Tuple; Assert.Throws<NullReferenceException>(() => comparable.CompareTo(Tuple, null)); } public void NotEqual() { Tuple<int> tupleB = new Tuple<int>((int)10000); Assert.NotEqual(Tuple, tupleB); } internal void CompareToThrows() { Tuple<int> tupleB = new Tuple<int>((int)10000); AssertExtensions.Throws<ArgumentException>("other", () => ((IComparable)Tuple).CompareTo(tupleB)); } } [Fact] public static void Constructor() { TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan> tupleDriverA; //Tuple-1 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue); tupleDriverA.Ctor(short.MaxValue); //Tuple-2 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); tupleDriverA.Ctor(short.MinValue, int.MaxValue); //Tuple-3 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); tupleDriverA.Ctor((short)0, (int)0, long.MaxValue); //Tuple-4 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); tupleDriverA.Ctor((short)1, (int)1, long.MinValue, "This"); //Tuple-5 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); tupleDriverA.Ctor((short)(-1), (int)(-1), (long)0, "is", 'A'); //Tuple-6 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue); tupleDriverA.Ctor((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue); //Tuple-7 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverA.Ctor((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); object myObj = new object(); //Tuple-10 DateTime now = DateTime.Now; tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverA.Ctor((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); } [Fact] public static void ToStringTest() { TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan> tupleDriverA; //Tuple-1 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue); tupleDriverA.ToString("(" + short.MaxValue + ")"); //Tuple-2 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); tupleDriverA.ToString("(" + short.MinValue + ", " + int.MaxValue + ")"); //Tuple-3 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); tupleDriverA.ToString("(" + ((short)0) + ", " + ((int)0) + ", " + long.MaxValue + ")"); //Tuple-4 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); tupleDriverA.Ctor((short)1, (int)1, long.MinValue, "This"); tupleDriverA.ToString("(" + ((short)1) + ", " + ((int)1) + ", " + long.MinValue + ", This)"); //Tuple-5 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); tupleDriverA.ToString("(" + ((short)(-1)) + ", " + ((int)(-1)) + ", " + ((long)0) + ", is, A)"); //Tuple-6 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue); tupleDriverA.ToString("(" + ((short)10) + ", " + ((int)100) + ", " + ((long)1) + ", testing, Z, " + Single.MaxValue + ")"); //Tuple-7 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverA.ToString("(" + ((short)(-100)) + ", " + ((int)(-1000)) + ", " + ((long)(-1)) + ", Tuples, , " + Single.MinValue + ", " + Double.MaxValue + ")"); object myObj = new object(); //Tuple-10 DateTime now = DateTime.Now; tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); // .NET Native bug 438149 - object.ToString in incorrect tupleDriverA.ToString("(" + ((short)10000) + ", " + ((int)1000000) + ", " + ((long)10000000) + ", 2008?7?2?, 0, " + ((Single)0.0001) + ", " + ((Double)0.0000001) + ", " + now + ", (False, System.Object), " + TimeSpan.Zero + ")"); } [Fact] public static void Equals_GetHashCode() { TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan> tupleDriverA, tupleDriverB, tupleDriverC, tupleDriverD; //Tuple-1 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue); tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue, int.MaxValue); tupleDriverA.Equals_GetHashCode(tupleDriverB, true, true); tupleDriverA.Equals_GetHashCode(tupleDriverC, false, false); tupleDriverA.Equals_GetHashCode(tupleDriverD, false, false); //Tuple-2 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue); tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue); tupleDriverA.Equals_GetHashCode(tupleDriverB, true, true); tupleDriverA.Equals_GetHashCode(tupleDriverC, false, false); tupleDriverA.Equals_GetHashCode(tupleDriverD, false, false); //Tuple-3 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue); tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this"); tupleDriverA.Equals_GetHashCode(tupleDriverB, true, true); tupleDriverA.Equals_GetHashCode(tupleDriverC, false, false); tupleDriverA.Equals_GetHashCode(tupleDriverD, false, false); //Tuple-4 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this"); tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a'); tupleDriverA.Equals_GetHashCode(tupleDriverB, true, true); tupleDriverA.Equals_GetHashCode(tupleDriverC, false, false); tupleDriverA.Equals_GetHashCode(tupleDriverD, false, false); //Tuple-5 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a'); tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MinValue); tupleDriverA.Equals_GetHashCode(tupleDriverB, true, true); tupleDriverA.Equals_GetHashCode(tupleDriverC, false, false); tupleDriverA.Equals_GetHashCode(tupleDriverD, false, false); //Tuple-6 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MinValue); tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "tuples", ' ', Single.MinValue, (Double)0.0); tupleDriverA.Equals_GetHashCode(tupleDriverB, true, true); tupleDriverA.Equals_GetHashCode(tupleDriverC, false, false); tupleDriverA.Equals_GetHashCode(tupleDriverD, false, false); //Tuple-7 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "tuples", ' ', Single.MinValue, (Double)0.0); tupleDriverD = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (Single)0.0002, (Double)0.0000002, DateTime.Now.AddMilliseconds(1)); tupleDriverA.Equals_GetHashCode(tupleDriverB, true, true); tupleDriverA.Equals_GetHashCode(tupleDriverC, false, false); tupleDriverA.Equals_GetHashCode(tupleDriverD, false, false); object myObj = new object(); //Tuple-10 DateTime now = DateTime.Now; tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (Single)0.0002, (Double)0.0000002, now.AddMilliseconds(1), Tuple.Create(true, myObj), TimeSpan.MaxValue); tupleDriverA.Equals_GetHashCode(tupleDriverB, true, true); tupleDriverA.Equals_GetHashCode(tupleDriverC, false, false); } [Fact] public static void CompareTo() { TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan> tupleDriverA, tupleDriverB, tupleDriverC; //Tuple-1 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue); tupleDriverA.CompareTo(tupleDriverB, 0, 5); tupleDriverA.CompareTo(tupleDriverC, 65535, 5); //Tuple-2 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue); tupleDriverA.CompareTo(tupleDriverB, 0, 5); tupleDriverA.CompareTo(tupleDriverC, 1, 5); //Tuple-3 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue); tupleDriverA.CompareTo(tupleDriverB, 0, 5); tupleDriverA.CompareTo(tupleDriverC, 1, 5); //Tuple-4 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This"); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this"); tupleDriverA.CompareTo(tupleDriverB, 0, 5); tupleDriverA.CompareTo(tupleDriverC, 1, 5); //Tuple-5 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A'); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a'); tupleDriverA.CompareTo(tupleDriverB, 0, 5); tupleDriverA.CompareTo(tupleDriverC, -1, 5); //Tuple-6 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MinValue); tupleDriverA.CompareTo(tupleDriverB, 0, 5); tupleDriverA.CompareTo(tupleDriverC, 1, 5); //Tuple-7 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "Tuples", ' ', Single.MinValue, Double.MaxValue); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "tuples", ' ', Single.MinValue, (Double)0.0); tupleDriverA.CompareTo(tupleDriverB, 0, 5); tupleDriverA.CompareTo(tupleDriverC, 1, 5); object myObj = new object(); //Tuple-10 DateTime now = DateTime.Now; tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverB = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, Tuple.Create(false, myObj), TimeSpan.Zero); tupleDriverC = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, Tuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (Single)0.0002, (Double)0.0000002, now.AddMilliseconds(1), Tuple.Create(true, myObj), TimeSpan.MaxValue); tupleDriverA.CompareTo(tupleDriverB, 0, 5); tupleDriverA.CompareTo(tupleDriverC, -1, 5); } [Fact] public static void NotEqual() { TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan> tupleDriverA; //Tuple-1 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000); tupleDriverA.NotEqual(); // This is for code coverage purposes //Tuple-2 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000); tupleDriverA.NotEqual(); //Tuple-3 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000); tupleDriverA.NotEqual(); //Tuple-4 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?"); tupleDriverA.NotEqual(); //Tuple-5 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0'); tupleDriverA.NotEqual(); //Tuple-6 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN); tupleDriverA.NotEqual(); //Tuple-7 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity); tupleDriverA.NotEqual(); //Tuple-8, extended tuple tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity, DateTime.Now); tupleDriverA.NotEqual(); //Tuple-9 and Tuple-10 are not necessary because they use the same code path as Tuple-8 } [Fact] public static void IncomparableTypes() { TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan> tupleDriverA; //Tuple-1 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000); tupleDriverA.CompareToThrows(); // This is for code coverage purposes //Tuple-2 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000); tupleDriverA.CompareToThrows(); //Tuple-3 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000); tupleDriverA.CompareToThrows(); //Tuple-4 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?"); tupleDriverA.CompareToThrows(); //Tuple-5 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0'); tupleDriverA.CompareToThrows(); //Tuple-6 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN); tupleDriverA.CompareToThrows(); //Tuple-7 tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity); tupleDriverA.CompareToThrows(); //Tuple-8, extended tuple tupleDriverA = new TupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity, DateTime.Now); tupleDriverA.CompareToThrows(); //Tuple-9 and Tuple-10 are not necessary because they use the same code path as Tuple-8 } [Fact] public static void FloatingPointNaNCases() { var a = Tuple.Create(Double.MinValue, Double.NaN, Single.MinValue, Single.NaN); var b = Tuple.Create(Double.MinValue, Double.NaN, Single.MinValue, Single.NaN); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void CustomTypeParameter1() { // Special case of Tuple<T1> where T1 is a custom type var testClass = new TestClass(); var a = Tuple.Create(testClass); var b = Tuple.Create(testClass); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void CustomTypeParameter2() { // Special case of Tuple<T1, T2> where T2 is a custom type var testClass = new TestClass(1); var a = Tuple.Create(1, testClass); var b = Tuple.Create(1, testClass); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); } [Fact] public static void CustomTypeParameter3() { // Special case of Tuple<T1, T2> where T1 and T2 are custom types var testClassA = new TestClass(100); var testClassB = new TestClass(101); var a = Tuple.Create(testClassA, testClassB); var b = Tuple.Create(testClassB, testClassA); Assert.False(a.Equals(b)); Assert.Equal(-1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); // Equals(IEqualityComparer) is false, ignore hash code } [Fact] public static void CustomTypeParameter4() { // Special case of Tuple<T1, T2> where T1 and T2 are custom types var testClassA = new TestClass(100); var testClassB = new TestClass(101); var a = Tuple.Create(testClassA, testClassB); var b = Tuple.Create(testClassA, testClassA); Assert.False(a.Equals(b)); Assert.Equal(1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); // Equals(IEqualityComparer) is false, ignore hash code } [Fact] public static void NestedTuples1() { var a = Tuple.Create(1, 2, Tuple.Create(31, 32), 4, 5, 6, 7, Tuple.Create(8, 9)); var b = Tuple.Create(1, 2, Tuple.Create(31, 32), 4, 5, 6, 7, Tuple.Create(8, 9)); Assert.True(a.Equals(b)); Assert.Equal(0, ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("(1, 2, (31, 32), 4, 5, 6, 7, (8, 9))", a.ToString()); Assert.Equal("(31, 32)", a.Item3.ToString()); Assert.Equal("((8, 9))", a.Rest.ToString()); } [Fact] public static void NestedTuples2() { var a = Tuple.Create(0, 1, 2, 3, 4, 5, 6, Tuple.Create(7, 8, 9, 10, 11, 12, 13, Tuple.Create(14, 15))); var b = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16))); Assert.False(a.Equals(b)); Assert.Equal(-1, ((IComparable)a).CompareTo(b)); Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal("(0, 1, 2, 3, 4, 5, 6, (7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.ToString()); Assert.Equal("(1, 2, 3, 4, 5, 6, 7, (8, 9, 10, 11, 12, 13, 14, (15, 16)))", b.ToString()); Assert.Equal("((7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.Rest.ToString()); } [Fact] public static void IncomparableTypesSpecialCase() { // Special case when T does not implement IComparable var testClassA = new TestClass2(100); var testClassB = new TestClass2(100); var a = Tuple.Create(testClassA); var b = Tuple.Create(testClassB); Assert.True(a.Equals(b)); AssertExtensions.Throws<ArgumentException>(null, () => ((IComparable)a).CompareTo(b)); Assert.Equal(a.GetHashCode(), b.GetHashCode()); Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance)); Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, TestComparer.Instance)); Assert.Equal( ((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance), ((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance)); Assert.Equal("([100])", a.ToString()); } private class TestClass : IComparable { private readonly int _value; internal TestClass() : this(0) { } internal TestClass(int value) { this._value = value; } public override string ToString() { return "{" + _value.ToString() + "}"; } public int CompareTo(object x) { TestClass tmp = x as TestClass; if (tmp != null) return this._value.CompareTo(tmp._value); else return 1; } } private class TestClass2 { private readonly int _value; internal TestClass2() : this(0) { } internal TestClass2(int value) { this._value = value; } public override string ToString() { return "[" + _value.ToString() + "]"; } public override bool Equals(object x) { TestClass2 tmp = x as TestClass2; if (tmp != null) return _value.Equals(tmp._value); else return false; } public override int GetHashCode() { return _value.GetHashCode(); } } private class TestComparer : IComparer { public static readonly TestComparer Instance = new TestComparer(); public int Compare(object x, object y) { return 5; } } private class TestEqualityComparer : IEqualityComparer { public static readonly TestEqualityComparer Instance = new TestEqualityComparer(); public new bool Equals(object x, object y) { return x.Equals(y); } public int GetHashCode(object x) { return x.GetHashCode(); } } } }
using System; using System.Collections; using Community.CsharpSqlite; public class SQLiteQuery { private SQLiteDB sqlDb; private Sqlite3.sqlite3 db; private Sqlite3.Vdbe vm; private string[] columnNames; private int[] columnTypes; private int bindIndex; public string[] Names { get {return columnNames;} } public int[] Types{ get { return columnTypes; } } public SQLiteQuery( SQLiteDB sqliteDb, string query ) { sqlDb = sqliteDb; bindIndex = 1; db = sqliteDb.Connection(); if( Sqlite3.sqlite3_prepare_v2( db, query, query.Length, ref vm, 0 ) != Sqlite3.SQLITE_OK ) { throw new Exception( "Error with prepare query! error:" + Sqlite3.sqlite3_errmsg(db) ); }; sqlDb.RegisterQuery(this); } public void Reset() { bindIndex = 1; if( Sqlite3.sqlite3_reset( vm ) != Sqlite3.SQLITE_OK ) { throw new Exception( "Error with sqlite3_reset!" ); }; } public void Release() { sqlDb.UnregisterQuery(this); if( Sqlite3.sqlite3_reset( vm ) != Sqlite3.SQLITE_OK ) { throw new Exception( "Error with sqlite3_reset!" ); }; if( Sqlite3.sqlite3_finalize( vm ) != Sqlite3.SQLITE_OK ) { throw new Exception( "Error with sqlite3_finalize!" ); }; } public void Bind( string str ) {BindAt(str,-1);} public void BindAt( string str, int bindAt ) { if( bindAt == -1 ) { bindAt = bindIndex++; } if( Sqlite3.sqlite3_bind_text( vm, bindAt, str, -1, null ) != Sqlite3.SQLITE_OK ) { throw new Exception( "SQLite fail to bind string with error: " + Sqlite3.sqlite3_errmsg(db) ); }; } public void Bind( int integer ) {BindAt(integer,-1);} public void BindAt( int integer, int bindAt ) { if( bindAt == -1 ) { bindAt = bindIndex++; } if( Sqlite3.sqlite3_bind_int( vm, bindAt, integer ) != Sqlite3.SQLITE_OK ) { throw new Exception( "SQLite fail to bind integer with error: " + Sqlite3.sqlite3_errmsg(db) ); }; } public void Bind( double real ) {BindAt(real,-1);} public void BindAt( double real, int bindAt ) { if( bindAt == -1 ) { bindAt = bindIndex++; } if( Sqlite3.sqlite3_bind_double( vm, bindAt, real ) != Sqlite3.SQLITE_OK ) { throw new Exception( "SQLite fail to bind double with error: " + Sqlite3.sqlite3_errmsg(db) ); }; } public void Bind( byte[] blob ) {BindAt(blob,-1);} public void BindAt( byte[] blob, int bindAt ) { if( bindAt == -1 ) { bindAt = bindIndex++; } if( Sqlite3.sqlite3_bind_blob( vm, bindAt, blob, blob.Length, null ) != Sqlite3.SQLITE_OK ) { throw new Exception( "SQLite fail to bind blob with error: " + Sqlite3.sqlite3_errmsg(db) ); }; } public void BindNull() {BindNullAt(-1);} public void BindNullAt( int bindAt ) { if( bindAt == -1 ) { bindAt = bindIndex++; } if( Sqlite3.sqlite3_bind_null( vm, bindAt ) != Sqlite3.SQLITE_OK ) { throw new Exception( "SQLite fail to bind null error: " + Sqlite3.sqlite3_errmsg(db) ); }; } public bool Step() { switch( Sqlite3.sqlite3_step( vm )) { case Sqlite3.SQLITE_DONE: return false; case Sqlite3.SQLITE_ROW: { int columnCount = Sqlite3.sqlite3_column_count( vm ); columnNames = new string[columnCount]; columnTypes = new int[columnCount]; try { // reads columns one by one for ( int i = 0; i < columnCount; i++ ) { columnNames[i] = Sqlite3.sqlite3_column_name( vm, i ); columnTypes[i] = Sqlite3.sqlite3_column_type( vm, i ); } } catch { throw new Exception( "SQLite fail to read column's names and types! error: " + Sqlite3.sqlite3_errmsg(db)); } return true; } } throw new Exception( "SQLite step fail! error: " + Sqlite3.sqlite3_errmsg(db)); } public bool IsNULL( string field ) { int i = GetFieldIndex( field ); return Sqlite3.SQLITE_NULL == columnTypes[i]; } public int GetFieldType( string field ) { for( int i = 0; i < columnNames.Length; i++ ) { if( columnNames[i] == field ) return columnTypes[i]; } throw new Exception( "SQLite unknown field name: " + field); } public int GetFieldType( int field ) { if ( columnTypes==null || field < 0 || field >= columnTypes.Length) { return -1; } return columnTypes[field]; // throw new Exception( "SQLite unknown field name: " + field); } public int GetFieldIndex(string field) { for( int i = 0; i < columnNames.Length; i++ ) { if( columnNames[i] == field ) return i; } return -1; //throw new Exception( "SQLite unknown field name: " + field); } public string GetString( string field ) { int i = GetFieldIndex( field ); if (i < 0) { return string.Empty; } if( Sqlite3.SQLITE_TEXT == columnTypes[i]) { return Sqlite3.sqlite3_column_text( vm, i ); } return string.Empty; //throw new Exception( "SQLite wrong field type (expecting String) : " + field); } public string GetString(int filedindex) { if (filedindex < 0 || filedindex >= Names.Length) { return string.Empty; } if( Sqlite3.SQLITE_TEXT == columnTypes[filedindex]) { return Sqlite3.sqlite3_column_text( vm, filedindex); } return string.Empty; } public int GetInteger( string field ) { int i = GetFieldIndex( field ); if (i < 0 || i>=Names.Length) { throw new Exception( "SQLite wrong field type (expecting Integer) : " + field); } if (Sqlite3.SQLITE_INTEGER == columnTypes [i]) { return Sqlite3.sqlite3_column_int (vm, i); } throw new Exception( "SQLite wrong field type (expecting Integer) : " + field); } public int GetInteger( int index ) { if (index < 0 || index >= Names.Length) { throw new Exception( "SQLite wrong field type (expecting Integer) : " + index); } //int i = GetFieldIndex( field ); if( Sqlite3.SQLITE_INTEGER == columnTypes[index]) { return Sqlite3.sqlite3_column_int( vm, index ); } throw new Exception( "SQLite wrong field type (expecting Integer) : " + index); } public float GetFloat( string field ) { int i = GetFieldIndex( field ); if (i < 0||i>=Names.Length) { throw new Exception( "SQLite wrong field type (expecting Double) : " + field); } if (Sqlite3.SQLITE_FLOAT == columnTypes [i]) { return (float )Sqlite3.sqlite3_column_double (vm, i); } throw new Exception( "SQLite wrong field type (expecting Double) : " + field); } public float GetFloat(int fieldindex ) { if (fieldindex < 0 || fieldindex>=Names.Length) { throw new Exception( "SQLite wrong field type (expecting FLOAT) : " + fieldindex); } //if (Sqlite3.SQLITE_FLOAT == columnTypes [fieldindex]) { return (float)Sqlite3.sqlite3_column_double (vm, fieldindex); } // throw new Exception( "SQLite wrong field type (expecting FLOAT) : " + fieldindex); } public byte[] GetBlob( string field ) { int i = GetFieldIndex( field ); if (i < 0) { return null; } if( Sqlite3.SQLITE_BLOB == columnTypes[i]) { return Sqlite3.sqlite3_column_blob( vm, i ); } return null; // throw new Exception( "SQLite wrong field type (expecting byte[]) : " + field); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Cache of <see cref="ValidationAttribute" />s /// </summary> /// <remarks> /// This internal class serves as a cache of validation attributes and [Display] attributes. /// It exists both to help performance as well as to abstract away the differences between /// Reflection and TypeDescriptor. /// </remarks> internal class ValidationAttributeStore { private readonly Dictionary<Type, TypeStoreItem> _typeStoreItems = new Dictionary<Type, TypeStoreItem>(); /// <summary> /// Gets the singleton <see cref="ValidationAttributeStore" /> /// </summary> internal static ValidationAttributeStore Instance { get; } = new ValidationAttributeStore(); /// <summary> /// Retrieves the type level validation attributes for the given type. /// </summary> /// <param name="validationContext">The context that describes the type. It cannot be null.</param> /// <returns>The collection of validation attributes. It could be empty.</returns> internal IEnumerable<ValidationAttribute> GetTypeValidationAttributes(ValidationContext validationContext) { EnsureValidationContext(validationContext); var item = GetTypeStoreItem(validationContext.ObjectType); return item.ValidationAttributes; } /// <summary> /// Retrieves the <see cref="DisplayAttribute" /> associated with the given type. It may be null. /// </summary> /// <param name="validationContext">The context that describes the type. It cannot be null.</param> /// <returns>The display attribute instance, if present.</returns> internal DisplayAttribute GetTypeDisplayAttribute(ValidationContext validationContext) { EnsureValidationContext(validationContext); var item = GetTypeStoreItem(validationContext.ObjectType); return item.DisplayAttribute; } /// <summary> /// Retrieves the set of validation attributes for the property /// </summary> /// <param name="validationContext">The context that describes the property. It cannot be null.</param> /// <returns>The collection of validation attributes. It could be empty.</returns> internal IEnumerable<ValidationAttribute> GetPropertyValidationAttributes(ValidationContext validationContext) { EnsureValidationContext(validationContext); var typeItem = GetTypeStoreItem(validationContext.ObjectType); var item = typeItem.GetPropertyStoreItem(validationContext.MemberName); return item.ValidationAttributes; } /// <summary> /// Retrieves the <see cref="DisplayAttribute" /> associated with the given property /// </summary> /// <param name="validationContext">The context that describes the property. It cannot be null.</param> /// <returns>The display attribute instance, if present.</returns> internal DisplayAttribute GetPropertyDisplayAttribute(ValidationContext validationContext) { EnsureValidationContext(validationContext); var typeItem = GetTypeStoreItem(validationContext.ObjectType); var item = typeItem.GetPropertyStoreItem(validationContext.MemberName); return item.DisplayAttribute; } /// <summary> /// Retrieves the Type of the given property. /// </summary> /// <param name="validationContext">The context that describes the property. It cannot be null.</param> /// <returns>The type of the specified property</returns> internal Type GetPropertyType(ValidationContext validationContext) { EnsureValidationContext(validationContext); var typeItem = GetTypeStoreItem(validationContext.ObjectType); var item = typeItem.GetPropertyStoreItem(validationContext.MemberName); return item.PropertyType; } /// <summary> /// Determines whether or not a given <see cref="ValidationContext" />'s /// <see cref="ValidationContext.MemberName" /> references a property on /// the <see cref="ValidationContext.ObjectType" />. /// </summary> /// <param name="validationContext">The <see cref="ValidationContext" /> to check.</param> /// <returns><c>true</c> when the <paramref name="validationContext" /> represents a property, <c>false</c> otherwise.</returns> internal bool IsPropertyContext(ValidationContext validationContext) { EnsureValidationContext(validationContext); var typeItem = GetTypeStoreItem(validationContext.ObjectType); PropertyStoreItem item; return typeItem.TryGetPropertyStoreItem(validationContext.MemberName, out item); } /// <summary> /// Retrieves or creates the store item for the given type /// </summary> /// <param name="type">The type whose store item is needed. It cannot be null</param> /// <returns>The type store item. It will not be null.</returns> private TypeStoreItem GetTypeStoreItem(Type type) { Debug.Assert(type != null); lock (_typeStoreItems) { if (!_typeStoreItems.TryGetValue(type, out TypeStoreItem item)) { // use CustomAttributeExtensions.GetCustomAttributes() to get inherited attributes as well as direct ones var attributes = CustomAttributeExtensions.GetCustomAttributes(type, true); item = new TypeStoreItem(type, attributes); _typeStoreItems[type] = item; } return item; } } /// <summary> /// Throws an ArgumentException of the validation context is null /// </summary> /// <param name="validationContext">The context to check</param> private static void EnsureValidationContext(ValidationContext validationContext) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } } internal static bool IsPublic(PropertyInfo p) => (p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic); internal static bool IsStatic(PropertyInfo p) => (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic); /// <summary> /// Private abstract class for all store items /// </summary> private abstract class StoreItem { internal StoreItem(IEnumerable<Attribute> attributes) { ValidationAttributes = attributes.OfType<ValidationAttribute>(); DisplayAttribute = attributes.OfType<DisplayAttribute>().SingleOrDefault(); } internal IEnumerable<ValidationAttribute> ValidationAttributes { get; } internal DisplayAttribute DisplayAttribute { get; } } /// <summary> /// Private class to store data associated with a type /// </summary> private class TypeStoreItem : StoreItem { private readonly object _syncRoot = new object(); private readonly Type _type; private Dictionary<string, PropertyStoreItem> _propertyStoreItems; internal TypeStoreItem(Type type, IEnumerable<Attribute> attributes) : base(attributes) { _type = type; } internal PropertyStoreItem GetPropertyStoreItem(string propertyName) { if (!TryGetPropertyStoreItem(propertyName, out PropertyStoreItem item)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, SR.AttributeStore_Unknown_Property, _type.Name, propertyName), nameof(propertyName)); } return item; } internal bool TryGetPropertyStoreItem(string propertyName, out PropertyStoreItem item) { if (string.IsNullOrEmpty(propertyName)) { throw new ArgumentNullException(nameof(propertyName)); } if (_propertyStoreItems == null) { lock (_syncRoot) { if (_propertyStoreItems == null) { _propertyStoreItems = CreatePropertyStoreItems(); } } } return _propertyStoreItems.TryGetValue(propertyName, out item); } private Dictionary<string, PropertyStoreItem> CreatePropertyStoreItems() { var propertyStoreItems = new Dictionary<string, PropertyStoreItem>(); // exclude index properties to match old TypeDescriptor functionality var properties = _type.GetRuntimeProperties() .Where(prop => IsPublic(prop) && !prop.GetIndexParameters().Any()); foreach (PropertyInfo property in properties) { // use CustomAttributeExtensions.GetCustomAttributes() to get inherited attributes as well as direct ones var item = new PropertyStoreItem(property.PropertyType, CustomAttributeExtensions.GetCustomAttributes(property, true)); propertyStoreItems[property.Name] = item; } return propertyStoreItems; } } /// <summary> /// Private class to store data associated with a property /// </summary> private class PropertyStoreItem : StoreItem { internal PropertyStoreItem(Type propertyType, IEnumerable<Attribute> attributes) : base(attributes) { Debug.Assert(propertyType != null); PropertyType = propertyType; } internal Type PropertyType { get; } } } }
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using ArcGISRuntime.Samples.Managers; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.GeoAnalysis; using System; using System.Drawing; using Windows.UI.Popups; using Microsoft.UI.Xaml; namespace ArcGISRuntime.WinUI.Samples.LineOfSightGeoElement { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Line of sight (geoelement)", category: "Analysis", description: "Show a line of sight between two moving objects.", instructions: "A line of sight will display between a point on the Empire State Building (observer) and a taxi (target).", tags: new[] { "3D", "line of sight", "visibility", "visibility analysis" })] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("3af5cfec0fd24dac8d88aea679027cb9")] public partial class LineOfSightGeoElement { // URL of the elevation service - provides elevation component of the scene. private readonly Uri _elevationUri = new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"); // URL of the building service - provides building models. private readonly Uri _buildingsUri = new Uri("https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/New_York_LoD2_3D_Buildings/SceneServer/layers/0"); // Starting point of the observation point. private readonly MapPoint _observerPoint = new MapPoint(-73.984988, 40.748131, 20, SpatialReferences.Wgs84); // Graphic to represent the observation point. private Graphic _observerGraphic; // Graphic to represent the observed target. private Graphic _taxiGraphic; // Line of Sight Analysis. private GeoElementLineOfSight _geoLine; // For taxi animation - four points in a loop. private readonly MapPoint[] _points = { new MapPoint(-73.984513, 40.748469, SpatialReferences.Wgs84), new MapPoint(-73.985068, 40.747786, SpatialReferences.Wgs84), new MapPoint(-73.983452, 40.747091, SpatialReferences.Wgs84), new MapPoint(-73.982961, 40.747762, SpatialReferences.Wgs84) }; // For taxi animation - tracks animation state. private int _pointIndex = 0; private int _frameIndex = 0; private const int FrameMax = 150; public LineOfSightGeoElement() { InitializeComponent(); // Setup the control references and execute initialization. Initialize(); } private async void Initialize() { // Create scene. Scene myScene = new Scene(BasemapStyle.ArcGISImagery) { InitialViewpoint = new Viewpoint(_observerPoint, 1600) }; // Create the elevation source. ElevationSource myElevationSource = new ArcGISTiledElevationSource(_elevationUri); // Add the elevation source to the scene. myScene.BaseSurface.ElevationSources.Add(myElevationSource); // Create the building scene layer. ArcGISSceneLayer mySceneLayer = new ArcGISSceneLayer(_buildingsUri); // Add the building layer to the scene. myScene.OperationalLayers.Add(mySceneLayer); // Add the observer to the scene. // Create a graphics overlay with relative surface placement; relative surface placement allows the Z position of the observation point to be adjusted. GraphicsOverlay overlay = new GraphicsOverlay() { SceneProperties = new LayerSceneProperties(SurfacePlacement.Relative) }; // Create the symbol that will symbolize the observation point. SimpleMarkerSceneSymbol symbol = new SimpleMarkerSceneSymbol(SimpleMarkerSceneSymbolStyle.Sphere, Color.Red, 10, 10, 10, SceneSymbolAnchorPosition.Bottom); // Create the observation point graphic from the point and symbol. _observerGraphic = new Graphic(_observerPoint, symbol); // Add the observer to the overlay. overlay.Graphics.Add(_observerGraphic); // Add the overlay to the scene. MySceneView.GraphicsOverlays.Add(overlay); try { // Add the taxi to the scene. // Create the model symbol for the taxi. ModelSceneSymbol taxiSymbol = await ModelSceneSymbol.CreateAsync(new Uri(DataManager.GetDataFolder("3af5cfec0fd24dac8d88aea679027cb9", "dolmus.3ds"))); // Set the anchor position for the mode; ensures that the model appears above the ground. taxiSymbol.AnchorPosition = SceneSymbolAnchorPosition.Bottom; // Create the graphic from the taxi starting point and the symbol. _taxiGraphic = new Graphic(_points[0], taxiSymbol); // Add the taxi graphic to the overlay. overlay.Graphics.Add(_taxiGraphic); // Create GeoElement Line of sight analysis (taxi to building). // Create the analysis. _geoLine = new GeoElementLineOfSight(_observerGraphic, _taxiGraphic) { // Apply an offset to the target. This helps avoid some false negatives. TargetOffsetZ = 2 }; // Create the analysis overlay. AnalysisOverlay myAnalysisOverlay = new AnalysisOverlay(); // Add the analysis to the overlay. myAnalysisOverlay.Analyses.Add(_geoLine); // Add the analysis overlay to the scene. MySceneView.AnalysisOverlays.Add(myAnalysisOverlay); // Create a timer; this will enable animating the taxi. DispatcherTimer animationTimer = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 60) }; // Move the taxi every time the timer expires. animationTimer.Tick += AnimationTimer_Tick; // Start the timer. animationTimer.Start(); // Subscribe to TargetVisible events; allows for updating the UI and selecting the taxi when it is visible. _geoLine.TargetVisibilityChanged += Geoline_TargetVisibilityChanged; // Add the scene to the view. MySceneView.Scene = myScene; } catch (Exception e) { await new MessageDialog2(e.ToString(), "Error").ShowAsync(); } } private void AnimationTimer_Tick(object sender, object e) { // Note: the contents of this function are solely related to animating the taxi. // Increment the frame counter. _frameIndex++; // Reset the frame counter once one segment of the path has been traveled. if (_frameIndex == FrameMax) { _frameIndex = 0; // Start navigating toward the next point. _pointIndex++; // Restart if finished circuit. if (_pointIndex == _points.Length) { _pointIndex = 0; } } // Get the point the taxi is traveling from. MapPoint starting = _points[_pointIndex]; // Get the point the taxi is traveling to. MapPoint ending = _points[(_pointIndex + 1) % _points.Length]; // Calculate the progress based on the current frame. double progress = _frameIndex / (double)FrameMax; // Calculate the position of the taxi when it is {progress}% of the way through. MapPoint intermediatePoint = InterpolatedPoint(starting, ending, progress); // Update the taxi geometry. _taxiGraphic.Geometry = intermediatePoint; // Update the taxi rotation. GeodeticDistanceResult distance = GeometryEngine.DistanceGeodetic(starting, ending, LinearUnits.Meters, AngularUnits.Degrees, GeodeticCurveType.Geodesic); ((ModelSceneSymbol)_taxiGraphic.Symbol).Heading = distance.Azimuth1; } private static MapPoint InterpolatedPoint(MapPoint firstPoint, MapPoint secondPoint, double progress) { // This function returns a MapPoint that is the result of traveling {progress}% of the way from {firstPoint} to {secondPoint}. // Get the difference between the two points. MapPoint difference = new MapPoint(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y, secondPoint.Z - firstPoint.Z, SpatialReferences.Wgs84); // Scale the difference by the progress towards the destination. MapPoint scaled = new MapPoint(difference.X * progress, difference.Y * progress, difference.Z * progress); // Add the scaled progress to the starting point. return new MapPoint(firstPoint.X + scaled.X, firstPoint.Y + scaled.Y, firstPoint.Z + scaled.Z); } private void Geoline_TargetVisibilityChanged(object sender, EventArgs e) { // This is needed because Runtime delivers notifications from a different thread that doesn't have access to UI controls. DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, UpdateUiAndSelection); } private void UpdateUiAndSelection() { switch (_geoLine.TargetVisibility) { case LineOfSightTargetVisibility.Obstructed: StatusLabel.Text = "Status: Obstructed"; _taxiGraphic.IsSelected = false; break; case LineOfSightTargetVisibility.Visible: StatusLabel.Text = "Status: Visible"; _taxiGraphic.IsSelected = true; break; default: case LineOfSightTargetVisibility.Unknown: StatusLabel.Text = "Status: Unknown"; _taxiGraphic.IsSelected = false; break; } } private void HeightSlider_ValueChanged(object sender, Microsoft.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e) { // Update the height of the observer based on the slider value. // Constrain the min and max to 20 and 150 units. const double minHeight = 20; const double maxHeight = 150; // Scale the slider value; its default range is 0-100. double value = e.NewValue / 100; // Get the current point. MapPoint oldPoint = (MapPoint)_observerGraphic.Geometry; // Create a new point with the same (x,y) but updated z. MapPoint newPoint = new MapPoint(oldPoint.X, oldPoint.Y, (maxHeight - minHeight) * value + minHeight); // Apply the updated geometry to the observer point. _observerGraphic.Geometry = newPoint; } } }
using System; using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ChargeBee.Internal; using ChargeBee.Api; using ChargeBee.Models.Enums; using ChargeBee.Filters.Enums; namespace ChargeBee.Models { public class UnbilledCharge : Resource { public UnbilledCharge() { } public UnbilledCharge(Stream stream) { using (StreamReader reader = new StreamReader(stream)) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } } public UnbilledCharge(TextReader reader) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } public UnbilledCharge(String jsonString) { JObj = JToken.Parse(jsonString); apiVersionCheck (JObj); } #region Methods public static CreateRequest Create() { string url = ApiUtil.BuildUrl("unbilled_charges"); return new CreateRequest(url, HttpMethod.POST); } public static InvoiceUnbilledChargesRequest InvoiceUnbilledCharges() { string url = ApiUtil.BuildUrl("unbilled_charges", "invoice_unbilled_charges"); return new InvoiceUnbilledChargesRequest(url, HttpMethod.POST); } public static EntityRequest<Type> Delete(string id) { string url = ApiUtil.BuildUrl("unbilled_charges", CheckNull(id), "delete"); return new EntityRequest<Type>(url, HttpMethod.POST); } public static UnbilledChargeListRequest List() { string url = ApiUtil.BuildUrl("unbilled_charges"); return new UnbilledChargeListRequest(url); } public static InvoiceNowEstimateRequest InvoiceNowEstimate() { string url = ApiUtil.BuildUrl("unbilled_charges", "invoice_now_estimate"); return new InvoiceNowEstimateRequest(url, HttpMethod.POST); } #endregion #region Properties public string Id { get { return GetValue<string>("id", false); } } public string CustomerId { get { return GetValue<string>("customer_id", false); } } public string SubscriptionId { get { return GetValue<string>("subscription_id", false); } } public DateTime? DateFrom { get { return GetDateTime("date_from", false); } } public DateTime? DateTo { get { return GetDateTime("date_to", false); } } public int? UnitAmount { get { return GetValue<int?>("unit_amount", false); } } public PricingModelEnum? PricingModel { get { return GetEnum<PricingModelEnum>("pricing_model", false); } } public int? Quantity { get { return GetValue<int?>("quantity", false); } } public int? Amount { get { return GetValue<int?>("amount", false); } } public string CurrencyCode { get { return GetValue<string>("currency_code", true); } } public int? DiscountAmount { get { return GetValue<int?>("discount_amount", false); } } public string Description { get { return GetValue<string>("description", false); } } public EntityTypeEnum EntityType { get { return GetEnum<EntityTypeEnum>("entity_type", true); } } public string EntityId { get { return GetValue<string>("entity_id", false); } } public bool IsVoided { get { return GetValue<bool>("is_voided", true); } } public DateTime? VoidedAt { get { return GetDateTime("voided_at", false); } } public string UnitAmountInDecimal { get { return GetValue<string>("unit_amount_in_decimal", false); } } public string QuantityInDecimal { get { return GetValue<string>("quantity_in_decimal", false); } } public string AmountInDecimal { get { return GetValue<string>("amount_in_decimal", false); } } public List<UnbilledChargeTier> Tiers { get { return GetResourceList<UnbilledChargeTier>("tiers"); } } public bool Deleted { get { return GetValue<bool>("deleted", true); } } #endregion #region Requests public class CreateRequest : EntityRequest<CreateRequest> { public CreateRequest(string url, HttpMethod method) : base(url, method) { } public CreateRequest SubscriptionId(string subscriptionId) { m_params.Add("subscription_id", subscriptionId); return this; } public CreateRequest CurrencyCode(string currencyCode) { m_params.AddOpt("currency_code", currencyCode); return this; } public CreateRequest ItemPriceItemPriceId(int index, string itemPriceItemPriceId) { m_params.AddOpt("item_prices[item_price_id][" + index + "]", itemPriceItemPriceId); return this; } public CreateRequest ItemPriceQuantity(int index, int itemPriceQuantity) { m_params.AddOpt("item_prices[quantity][" + index + "]", itemPriceQuantity); return this; } public CreateRequest ItemPriceQuantityInDecimal(int index, string itemPriceQuantityInDecimal) { m_params.AddOpt("item_prices[quantity_in_decimal][" + index + "]", itemPriceQuantityInDecimal); return this; } public CreateRequest ItemPriceUnitPrice(int index, int itemPriceUnitPrice) { m_params.AddOpt("item_prices[unit_price][" + index + "]", itemPriceUnitPrice); return this; } public CreateRequest ItemPriceUnitPriceInDecimal(int index, string itemPriceUnitPriceInDecimal) { m_params.AddOpt("item_prices[unit_price_in_decimal][" + index + "]", itemPriceUnitPriceInDecimal); return this; } public CreateRequest ItemPriceDateFrom(int index, long itemPriceDateFrom) { m_params.AddOpt("item_prices[date_from][" + index + "]", itemPriceDateFrom); return this; } public CreateRequest ItemPriceDateTo(int index, long itemPriceDateTo) { m_params.AddOpt("item_prices[date_to][" + index + "]", itemPriceDateTo); return this; } public CreateRequest ItemTierItemPriceId(int index, string itemTierItemPriceId) { m_params.AddOpt("item_tiers[item_price_id][" + index + "]", itemTierItemPriceId); return this; } public CreateRequest ItemTierStartingUnit(int index, int itemTierStartingUnit) { m_params.AddOpt("item_tiers[starting_unit][" + index + "]", itemTierStartingUnit); return this; } public CreateRequest ItemTierEndingUnit(int index, int itemTierEndingUnit) { m_params.AddOpt("item_tiers[ending_unit][" + index + "]", itemTierEndingUnit); return this; } public CreateRequest ItemTierPrice(int index, int itemTierPrice) { m_params.AddOpt("item_tiers[price][" + index + "]", itemTierPrice); return this; } public CreateRequest ItemTierStartingUnitInDecimal(int index, string itemTierStartingUnitInDecimal) { m_params.AddOpt("item_tiers[starting_unit_in_decimal][" + index + "]", itemTierStartingUnitInDecimal); return this; } public CreateRequest ItemTierEndingUnitInDecimal(int index, string itemTierEndingUnitInDecimal) { m_params.AddOpt("item_tiers[ending_unit_in_decimal][" + index + "]", itemTierEndingUnitInDecimal); return this; } public CreateRequest ItemTierPriceInDecimal(int index, string itemTierPriceInDecimal) { m_params.AddOpt("item_tiers[price_in_decimal][" + index + "]", itemTierPriceInDecimal); return this; } public CreateRequest ChargeAmount(int index, int chargeAmount) { m_params.AddOpt("charges[amount][" + index + "]", chargeAmount); return this; } public CreateRequest ChargeAmountInDecimal(int index, string chargeAmountInDecimal) { m_params.AddOpt("charges[amount_in_decimal][" + index + "]", chargeAmountInDecimal); return this; } public CreateRequest ChargeDescription(int index, string chargeDescription) { m_params.AddOpt("charges[description][" + index + "]", chargeDescription); return this; } public CreateRequest ChargeTaxable(int index, bool chargeTaxable) { m_params.AddOpt("charges[taxable][" + index + "]", chargeTaxable); return this; } public CreateRequest ChargeTaxProfileId(int index, string chargeTaxProfileId) { m_params.AddOpt("charges[tax_profile_id][" + index + "]", chargeTaxProfileId); return this; } public CreateRequest ChargeAvalaraTaxCode(int index, string chargeAvalaraTaxCode) { m_params.AddOpt("charges[avalara_tax_code][" + index + "]", chargeAvalaraTaxCode); return this; } public CreateRequest ChargeHsnCode(int index, string chargeHsnCode) { m_params.AddOpt("charges[hsn_code][" + index + "]", chargeHsnCode); return this; } public CreateRequest ChargeTaxjarProductCode(int index, string chargeTaxjarProductCode) { m_params.AddOpt("charges[taxjar_product_code][" + index + "]", chargeTaxjarProductCode); return this; } public CreateRequest ChargeAvalaraSaleType(int index, ChargeBee.Models.Enums.AvalaraSaleTypeEnum chargeAvalaraSaleType) { m_params.AddOpt("charges[avalara_sale_type][" + index + "]", chargeAvalaraSaleType); return this; } public CreateRequest ChargeAvalaraTransactionType(int index, int chargeAvalaraTransactionType) { m_params.AddOpt("charges[avalara_transaction_type][" + index + "]", chargeAvalaraTransactionType); return this; } public CreateRequest ChargeAvalaraServiceType(int index, int chargeAvalaraServiceType) { m_params.AddOpt("charges[avalara_service_type][" + index + "]", chargeAvalaraServiceType); return this; } public CreateRequest ChargeDateFrom(int index, long chargeDateFrom) { m_params.AddOpt("charges[date_from][" + index + "]", chargeDateFrom); return this; } public CreateRequest ChargeDateTo(int index, long chargeDateTo) { m_params.AddOpt("charges[date_to][" + index + "]", chargeDateTo); return this; } } public class InvoiceUnbilledChargesRequest : EntityRequest<InvoiceUnbilledChargesRequest> { public InvoiceUnbilledChargesRequest(string url, HttpMethod method) : base(url, method) { } public InvoiceUnbilledChargesRequest SubscriptionId(string subscriptionId) { m_params.AddOpt("subscription_id", subscriptionId); return this; } public InvoiceUnbilledChargesRequest CustomerId(string customerId) { m_params.AddOpt("customer_id", customerId); return this; } } public class UnbilledChargeListRequest : ListRequestBase<UnbilledChargeListRequest> { public UnbilledChargeListRequest(string url) : base(url) { } public UnbilledChargeListRequest IncludeDeleted(bool includeDeleted) { m_params.AddOpt("include_deleted", includeDeleted); return this; } public UnbilledChargeListRequest IsVoided(bool isVoided) { m_params.AddOpt("is_voided", isVoided); return this; } public StringFilter<UnbilledChargeListRequest> SubscriptionId() { return new StringFilter<UnbilledChargeListRequest>("subscription_id", this).SupportsMultiOperators(true).SupportsPresenceOperator(true); } public StringFilter<UnbilledChargeListRequest> CustomerId() { return new StringFilter<UnbilledChargeListRequest>("customer_id", this).SupportsMultiOperators(true).SupportsPresenceOperator(true); } } public class InvoiceNowEstimateRequest : EntityRequest<InvoiceNowEstimateRequest> { public InvoiceNowEstimateRequest(string url, HttpMethod method) : base(url, method) { } public InvoiceNowEstimateRequest SubscriptionId(string subscriptionId) { m_params.AddOpt("subscription_id", subscriptionId); return this; } public InvoiceNowEstimateRequest CustomerId(string customerId) { m_params.AddOpt("customer_id", customerId); return this; } } #endregion public enum EntityTypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "plan_setup")] PlanSetup, [EnumMember(Value = "plan")] Plan, [EnumMember(Value = "addon")] Addon, [EnumMember(Value = "adhoc")] Adhoc, [EnumMember(Value = "plan_item_price")] PlanItemPrice, [EnumMember(Value = "addon_item_price")] AddonItemPrice, [EnumMember(Value = "charge_item_price")] ChargeItemPrice, } #region Subclasses public class UnbilledChargeTier : Resource { public int StartingUnit { get { return GetValue<int>("starting_unit", true); } } public int? EndingUnit { get { return GetValue<int?>("ending_unit", false); } } public int QuantityUsed { get { return GetValue<int>("quantity_used", true); } } public int UnitAmount { get { return GetValue<int>("unit_amount", true); } } public string StartingUnitInDecimal { get { return GetValue<string>("starting_unit_in_decimal", false); } } public string EndingUnitInDecimal { get { return GetValue<string>("ending_unit_in_decimal", false); } } public string QuantityUsedInDecimal { get { return GetValue<string>("quantity_used_in_decimal", false); } } public string UnitAmountInDecimal { get { return GetValue<string>("unit_amount_in_decimal", false); } } } #endregion } }
using System.Data; using NUnit.Framework; using System.Threading.Tasks; using System.Collections.Generic; namespace SequelocityDotNet.Tests.SqlServer.DatabaseCommandExtensionsTests { [TestFixture] public class ExecuteToMapAsyncTests { public class SuperHero { public long SuperHeroId; public string SuperHeroName; } [Test] public void Should_Call_The_DataRecordCall_Action_For_Each_Record_In_The_Result_Set() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; // Act var superHeroesTask = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ) .ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ); // Assert Assert.IsInstanceOf<Task<List<SuperHero>>>(superHeroesTask); Assert.That(superHeroesTask.Result.Count == 2); } [Test] public void Should_Null_The_DbCommand_By_Default() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ); // Act databaseCommand.ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ) .Wait(); // Block until the task completes. // Assert Assert.IsNull( databaseCommand.DbCommand ); } [Test] public void Should_Keep_The_Database_Connection_Open_If_keepConnectionOpen_Parameter_Was_True() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ); // Act databaseCommand.ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; }, true ) .Wait(); // Block until the task completes. // Assert Assert.That( databaseCommand.DbCommand.Connection.State == ConnectionState.Open ); // Cleanup databaseCommand.Dispose(); } [Test] public void Should_Call_The_DatabaseCommandPreExecuteEventHandler() { // Arrange bool wasPreExecuteEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPreExecuteEventHandlers.Add( command => wasPreExecuteEventHandlerCalled = true ); // Act Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( "SELECT 1 as SuperHeroId, 'Superman' as SuperHeroName" ) .ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ) .Wait(); // Block until the task completes. // Assert Assert.IsTrue( wasPreExecuteEventHandlerCalled ); } [Test] public void Should_Call_The_DatabaseCommandPostExecuteEventHandler() { // Arrange bool wasPostExecuteEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPostExecuteEventHandlers.Add( command => wasPostExecuteEventHandlerCalled = true ); // Act Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( "SELECT 1 as SuperHeroId, 'Superman' as SuperHeroName" ) .ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ) .Wait(); // Block until the task completes. // Assert Assert.IsTrue( wasPostExecuteEventHandlerCalled ); } [Test] public void Should_Call_The_DatabaseCommandUnhandledExceptionEventHandler() { // Arrange bool wasUnhandledExceptionEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandUnhandledExceptionEventHandlers.Add( ( exception, command ) => { wasUnhandledExceptionEventHandlerCalled = true; } ); // Act TestDelegate action = async () => await Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( "asdf;lkj" ) .ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ); // Assert Assert.Throws<System.Data.SqlClient.SqlException>( action ); Assert.IsTrue( wasUnhandledExceptionEventHandlerCalled ); } } }
namespace Microsoft.Protocols.TestSuites.MS_ADMINS { using System; using System.Web.Services.Protocols; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// Scenario 2 Test cases. Test the CreateSite, DeleteSite and GetLanguages operations error conditions. /// </summary> [TestClass] public class S02_ErrorConditions : TestClassBase { #region Variables /// <summary> /// An instance of IMSADMINSAdapter. /// </summary> private IMS_ADMINSAdapter adminsAdapter; #endregion #region Test Suite Initialization /// <summary> /// Initialize the test suite. /// </summary> /// <param name="testContext">The test context instance</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { // Setup test site. TestClassBase.Initialize(testContext); } /// <summary> /// Reset the test environment. /// </summary> [ClassCleanup] public static void ClassCleanup() { // Cleanup test site, must be called to ensure closing of logs. TestClassBase.Cleanup(); } #endregion #region Test Cases /// <summary> /// This test case is used to create the specified site collection with URL exceeding the max length. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC01_CreateSiteFailed_UrlExceedMaxLength() { bool isSoapFaultReturn = false; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string urlExceedMaxLength = TestSuiteBase.GenerateUrlWithoutPort(129); string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method to create a site collection with Url exceeding the max length. this.adminsAdapter.CreateSite(urlExceedMaxLength, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException) { isSoapFaultReturn = true; } Site.Log.Add(LogEntryKind.Debug, "If the Soap fault returned when set the length of Url exceeding 128 characters, MS-ADMINS_R1028 can be verified."); // Verify MS-ADMINS requirement: MS-ADMINS_R1028 Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 1028, @"[In CreateSiteSoapIn]If Url's length not including ""http://ServerName"" exceeds 128 characters, the server MUST return a SOAP fault."); } /// <summary> /// This test case is used to create the specified site collection with URL server name invalid. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC02_CreateSiteFailed_UrlServerNameInvalid() { bool isSoapFaultReturn = false; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string urlServerNameInvalid = Common.GetConfigurationPropertyValue("TransportType", this.Site) + "://" + TestSuiteBase.GenerateRandomString(5) + "/sites/" + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method to create a site collection with invalid Url server name. this.adminsAdapter.CreateSite(urlServerNameInvalid, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException) { isSoapFaultReturn = true; } Site.Log.Add(LogEntryKind.Debug, "If the Soap fault returned when set the server name invalid, MS-ADMINS_R1024 can be verified."); // Verify MS-ADMINS requirement: MS-ADMINS_R1024 Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 1024, @"[In CreateSiteSoapIn]If ServerName in the URL is invalid, the server MUST return a SOAP fault."); } /// <summary> /// This test case is used to create the specified site collection with invalid port number. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC03_CreateSiteFailed_UrlPortNumberInvalid() { bool isSoapFaultReturn = false; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string urlPortNumberInvalid = Common.GetConfigurationPropertyValue("TransportType", this.Site) + "://" + Common.GetConfigurationPropertyValue("SutComputerName", this.Site) + ":" + Common.GetConfigurationPropertyValue("InvalidPortNumber", this.Site) + "/sites/" + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method to create a site collection with invalid port number. this.adminsAdapter.CreateSite(urlPortNumberInvalid, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException) { isSoapFaultReturn = true; } Site.Log.Add(LogEntryKind.Debug, "If the Soap fault returned when set the port number invalid, MS-ADMINS_R1025 can be verified."); // Verify MS-ADMINS requirement: MS-ADMINS_R1025 Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 1025, @"[In CreateSiteSoapIn]If the PortNumber in the URL given an invalid value, the server MUST return a SOAP fault."); } /// <summary> /// This test case is used to create the specified site collection with invalid URL format. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC04_CreateSiteFailed_UrlInvalidFormat() { bool isSoapFaultReturn = false; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string urlInvalidFormat = Common.GetConfigurationPropertyValue("TransportType", this.Site) + "://" + "sites/" + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method to create a site collection with invalid Url format. this.adminsAdapter.CreateSite(urlInvalidFormat, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException) { isSoapFaultReturn = true; } Site.Log.Add(LogEntryKind.Debug, "If the Soap fault returned when set the url format invalid, MS-ADMINS_R1026 can be verified."); // Verify MS-ADMINS requirement: MS-ADMINS_R1026 Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 1026, @"[In CreateSiteSoapIn]If the URL does not comply with either of the two formats: http://ServerName:PortNumber/sites/SiteCollectionName or http://ServerName/sites/SiteCollectionName, the server MUST return a SOAP fault."); } /// <summary> /// This test case is used to create the specified site collection with URL already existed. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC05_CreateSiteFailed_UrlExisted() { bool isSoapFaultReturn = false; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = Common.GetConfigurationPropertyValue("UrlWithOutPort", this.Site) + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); // Call CreateSite method to create a site collection. string result = this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); Site.Assert.IsTrue(Uri.IsWellFormedUriString(result, UriKind.Absolute), "Create site should succeed."); string titleSnd = TestSuiteBase.GenerateUniqueSiteTitle(); string descriptionSnd = TestSuiteBase.GenerateRandomString(30); string webTemplateSnd = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLoginSnd = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerNameSnd = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmailSnd = TestSuiteBase.GenerateEmail(20); string portalUrlSnd = TestSuiteBase.GeneratePortalUrl(20); string portalNameSnd = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method again to create a site collection with existed Url. this.adminsAdapter.CreateSite(url, titleSnd, descriptionSnd, lcid, webTemplateSnd, ownerLoginSnd, ownerNameSnd, ownerEmailSnd, portalUrlSnd, portalNameSnd); } catch (SoapException) { isSoapFaultReturn = true; } Site.Log.Add(LogEntryKind.Debug, "If the Soap fault returned when give an existed Url, MS-ADMINS_R17 can be verified."); // Verify MS-ADMINS requirement: MS-ADMINS_R17 Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 17, @"[In CreateSiteSoapIn][The request message is governed by the following rules:]If the URL already exists, the server MUST return a SOAP fault."); // Call DeleteSite method to delete the site collection created in above steps. this.adminsAdapter.DeleteSite(result); } /// <summary> /// This test case is used to create the specified site collection with URL absent. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC06_CreateSiteFailed_UrlAbsent() { bool isSoapFaultReturn = false; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method to create a site collection with Url absent. this.adminsAdapter.CreateSite(null, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException) { isSoapFaultReturn = true; } Site.Log.Add(LogEntryKind.Debug, "If the Soap fault returned when Url absent, MS-ADMINS_R14 and MS-ADMINS_R2041 can be verified."); // Verify MS-ADMINS requirement: MS-ADMINS_R14 Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 14, @"[In CreateSiteSoapIn][The request message is governed by the following rules:]If the URL is missing, the server MUST return a SOAP fault."); Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 2041, @"[In CreateSite]If it[Url] is missing or absent, the server MUST return a SOAP fault."); } /// <summary> /// This test case is used to create the specified site collection with URL empty. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC07_CreateSiteFailed_UrlEmpty() { bool isSoapFaultReturn = false; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = string.Empty; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method to create a site collection with Url empty. this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException) { isSoapFaultReturn = true; } Site.Log.Add(LogEntryKind.Debug, "If the Soap fault returned when Url empty, MS-ADMINS_R1027 can be verified."); // Verify MS-ADMINS requirement: MS-ADMINS_R1027 Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 1027, @"[In CreateSiteSoapIn]If the URL is empty, the server MUST return a SOAP fault."); } /// <summary> /// This test case is used to create the specified site collection without installed LCID. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC08_CreateSiteFailed_LcidNotInstalled() { string strErrorCode = string.Empty; int notInstalledLcid = int.Parse(Common.GetConfigurationPropertyValue("NotInstalledLCID", this.Site)); string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = TestSuiteBase.GenerateUrlPrefixWithPortNumber() + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method to create a site collection with a not installed LCID. this.adminsAdapter.CreateSite(url, title, description, notInstalledLcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException exp) { strErrorCode = Common.ExtractErrorCodeFromSoapFault(exp); } // If the returned error code equals to 0x8102005e, then MS-ADMINS_R18 can be captured. Site.CaptureRequirementIfAreEqual<string>( "0x8102005e", strErrorCode, 18002, @"[In CreateSiteSoapIn] If the LCID is invalid [or not installed], then the server MUST return a SOAP fault with error code 0x8102005e."); } /// <summary> /// This test case is used to create the specified site collection with an invalid LCID. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC09_CreateSiteFailed_LcidInvalid() { string strErrorCode = string.Empty; int invalidLcid = TestSuiteBase.GenerateRandomNumber(0, 99); string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = TestSuiteBase.GenerateUrlPrefixWithPortNumber() + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite to create a site collection with an invalid LCID. this.adminsAdapter.CreateSite(url, title, description, invalidLcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException exp) { strErrorCode = Common.ExtractErrorCodeFromSoapFault(exp); Site.Log.Add(LogEntryKind.Debug, "Soap exception returned, it means the create site operation failed with invalid LCID inputting, the message is: {0}", exp.Message); } // If the returned error code equals to 0x8102005e, then MS-ADMINS_R18 can be captured. Site.CaptureRequirementIfAreEqual<string>( "0x8102005e", strErrorCode, 18, @"[In CreateSiteSoapIn] If the LCID is invalid [or not installed], then the server MUST return a SOAP fault with error code 0x8102005e."); } /// <summary> /// This test case is used to create the specified site collection with invalid WebTemplate. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC10_CreateSiteFailed_WebTemplateInvalid() { bool isSoapFaultReturn = false; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = TestSuiteBase.GenerateUrlPrefixWithPortNumber() + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplateInvalid = TestSuiteBase.GenerateRandomString(5); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method to create a site collection with invalid WebTemplate. this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplateInvalid, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException) { isSoapFaultReturn = true; } // If a SOAP fault is returned, then MS-ADMINS_R19 can be captured. Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 19, @"[In CreateSiteSoapIn]If WebTemplate is not empty, and if it is not available in the list of templates and it is not a custom template, then the server MUST return a SOAP fault."); } /// <summary> /// This test case is used to create the specified site collection with owner login name not existed. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC11_CreateSiteFailed_OwnerLoginAccountNotExisted() { string strErrorCode = string.Empty; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = TestSuiteBase.GenerateUrlPrefixWithPortNumber() + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLoginNotExisted = TestSuiteBase.GenerateRandomString(10); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call the CreateSite method to create a site collection with owner login name not existed. this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplate, ownerLoginNotExisted, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException exp) { strErrorCode = Common.ExtractErrorCodeFromSoapFault(exp); } // If the returned error code equals to 0x80131600, then MS-ADMINS_R1022 can be captured. Site.CaptureRequirementIfAreEqual<string>( "0x80131600", strErrorCode, 1022, @"[In CreateSiteSoapIn]If OwnerLogin is not an existing domain user account, the server MUST return a SOAP fault with error code 0x80131600."); } /// <summary> /// This test case is used to create the specified site collection without owner login. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC12_CreateSiteFailed_OwnerLoginAbsent() { bool isSoapFaultReturn = false; // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = TestSuiteBase.GenerateUrlPrefixWithPortNumber() + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite method to create a site collection without owner login. this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplate, null, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException) { isSoapFaultReturn = true; } // If a SOAP fault is returned, then MS-ADMINS_R2050 can be captured. Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 2050, @"[In CreateSite]If it[OwnerLogin] is missing, the server MUST return a SOAP fault."); isSoapFaultReturn = false; try { // Call CreateSite method to create a site collection with empty owner login. this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplate, string.Empty, ownerName, ownerEmail, portalUrl, portalName); } catch (SoapException) { isSoapFaultReturn = true; } // If a SOAP fault is returned, then MS-ADMINS_R2050 can be captured. Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 2050001, @"[In CreateSite]If it[OwnerLogin] is empty, the server MUST return a SOAP fault."); } /// <summary> /// This test case is used to create the specified site collection with empty ownerLogin. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC13_CreateSiteFailed_OwnerLoginEmpty() { // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = TestSuiteBase.GenerateUrlPrefixWithPortNumber() + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLoginEmpty = string.Empty; string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); try { // Call CreateSite to create a site collection with empty ownerLogin. string result = this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplate, ownerLoginEmpty, ownerName, ownerEmail, portalUrl, portalName); Site.Assert.IsFalse(Uri.IsWellFormedUriString(result, UriKind.Absolute), "Create site operation should fail."); } catch (SoapException) { Site.Log.Add(LogEntryKind.Debug, "Create site operation should fail with empty OwnerLogin."); } } /// <summary> /// This test case is used to delete the site without URL specified. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC14_DeleteSiteFailed_UrlMissing() { // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); // Call CreateSite to create a site collection without port number. int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = Common.GetConfigurationPropertyValue("UrlWithOutPort", this.Site) + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); string result = this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); Site.Assert.IsTrue(Uri.IsWellFormedUriString(result, UriKind.Absolute), "Create site should succeed."); bool isSoapFaultReturn = false; try { // Call DeleteSite method without URL specified. this.adminsAdapter.DeleteSite(null); } catch (SoapException) { isSoapFaultReturn = true; } // If a SOAP fault is returned, then MS-ADMINS_R121 can be captured. Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 121, @"[In DeleteSiteSoapIn][The request message is governed by the following rules:] If the URL is missing, the server MUST return a SOAP fault."); // Call DeleteSite method to delete the site collection created in above steps. this.adminsAdapter.DeleteSite(result); } /// <summary> /// This test case is used to delete the site collection with invalid URL (using server name without port number as an example). /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC15_DeleteSiteFailed_UrlNameInvalid() { // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); // Call CreateSite method to create a site collection without port number. int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = Common.GetConfigurationPropertyValue("UrlWithOutPort", this.Site) + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); string result = this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); Site.Assert.IsTrue(Uri.IsWellFormedUriString(result, UriKind.Absolute), "Create site should succeed."); bool isSoapFaultReturn = false; try { string invalidUrl = Common.GetConfigurationPropertyValue("TransportType", this.Site) + TestSuiteBase.GenerateRandomString(5) + "/sites/" + title; // Call DeleteSite method with invalid URL. this.adminsAdapter.DeleteSite(invalidUrl); } catch (SoapException) { isSoapFaultReturn = true; } // If a SOAP fault is returned, then MS-ADMINS_R122 can be captured. Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 122, @"[In DeleteSiteSoapIn][The request message is governed by the following rules:] If the URL is not valid, the server MUST return a SOAP fault."); // Call DeleteSite to delete the site collection created in above steps. this.adminsAdapter.DeleteSite(result); } /// <summary> /// This test case is used to delete the site collection with a nonexistent URL. /// </summary> [TestCategory("MSADMINS"), TestMethod()] public void MSADMINS_S02_TC16_DeleteSiteFailed_UrlNotExist() { // Call GetLanguages method to obtain LCID values used in the protocol server deployment. GetLanguagesResponseGetLanguagesResult lcids = this.adminsAdapter.GetLanguages(); Site.Assert.IsNotNull(lcids, "Get languages should succeed and a list of LCIDs should return. If no LCID returns the get languages method is failed."); // Call CreateSite method to create a site collection without port number. int lcid = lcids.Languages[0]; string title = TestSuiteBase.GenerateUniqueSiteTitle(); string url = Common.GetConfigurationPropertyValue("UrlWithOutPort", this.Site) + title; string description = TestSuiteBase.GenerateRandomString(20); string webTemplate = Common.GetConfigurationPropertyValue("CustomizedTemplate", this.Site); string ownerLogin = Common.GetConfigurationPropertyValue("OwnerLogin", this.Site); string ownerName = TestSuiteBase.GenerateUniqueOwnerName(); string ownerEmail = TestSuiteBase.GenerateEmail(20); string portalUrl = TestSuiteBase.GeneratePortalUrl(20); string portalName = TestSuiteBase.GenerateUniquePortalName(); string result = this.adminsAdapter.CreateSite(url, title, description, lcid, webTemplate, ownerLogin, ownerName, ownerEmail, portalUrl, portalName); Site.Assert.IsTrue(Uri.IsWellFormedUriString(result, UriKind.Absolute), "Create site should succeed."); // Call DeleteSite method to delete the site collection created in above steps. this.adminsAdapter.DeleteSite(result); bool isSoapFaultReturn = false; try { // Call DeleteSite method with a nonexistent URL. this.adminsAdapter.DeleteSite(result); } catch (SoapException) { isSoapFaultReturn = true; } // If a SOAP fault is returned, then MS-ADMINS_R123 can be captured. Site.CaptureRequirementIfIsTrue( isSoapFaultReturn, 123, @"[In DeleteSiteSoapIn][The request message is governed by the following rules:] If the URL does not exist, the server MUST return a SOAP fault."); } #endregion #region Test Case Initialization and Cleanup /// <summary> /// Overrides TestClassBase's TestInitialize(). /// </summary> [TestInitialize] public void TestCaseInitialize() { // Initialization of adapter. this.adminsAdapter = Site.GetAdapter<IMS_ADMINSAdapter>(); Common.CheckCommonProperties(this.Site, true); // Initialize the TestSuiteBase TestSuiteBase.Initialize(this.Site); } /// <summary> /// Overrides TestClassBase's TestCleanup(). /// </summary> [TestCleanup] public void TestCaseCleanup() { // Resetting of adapter. this.adminsAdapter.Reset(); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.IO.Compression.Tests { public partial class ZipTest { private static void ConstructorThrows<TException>(Func<ZipArchive> constructor, string Message = "") where TException : Exception { Assert.Throws<TException>(() => { using (ZipArchive archive = constructor()) { } }); } [Fact] public void InvalidInstanceMethods() { string zipFileName = CreateTempCopyFile(zfile("normal.zip")); using (ZipArchive archive = ZipFile.Open(zipFileName, ZipArchiveMode.Update)) { //non-existent entry Assert.True(null == archive.GetEntry("nonExistentEntry")); //null/empty string Assert.Throws<ArgumentNullException>(() => archive.GetEntry(null)); ZipArchiveEntry entry = archive.GetEntry("first.txt"); //null/empty string Assert.Throws<ArgumentException>(() => archive.CreateEntry("")); Assert.Throws<ArgumentNullException>(() => archive.CreateEntry(null)); } } [Fact] public void InvalidConstructors() { //out of range enum values ConstructorThrows<ArgumentOutOfRangeException>(() => ZipFile.Open("bad file", (ZipArchiveMode)(10))); } [Fact] public void InvalidFiles() { ConstructorThrows<InvalidDataException>(() => ZipFile.OpenRead(bad("EOCDmissing.zip"))); ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("EOCDmissing.zip"), ZipArchiveMode.Update)); ConstructorThrows<InvalidDataException>(() => ZipFile.OpenRead(bad("CDoffsetOutOfBounds.zip"))); ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("CDoffsetOutOfBounds.zip"), ZipArchiveMode.Update)); using (ZipArchive archive = ZipFile.OpenRead(bad("CDoffsetInBoundsWrong.zip"))) { Assert.Throws<InvalidDataException>(() => { var x = archive.Entries; }); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("CDoffsetInBoundsWrong.zip"), ZipArchiveMode.Update)); using (ZipArchive archive = ZipFile.OpenRead(bad("numberOfEntriesDifferent.zip"))) { Assert.Throws<InvalidDataException>(() => { var x = archive.Entries; }); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("numberOfEntriesDifferent.zip"), ZipArchiveMode.Update)); //read mode on empty file ConstructorThrows<InvalidDataException>(() => new ZipArchive(new MemoryStream())); //offset out of bounds using (ZipArchive archive = ZipFile.OpenRead(bad("localFileOffsetOutOfBounds.zip"))) { ZipArchiveEntry e = archive.Entries[0]; Assert.Throws<InvalidDataException>(() => e.Open()); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("localFileOffsetOutOfBounds.zip"), ZipArchiveMode.Update)); //compressed data offset + compressed size out of bounds using (ZipArchive archive = ZipFile.OpenRead(bad("compressedSizeOutOfBounds.zip"))) { ZipArchiveEntry e = archive.Entries[0]; Assert.Throws<InvalidDataException>(() => e.Open()); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("compressedSizeOutOfBounds.zip"), ZipArchiveMode.Update)); //signature wrong using (ZipArchive archive = ZipFile.OpenRead(bad("localFileHeaderSignatureWrong.zip"))) { ZipArchiveEntry e = archive.Entries[0]; Assert.Throws<InvalidDataException>(() => e.Open()); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("localFileHeaderSignatureWrong.zip"), ZipArchiveMode.Update)); } [Fact] public void UnsupportedCompression() { //lzma compression method UnsupportedCompressionRoutine(bad("LZMA.zip"), true); UnsupportedCompressionRoutine(bad("invalidDeflate.zip"), false); } private void UnsupportedCompressionRoutine(string filename, Boolean throwsOnOpen) { using (ZipArchive archive = ZipFile.OpenRead(filename)) { ZipArchiveEntry e = archive.Entries[0]; if (throwsOnOpen) { Assert.Throws<InvalidDataException>(() => e.Open()); } else { using (Stream s = e.Open()) { Assert.Throws<InvalidDataException>(() => s.ReadByte()); } } } string updatedCopyName = CreateTempCopyFile(filename); string name; Int64 length, compressedLength; DateTimeOffset lastWriteTime; using (ZipArchive archive = ZipFile.Open(updatedCopyName, ZipArchiveMode.Update)) { ZipArchiveEntry e = archive.Entries[0]; name = e.FullName; lastWriteTime = e.LastWriteTime; length = e.Length; compressedLength = e.CompressedLength; Assert.Throws<InvalidDataException>(() => e.Open()); } //make sure that update mode preserves that unreadable file using (ZipArchive archive = ZipFile.Open(updatedCopyName, ZipArchiveMode.Update)) { ZipArchiveEntry e = archive.Entries[0]; Assert.Equal(name, e.FullName); Assert.Equal(lastWriteTime, e.LastWriteTime); Assert.Equal(length, e.Length); Assert.Equal(compressedLength, e.CompressedLength); Assert.Throws<InvalidDataException>(() => e.Open()); } } [Fact] public void InvalidDates() { using (ZipArchive archive = ZipFile.OpenRead(bad("invaliddate.zip"))) { Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime); } FileInfo fileWithBadDate = new FileInfo(GetTmpFilePath()); fileWithBadDate.Create().Dispose(); fileWithBadDate.LastWriteTimeUtc = new DateTime(1970, 1, 1, 1, 1, 1); string archivePath = GetTmpFilePath(); using (FileStream output = File.Open(archivePath, FileMode.Create)) using (ZipArchive archive = new ZipArchive(output, ZipArchiveMode.Create)) { archive.CreateEntryFromFile(fileWithBadDate.FullName, "SomeEntryName"); } using (ZipArchive archive = ZipFile.OpenRead(archivePath)) { Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime); } } [Fact] public void FilesOutsideDirectory() { string archivePath = GetTmpFilePath(); using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create)) using (StreamWriter writer = new StreamWriter(archive.CreateEntry(Path.Combine("..", "entry1"), CompressionLevel.Optimal).Open())) { writer.Write("This is a test."); } Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(archivePath, GetTmpDirPath())); } [Fact] public void DirectoryEntryWithData() { string archivePath = GetTmpFilePath(); using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create)) using (StreamWriter writer = new StreamWriter(archive.CreateEntry("testdir" + Path.DirectorySeparatorChar, CompressionLevel.Optimal).Open())) { writer.Write("This is a test."); } Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(archivePath, GetTmpDirPath())); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace System.Security.Cryptography.X509Certificates { internal static partial class X509Native { /// <summary> /// Determine if a certificate has a specific property /// </summary> [SecuritySafeCritical] internal static bool HasCertificateProperty(SafeCertContextHandle certificateContext, CertificateProperty property) { Debug.Assert(certificateContext != null, "certificateContext != null"); Debug.Assert(!certificateContext.IsClosed && !certificateContext.IsInvalid, "!certificateContext.IsClosed && !certificateContext.IsInvalid"); byte[] buffer = null; int bufferSize = 0; bool gotProperty = UnsafeNativeMethods.CertGetCertificateContextProperty(certificateContext, property, buffer, ref bufferSize); return gotProperty || (ErrorCode)Marshal.GetLastWin32Error() == ErrorCode.MoreData; } /// <summary> /// Get the NCrypt handle to the private key of a certificate /// or null if the private key cannot be acquired by NCrypt. /// </summary> [SecuritySafeCritical] internal static SafeNCryptKeyHandle TryAcquireCngPrivateKey(SafeCertContextHandle certificateContext) { Debug.Assert(certificateContext != null, "certificateContext != null"); Debug.Assert(!certificateContext.IsClosed && !certificateContext.IsInvalid, "!certificateContext.IsClosed && !certificateContext.IsInvalid"); bool freeKey = true; SafeNCryptKeyHandle privateKey = null; RuntimeHelpers.PrepareConstrainedRegions(); try { int keySpec = 0; if (!UnsafeNativeMethods.CryptAcquireCertificatePrivateKey(certificateContext, AcquireCertificateKeyOptions.AcquireOnlyNCryptKeys, IntPtr.Zero, out privateKey, out keySpec, out freeKey)) { return null; } return privateKey; } finally { // If we're not supposed to release they key handle, then we need to bump the reference count // on the safe handle to correspond to the reference that Windows is holding on to. This will // prevent the CLR from freeing the object handle. // // This is certainly not the ideal way to solve this problem - it would be better for // SafeNCryptKeyHandle to maintain an internal bool field that we could toggle here and // have that suppress the release when the CLR calls the ReleaseHandle override. However, that // field does not currently exist, so we'll use this hack instead. if (privateKey != null && !freeKey) { bool addedRef = false; privateKey.DangerousAddRef(ref addedRef); } } } /// <summary> /// Get an arbitrary property of a certificate /// </summary> [SecuritySafeCritical] internal static byte[] GetCertificateProperty(SafeCertContextHandle certificateContext, CertificateProperty property) { Debug.Assert(certificateContext != null, "certificateContext != null"); Debug.Assert(!certificateContext.IsClosed && !certificateContext.IsInvalid, "!certificateContext.IsClosed && !certificateContext.IsInvalid"); byte[] buffer = null; int bufferSize = 0; if (!UnsafeNativeMethods.CertGetCertificateContextProperty(certificateContext, property, buffer, ref bufferSize)) { ErrorCode errorCode = (ErrorCode)Marshal.GetLastWin32Error(); if (errorCode != ErrorCode.MoreData) { throw new CryptographicException((int)errorCode); } } buffer = new byte[bufferSize]; if (!UnsafeNativeMethods.CertGetCertificateContextProperty(certificateContext, property, buffer, ref bufferSize)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } return buffer; } /// <summary> /// Get a property of a certificate formatted as a structure /// </summary> [SecurityCritical] internal static T GetCertificateProperty<T>(SafeCertContextHandle certificateContext, CertificateProperty property) where T : struct { Debug.Assert(certificateContext != null, "certificateContext != null"); Debug.Assert(!certificateContext.IsClosed && !certificateContext.IsInvalid, "!certificateContext.IsClosed && !certificateContext.IsInvalid"); byte[] rawProperty = GetCertificateProperty(certificateContext, property); Debug.Assert(rawProperty.Length >= Marshal.SizeOf(typeof(T)), "Property did not return expected structure"); unsafe { fixed (byte* pRawProperty = &rawProperty[0]) { return (T)Marshal.PtrToStructure(new IntPtr(pRawProperty), typeof(T)); } } } /// <summary> /// Duplicate the certificate context into a safe handle /// </summary> [SecuritySafeCritical] internal static SafeCertContextHandle DuplicateCertContext(IntPtr context) { Debug.Assert(context != IntPtr.Zero); return UnsafeNativeMethods.CertDuplicateCertificateContext(context); } // Gets a SafeHandle for the X509 certificate. The caller owns the returned handle and should dispose of it. It // can be used independently of the lifetime of the original X509Certificate. [SecuritySafeCritical] internal static SafeCertContextHandle GetCertificateContext(X509Certificate certificate) { SafeCertContextHandle certificateContext = DuplicateCertContext(certificate.Handle); // Make sure to keep the X509Certificate object alive until after its certificate context is // duplicated, otherwise it could end up being closed out from underneath us before we get a // chance to duplicate the handle. GC.KeepAlive(certificate); return certificateContext; } } /// <summary> /// Native interop layer for X509 certificate and Authenticode functions. Native definitions can be /// found in wincrypt.h or msaxlapi.h /// </summary> internal static class X509Native { /// <summary> /// Flags for CertVerifyAuthenticodeLicense /// </summary> [Flags] public enum AxlVerificationFlags { None = 0x00000000, NoRevocationCheck = 0x00000001, // AXL_REVOCATION_NO_ RevocationCheckEndCertOnly = 0x00000002, // AXL_REVOCATION_ RevocationCheckEntireChain = 0x00000004, // AXL_REVOCATION_ UrlOnlyCacheRetrieval = 0x00000008, // AXL_URL_ONLY_CACHE_RETRIEVAL LifetimeSigning = 0x00000010, // AXL_LIFETIME_SIGNING TrustMicrosoftRootOnly = 0x00000020 // AXL_TRUST_MICROSOFT_ROOT_ONLY } internal const uint X509_ASN_ENCODING = 0x00000001; internal const string szOID_ECC_PUBLIC_KEY = "1.2.840.10045.2.1"; //Copied from Windows header file [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CERT_CONTEXT { internal uint dwCertEncodingType; internal IntPtr pbCertEncoded; internal uint cbCertEncoded; internal IntPtr pCertInfo; internal IntPtr hCertStore; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CERT_PUBLIC_KEY_INFO { internal CRYPT_ALGORITHM_IDENTIFIER Algorithm; internal CRYPT_BIT_BLOB PublicKey; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CERT_INFO { internal uint dwVersion; internal CRYPTOAPI_BLOB SerialNumber; internal CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; internal CRYPTOAPI_BLOB Issuer; internal FILETIME NotBefore; internal FILETIME NotAfter; internal CRYPTOAPI_BLOB Subject; internal CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; internal CRYPT_BIT_BLOB IssuerUniqueId; internal CRYPT_BIT_BLOB SubjectUniqueId; internal uint cExtension; internal IntPtr rgExtension; // PCERT_EXTENSION } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CRYPT_ALGORITHM_IDENTIFIER { [MarshalAs(UnmanagedType.LPStr)] internal string pszObjId; internal CRYPTOAPI_BLOB Parameters; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CRYPT_BIT_BLOB { internal uint cbData; internal IntPtr pbData; internal uint cUnusedBits; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CRYPTOAPI_BLOB { internal uint cbData; internal IntPtr pbData; } /// <summary> /// Flags for the CryptAcquireCertificatePrivateKey API /// </summary> internal enum AcquireCertificateKeyOptions { None = 0x00000000, AcquireOnlyNCryptKeys = 0x00040000, // CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG } /// <summary> /// Well known certificate property IDs /// </summary> internal enum CertificateProperty { KeyProviderInfo = 2, // CERT_KEY_PROV_INFO_PROP_ID KeyContext = 5, // CERT_KEY_CONTEXT_PROP_ID } /// <summary> /// Error codes returned from X509 APIs /// </summary> internal enum ErrorCode { Success = 0x00000000, // ERROR_SUCCESS MoreData = 0x000000ea, // ERROR_MORE_DATA } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_KEY_PROV_INFO { [MarshalAs(UnmanagedType.LPWStr)] internal string pwszContainerName; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszProvName; internal int dwProvType; internal int dwFlags; internal int cProvParam; internal IntPtr rgProvParam; // PCRYPT_KEY_PROV_PARAM internal int dwKeySpec; } [StructLayout(LayoutKind.Sequential)] [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public struct AXL_AUTHENTICODE_SIGNER_INFO { public int cbSize; public int dwError; public CapiNative.AlgorithmId algHash; // Each of the next fields are Unicode strings, however we need to manually marshal them since // they are allocated and freed by the native AXL code and should not have their memory handled // by the marshaller. public IntPtr pwszHash; public IntPtr pwszDescription; public IntPtr pwszDescriptionUrl; public IntPtr pChainContext; // PCERT_CHAIN_CONTEXT } [StructLayout(LayoutKind.Sequential)] [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public struct AXL_AUTHENTICODE_TIMESTAMPER_INFO { public int cbsize; public int dwError; public CapiNative.AlgorithmId algHash; public FILETIME ftTimestamp; public IntPtr pChainContext; // PCERT_CHAIN_CONTEXT } [SuppressUnmanagedCodeSecurity] [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] #pragma warning disable 618 // System.Core.dll still uses SecurityRuleSet.Level1 [SecurityCritical(SecurityCriticalScope.Everything)] #pragma warning restore 618 public static class UnsafeNativeMethods { /// <summary> /// Get the hash value of a key blob /// </summary> [DllImport("clr")] public static extern int _AxlGetIssuerPublicKeyHash(IntPtr pCertContext, [Out]out SafeAxlBufferHandle ppwszPublicKeyHash); /// <summary> /// Release any resources used to create an authenticode signer info structure /// </summary> [DllImport("clr")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static extern int CertFreeAuthenticodeSignerInfo(ref AXL_AUTHENTICODE_SIGNER_INFO pSignerInfo); /// <summary> /// Release any resources used to create an authenticode timestamper info structure /// </summary> [DllImport("clr")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static extern int CertFreeAuthenticodeTimestamperInfo(ref AXL_AUTHENTICODE_TIMESTAMPER_INFO pTimestamperInfo); /// <summary> /// Verify the authenticode signature on a manifest /// </summary> /// <remarks> /// Code must have permission to open and enumerate certificate stores to use this API /// </remarks> [DllImport("clr")] public static extern int CertVerifyAuthenticodeLicense(ref CapiNative.CRYPTOAPI_BLOB pLicenseBlob, AxlVerificationFlags dwFlags, [In, Out] ref AXL_AUTHENTICODE_SIGNER_INFO pSignerInfo, [In, Out] ref AXL_AUTHENTICODE_TIMESTAMPER_INFO pTimestamperInfo); } } }
namespace EIDSS.Reports.Parameterized.Human.AJ.Reports { partial class VetLabReport { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VetLabReport)); DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary(); DevExpress.XtraReports.UI.XRSummary xrSummary2 = new DevExpress.XtraReports.UI.XRSummary(); DevExpress.XtraReports.UI.XRSummary xrSummary3 = new DevExpress.XtraReports.UI.XRSummary(); this.VetReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.SignatureTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.DateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.FooterDataTable = new DevExpress.XtraReports.UI.XRTable(); this.FooterDataRow = new DevExpress.XtraReports.UI.XRTableRow(); this.FooterTotalCell = new DevExpress.XtraReports.UI.XRTableCell(); this.AmountOfSpecimenTotalCell = new DevExpress.XtraReports.UI.XRTableCell(); this.TestCountTotalCell_1 = new DevExpress.XtraReports.UI.XRTableCell(); this.PositiveResultsTotalCell = new DevExpress.XtraReports.UI.XRTableCell(); this.VetDetail = new DevExpress.XtraReports.UI.DetailBand(); this.DetailsDataTable = new DevExpress.XtraReports.UI.XRTable(); this.DetailsDataRow = new DevExpress.XtraReports.UI.XRTableRow(); this.RowNumberCell = new DevExpress.XtraReports.UI.XRTableCell(); this.DiseaseCell = new DevExpress.XtraReports.UI.XRTableCell(); this.OIECell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpeciesCell = new DevExpress.XtraReports.UI.XRTableCell(); this.AmountOfSpecimenCell = new DevExpress.XtraReports.UI.XRTableCell(); this.TestCountCell_1 = new DevExpress.XtraReports.UI.XRTableCell(); this.PositiveResultsCell = new DevExpress.XtraReports.UI.XRTableCell(); this.VetReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderDataTable = new DevExpress.XtraReports.UI.XRTable(); this.HeaderDataRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.UnderRowNumberHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderDiseaseHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderOIEHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderSpeciesHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderAmountOfSpecimenHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.TestsConductedHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.UnderPositiveResultsHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderDataRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.RowNumberHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.DiseaseHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.OIEHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpeciesHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.AmountOfSpecimenHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.TestNameHeaderCell_1 = new DevExpress.XtraReports.UI.XRTableCell(); this.PositiveResultsHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.RecipientHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.SentByCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.ForDateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.HeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrPictureBox1 = new DevExpress.XtraReports.UI.XRPictureBox(); this.GroupHeaderDiagnosis = new DevExpress.XtraReports.UI.GroupHeaderBand(); this.GroupFooterDiagnosis = new DevExpress.XtraReports.UI.GroupFooterBand(); this.GroupHeaderLine = new DevExpress.XtraReports.UI.GroupHeaderBand(); this.xrLine2 = new DevExpress.XtraReports.UI.XRLine(); this.GroupFooterLine = new DevExpress.XtraReports.UI.GroupFooterBand(); this.xrLine1 = new DevExpress.XtraReports.UI.XRLine(); this.m_DataAdapter = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.VetLabReportDataSetTableAdapters.VetLabAdapter(); this.m_DataSet = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.VetLabReportDataSet(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.FooterDataTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.DetailsDataTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderDataTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // resources.ApplyResources(this.cellLanguage, "cellLanguage"); this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // resources.ApplyResources(this.Detail, "Detail"); this.Detail.Expanded = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.Expanded = false; this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Expanded = false; // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; this.xrPageInfo1.StylePriority.UseFont = false; // // cellReportHeader // resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; // // cellBaseSite // resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; // // cellBaseCountry // resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry"); // // cellBaseLeftHeader // resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // VetReport // this.VetReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.ReportFooter, this.VetDetail, this.VetReportHeader, this.GroupHeaderDiagnosis, this.GroupFooterDiagnosis, this.GroupHeaderLine, this.GroupFooterLine}); this.VetReport.DataAdapter = this.m_DataAdapter; this.VetReport.DataMember = "spRepVetLabReportAZ"; this.VetReport.DataSource = this.m_DataSet; resources.ApplyResources(this.VetReport, "VetReport"); this.VetReport.Level = 0; this.VetReport.Name = "VetReport"; // // ReportFooter // this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.SignatureTable, this.FooterDataTable}); resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; this.ReportFooter.StylePriority.UseFont = false; // // SignatureTable // resources.ApplyResources(this.SignatureTable, "SignatureTable"); this.SignatureTable.Name = "SignatureTable"; this.SignatureTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow12, this.xrTableRow13}); this.SignatureTable.StylePriority.UseFont = false; this.SignatureTable.StylePriority.UseTextAlignment = false; // // xrTableRow12 // this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1}); resources.ApplyResources(this.xrTableRow12, "xrTableRow12"); this.xrTableRow12.Name = "xrTableRow12"; // // xrTableCell1 // resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Name = "xrTableCell1"; // // xrTableRow13 // this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell2, this.DateCell, this.xrTableCell17, this.xrTableCell19}); resources.ApplyResources(this.xrTableRow13, "xrTableRow13"); this.xrTableRow13.Name = "xrTableRow13"; // // xrTableCell2 // resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Name = "xrTableCell2"; // // DateCell // resources.ApplyResources(this.DateCell, "DateCell"); this.DateCell.Name = "DateCell"; this.DateCell.StylePriority.UseFont = false; // // xrTableCell17 // resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); this.xrTableCell17.Name = "xrTableCell17"; // // xrTableCell19 // this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strUserOrganization")}); resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); this.xrTableCell19.Name = "xrTableCell19"; this.xrTableCell19.StylePriority.UseFont = false; // // FooterDataTable // this.FooterDataTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.FooterDataTable, "FooterDataTable"); this.FooterDataTable.Name = "FooterDataTable"; this.FooterDataTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.FooterDataRow}); this.FooterDataTable.StylePriority.UseBorders = false; this.FooterDataTable.StylePriority.UseTextAlignment = false; // // FooterDataRow // this.FooterDataRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.FooterTotalCell, this.AmountOfSpecimenTotalCell, this.TestCountTotalCell_1, this.PositiveResultsTotalCell}); resources.ApplyResources(this.FooterDataRow, "FooterDataRow"); this.FooterDataRow.Name = "FooterDataRow"; // // FooterTotalCell // resources.ApplyResources(this.FooterTotalCell, "FooterTotalCell"); this.FooterTotalCell.Name = "FooterTotalCell"; // // AmountOfSpecimenTotalCell // this.AmountOfSpecimenTotalCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.AmountOfSpecimenTaken")}); resources.ApplyResources(this.AmountOfSpecimenTotalCell, "AmountOfSpecimenTotalCell"); this.AmountOfSpecimenTotalCell.Name = "AmountOfSpecimenTotalCell"; resources.ApplyResources(xrSummary1, "xrSummary1"); xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Report; this.AmountOfSpecimenTotalCell.Summary = xrSummary1; // // TestCountTotalCell_1 // this.TestCountTotalCell_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.intTest_1")}); resources.ApplyResources(this.TestCountTotalCell_1, "TestCountTotalCell_1"); this.TestCountTotalCell_1.Name = "TestCountTotalCell_1"; resources.ApplyResources(xrSummary2, "xrSummary2"); xrSummary2.Running = DevExpress.XtraReports.UI.SummaryRunning.Report; this.TestCountTotalCell_1.Summary = xrSummary2; // // PositiveResultsTotalCell // this.PositiveResultsTotalCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.PositiveResults")}); resources.ApplyResources(this.PositiveResultsTotalCell, "PositiveResultsTotalCell"); this.PositiveResultsTotalCell.Name = "PositiveResultsTotalCell"; resources.ApplyResources(xrSummary3, "xrSummary3"); xrSummary3.Running = DevExpress.XtraReports.UI.SummaryRunning.Report; this.PositiveResultsTotalCell.Summary = xrSummary3; // // VetDetail // this.VetDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.DetailsDataTable}); resources.ApplyResources(this.VetDetail, "VetDetail"); this.VetDetail.KeepTogether = true; this.VetDetail.Name = "VetDetail"; this.VetDetail.StylePriority.UseFont = false; // // DetailsDataTable // this.DetailsDataTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.DetailsDataTable, "DetailsDataTable"); this.DetailsDataTable.Name = "DetailsDataTable"; this.DetailsDataTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.DetailsDataRow}); this.DetailsDataTable.StylePriority.UseBorders = false; this.DetailsDataTable.StylePriority.UseTextAlignment = false; // // DetailsDataRow // this.DetailsDataRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.RowNumberCell, this.DiseaseCell, this.OIECell, this.SpeciesCell, this.AmountOfSpecimenCell, this.TestCountCell_1, this.PositiveResultsCell}); resources.ApplyResources(this.DetailsDataRow, "DetailsDataRow"); this.DetailsDataRow.Name = "DetailsDataRow"; // // RowNumberCell // resources.ApplyResources(this.RowNumberCell, "RowNumberCell"); this.RowNumberCell.Name = "RowNumberCell"; this.RowNumberCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.RowNumberCell_BeforePrint); // // DiseaseCell // this.DiseaseCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strDiagnosisName")}); resources.ApplyResources(this.DiseaseCell, "DiseaseCell"); this.DiseaseCell.Name = "DiseaseCell"; // // OIECell // this.OIECell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strOIECode")}); resources.ApplyResources(this.OIECell, "OIECell"); this.OIECell.Name = "OIECell"; // // SpeciesCell // this.SpeciesCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strSpecies")}); resources.ApplyResources(this.SpeciesCell, "SpeciesCell"); this.SpeciesCell.Name = "SpeciesCell"; // // AmountOfSpecimenCell // this.AmountOfSpecimenCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.AmountOfSpecimenTaken")}); resources.ApplyResources(this.AmountOfSpecimenCell, "AmountOfSpecimenCell"); this.AmountOfSpecimenCell.Name = "AmountOfSpecimenCell"; // // TestCountCell_1 // this.TestCountCell_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.intTest_1")}); resources.ApplyResources(this.TestCountCell_1, "TestCountCell_1"); this.TestCountCell_1.Name = "TestCountCell_1"; // // PositiveResultsCell // this.PositiveResultsCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.PositiveResults")}); resources.ApplyResources(this.PositiveResultsCell, "PositiveResultsCell"); this.PositiveResultsCell.Name = "PositiveResultsCell"; // // VetReportHeader // this.VetReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1, this.HeaderDataTable, this.HeaderTable, this.xrPictureBox1}); resources.ApplyResources(this.VetReportHeader, "VetReportHeader"); this.VetReportHeader.Name = "VetReportHeader"; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow4, this.xrTableRow6, this.xrTableRow7, this.xrTableRow8, this.xrTableRow9}); this.xrTable1.StylePriority.UseFont = false; this.xrTable1.StylePriority.UsePadding = false; this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell8}); resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); this.xrTableRow4.Name = "xrTableRow4"; // // xrTableCell8 // resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Multiline = true; this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseFont = false; // // xrTableRow6 // this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell10}); resources.ApplyResources(this.xrTableRow6, "xrTableRow6"); this.xrTableRow6.Name = "xrTableRow6"; // // xrTableCell10 // resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); this.xrTableCell10.Multiline = true; this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseFont = false; // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell13, this.xrTableCell12}); resources.ApplyResources(this.xrTableRow7, "xrTableRow7"); this.xrTableRow7.Name = "xrTableRow7"; // // xrTableCell13 // resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.StylePriority.UseFont = false; // // xrTableCell12 // resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.StylePriority.UseFont = false; // // xrTableRow8 // this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell18}); resources.ApplyResources(this.xrTableRow8, "xrTableRow8"); this.xrTableRow8.Name = "xrTableRow8"; // // xrTableCell18 // resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); this.xrTableCell18.Name = "xrTableCell18"; // // xrTableRow9 // this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell20}); resources.ApplyResources(this.xrTableRow9, "xrTableRow9"); this.xrTableRow9.Name = "xrTableRow9"; // // xrTableCell20 // resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); this.xrTableCell20.Multiline = true; this.xrTableCell20.Name = "xrTableCell20"; // // HeaderDataTable // this.HeaderDataTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.HeaderDataTable, "HeaderDataTable"); this.HeaderDataTable.Name = "HeaderDataTable"; this.HeaderDataTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.HeaderDataRow1, this.HeaderDataRow2}); this.HeaderDataTable.StylePriority.UseBorders = false; this.HeaderDataTable.StylePriority.UseFont = false; this.HeaderDataTable.StylePriority.UseTextAlignment = false; // // HeaderDataRow1 // this.HeaderDataRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.UnderRowNumberHeaderCell, this.UnderDiseaseHeaderCell, this.UnderOIEHeaderCell, this.UnderSpeciesHeaderCell, this.UnderAmountOfSpecimenHeaderCell, this.TestsConductedHeaderCell, this.UnderPositiveResultsHeaderCell}); resources.ApplyResources(this.HeaderDataRow1, "HeaderDataRow1"); this.HeaderDataRow1.Name = "HeaderDataRow1"; // // UnderRowNumberHeaderCell // this.UnderRowNumberHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.UnderRowNumberHeaderCell, "UnderRowNumberHeaderCell"); this.UnderRowNumberHeaderCell.Name = "UnderRowNumberHeaderCell"; this.UnderRowNumberHeaderCell.StylePriority.UseBorders = false; // // UnderDiseaseHeaderCell // this.UnderDiseaseHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.UnderDiseaseHeaderCell, "UnderDiseaseHeaderCell"); this.UnderDiseaseHeaderCell.Name = "UnderDiseaseHeaderCell"; this.UnderDiseaseHeaderCell.StylePriority.UseBorders = false; // // UnderOIEHeaderCell // this.UnderOIEHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.UnderOIEHeaderCell, "UnderOIEHeaderCell"); this.UnderOIEHeaderCell.Name = "UnderOIEHeaderCell"; this.UnderOIEHeaderCell.StylePriority.UseBorders = false; // // UnderSpeciesHeaderCell // this.UnderSpeciesHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.UnderSpeciesHeaderCell, "UnderSpeciesHeaderCell"); this.UnderSpeciesHeaderCell.Name = "UnderSpeciesHeaderCell"; this.UnderSpeciesHeaderCell.StylePriority.UseBorders = false; // // UnderAmountOfSpecimenHeaderCell // this.UnderAmountOfSpecimenHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.UnderAmountOfSpecimenHeaderCell, "UnderAmountOfSpecimenHeaderCell"); this.UnderAmountOfSpecimenHeaderCell.Name = "UnderAmountOfSpecimenHeaderCell"; this.UnderAmountOfSpecimenHeaderCell.StylePriority.UseBorders = false; // // TestsConductedHeaderCell // resources.ApplyResources(this.TestsConductedHeaderCell, "TestsConductedHeaderCell"); this.TestsConductedHeaderCell.Name = "TestsConductedHeaderCell"; // // UnderPositiveResultsHeaderCell // resources.ApplyResources(this.UnderPositiveResultsHeaderCell, "UnderPositiveResultsHeaderCell"); this.UnderPositiveResultsHeaderCell.Name = "UnderPositiveResultsHeaderCell"; // // HeaderDataRow2 // this.HeaderDataRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.RowNumberHeaderCell, this.DiseaseHeaderCell, this.OIEHeaderCell, this.SpeciesHeaderCell, this.AmountOfSpecimenHeaderCell, this.TestNameHeaderCell_1, this.PositiveResultsHeaderCell}); resources.ApplyResources(this.HeaderDataRow2, "HeaderDataRow2"); this.HeaderDataRow2.Name = "HeaderDataRow2"; // // RowNumberHeaderCell // this.RowNumberHeaderCell.Angle = 90F; this.RowNumberHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.RowNumberHeaderCell, "RowNumberHeaderCell"); this.RowNumberHeaderCell.Name = "RowNumberHeaderCell"; this.RowNumberHeaderCell.StylePriority.UseBorders = false; // // DiseaseHeaderCell // this.DiseaseHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.DiseaseHeaderCell, "DiseaseHeaderCell"); this.DiseaseHeaderCell.Name = "DiseaseHeaderCell"; this.DiseaseHeaderCell.StylePriority.UseBorders = false; // // OIEHeaderCell // this.OIEHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.OIEHeaderCell, "OIEHeaderCell"); this.OIEHeaderCell.Name = "OIEHeaderCell"; this.OIEHeaderCell.StylePriority.UseBorders = false; // // SpeciesHeaderCell // this.SpeciesHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.SpeciesHeaderCell, "SpeciesHeaderCell"); this.SpeciesHeaderCell.Name = "SpeciesHeaderCell"; this.SpeciesHeaderCell.StylePriority.UseBorders = false; // // AmountOfSpecimenHeaderCell // this.AmountOfSpecimenHeaderCell.Angle = 90F; this.AmountOfSpecimenHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.AmountOfSpecimenHeaderCell, "AmountOfSpecimenHeaderCell"); this.AmountOfSpecimenHeaderCell.Name = "AmountOfSpecimenHeaderCell"; this.AmountOfSpecimenHeaderCell.StylePriority.UseBorders = false; // // TestNameHeaderCell_1 // this.TestNameHeaderCell_1.Angle = 90F; this.TestNameHeaderCell_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLabReportAZ.strTestName_1")}); resources.ApplyResources(this.TestNameHeaderCell_1, "TestNameHeaderCell_1"); this.TestNameHeaderCell_1.Name = "TestNameHeaderCell_1"; // // PositiveResultsHeaderCell // this.PositiveResultsHeaderCell.Angle = 90F; this.PositiveResultsHeaderCell.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.PositiveResultsHeaderCell, "PositiveResultsHeaderCell"); this.PositiveResultsHeaderCell.Name = "PositiveResultsHeaderCell"; this.PositiveResultsHeaderCell.StylePriority.UseBorders = false; // // HeaderTable // resources.ApplyResources(this.HeaderTable, "HeaderTable"); this.HeaderTable.Name = "HeaderTable"; this.HeaderTable.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.HeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow5, this.xrTableRow3, this.xrTableRow2, this.xrTableRow1}); this.HeaderTable.StylePriority.UseFont = false; this.HeaderTable.StylePriority.UsePadding = false; this.HeaderTable.StylePriority.UseTextAlignment = false; // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell4, this.RecipientHeaderCell, this.xrTableCell7}); resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); this.xrTableRow5.Name = "xrTableRow5"; // // xrTableCell4 // resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Name = "xrTableCell4"; // // RecipientHeaderCell // this.RecipientHeaderCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.RecipientHeaderCell, "RecipientHeaderCell"); this.RecipientHeaderCell.Name = "RecipientHeaderCell"; this.RecipientHeaderCell.StylePriority.UseBorders = false; this.RecipientHeaderCell.StylePriority.UseFont = false; // // xrTableCell7 // resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); this.xrTableCell7.Name = "xrTableCell7"; // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell5, this.SentByCell, this.xrTableCell9}); resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); this.xrTableRow3.Name = "xrTableRow3"; // // xrTableCell5 // resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); this.xrTableCell5.Name = "xrTableCell5"; // // SentByCell // this.SentByCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.SentByCell, "SentByCell"); this.SentByCell.Multiline = true; this.SentByCell.Name = "SentByCell"; this.SentByCell.StylePriority.UseBorders = false; this.SentByCell.StylePriority.UseFont = false; // // xrTableCell9 // resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Name = "xrTableCell9"; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell6, this.ForDateCell, this.xrTableCell11}); resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); this.xrTableRow2.Name = "xrTableRow2"; // // xrTableCell6 // resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); this.xrTableCell6.Name = "xrTableCell6"; // // ForDateCell // this.ForDateCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.ForDateCell, "ForDateCell"); this.ForDateCell.Name = "ForDateCell"; this.ForDateCell.StylePriority.UseBorders = false; this.ForDateCell.StylePriority.UseFont = false; // // xrTableCell11 // resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); this.xrTableCell11.Name = "xrTableCell11"; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.HeaderCell}); resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); this.xrTableRow1.Name = "xrTableRow1"; // // HeaderCell // resources.ApplyResources(this.HeaderCell, "HeaderCell"); this.HeaderCell.Name = "HeaderCell"; this.HeaderCell.StylePriority.UseFont = false; this.HeaderCell.StylePriority.UseTextAlignment = false; // // xrPictureBox1 // resources.ApplyResources(this.xrPictureBox1, "xrPictureBox1"); this.xrPictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("xrPictureBox1.Image"))); this.xrPictureBox1.Name = "xrPictureBox1"; this.xrPictureBox1.Sizing = DevExpress.XtraPrinting.ImageSizeMode.ZoomImage; // // GroupHeaderDiagnosis // resources.ApplyResources(this.GroupHeaderDiagnosis, "GroupHeaderDiagnosis"); this.GroupHeaderDiagnosis.GroupFields.AddRange(new DevExpress.XtraReports.UI.GroupField[] { new DevExpress.XtraReports.UI.GroupField("DiagniosisOrder", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending), new DevExpress.XtraReports.UI.GroupField("strDiagnosisName", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)}); this.GroupHeaderDiagnosis.Name = "GroupHeaderDiagnosis"; // // GroupFooterDiagnosis // resources.ApplyResources(this.GroupFooterDiagnosis, "GroupFooterDiagnosis"); this.GroupFooterDiagnosis.Name = "GroupFooterDiagnosis"; this.GroupFooterDiagnosis.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.GroupFooterDiagnosis_BeforePrint); // // GroupHeaderLine // this.GroupHeaderLine.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLine2}); resources.ApplyResources(this.GroupHeaderLine, "GroupHeaderLine"); this.GroupHeaderLine.Level = 1; this.GroupHeaderLine.Name = "GroupHeaderLine"; this.GroupHeaderLine.RepeatEveryPage = true; this.GroupHeaderLine.StylePriority.UseTextAlignment = false; // // xrLine2 // this.xrLine2.BorderWidth = 0F; resources.ApplyResources(this.xrLine2, "xrLine2"); this.xrLine2.LineWidth = 0; this.xrLine2.Name = "xrLine2"; this.xrLine2.StylePriority.UseBorderWidth = false; // // GroupFooterLine // this.GroupFooterLine.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLine1}); resources.ApplyResources(this.GroupFooterLine, "GroupFooterLine"); this.GroupFooterLine.Level = 1; this.GroupFooterLine.Name = "GroupFooterLine"; this.GroupFooterLine.RepeatEveryPage = true; // // xrLine1 // this.xrLine1.BorderWidth = 0F; resources.ApplyResources(this.xrLine1, "xrLine1"); this.xrLine1.LineWidth = 0; this.xrLine1.Name = "xrLine1"; this.xrLine1.StylePriority.UseBorderWidth = false; // // m_DataAdapter // this.m_DataAdapter.ClearBeforeFill = true; // // m_DataSet // this.m_DataSet.DataSetName = "VetLabReportDataSet"; this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // VetLabReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.VetReport}); resources.ApplyResources(this, "$this"); this.Version = "14.1"; this.Controls.SetChildIndex(this.VetReport, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.FooterDataTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.DetailsDataTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderDataTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand VetReport; private DevExpress.XtraReports.UI.DetailBand VetDetail; private DevExpress.XtraReports.UI.ReportHeaderBand VetReportHeader; private DevExpress.XtraReports.UI.XRTable HeaderTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell HeaderCell; private DevExpress.XtraReports.UI.XRTable HeaderDataTable; private DevExpress.XtraReports.UI.XRTableRow HeaderDataRow2; private DevExpress.XtraReports.UI.XRTableCell RowNumberHeaderCell; private DevExpress.XtraReports.UI.XRTableCell DiseaseHeaderCell; private DevExpress.XtraReports.UI.XRTableCell OIEHeaderCell; private DevExpress.XtraReports.UI.XRTableCell SpeciesHeaderCell; private DevExpress.XtraReports.UI.XRTableCell PositiveResultsHeaderCell; private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeaderDiagnosis; private DevExpress.XtraReports.UI.GroupFooterBand GroupFooterDiagnosis; private DevExpress.XtraReports.UI.XRLine xrLine1; private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeaderLine; private DevExpress.XtraReports.UI.GroupFooterBand GroupFooterLine; private DevExpress.XtraReports.UI.XRTable DetailsDataTable; private DevExpress.XtraReports.UI.XRTableRow DetailsDataRow; private DevExpress.XtraReports.UI.XRTableCell RowNumberCell; private DevExpress.XtraReports.UI.XRTableCell DiseaseCell; private DevExpress.XtraReports.UI.XRTableCell OIECell; private DevExpress.XtraReports.UI.XRTableCell SpeciesCell; private DevExpress.XtraReports.UI.XRTableCell PositiveResultsCell; private DataSets.VetLabReportDataSet m_DataSet; private DataSets.VetLabReportDataSetTableAdapters.VetLabAdapter m_DataAdapter; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private DevExpress.XtraReports.UI.XRLine xrLine2; private DevExpress.XtraReports.UI.XRTableRow HeaderDataRow1; private DevExpress.XtraReports.UI.XRTableCell UnderRowNumberHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderDiseaseHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderOIEHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderSpeciesHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderAmountOfSpecimenHeaderCell; private DevExpress.XtraReports.UI.XRTableCell UnderPositiveResultsHeaderCell; private DevExpress.XtraReports.UI.XRTableCell AmountOfSpecimenHeaderCell; private DevExpress.XtraReports.UI.XRTableCell TestsConductedHeaderCell; private DevExpress.XtraReports.UI.XRTableCell TestNameHeaderCell_1; private DevExpress.XtraReports.UI.XRTableCell AmountOfSpecimenCell; private DevExpress.XtraReports.UI.XRTableCell TestCountCell_1; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableRow xrTableRow6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableRow xrTableRow8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell RecipientHeaderCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell SentByCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell ForDateCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRPictureBox xrPictureBox1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTable FooterDataTable; private DevExpress.XtraReports.UI.XRTableRow FooterDataRow; private DevExpress.XtraReports.UI.XRTableCell FooterTotalCell; private DevExpress.XtraReports.UI.XRTableCell AmountOfSpecimenTotalCell; private DevExpress.XtraReports.UI.XRTableCell TestCountTotalCell_1; private DevExpress.XtraReports.UI.XRTableCell PositiveResultsTotalCell; private DevExpress.XtraReports.UI.XRTable SignatureTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell DateCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; } }
#define COMPILE_IL using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using NQuery.Compilation; using Comparer = System.Collections.Comparer; namespace NQuery.Runtime.ExecutionPlan { [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal sealed class IteratorCreator : StandardVisitor { private MetadataContext _metadataContext; private bool _includeStatistics; private Iterator _lastIterator; private Stack<BoundRowBufferEntrySet> _outerReferenceStack = new Stack<BoundRowBufferEntrySet>(); private IteratorCreator(MetadataContext metadataContext, bool includeStatistics) { _metadataContext = metadataContext; _includeStatistics = includeStatistics; } public static ResultIterator Convert(MetadataContext metadataContext, bool includeStatistics, ResultAlgebraNode resultAlgebraNode) { IteratorCreator iteratorCreator = new IteratorCreator(metadataContext, includeStatistics); Iterator iterator = iteratorCreator.ConvertAlgebraNode(resultAlgebraNode); ILEmitContext.CompleteILCompilation(); if (includeStatistics) return (ResultIterator) ((StatisticsIterator) iterator).Input; return (ResultIterator) iterator; } #region Helpers private sealed class BoundRowBufferEntrySet { public BoundRowBufferEntrySet(object[] rowBuffer, RowBufferEntry[] entries) { RowBuffer = rowBuffer; Entries = entries; } public object[] RowBuffer; public RowBufferEntry[] Entries; } private sealed class RowBufferEntryExpressionUpdater : StandardVisitor { private BoundRowBufferEntrySet[] _bufferEntrySets; public RowBufferEntryExpressionUpdater(BoundRowBufferEntrySet[] bufferEntrySets) { _bufferEntrySets = bufferEntrySets; } public override ExpressionNode VisitRowBufferEntryExpression(RowBufferEntryExpression expression) { foreach (BoundRowBufferEntrySet boundRowBufferEntrySet in _bufferEntrySets) { int rowBufferIndex = Array.IndexOf(boundRowBufferEntrySet.Entries, expression.RowBufferEntry); if (rowBufferIndex >= 0) { expression.RowBuffer = boundRowBufferEntrySet.RowBuffer; expression.RowBufferIndex = rowBufferIndex; break; } } return expression; } } private void SetLastIterator(AlgebraNode owner, Iterator iterator) { if (_includeStatistics && owner.StatisticsIterator == null) { owner.StatisticsIterator = new StatisticsIterator(); owner.StatisticsIterator.RowBuffer = iterator.RowBuffer; owner.StatisticsIterator.Input = iterator; iterator = owner.StatisticsIterator; } _lastIterator = iterator; } private Iterator GetLastIterator() { Iterator result = _lastIterator; _lastIterator = null; return result; } private Iterator ConvertAlgebraNode(AlgebraNode algebraNode) { Visit(algebraNode); Iterator iterator = GetLastIterator(); return iterator; } private static IteratorInput[] GetIteratorInput(RowBufferEntry[] allEntries, RowBufferEntry[] neededEntries) { IteratorInput[] result = new IteratorInput[neededEntries.Length]; for (int i = 0; i < neededEntries.Length; i++) { result[i] = new IteratorInput(); result[i].SourceIndex = Array.IndexOf(allEntries, neededEntries[i]); } return result; } private static IteratorOutput[] GetIteratorOutput(int offset, RowBufferEntry[] allEntries, RowBufferEntry[] neededEntries) { List<IteratorOutput> result = new List<IteratorOutput>(neededEntries.Length); for (int i = 0; i < allEntries.Length; i++) { if (ArrayHelpers.Contains(neededEntries, allEntries[i])) { IteratorOutput iteratorOutput = new IteratorOutput(); iteratorOutput.SourceIndex = i; iteratorOutput.TargetIndex = offset + result.Count; result.Add(iteratorOutput); } } return result.ToArray(); } private RuntimeComputedValueOutput[] GetDefinedValues(RowBufferEntry[] outputList, ComputedValueDefinition[] definedValues, params BoundRowBufferEntrySet[] boundRowBufferEntrySets) { RuntimeComputedValueOutput[] result = new RuntimeComputedValueOutput[definedValues.Length]; for (int i = 0; i < definedValues.Length; i++) { RuntimeComputedValueOutput definedValue = new RuntimeComputedValueOutput(); definedValue.Expression = CreateRuntimeExpression(definedValues[i].Expression, boundRowBufferEntrySets); definedValue.TargetIndex = Array.IndexOf(outputList, definedValues[i].Target); result[i] = definedValue; } return result; } private static RuntimeValueOutput GetDefinedValue(RowBufferEntry[] outputList, RowBufferEntry rowBufferEntry) { RuntimeValueOutput result = new RuntimeValueOutput(); result.TargetIndex = Array.IndexOf(outputList, rowBufferEntry); return result; } private RuntimeAggregateValueOutput[] GetDefinedValues(RowBufferEntry[] outputList, AggregatedValueDefinition[] definedValues, params BoundRowBufferEntrySet[] boundRowBufferEntrySets) { RuntimeAggregateValueOutput[] result = new RuntimeAggregateValueOutput[definedValues.Length]; for (int i = 0; i < definedValues.Length; i++) { RuntimeAggregateValueOutput definedValue = new RuntimeAggregateValueOutput(); definedValue.Aggregator = definedValues[i].Aggregator; definedValue.Argument = CreateRuntimeExpression(definedValues[i].Argument, boundRowBufferEntrySets); definedValue.TargetIndex = Array.IndexOf(outputList, definedValues[i].Target); result[i] = definedValue; } return result; } private RuntimeExpression CreateRuntimeExpression(ExpressionNode expression, params BoundRowBufferEntrySet[] boundRowBufferEntrySets) { // Update row buffer references List<BoundRowBufferEntrySet> boundRowBufferEntrySetList = new List<BoundRowBufferEntrySet>(); boundRowBufferEntrySetList.AddRange(boundRowBufferEntrySets); foreach (BoundRowBufferEntrySet outerreferenceBoundRowBufferEntrySet in _outerReferenceStack) boundRowBufferEntrySetList.Add(outerreferenceBoundRowBufferEntrySet); boundRowBufferEntrySets = boundRowBufferEntrySetList.ToArray(); RowBufferEntryExpressionUpdater rowBufferEntryExpressionUpdater = new RowBufferEntryExpressionUpdater(boundRowBufferEntrySets); expression = rowBufferEntryExpressionUpdater.VisitExpression(expression); #if COMPILE_IL return ExpressionCompiler.CreateCompiled(expression); #else return ExpressionCompiler.CreateInterpreded(expression); #endif } private IComparer[] GetComparersFromExpressionTypes(RowBufferEntry[] rowBufferEntries) { IComparer[] result = new IComparer[rowBufferEntries.Length]; for (int i = 0; i < result.Length; i++) { IComparer customComparer = _metadataContext.Comparers[rowBufferEntries[i].DataType]; if (customComparer != null) result[i] = customComparer; else result[i] = Comparer.Default; } return result; } private void PushOuterReferences(object[] rowBuffer, JoinAlgebraNode node) { if (node.OuterReferences != null && node.OuterReferences.Length > 0) { // Important: We cannot use node.OuterReferences as argument for BoundRowBufferEntrySet(). // The replacment strategy below will replace occurences to the entries by their index // within the array. Therefore we need an array with the same layout as the row buffer. RowBufferEntry[] outerReferences = new RowBufferEntry[node.Left.OutputList.Length]; for (int i = 0; i < outerReferences.Length; i++) { if (ArrayHelpers.Contains(node.OuterReferences, node.Left.OutputList[i])) outerReferences[i] = node.Left.OutputList[i]; } BoundRowBufferEntrySet bufferEntrySet = new BoundRowBufferEntrySet(rowBuffer, outerReferences); _outerReferenceStack.Push(bufferEntrySet); } } private void UpdatePredicateRowBufferReferences(NestedLoopsIterator nestedLoopsIterator, JoinAlgebraNode node) { BoundRowBufferEntrySet leftBoundRowBufferEntrySet = new BoundRowBufferEntrySet(nestedLoopsIterator.Left.RowBuffer, node.Left.OutputList); BoundRowBufferEntrySet rightBoundRowBufferEntrySet = new BoundRowBufferEntrySet(nestedLoopsIterator.Right.RowBuffer, node.Right.OutputList); if (node.Predicate != null) nestedLoopsIterator.Predicate = CreateRuntimeExpression(node.Predicate, leftBoundRowBufferEntrySet, rightBoundRowBufferEntrySet); if (node.PassthruPredicate != null) nestedLoopsIterator.PassthruPredicate = CreateRuntimeExpression(node.PassthruPredicate, leftBoundRowBufferEntrySet, rightBoundRowBufferEntrySet); } private void UpdatePredicateRowBufferReferences(HashMatchIterator hashMatchIterator, HashMatchAlgebraNode node) { if (node.ProbeResidual != null) { BoundRowBufferEntrySet leftBoundRowBufferEntrySet = new BoundRowBufferEntrySet(hashMatchIterator.Left.RowBuffer, node.Left.OutputList); BoundRowBufferEntrySet rightBoundRowBufferEntrySet = new BoundRowBufferEntrySet(hashMatchIterator.Right.RowBuffer, node.Right.OutputList); hashMatchIterator.ProbeResidual = CreateRuntimeExpression(node.ProbeResidual, leftBoundRowBufferEntrySet, rightBoundRowBufferEntrySet); } } #endregion public override AlgebraNode VisitTableAlgebraNode(TableAlgebraNode node) { List<RuntimeColumnValueOutput> definedValues = new List<RuntimeColumnValueOutput>(); foreach (ColumnValueDefinition columnValueDefinition in node.DefinedValues) { RuntimeColumnValueOutput definedValue = new RuntimeColumnValueOutput(); definedValue.TargetIndex = definedValues.Count; definedValue.ColumnBinding = columnValueDefinition.ColumnRefBinding.ColumnBinding; definedValues.Add(definedValue); } TableIterator tableIterator = new TableIterator(); tableIterator.RowBuffer = new object[node.OutputList.Length]; tableIterator.DefinedValues = definedValues.ToArray(); tableIterator.Table = node.TableRefBinding.TableBinding; SetLastIterator(node, tableIterator); return node; } public override AlgebraNode VisitJoinAlgebraNode(JoinAlgebraNode node) { if (node.Op == JoinAlgebraNode.JoinOperator.RightOuterJoin || node.Op == JoinAlgebraNode.JoinOperator.RightAntiSemiJoin || node.Op == JoinAlgebraNode.JoinOperator.RightSemiJoin) { if (node.OuterReferences != null && node.OuterReferences.Length > 0) throw ExceptionBuilder.InternalError("Outer references should not be possible for {0} and are not supported.", node.Op); node.SwapSides(); } NestedLoopsIterator nestedLoopsIterator; switch (node.Op) { case JoinAlgebraNode.JoinOperator.InnerJoin: nestedLoopsIterator = new InnerNestedLoopsIterator(); break; case JoinAlgebraNode.JoinOperator.LeftOuterJoin: nestedLoopsIterator = new LeftOuterNestedLoopsIterator(); break; case JoinAlgebraNode.JoinOperator.LeftSemiJoin: if (node.ProbeBufferEntry == null) nestedLoopsIterator = new LeftSemiNestedLoopsIterator(); else { ProbedSemiJoinNestedLoopsIterator probedSemiJoinNestedLoopsIterator = new ProbedSemiJoinNestedLoopsIterator(); probedSemiJoinNestedLoopsIterator.ProbeOutput = GetDefinedValue(node.OutputList, node.ProbeBufferEntry); nestedLoopsIterator = probedSemiJoinNestedLoopsIterator; } break; case JoinAlgebraNode.JoinOperator.LeftAntiSemiJoin: if (node.ProbeBufferEntry == null) nestedLoopsIterator = new LeftAntiSemiNestedLoopsIterator(); else { ProbedAntiSemiJoinNestedLoopsIterator probedSemiJoinNestedLoopsIterator = new ProbedAntiSemiJoinNestedLoopsIterator(); probedSemiJoinNestedLoopsIterator.ProbeOutput = GetDefinedValue(node.OutputList, node.ProbeBufferEntry); nestedLoopsIterator = probedSemiJoinNestedLoopsIterator; } break; default: throw ExceptionBuilder.UnhandledCaseLabel(node.Op); } nestedLoopsIterator.RowBuffer = new object[node.OutputList.Length]; nestedLoopsIterator.Left = ConvertAlgebraNode(node.Left); nestedLoopsIterator.LeftOutput = GetIteratorOutput(0, node.Left.OutputList, node.OutputList); PushOuterReferences(nestedLoopsIterator.Left.RowBuffer, node); nestedLoopsIterator.Right = ConvertAlgebraNode(node.Right); nestedLoopsIterator.RightOutput = GetIteratorOutput(nestedLoopsIterator.LeftOutput.Length, node.Right.OutputList, node.OutputList); UpdatePredicateRowBufferReferences(nestedLoopsIterator, node); if (node.OuterReferences != null && node.OuterReferences.Length > 0) _outerReferenceStack.Pop(); SetLastIterator(node, nestedLoopsIterator); return node; } public override AlgebraNode VisitConstantScanAlgebraNode(ConstantScanAlgebraNode node) { ConstantIterator constantIterator = new ConstantIterator(); constantIterator.RowBuffer = new object[node.OutputList.Length]; constantIterator.DefinedValues = GetDefinedValues(node.OutputList, node.DefinedValues); SetLastIterator(node, constantIterator); return node; } public override AlgebraNode VisitNullScanAlgebraNode(NullScanAlgebraNode node) { NullIterator nullIterator = new NullIterator(); nullIterator.RowBuffer = new object[node.OutputList.Length]; SetLastIterator(node, nullIterator); return node; } public override AlgebraNode VisitConcatAlgebraNode(ConcatAlgebraNode node) { ConcatenationIterator concatenationIterator = new ConcatenationIterator(); concatenationIterator.RowBuffer = new object[node.OutputList.Length]; concatenationIterator.Inputs = new Iterator[node.Inputs.Length]; concatenationIterator.InputOutput = new IteratorOutput[node.Inputs.Length][]; for (int i = 0; i < concatenationIterator.Inputs.Length; i++) { concatenationIterator.Inputs[i] = ConvertAlgebraNode(node.Inputs[i]); List<IteratorOutput> inputOutputList = new List<IteratorOutput>(); foreach (UnitedValueDefinition unitedValueDefinition in node.DefinedValues) { IteratorOutput iteratorOutput = new IteratorOutput(); iteratorOutput.SourceIndex = Array.IndexOf(node.Inputs[i].OutputList, unitedValueDefinition.DependendEntries[i]); iteratorOutput.TargetIndex = Array.IndexOf(node.OutputList, unitedValueDefinition.Target); inputOutputList.Add(iteratorOutput); } concatenationIterator.InputOutput[i] = inputOutputList.ToArray(); } SetLastIterator(node, concatenationIterator); return node; } public override AlgebraNode VisitSortAlgebraNode(SortAlgebraNode node) { SortIterator sortIterator; if (node.Distinct) sortIterator = new DistinctSortIterator(); else sortIterator = new SortIterator(); sortIterator.RowBuffer = new object[node.OutputList.Length]; sortIterator.SortOrders = node.SortOrders; sortIterator.SortEntries = GetIteratorInput(node.Input.OutputList, node.SortEntries); sortIterator.Comparers = GetComparersFromExpressionTypes(node.SortEntries); sortIterator.Input = ConvertAlgebraNode(node.Input); sortIterator.InputOutput = GetIteratorOutput(0, node.Input.OutputList, node.OutputList); SetLastIterator(node, sortIterator); return node; } public override AlgebraNode VisitAggregateAlgebraNode(AggregateAlgebraNode node) { StreamAggregateIterator streamAggregateIterator = new StreamAggregateIterator(); streamAggregateIterator.RowBuffer = new object[node.OutputList.Length]; streamAggregateIterator.Input = ConvertAlgebraNode(node.Input); streamAggregateIterator.InputOutput = GetIteratorOutput(0, node.Input.OutputList, node.OutputList); BoundRowBufferEntrySet boundRowBufferEntrySet = new BoundRowBufferEntrySet(streamAggregateIterator.Input.RowBuffer, node.Input.OutputList); if (node.Groups == null) { streamAggregateIterator.GroupByEntries = new IteratorInput[0]; streamAggregateIterator.DefinedValues = GetDefinedValues(node.OutputList, node.DefinedValues, boundRowBufferEntrySet); } else { streamAggregateIterator.GroupByEntries = GetIteratorInput(node.Input.OutputList, node.Groups); streamAggregateIterator.DefinedValues = GetDefinedValues(node.OutputList, node.DefinedValues, boundRowBufferEntrySet); } SetLastIterator(node, streamAggregateIterator); return node; } public override AlgebraNode VisitTopAlgebraNode(TopAlgebraNode node) { TopIterator topIterator; if (node.TieEntries == null) { topIterator = new TopIterator(); } else { TopWithTiesIterator topWithTiesIterator = new TopWithTiesIterator(); topWithTiesIterator.TieEntries = GetIteratorInput(node.Input.OutputList, node.TieEntries); topIterator = topWithTiesIterator; } topIterator.RowBuffer = new object[node.OutputList.Length]; topIterator.Limit = node.Limit; topIterator.Input = ConvertAlgebraNode(node.Input); topIterator.InputOutput = GetIteratorOutput(0, node.Input.OutputList, node.OutputList); SetLastIterator(node, topIterator); return node; } public override AlgebraNode VisitFilterAlgebraNode(FilterAlgebraNode node) { FilterIterator filterIterator = new FilterIterator(); filterIterator.RowBuffer = new object[node.OutputList.Length]; filterIterator.Input = ConvertAlgebraNode(node.Input); filterIterator.InputOutput = GetIteratorOutput(0, node.Input.OutputList, node.OutputList); BoundRowBufferEntrySet boundRowBufferEntrySet = new BoundRowBufferEntrySet(filterIterator.Input.RowBuffer, node.Input.OutputList); filterIterator.Predicate = CreateRuntimeExpression(node.Predicate, boundRowBufferEntrySet); SetLastIterator(node, filterIterator); return node; } public override AlgebraNode VisitComputeScalarAlgebraNode(ComputeScalarAlgebraNode node) { ComputeScalarIterator computeScalarIterator = new ComputeScalarIterator(); computeScalarIterator.RowBuffer = new object[node.OutputList.Length]; computeScalarIterator.Input = ConvertAlgebraNode(node.Input); computeScalarIterator.InputOutput = GetIteratorOutput(0, node.Input.OutputList, node.OutputList); BoundRowBufferEntrySet boundRowBufferEntrySet = new BoundRowBufferEntrySet(computeScalarIterator.Input.RowBuffer, node.Input.OutputList); computeScalarIterator.DefinedValues = GetDefinedValues(node.OutputList, node.DefinedValues, boundRowBufferEntrySet); SetLastIterator(node, computeScalarIterator); return node; } public override AlgebraNode VisitResultAlgebraNode(ResultAlgebraNode node) { ResultIterator resultIterator = new ResultIterator(); resultIterator.RowBuffer = new object[node.OutputList.Length]; resultIterator.Input = ConvertAlgebraNode(node.Input); resultIterator.InputOutput = new IteratorOutput[node.OutputList.Length]; resultIterator.ColumnNames = new string[node.OutputList.Length]; resultIterator.ColumnTypes = new Type[node.OutputList.Length]; for (int i = 0; i < node.OutputList.Length; i++) { IteratorOutput iteratorOutput = new IteratorOutput(); iteratorOutput.SourceIndex = Array.IndexOf(node.Input.OutputList, node.OutputList[i]); iteratorOutput.TargetIndex = i; resultIterator.InputOutput[i] = iteratorOutput; resultIterator.ColumnNames[i] = node.ColumnNames[i]; resultIterator.ColumnTypes[i] = node.OutputList[i].DataType; } SetLastIterator(node, resultIterator); return node; } public override AlgebraNode VisitAssertAlgebraNode(AssertAlgebraNode node) { string message; switch(node.AssertionType) { case AssertionType.MaxOneRow: message = Resources.SubqueryReturnedMoreThanRow; break; case AssertionType.BelowRecursionLimit: message = Resources.MaximumRecursionLevelExceeded; break; default: throw ExceptionBuilder.UnhandledCaseLabel(node.AssertionType); } AssertIterator assertIterator = new AssertIterator(); assertIterator.RowBuffer = new object[node.OutputList.Length]; assertIterator.Input = ConvertAlgebraNode(node.Input); assertIterator.InputOutput = GetIteratorOutput(0, node.Input.OutputList, node.OutputList); assertIterator.Message = message; BoundRowBufferEntrySet boundRowBufferEntrySet = new BoundRowBufferEntrySet(assertIterator.Input.RowBuffer, node.Input.OutputList); assertIterator.Predicate = CreateRuntimeExpression(node.Predicate, boundRowBufferEntrySet); SetLastIterator(node, assertIterator); return node; } public override AlgebraNode VisitIndexSpoolAlgebraNode(IndexSpoolAlgebraNode node) { IndexSpoolIterator indexSpoolIterator = new IndexSpoolIterator(); indexSpoolIterator.RowBuffer = new object[node.OutputList.Length]; indexSpoolIterator.Input = ConvertAlgebraNode(node.Input); indexSpoolIterator.InputOutput = GetIteratorOutput(0, node.Input.OutputList, node.OutputList); indexSpoolIterator.IndexEntry = GetIteratorInput(node.Input.OutputList, new RowBufferEntry[] { node.IndexEntry })[0]; BoundRowBufferEntrySet boundRowBufferEntrySet = new BoundRowBufferEntrySet(indexSpoolIterator.Input.RowBuffer, node.Input.OutputList); indexSpoolIterator.ProbeExpression = CreateRuntimeExpression(node.ProbeExpression, boundRowBufferEntrySet); SetLastIterator(node, indexSpoolIterator); return node; } private Dictionary<StackedTableSpoolAlgebraNode, TableSpoolIterator> tableSpoolIterators = new Dictionary<StackedTableSpoolAlgebraNode, TableSpoolIterator>(); public override AstNode VisitStackedTableSpoolAlgebraNode(StackedTableSpoolAlgebraNode node) { TableSpoolIterator tableSpoolIterator = new TableSpoolIterator(); tableSpoolIterators.Add(node, tableSpoolIterator); tableSpoolIterator.RowBuffer = new object[node.OutputList.Length]; tableSpoolIterator.Input = ConvertAlgebraNode(node.Input); tableSpoolIterator.InputOutput = GetIteratorOutput(0, node.Input.OutputList, node.OutputList); SetLastIterator(node, tableSpoolIterator); return node; } public override AstNode VisitTableSpoolRefAlgebraNode(StackedTableSpoolRefAlgebraNode node) { TableSpoolRefIterator tableSpoolRefIterator = new TableSpoolRefIterator(); tableSpoolRefIterator.RowBuffer = new object[node.OutputList.Length]; tableSpoolRefIterator.PrimarySpool = tableSpoolIterators[node.PrimarySpool]; SetLastIterator(node, tableSpoolRefIterator); return node; } public override AlgebraNode VisitHashMatchAlgebraNode(HashMatchAlgebraNode node) { HashMatchIterator hashMatchIterator = new HashMatchIterator(); hashMatchIterator.RowBuffer = new object[node.OutputList.Length]; hashMatchIterator.Left = ConvertAlgebraNode(node.Left); hashMatchIterator.LeftOutput = GetIteratorOutput(0, node.Left.OutputList, node.OutputList); hashMatchIterator.Right = ConvertAlgebraNode(node.Right); hashMatchIterator.RightOutput = GetIteratorOutput(hashMatchIterator.LeftOutput.Length, node.Right.OutputList, node.OutputList); hashMatchIterator.BuildKeyEntry = GetIteratorInput(node.Left.OutputList, new RowBufferEntry[] { node.BuildKeyEntry })[0]; hashMatchIterator.ProbeEntry = GetIteratorInput(node.Right.OutputList, new RowBufferEntry[] { node.ProbeEntry })[0]; switch (node.Op) { case JoinAlgebraNode.JoinOperator.InnerJoin: hashMatchIterator.LogicalOp = JoinType.Inner; break; case JoinAlgebraNode.JoinOperator.RightOuterJoin: hashMatchIterator.LogicalOp = JoinType.RightOuter; break; case JoinAlgebraNode.JoinOperator.FullOuterJoin: hashMatchIterator.LogicalOp = JoinType.FullOuter; break; default: throw ExceptionBuilder.UnhandledCaseLabel(node.Op); } UpdatePredicateRowBufferReferences(hashMatchIterator, node); SetLastIterator(node, hashMatchIterator); return node; } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2017 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq.Test { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using LinqEnumerable = System.Linq.Enumerable; [DebuggerStepThrough] static partial class Enumerable { public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func) => LinqEnumerable.Aggregate(source, func); public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func) => LinqEnumerable.Aggregate(source, seed, func); public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector) => LinqEnumerable.Aggregate(source, seed, func, resultSelector); public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.All(source, predicate); public static bool Any<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.Any(source); public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.Any(source, predicate); public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.AsEnumerable(source); public static double Average<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector) => LinqEnumerable.Average(source, selector); public static decimal? Average<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector) => LinqEnumerable.Average(source, selector); public static double? Average<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector) => LinqEnumerable.Average(source, selector); public static float Average<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector) => LinqEnumerable.Average(source, selector); public static double? Average<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector) => LinqEnumerable.Average(source, selector); public static float? Average<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector) => LinqEnumerable.Average(source, selector); public static double Average<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => LinqEnumerable.Average(source, selector); public static double? Average<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector) => LinqEnumerable.Average(source, selector); public static decimal Average<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector) => LinqEnumerable.Average(source, selector); public static double Average<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector) => LinqEnumerable.Average(source, selector); public static float? Average(this IEnumerable<float?> source) => LinqEnumerable.Average(source); public static double? Average(this IEnumerable<long?> source) => LinqEnumerable.Average(source); public static double? Average(this IEnumerable<int?> source) => LinqEnumerable.Average(source); public static double? Average(this IEnumerable<double?> source) => LinqEnumerable.Average(source); public static decimal? Average(this IEnumerable<decimal?> source) => LinqEnumerable.Average(source); public static double Average(this IEnumerable<long> source) => LinqEnumerable.Average(source); public static double Average(this IEnumerable<int> source) => LinqEnumerable.Average(source); public static double Average(this IEnumerable<double> source) => LinqEnumerable.Average(source); public static float Average(this IEnumerable<float> source) => LinqEnumerable.Average(source); public static decimal Average(this IEnumerable<decimal> source) => LinqEnumerable.Average(source); public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) => LinqEnumerable.Cast<TResult>(source); public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) => LinqEnumerable.Concat(first, second); public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value) => LinqEnumerable.Contains(source, value); public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer) => LinqEnumerable.Contains(source, value, comparer); public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.Count(source, predicate); public static int Count<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.Count(source); public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.DefaultIfEmpty(source); public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, TSource defaultValue) => LinqEnumerable.DefaultIfEmpty(source, defaultValue); public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.Distinct(source); public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) => LinqEnumerable.Distinct(source, comparer); public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index) => LinqEnumerable.ElementAt(source, index); public static TSource ElementAtOrDefault<TSource>(this IEnumerable<TSource> source, int index) => LinqEnumerable.ElementAtOrDefault(source, index); public static IEnumerable<TResult> Empty<TResult>() => LinqEnumerable.Empty<TResult>(); public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) => LinqEnumerable.Except(first, second); public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) => LinqEnumerable.Except(first, second, comparer); public static TSource First<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.First(source); public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.First(source, predicate); public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.FirstOrDefault(source); public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.FirstOrDefault(source, predicate); public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.GroupBy(source, keySelector, resultSelector, comparer); public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector) => LinqEnumerable.GroupBy(source, keySelector, resultSelector); public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.GroupBy(source, keySelector, elementSelector, comparer); public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector) => LinqEnumerable.GroupBy(source, keySelector, elementSelector, resultSelector); public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.GroupBy(source, keySelector, comparer); public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => LinqEnumerable.GroupBy(source, keySelector); public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) => LinqEnumerable.GroupBy(source, keySelector, elementSelector); public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.GroupBy(source, keySelector, elementSelector, resultSelector, comparer); public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector) => LinqEnumerable.GroupJoin(outer, inner, outerKeySelector, innerKeySelector, resultSelector); public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.GroupJoin(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) => LinqEnumerable.Intersect(first, second); public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) => LinqEnumerable.Intersect(first, second, comparer); public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector) => LinqEnumerable.Join(outer, inner, outerKeySelector, innerKeySelector, resultSelector); public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.Join(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); public static TSource Last<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.Last(source); public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.Last(source, predicate); public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.LastOrDefault(source); public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.LastOrDefault(source, predicate); public static long LongCount<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.LongCount(source); public static long LongCount<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.LongCount(source, predicate); public static double Max<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector) => LinqEnumerable.Max(source, selector); public static int Max<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => LinqEnumerable.Max(source, selector); public static long Max<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector) => LinqEnumerable.Max(source, selector); public static decimal? Max<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector) => LinqEnumerable.Max(source, selector); public static decimal Max<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector) => LinqEnumerable.Max(source, selector); public static int? Max<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector) => LinqEnumerable.Max(source, selector); public static long? Max<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector) => LinqEnumerable.Max(source, selector); public static float? Max<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector) => LinqEnumerable.Max(source, selector); public static TResult Max<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) => LinqEnumerable.Max(source, selector); public static double? Max<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector) => LinqEnumerable.Max(source, selector); public static TSource Max<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.Max(source); public static float Max<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector) => LinqEnumerable.Max(source, selector); public static float? Max(this IEnumerable<float?> source) => LinqEnumerable.Max(source); public static long? Max(this IEnumerable<long?> source) => LinqEnumerable.Max(source); public static int? Max(this IEnumerable<int?> source) => LinqEnumerable.Max(source); public static double? Max(this IEnumerable<double?> source) => LinqEnumerable.Max(source); public static decimal? Max(this IEnumerable<decimal?> source) => LinqEnumerable.Max(source); public static long Max(this IEnumerable<long> source) => LinqEnumerable.Max(source); public static int Max(this IEnumerable<int> source) => LinqEnumerable.Max(source); public static double Max(this IEnumerable<double> source) => LinqEnumerable.Max(source); public static decimal Max(this IEnumerable<decimal> source) => LinqEnumerable.Max(source); public static float Max(this IEnumerable<float> source) => LinqEnumerable.Max(source); public static int Min<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => LinqEnumerable.Min(source, selector); public static long Min<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector) => LinqEnumerable.Min(source, selector); public static decimal? Min<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector) => LinqEnumerable.Min(source, selector); public static double? Min<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector) => LinqEnumerable.Min(source, selector); public static TResult Min<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) => LinqEnumerable.Min(source, selector); public static long? Min<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector) => LinqEnumerable.Min(source, selector); public static float? Min<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector) => LinqEnumerable.Min(source, selector); public static float Min<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector) => LinqEnumerable.Min(source, selector); public static decimal Min<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector) => LinqEnumerable.Min(source, selector); public static int? Min<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector) => LinqEnumerable.Min(source, selector); public static TSource Min<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.Min(source); public static double Min<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector) => LinqEnumerable.Min(source, selector); public static float? Min(this IEnumerable<float?> source) => LinqEnumerable.Min(source); public static long? Min(this IEnumerable<long?> source) => LinqEnumerable.Min(source); public static int? Min(this IEnumerable<int?> source) => LinqEnumerable.Min(source); public static double? Min(this IEnumerable<double?> source) => LinqEnumerable.Min(source); public static decimal? Min(this IEnumerable<decimal?> source) => LinqEnumerable.Min(source); public static long Min(this IEnumerable<long> source) => LinqEnumerable.Min(source); public static int Min(this IEnumerable<int> source) => LinqEnumerable.Min(source); public static double Min(this IEnumerable<double> source) => LinqEnumerable.Min(source); public static decimal Min(this IEnumerable<decimal> source) => LinqEnumerable.Min(source); public static float Min(this IEnumerable<float> source) => LinqEnumerable.Min(source); public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source) => LinqEnumerable.OfType<TResult>(source); public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) => LinqEnumerable.OrderBy(source, keySelector, comparer); public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => LinqEnumerable.OrderBy(source, keySelector); public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => LinqEnumerable.OrderByDescending(source, keySelector); public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) => LinqEnumerable.OrderByDescending(source, keySelector, comparer); public static IEnumerable<int> Range(int start, int count) => LinqEnumerable.Range(start, count); public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count) => LinqEnumerable.Repeat(element, count); public static IEnumerable<TSource> Reverse<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.Reverse(source); public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) => LinqEnumerable.Select(source, selector); public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector) => LinqEnumerable.Select(source, selector); public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) => LinqEnumerable.SelectMany(source, collectionSelector, resultSelector); public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector) => LinqEnumerable.SelectMany(source, selector); public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector) => LinqEnumerable.SelectMany(source, selector); public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) => LinqEnumerable.SelectMany(source, collectionSelector, resultSelector); public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) => LinqEnumerable.SequenceEqual(first, second, comparer); public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) => LinqEnumerable.SequenceEqual(first, second); public static TSource Single<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.Single(source); public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.Single(source, predicate); public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.SingleOrDefault(source); public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.SingleOrDefault(source, predicate); public static IEnumerable<TSource> Skip<TSource>(this IEnumerable<TSource> source, int count) => LinqEnumerable.Skip(source, count); public static IEnumerable<TSource> SkipWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.SkipWhile(source, predicate); public static IEnumerable<TSource> SkipWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) => LinqEnumerable.SkipWhile(source, predicate); public static int? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector) => LinqEnumerable.Sum(source, selector); public static int Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector) => LinqEnumerable.Sum(source, selector); public static long Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, long> selector) => LinqEnumerable.Sum(source, selector); public static decimal? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector) => LinqEnumerable.Sum(source, selector); public static float Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector) => LinqEnumerable.Sum(source, selector); public static float? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector) => LinqEnumerable.Sum(source, selector); public static double Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector) => LinqEnumerable.Sum(source, selector); public static long? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, long?> selector) => LinqEnumerable.Sum(source, selector); public static decimal Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector) => LinqEnumerable.Sum(source, selector); public static double? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector) => LinqEnumerable.Sum(source, selector); public static float? Sum(this IEnumerable<float?> source) => LinqEnumerable.Sum(source); public static long? Sum(this IEnumerable<long?> source) => LinqEnumerable.Sum(source); public static int? Sum(this IEnumerable<int?> source) => LinqEnumerable.Sum(source); public static double? Sum(this IEnumerable<double?> source) => LinqEnumerable.Sum(source); public static decimal? Sum(this IEnumerable<decimal?> source) => LinqEnumerable.Sum(source); public static float Sum(this IEnumerable<float> source) => LinqEnumerable.Sum(source); public static long Sum(this IEnumerable<long> source) => LinqEnumerable.Sum(source); public static int Sum(this IEnumerable<int> source) => LinqEnumerable.Sum(source); public static double Sum(this IEnumerable<double> source) => LinqEnumerable.Sum(source); public static decimal Sum(this IEnumerable<decimal> source) => LinqEnumerable.Sum(source); public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count) => LinqEnumerable.Take(source, count); public static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.TakeWhile(source, predicate); public static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) => LinqEnumerable.TakeWhile(source, predicate); public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) => LinqEnumerable.ThenBy(source, keySelector, comparer); public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector) => LinqEnumerable.ThenBy(source, keySelector); public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector) => LinqEnumerable.ThenByDescending(source, keySelector); public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) => LinqEnumerable.ThenByDescending(source, keySelector, comparer); public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.ToArray(source); public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => LinqEnumerable.ToDictionary(source, keySelector); public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.ToDictionary(source, keySelector, comparer); public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) => LinqEnumerable.ToDictionary(source, keySelector, elementSelector); public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.ToDictionary(source, keySelector, elementSelector, comparer); public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) => LinqEnumerable.ToList(source); public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => LinqEnumerable.ToLookup(source, keySelector); public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.ToLookup(source, keySelector, comparer); public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) => LinqEnumerable.ToLookup(source, keySelector, elementSelector); public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) => LinqEnumerable.ToLookup(source, keySelector, elementSelector, comparer); public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) => LinqEnumerable.Union(first, second); public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) => LinqEnumerable.Union(first, second, comparer); public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) => LinqEnumerable.Where(source, predicate); public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => LinqEnumerable.Where(source, predicate); public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) => LinqEnumerable.Zip(first, second, resultSelector); } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using System.IO; using System.Threading; using System.Diagnostics; using NUnit.Framework; namespace Pivotal.Data.GemFireXD.Tests { /// <summary> /// Tests for ConnectionFailover with and without locator. /// </summary> [TestFixture] public class ConnectionFailoverTests : TestBase { private static int locPort = -1; private static int locPort2 = -1; private static int mCastPort = -1; private int numThreads = 5; #region Setup/TearDown methods [TestFixtureSetUp] public override void FixtureSetup() { InternalSetup(GetType()); SetDefaultDriverType(); // not starting any servers/locators here rather it will be per test } [TestFixtureTearDown] public override void FixtureTearDown() { // not stopping any servers/locators here rather it will be per test com.pivotal.gemfirexd.@internal.shared.common.sanity.SanityManager .SET_DEBUG_STREAM(null); if (s_logFileWriter != null) { s_logFileWriter.close(); s_logFileWriter = null; } } [SetUp] public override void SetUp() { // nothing since we do not create/drop any DB object in this test } [TearDown] public override void TearDown() { StopServer("/gfxdserver1"); StopServer("/gfxdserver2"); StopServer("/gfxdserver3"); StopServer("/gfxdserver4"); StopLocator("/gfxdlocator", true); StopLocator2("/gfxdlocator2"); } protected void StartServerWithLocatorPort(string args) { int clientPort = GetAvailableTCPPort(); string serverDir = s_testOutDir + args; if (Directory.Exists(serverDir)) { Directory.Delete(serverDir, true); } Directory.CreateDirectory(serverDir); StartGFXDPeer(m_defaultDriverType, "server", serverDir, getlocatorString() , clientPort, ""); } protected void StartServer(string args, int clientPort) { if (mCastPort == -1) { mCastPort = GetAvailableTCPPort(); } string serverDir = s_testOutDir + args; if (Directory.Exists(serverDir)) { Directory.Delete(serverDir, true); } Directory.CreateDirectory(serverDir); StartGFXDPeer(m_defaultDriverType, "server", serverDir, "-mcast-port=" + mCastPort, clientPort, ""); } protected void StopServers() { StopServer("/gfxdserver2"); Thread.Sleep(5000); StopServer("/gfxdserver3"); } protected void StopServer(string args) { string serverDir = s_testOutDir + args; StopGFXDPeer(m_defaultDriverType, "server", serverDir); } protected void StartLocator(string args) { locPort = GetAvailableTCPPort(); // starting a locator initClientPort(); string locDir = s_testOutDir + args; if (Directory.Exists(locDir)) { Directory.Delete(locDir, true); } Directory.CreateDirectory(locDir); StartGFXDPeer(m_defaultDriverType, "locator", locDir, string.Empty, s_clientPort, " -peer-discovery-address=localhost" + " -peer-discovery-port=" + locPort + ""); } protected void StartTwoLocator(string args) { locPort = GetAvailableTCPPort(); locPort2 = GetAvailableTCPPort(); // starting a locator initClientPort(); string locDir = s_testOutDir + args; if (Directory.Exists(locDir)) { Directory.Delete(locDir, true); } Directory.CreateDirectory(locDir); StartGFXDPeer(m_defaultDriverType, "locator", locDir, string.Empty, s_clientPort, " -peer-discovery-address=localhost" + getlocatorString() + " -peer-discovery-port=" + locPort + ""); string locDir2 = s_testOutDir + args + "2"; if (Directory.Exists(locDir2)) { Directory.Delete(locDir2, true); } Directory.CreateDirectory(locDir2); s_clientPortLoc2 = GetAvailableTCPPort(); StartGFXDPeer(m_defaultDriverType, "locator", locDir2, string.Empty, s_clientPortLoc2, " -peer-discovery-address=localhost" + getlocatorString() + " -peer-discovery-port=" + locPort2 + ""); } private string getlocatorString() { string locString = ""; if (locPort != -1) { locString = " -locators=localhost[" + locPort + ']'; if (locPort2 != -1) { locString += "," + "localhost[" + locPort2 + ']'; } } Console.WriteLine("getlocatorString: " + locString); return locString; } protected void StopLocator(string args) { StopLocator(args, false); } protected void StopLocator(string args, bool force) { if (!force && s_clientPort <= 0) { throw new NotSupportedException("No locator is running"); } string locDir = s_testOutDir + args; StopGFXDPeer(m_defaultDriverType, "locator", locDir); s_savedClientPortBeforeStopping = s_clientPort; s_clientPort = -1; } protected void StopLocator2(string args) { string locDir = s_testOutDir + args ; StopGFXDPeer(m_defaultDriverType, "locator", locDir); locPort2 = -1; s_clientPortLoc2 = -1; } protected void InitializeClientPort() { initClientPort(); initClientPort1(); initClientPort2(); } private void UpdateTable(object connection) { DbConnection conn = (DbConnection)connection; DbCommand cmd = conn.CreateCommand(); for (int i = 0; i < 1000; i++) { cmd.CommandText = "UPDATE ORDERS SET VOL=? WHERE ID = ?"; Log(cmd.CommandText); cmd.Parameters.Clear(); cmd.Parameters.Add(i + 1001); cmd.Parameters.Add(i); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } cmd.Dispose(); Log("Updation in table done."); } private void UpdateTable2() { for (int i = 0; i < 1000; i++) { DbConnection conn = (DbConnection)OpenNewConnection("Maximum Pool Size=10", false, null); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "UPDATE ORDERS SET VOL=? WHERE ID = ?"; Log(cmd.CommandText); cmd.Parameters.Clear(); cmd.Parameters.Add(i + 1001); cmd.Parameters.Add(i); Assert.AreEqual(1, cmd.ExecuteNonQuery()); conn.Close(); } Log("Updation in table done."); } private void UpdateTable3() { try { DbConnection conn = (DbConnection)OpenNewConnection(); for (int i = 0; i < 1000; i++) { DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "UPDATE ORDERS SET VOL=? WHERE ID = ?"; Log(cmd.CommandText); cmd.Parameters.Clear(); cmd.Parameters.Add(i + 1001); cmd.Parameters.Add(i); Assert.AreEqual(1, cmd.ExecuteNonQuery()); cmd.Dispose(); } conn.Close(); } catch (Exception ex) { Console.WriteLine("hitesh got " + ex); } Log("Updation in table done."); } #endregion /// <summary> /// two pool test /// </summary> [Test] public void TestTwoPool() { if(!isRunningWithPool()) return; // start the locator and 1 server first and let client connect with this server only. Console.WriteLine("Pool test TestTwoPool"); StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); Console.WriteLine("test starts"); DbConnection conn1 = OpenNewConnection(); { //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } DbConnection conn2 = OpenNewConnection("secondary-locators=localserver:96897", false, null); DbCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd2.Parameters.Add(1); cmd2.Parameters.Add(1); string str = "Char " + 1; cmd2.Parameters.Add(str); Assert.AreEqual(1, cmd2.ExecuteNonQuery()); //that will force new connection DbConnection conn3 = OpenNewConnection("secondary-locators=localserver:96897", false, null); for (int i = 10; i < 100; i++) { DbCommand cmd = conn3.CreateCommand(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str2 = "Char " + i; cmd.Parameters.Add(str2); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } conn2.Close(); conn3.Close(); //pool1 should have one connection n=only Assert.AreEqual(1, ((GFXDClientConnection)conn1).PoolConnectionCount); //pool2 should have one connection Assert.AreEqual(2, ((GFXDClientConnection)conn2).PoolConnectionCount); StopServer("/gfxdserver1"); StopLocator2("/gfxdlocator2"); } /// <summary> /// stops first locator, it return connection to pool /// </summary> [Test] public void TestLocatorStop1() { if (!isRunningWithPool()) return; Console.WriteLine("Pool test TestLocatorStop1"); // start the locator and 1 server first and let client connect with this server only. StartTwoLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection()) { //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } DbConnection conn2 = OpenNewConnection(); DbCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd2.Parameters.Add(1); cmd2.Parameters.Add(1); string str = "Char " + 1; cmd2.Parameters.Add(str); Assert.AreEqual(1, cmd2.ExecuteNonQuery()); conn2.Close(); //stopped first locator StopLocator("/gfxdlocator"); //that will force new connection DbConnection conn3 = OpenNewConnection(); for (int i = 10; i < 100; i++) { DbCommand cmd = conn3.CreateCommand(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str2 = "Char " + i; cmd.Parameters.Add(str2); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } conn2.Close(); conn3.Close(); //pool should have one connection Assert.AreEqual(1, ((GFXDClientConnection)conn2).PoolConnectionCount); StopServer("/gfxdserver1"); StopLocator2("/gfxdlocator2"); } /// <summary> /// stops first locator. But it didn't return connection(conn2) to pool /// </summary> [Test] public void TestLocatorStop2() { if (!isRunningWithPool()) return; // start the locator and 1 server first and let client connect with this server only. Console.WriteLine("Pool test TestLocatorStop2"); StartTwoLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection()) { //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } DbConnection conn2 = OpenNewConnection(); DbCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd2.Parameters.Add(1); cmd2.Parameters.Add(1); string str = "Char " + 1; cmd2.Parameters.Add(str); Assert.AreEqual(1, cmd2.ExecuteNonQuery()); //stopped first locator StopLocator("/gfxdlocator"); //that will force new connection DbConnection conn3 = OpenNewConnection(); for (int i = 10; i < 100; i++) { DbCommand cmd = conn3.CreateCommand(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str2 = "Char " + i; cmd.Parameters.Add(str2); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } conn2.Close(); conn3.Close(); //pool should have two connection Assert.AreEqual(2, ((GFXDClientConnection)conn2).PoolConnectionCount); StopServer("/gfxdserver1"); StopLocator2("/gfxdlocator2"); } /// <summary> /// test server fail over /// </summary> [Test] public void TestServerFailed() { if (!isRunningWithPool()) return; // start the locator and 1 server first and let client connect with this server only. Console.WriteLine("Pool test TestServerFailed"); StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection()) { //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } DbConnection conn2 = OpenNewConnection(); DbCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd2.Parameters.Add(1); cmd2.Parameters.Add(1); string str = "Char " + 1; cmd2.Parameters.Add(str); Assert.AreEqual(1, cmd2.ExecuteNonQuery()); StopServer("/gfxdserver1"); Console.WriteLine("server closed"); Thread.Sleep(2000); bool gotException = false; try { for (int i = 10; i < 100; i++) { DbCommand cmd = conn2.CreateCommand(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str2 = "Char " + i; cmd.Parameters.Add(str2); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } } catch (GFXDException ex) { Console.WriteLine("got exception " + ex.Message); gotException = true; } Assert.AreEqual(true, gotException); conn2.Close(); //pool should not have any single connection Assert.AreEqual(0, ((GFXDClientConnection)conn2).PoolConnectionCount); Assert.AreEqual(1, ((GFXDClientConnection)conn2).GCReferenceCount, "We should have released GC reference 1 (in driver)."); StopLocator("/gfxdlocator"); } /// <summary> /// test server fail over /// </summary> [Test] public void TestServerFailover() { if (!isRunningWithPool()) return; // start the locator and 1 server first and let client connect with this server only. Console.WriteLine("Pool test TestServerFailover"); StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection()) { //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } StartServerWithLocatorPort("/gfxdserver2"); DbConnection conn2 = OpenNewConnection(); DbCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd2.Parameters.Add(1); cmd2.Parameters.Add(1); string str = "Char " + 1; cmd2.Parameters.Add(str); Assert.AreEqual(1, cmd2.ExecuteNonQuery()); StopServer("/gfxdserver1"); Thread.Sleep(2000); for (int i = 10; i < 100; i++) { DbCommand cmd = conn2.CreateCommand(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str2 = "Char " + i; cmd.Parameters.Add(str2); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } Assert.AreEqual(1, ((GFXDClientConnection)conn2).PoolConnectionCount); conn2.Close(); // Stop the server where client-connection was established for failover. StopServer("/gfxdserver2"); StopLocator("/gfxdlocator"); } /// <summary> /// test connection idle time /// </summary> [Test] public void TestConnectionIdleTime() { if (!isRunningWithPool()) return; // start the locator and 1 server first and let client connect with this server only. Console.WriteLine("Pool test TestConnectionIdleTime"); StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection()) { //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } DbConnection conn2 = OpenNewConnection(); DbCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd2.Parameters.Add(1); cmd2.Parameters.Add(1); string str = "Char " + 1; cmd2.Parameters.Add(str); Assert.AreEqual(1, cmd2.ExecuteNonQuery()); //conn2.Close() not closing the connection object storeConnectionObject = ((GFXDClientConnection)conn2).RealPooledConnection; Assert.AreEqual(2, ((GFXDClientConnection)conn2).GCReferenceCount, "We should have GC reference count 2(one in pool and one in driver)."); conn2.Close(); Assert.AreEqual(1, ((GFXDClientConnection)conn2).GCReferenceCount, "We should have GC reference count 1(one in pool)."); //180 second is default Thread.Sleep(200000); Assert.AreEqual( 0, ((GFXDClientConnection)conn2).PoolConnectionCount, "Connection count should be zero"); Assert.AreEqual(0, ((GFXDClientConnection)conn2).GCReferenceCount , "We should have released GC reference count."); DbConnection conn3 = OpenNewConnection(); //now there should be new connection Assert.AreNotEqual(storeConnectionObject, ((GFXDClientConnection)conn3).RealPooledConnection); conn3.Close(); // Stop the server where client-connection was established for failover. StopServer("/gfxdserver1"); StopLocator("/gfxdlocator"); } /// <summary> /// test connection idle time which modified /// </summary> [Test] public void TestConnectionIdleTimeM() { if (!isRunningWithPool()) return; // start the locator and 1 server first and let client connect with this server only. Environment.SetEnvironmentVariable("IDLE_TIMEOUT", "100"); StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection("Connection Lifetime=10", false, null)) { //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } DbConnection conn2 = OpenNewConnection("Connection Lifetime=10", false, null); DbCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd2.Parameters.Add(1); cmd2.Parameters.Add(1); string str = "Char " + 1; cmd2.Parameters.Add(str); Assert.AreEqual(1, cmd2.ExecuteNonQuery()); //conn2.Close() not closing the connection object storeConnectionObject = ((GFXDClientConnection)conn2).RealPooledConnection; conn2.Close(); //10 second is set Thread.Sleep(31000); Assert.IsTrue(((GFXDClientConnection)conn2).PoolConnectionCount == 0); DbConnection conn3 = OpenNewConnection("Connection Lifetime=10", false, null); //now there should be new connection Assert.AreNotEqual(storeConnectionObject, ((GFXDClientConnection)conn3).RealPooledConnection); conn3.Close(); // Stop the server where client-connection was established for failover. StopServer("/gfxdserver1"); StopLocator("/gfxdlocator"); Environment.SetEnvironmentVariable("IDLE_TIMEOUT", null); } /// <summary> /// test pool max connection limit /// /// </summary> [Test] public void TestPoolMaxConnections() { if (!isRunningWithPool()) return; Console.WriteLine("Pool test TestPoolMaxConnections"); Environment.SetEnvironmentVariable("POOL_MAX_CONNECTION", "1"); // start the locator and 1 server first and let client connect with this server only. StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection()) { //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } DbConnection conn2 = OpenNewConnection(); DbCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd2.Parameters.Add(1); cmd2.Parameters.Add(1); string str = "Char " + 1; cmd2.Parameters.Add(str); Assert.AreEqual(1, cmd2.ExecuteNonQuery()); //conn2.Close() not closing the connection bool gotexception = false; long st = DateTime.Now.Ticks; try { DbConnection conn3 = OpenNewConnection(); } catch (GFXDException sx) { Console.WriteLine("got exception " + sx.Message); gotexception = true; } Assert.IsTrue(gotexception); long end = DateTime.Now.Ticks; //default Assert.GreaterOrEqual(end, st + 15 * TimeSpan.TicksPerSecond); // Stop the server where client-connection was established for failover. StopServer("/gfxdserver1"); StopLocator("/gfxdlocator"); Environment.SetEnvironmentVariable("POOL_MAX_CONNECTION", null); } /// <summary> /// test pool max connection limit /// /// </summary> [Test] public void TestPoolMaxConnections2() { if (!isRunningWithPool()) return; Console.WriteLine("Pool test TestPoolMaxConnections"); Environment.SetEnvironmentVariable("POOL_MAX_CONNECTION", "1"); // start the locator and 1 server first and let client connect with this server only. StartLocator("/sqlflocator"); StartServerWithLocatorPort("/sqlfserver1"); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection("Connect Timeout=30", false, null)) { //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } DbConnection conn2 = OpenNewConnection("Connect Timeout=30", false, null); DbCommand cmd2 = conn2.CreateCommand(); cmd2.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd2.Parameters.Add(1); cmd2.Parameters.Add(1); string str = "Char " + 1; cmd2.Parameters.Add(str); Assert.AreEqual(1, cmd2.ExecuteNonQuery()); //conn2.Close() not closing the connection bool gotexception = false; long st = DateTime.Now.Ticks; try { DbConnection conn3 = OpenNewConnection("Connect Timeout=30", false, null); } catch (GFXDException sx) { Console.WriteLine("got exception " + sx.Message); gotexception = true; } Assert.IsTrue(gotexception); long end = DateTime.Now.Ticks; Console.WriteLine("hitesh gote " + end + " st " + (st + 30 * TimeSpan.TicksPerSecond)); Assert.GreaterOrEqual(end, st + 30 * TimeSpan.TicksPerSecond); // Stop the server where client-connection was established for failover. StopServer("/sqlfserver1"); StopLocator("/sqlflocator"); Environment.SetEnvironmentVariable("POOL_MAX_CONNECTION", null); } [Test] public void TestPoolConnectionsGC() { if (!isRunningWithPool()) return; Console.WriteLine("Pool test TestPoolConnections"); // start the locator and 1 server first and let client connect with this server only. StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); object storeConnectionObject = null; Dictionary<object, bool> conns = new Dictionary<object, bool>(); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection()) { GFXDClientConnection scc = (GFXDClientConnection)conn1; storeConnectionObject = scc.RealPooledConnection; conns[scc.RealPooledConnection] = true; //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } //GC check after connection close for (int i = 0; i < 1000; i++) { DbConnection conn = OpenNewConnection(); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Assert.AreEqual(1, cmd.ExecuteNonQuery()); conn.Close(); } bool gotExpectedException = false; string excepMsg = ""; //GC check after without connection close try { for (int i = 1001; i < 5000; i++) { DbConnection conn = OpenNewConnection(); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } } catch (Exception ex) { excepMsg = ex.Message; if(ex.Message.IndexOf("All connections are used") > 0) gotExpectedException = true; } Assert.IsTrue(gotExpectedException, "didn't get expected exception " + excepMsg); // Stop the server where client-connection was established for failover. StopServer("/sqlfserver1"); StopLocator("/sqlflocator"); } public void TestPoolConnections() { if (!isRunningWithPool()) return; Console.WriteLine("Pool test TestPoolConnections"); // start the locator and 1 server first and let client connect with this server only. StartLocator("/sqlflocator"); StartServerWithLocatorPort("/sqlfserver1"); object storeConnectionObject = null; Dictionary<object, bool> conns = new Dictionary<object, bool>(); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection()) { GFXDClientConnection scc = (GFXDClientConnection)conn1; storeConnectionObject = scc.RealPooledConnection; conns[scc.RealPooledConnection] = true; //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } for (int i = 0; i < 10; i++) { DbConnection conn = OpenNewConnection(); GFXDClientConnection scc = (GFXDClientConnection)conn; Log("Conenctions " + scc.PoolConnectionCount + " stored one " + storeConnectionObject.GetHashCode() + " newone:" + scc.RealPooledConnection.GetHashCode()); conns[scc.RealPooledConnection] = true; DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Assert.AreEqual(1, cmd.ExecuteNonQuery()); conn.Close(); conn.Close();//extra close } using (DbConnection c2 = OpenNewConnection()) { GFXDClientConnection scc = (GFXDClientConnection)c2; Assert.AreEqual(1, scc.PoolConnectionCount); Assert.AreEqual(conns.Count, scc.PoolConnectionCount); c2.Close(); } // Stop the server where client-connection was established for failover. StopServer("/gfxdserver1"); StopLocator("/gfxdlocator"); } [Test] public void TestPoolConnectionsWithTx() { if (!isRunningWithPool()) return; // start the locator and 1 server first and let client connect with this server only. Console.WriteLine("Pool test TestPoolConnectionsWithTx"); StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); object storeConnectionObject = null; Dictionary<object, bool> conns = new Dictionary<object, bool>(); Console.WriteLine("test starts"); using (DbConnection conn1 = OpenNewConnection()) { GFXDClientConnection scc = (GFXDClientConnection)conn1; storeConnectionObject = scc.RealPooledConnection; conns[scc.RealPooledConnection] = true; //create table DbCommand cmd = conn1.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn1.Close(); } for (int i = 0; i < 10; i++) { DbConnection conn = OpenNewConnection(); GFXDClientConnection scc = (GFXDClientConnection)conn; Log("Conenctions " + scc.PoolConnectionCount + " stored one " + storeConnectionObject.GetHashCode() + " newone:" + scc.RealPooledConnection.GetHashCode()); conns[scc.RealPooledConnection] = true; GFXDTransaction tran = (GFXDTransaction)conn.BeginTransaction(IsolationLevel .ReadCommitted); DbCommand cmd = new GFXDCommand("INSERT INTO ORDERS VALUES (?, ?, ?)" , (GFXDConnection)conn); cmd.Prepare(); cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Assert.AreEqual(1, cmd.ExecuteNonQuery()); tran.Commit(); conn.Close(); } using (DbConnection c2 = OpenNewConnection()) { GFXDClientConnection scc = (GFXDClientConnection)c2; Assert.AreEqual(1, scc.PoolConnectionCount); Assert.AreEqual(conns.Count, scc.PoolConnectionCount); c2.Close(); } // Stop the server where client-connection was established for failover. StopServer("/gfxdserver1"); StopLocator("/gfxdlocator"); } [Test] public void TestPoolConnectionsWithMultipleThreads() { if (!isRunningWithPool()) return; Console.WriteLine("Pool test TestPoolConnectionsWithMultipleThreads"); // Environment.SetEnvironmentVariable("POOL_MAX_CONNECTION", "10"); // start the locator and servers and let client connect with the first server only. StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); StartServerWithLocatorPort("/gfxdserver2"); StartServerWithLocatorPort("/gfxdserver3"); StartServerWithLocatorPort("/gfxdserver4"); using (DbConnection conn = OpenNewConnection("Maximum Pool Size=10", false, null)) { DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; for (int i = 0; i < 1000; i++) { cmd.Parameters.Clear(); cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Log(cmd.CommandText); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } Log("Insertion in table done."); Stopwatch sw = new Stopwatch(); sw.Start(); int nthreads = 25; Thread[] ts = new Thread[nthreads]; for (int i = 0; i < nthreads; i++) { ThreadStart tsm = new ThreadStart(UpdateTable2); ts[i] = new Thread(tsm); Log(String.Format("Start order table update thread. TID: [{0}]", ts[i].ManagedThreadId)); ts[i].Start(); } for (int i = 0; i < nthreads; i++) ts[i].Join(); Console.WriteLine("test took time " + sw.ElapsedMilliseconds); //total connection should be less than 10, POOL_MAX_CONNECTION limit Assert.IsTrue(((GFXDClientConnection)conn).PoolConnectionCount <= 10); Thread ts1 = new Thread(new ThreadStart(StopServers)); ts1.Start(); Thread.Sleep(10); cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * from ORDERS WHERE VOL > 0 and VOL < 1000"; Log(cmd.CommandText); DbDataReader reader = cmd.ExecuteReader(); int rows = 0; do { while (reader.Read()) { ++rows; } Assert.AreEqual(0, rows, "#1 No rows shud be returned"); Log(rows.ToString()); } while (reader.NextResult()); reader.Close(); cmd.CommandText = "SELECT * from ORDERS WHERE VOL > 1000 and VOL < 2000"; Log(cmd.CommandText); reader = cmd.ExecuteReader(); rows = 0; do { while (reader.Read()) { ++rows; } Assert.AreEqual(999, rows, "#1 Multiple rows shud be returned"); Log(rows.ToString()); } while (reader.NextResult()); conn.Close(); StopServer("/gfxdserver4"); StopLocator("/gfxdlocator"); } Environment.SetEnvironmentVariable("POOL_MAX_CONNECTION", null); } //hitesh need to look [Test] public void TestPoolConnectionsWithMultipleThreads2() { if (!isRunningWithPool()) return; Console.WriteLine("Pool test TestPoolConnectionsWithMultipleThreads"); // Environment.SetEnvironmentVariable("POOL_MAX_CONNECTION", "10"); // start the locator and servers and let client connect with the first server only. StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); StartServerWithLocatorPort("/gfxdserver2"); StartServerWithLocatorPort("/gfxdserver3"); StartServerWithLocatorPort("/gfxdserver4"); using (DbConnection conn = OpenNewConnection()) { DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; for (int i = 0; i < 1000; i++) { cmd.Parameters.Clear(); cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Log(cmd.CommandText); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } Log("Insertion in table done."); Stopwatch sw = new Stopwatch(); sw.Start(); int nthreads = 25; Thread[] ts = new Thread[nthreads]; for (int i = 0; i < nthreads; i++) { ThreadStart tsm = new ThreadStart(UpdateTable3); ts[i] = new Thread(tsm); Log(String.Format("Start order table update thread. TID: [{0}]", ts[i].ManagedThreadId)); ts[i].Start(); } for (int i = 0; i < nthreads; i++) { Console.WriteLine("thread returned " + i); ts[i].Join(); } Console.WriteLine("test took time " + sw.ElapsedMilliseconds); //total connection should be less than 10, POOL_MAX_CONNECTION limit Assert.AreEqual(((GFXDClientConnection)conn).PoolConnectionCount, nthreads +1); Thread ts1 = new Thread(new ThreadStart(StopServers)); ts1.Start(); Thread.Sleep(10); cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * from ORDERS WHERE VOL > 0 and VOL < 1000"; Log(cmd.CommandText); DbDataReader reader = cmd.ExecuteReader(); int rows = 0; do { while (reader.Read()) { ++rows; } Assert.AreEqual(0, rows, "#1 No rows shud be returned"); Log(rows.ToString()); } while (reader.NextResult()); reader.Close(); cmd.CommandText = "SELECT * from ORDERS WHERE VOL > 1000 and VOL < 2000"; Log(cmd.CommandText); reader = cmd.ExecuteReader(); rows = 0; do { while (reader.Read()) { ++rows; } Assert.AreEqual(999, rows, "#1 Multiple rows shud be returned"); Log(rows.ToString()); } while (reader.NextResult()); conn.Close(); StopServer("/gfxdserver4"); StopLocator("/gfxdlocator"); } Environment.SetEnvironmentVariable("POOL_MAX_CONNECTION", null); } /// <summary> /// Test with locator and replicated table. /// </summary> [Test] public void TestConnectionFailover1_WithLocator() { // start the locator and 1 server first and let client connect with this server only. StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); // Open a new connection to the network server using (DbConnection conn = OpenNewConnection()) { // After client-server connection is established start the other server. StartServerWithLocatorPort("/gfxdserver2"); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; for (int i = 0; i < 1000; i++) { cmd.Parameters.Clear(); cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Log(cmd.CommandText); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } Log("Insertion in table done."); // Stop the server where client-connection was established for failover. StopServer("/gfxdserver1"); cmd.CommandText = "SELECT * from ORDERS"; Log(cmd.CommandText); DbDataReader reader = cmd.ExecuteReader(); int rows = 0; int results = 0; do { while (reader.Read()) { ++rows; } Log(rows.ToString()); Assert.AreEqual(1000, rows, "#1 rows shud be 1000"); ++results; rows = 0; } while (reader.NextResult()); Log(results.ToString()); Assert.AreEqual(1, results, "#2 result sets shud be returned"); reader.Close(); cmd.CommandText = "Drop Table ORDERS "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn.Close(); //Close the remaining server and locator. StopServer("/gfxdserver2"); StopLocator("/gfxdlocator"); } } /// <summary> /// Test with locator and partitioned table. /// </summary> [Test] public void TestConnectionFailover2_WithLocator() { // start the locator and 1 server first and let client connect with this server only. StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); // Open a new connection to the network server using (DbConnection conn = OpenNewConnection()) { // After client-server connection is established start the other servers. StartServerWithLocatorPort("/gfxdserver2"); StartServerWithLocatorPort("/gfxdserver3"); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "partition by Primary Key redundancy 1 "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; for (int i = 0; i < 1000; i++) { cmd.Parameters.Clear(); cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Log(cmd.CommandText); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } Log("Insertion in table done."); // Stop the server where client-connection was established for failover. StopServer("/gfxdserver1"); cmd.CommandText = "SELECT * from ORDERS"; Log(cmd.CommandText); DbDataReader reader = cmd.ExecuteReader(); int rows = 0; int results = 0; do { while (reader.Read()) { ++rows; } Log(rows.ToString()); Assert.AreEqual(1000, rows, "#1 rows shud be 1000"); ++results; rows = 0; } while (reader.NextResult()); Log(results.ToString()); Assert.AreEqual(1, results, "#2 result sets shud be returned"); reader.Close(); cmd.CommandText = "Drop Table ORDERS "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn.Close(); //Close the remaining servers and locator. StopServer("/gfxdserver2"); StopServer("/gfxdserver3"); StopLocator("/gfxdlocator"); } } /// <summary> /// Test without locator and partitioned table. /// </summary> [Test] public void TestConnectionFailover2_WithoutLocator() { InitializeClientPort(); // start first 2 servers and let client connect with the first one only. StartServer("/gfxdserver1", s_clientPort); StartServer("/gfxdserver2", s_clientPort1); // Open a new connection to the network server using (DbConnection conn = OpenNewConnection()) { // After client-server connection is established start the other server. StartServer("/gfxdserver3", s_clientPort2); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "partition by Primary Key redundancy 1 "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; for (int i = 0; i < 1000; i++) { cmd.Parameters.Clear(); cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Log(cmd.CommandText); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } Log("Insertion in table done."); // Stop the server where client-connection was established for failover. StopServer("/gfxdserver1"); cmd.CommandText = "SELECT * from ORDERS"; Log(cmd.CommandText); DbDataReader reader = cmd.ExecuteReader(); int rows = 0; int results = 0; do { while (reader.Read()) { ++rows; } Log(rows.ToString()); Assert.AreEqual(1000, rows, "#1 rows shud be 1000"); ++results; rows = 0; } while (reader.NextResult()); Log(results.ToString()); Assert.AreEqual(1, results, "#2 result sets shud be returned"); reader.Close(); cmd.CommandText = "Drop Table ORDERS "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn.Close(); //Close the remaining servers. StopServer("/gfxdserver2"); StopServer("/gfxdserver3"); s_clientPort = -1; s_clientPort1 = -1; s_clientPort2 = -1; } } /// <summary> /// Test without locator and replcated table. /// </summary> [Test] public void TestConnectionFailover1_WithoutLocator() { InitializeClientPort(); // start first 2 servers and let client connect with the first one only. StartServer("/gfxdserver1", s_clientPort); StartServer("/gfxdserver2", s_clientPort1); // Open a new connection to the network server using (DbConnection conn = OpenNewConnection()) { // After client-server connection is established start the other server. StartServer("/gfxdserver3", s_clientPort2); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; for (int i = 0; i < 1000; i++) { cmd.Parameters.Clear(); cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Log(cmd.CommandText); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } Log("Insertion in table done."); // Stop the server where client-connection was established for failover. StopServer("/gfxdserver1"); cmd.CommandText = "SELECT * from ORDERS"; Log(cmd.CommandText); DbDataReader reader = cmd.ExecuteReader(); int rows = 0; int results = 0; do { while (reader.Read()) { ++rows; } Log(rows.ToString()); Assert.AreEqual(1000, rows, "#1 rows shud be 1000"); ++results; rows = 0; } while (reader.NextResult()); Log(results.ToString()); Assert.AreEqual(1, results, "#2 result sets shud be returned"); reader.Close(); cmd.CommandText = "Drop Table ORDERS "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); conn.Close(); //Close the remaining server. StopServer("/gfxdserver2"); StopServer("/gfxdserver3"); s_clientPort = -1; s_clientPort1 = -1; s_clientPort2 = -1; } } /// <summary> /// Test connection failover with threads. /// </summary> [Test] public void TestConnectionFailover_WithMultipleThreads() { // start the locator and servers and let client connect with the first server only. StartLocator("/gfxdlocator"); StartServerWithLocatorPort("/gfxdserver1"); StartServerWithLocatorPort("/gfxdserver2"); StartServerWithLocatorPort("/gfxdserver3"); using (DbConnection conn = OpenNewConnection()) { // After client-server connection is established start the other server. StartServerWithLocatorPort("/gfxdserver4"); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = "create table ORDERS (ID int primary key, " + "VOL int NOT NULL unique, SECURITY_ID varchar(10)) " + "REPLICATE "; Log(cmd.CommandText); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO ORDERS VALUES (?, ?, ?)"; for (int i = 0; i < 1000; i++) { cmd.Parameters.Clear(); cmd.Parameters.Add(i); cmd.Parameters.Add(i); string str = "Char " + i; cmd.Parameters.Add(str); Log(cmd.CommandText); Assert.AreEqual(1, cmd.ExecuteNonQuery()); } Log("Insertion in table done."); // Stop the server where client-connection was established. StopServer("/gfxdserver1"); Thread[] ts = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) { ts[i] = new Thread(new ParameterizedThreadStart(UpdateTable)); Log(String.Format("Start order table update thread. TID: [{0}]", ts[i].ManagedThreadId)); ts[i].Start(conn); Thread.Sleep(10); } for (int i = 0; i < numThreads; i++) ts[i].Join(); Thread ts1 = new Thread(new ThreadStart(StopServers)); ts1.Start(); Thread.Sleep(10); cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * from ORDERS WHERE VOL > 0 and VOL < 1000"; Log(cmd.CommandText); DbDataReader reader = cmd.ExecuteReader(); int rows = 0; do { while (reader.Read()) { ++rows; } Assert.AreEqual(0, rows, "#1 No rows shud be returned"); Log(rows.ToString()); } while (reader.NextResult()); reader.Close(); cmd.CommandText = "SELECT * from ORDERS WHERE VOL > 1000 and VOL < 2000"; Log(cmd.CommandText); reader = cmd.ExecuteReader(); rows = 0; do { while (reader.Read()) { ++rows; } Assert.AreEqual(999, rows, "#1 Multiple rows shud be returned"); Log(rows.ToString()); } while (reader.NextResult()); conn.Close(); StopServer("/gfxdserver4"); StopLocator("/gfxdlocator"); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Audio; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Objects; using osuTK; namespace osu.Game.Screens.Edit.Compose.Components.Timeline { [Cached(typeof(IPositionSnapProvider))] [Cached] public class Timeline : ZoomableScrollContainer, IPositionSnapProvider { private readonly Drawable userContent; public readonly Bindable<bool> WaveformVisible = new Bindable<bool>(); public readonly Bindable<bool> ControlPointsVisible = new Bindable<bool>(); public readonly Bindable<bool> TicksVisible = new Bindable<bool>(); public readonly IBindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>(); [Resolved] private EditorClock editorClock { get; set; } /// <summary> /// The timeline's scroll position in the last frame. /// </summary> private float lastScrollPosition; /// <summary> /// The track time in the last frame. /// </summary> private double lastTrackTime; /// <summary> /// Whether the user is currently dragging the timeline. /// </summary> private bool handlingDragInput; /// <summary> /// Whether the track was playing before a user drag event. /// </summary> private bool trackWasPlaying; private Track track; private const float timeline_height = 72; private const float timeline_expanded_height = 94; public Timeline(Drawable userContent) { this.userContent = userContent; RelativeSizeAxes = Axes.X; Height = timeline_height; ZoomDuration = 200; ZoomEasing = Easing.OutQuint; ScrollbarVisible = false; } private WaveformGraph waveform; private TimelineTickDisplay ticks; private TimelineControlPointDisplay controlPoints; private Container mainContent; private Bindable<float> waveformOpacity; [BackgroundDependencyLoader] private void load(IBindable<WorkingBeatmap> beatmap, OsuColour colours, OsuConfigManager config) { CentreMarker centreMarker; // We don't want the centre marker to scroll AddInternal(centreMarker = new CentreMarker()); AddRange(new Drawable[] { controlPoints = new TimelineControlPointDisplay { RelativeSizeAxes = Axes.X, Height = timeline_expanded_height, }, mainContent = new Container { RelativeSizeAxes = Axes.X, Height = timeline_height, Depth = float.MaxValue, Children = new[] { waveform = new WaveformGraph { RelativeSizeAxes = Axes.Both, BaseColour = colours.Blue.Opacity(0.2f), LowColour = colours.BlueLighter, MidColour = colours.BlueDark, HighColour = colours.BlueDarker, }, centreMarker.CreateProxy(), ticks = new TimelineTickDisplay(), new Box { Name = "zero marker", RelativeSizeAxes = Axes.Y, Width = 2, Origin = Anchor.TopCentre, Colour = colours.YellowDarker, }, userContent, } }, }); waveformOpacity = config.GetBindable<float>(OsuSetting.EditorWaveformOpacity); Beatmap.BindTo(beatmap); Beatmap.BindValueChanged(b => { waveform.Waveform = b.NewValue.Waveform; track = b.NewValue.Track; // todo: i don't think this is safe, the track may not be loaded yet. if (track.Length > 0) { MaxZoom = getZoomLevelForVisibleMilliseconds(500); MinZoom = getZoomLevelForVisibleMilliseconds(10000); Zoom = getZoomLevelForVisibleMilliseconds(2000); } }, true); } protected override void LoadComplete() { base.LoadComplete(); waveformOpacity.BindValueChanged(_ => updateWaveformOpacity(), true); WaveformVisible.ValueChanged += _ => updateWaveformOpacity(); TicksVisible.ValueChanged += visible => ticks.FadeTo(visible.NewValue ? 1 : 0, 200, Easing.OutQuint); ControlPointsVisible.BindValueChanged(visible => { if (visible.NewValue) { this.ResizeHeightTo(timeline_expanded_height, 200, Easing.OutQuint); mainContent.MoveToY(20, 200, Easing.OutQuint); // delay the fade in else masking looks weird. controlPoints.Delay(180).FadeIn(400, Easing.OutQuint); } else { controlPoints.FadeOut(200, Easing.OutQuint); // likewise, delay the resize until the fade is complete. this.Delay(180).ResizeHeightTo(timeline_height, 200, Easing.OutQuint); mainContent.Delay(180).MoveToY(0, 200, Easing.OutQuint); } }, true); } private void updateWaveformOpacity() => waveform.FadeTo(WaveformVisible.Value ? waveformOpacity.Value : 0, 200, Easing.OutQuint); private float getZoomLevelForVisibleMilliseconds(double milliseconds) => Math.Max(1, (float)(track.Length / milliseconds)); protected override void Update() { base.Update(); // The extrema of track time should be positioned at the centre of the container when scrolled to the start or end Content.Margin = new MarginPadding { Horizontal = DrawWidth / 2 }; // This needs to happen after transforms are updated, but before the scroll position is updated in base.UpdateAfterChildren if (editorClock.IsRunning) scrollToTrackTime(); } protected override bool OnScroll(ScrollEvent e) { // if this is not a precision scroll event, let the editor handle the seek itself (for snapping support) if (!e.AltPressed && !e.IsPrecise) return false; return base.OnScroll(e); } protected override void UpdateAfterChildren() { base.UpdateAfterChildren(); if (handlingDragInput) seekTrackToCurrent(); else if (!editorClock.IsRunning) { // The track isn't running. There are three cases we have to be wary of: // 1) The user flick-drags on this timeline and we are applying an interpolated seek on the clock, until interrupted by 2 or 3. // 2) The user changes the track time through some other means (scrolling in the editor or overview timeline; clicking a hitobject etc.). We want the timeline to track the clock's time. // 3) An ongoing seek transform is running from an external seek. We want the timeline to track the clock's time. // The simplest way to cover the first two cases is by checking whether the scroll position has changed and the audio hasn't been changed externally // Checking IsSeeking covers the third case, where the transform may not have been applied yet. if (Current != lastScrollPosition && editorClock.CurrentTime == lastTrackTime && !editorClock.IsSeeking) seekTrackToCurrent(); else scrollToTrackTime(); } lastScrollPosition = Current; lastTrackTime = editorClock.CurrentTime; } private void seekTrackToCurrent() { if (!track.IsLoaded) return; double target = Current / Content.DrawWidth * track.Length; editorClock.Seek(Math.Min(track.Length, target)); } private void scrollToTrackTime() { if (!track.IsLoaded || track.Length == 0) return; // covers the case where the user starts playback after a drag is in progress. // we want to ensure the clock is always stopped during drags to avoid weird audio playback. if (handlingDragInput) editorClock.Stop(); ScrollTo((float)(editorClock.CurrentTime / track.Length) * Content.DrawWidth, false); } protected override bool OnMouseDown(MouseDownEvent e) { if (base.OnMouseDown(e)) { beginUserDrag(); return true; } return false; } protected override void OnMouseUp(MouseUpEvent e) { endUserDrag(); base.OnMouseUp(e); } private void beginUserDrag() { handlingDragInput = true; trackWasPlaying = editorClock.IsRunning; editorClock.Stop(); } private void endUserDrag() { handlingDragInput = false; if (trackWasPlaying) editorClock.Start(); } [Resolved] private EditorBeatmap beatmap { get; set; } [Resolved] private IBeatSnapProvider beatSnapProvider { get; set; } /// <summary> /// The total amount of time visible on the timeline. /// </summary> public double VisibleRange => track.Length / Zoom; public SnapResult SnapScreenSpacePositionToValidPosition(Vector2 screenSpacePosition) => new SnapResult(screenSpacePosition, null); public SnapResult SnapScreenSpacePositionToValidTime(Vector2 screenSpacePosition) => new SnapResult(screenSpacePosition, beatSnapProvider.SnapTime(getTimeFromPosition(Content.ToLocalSpace(screenSpacePosition)))); private double getTimeFromPosition(Vector2 localPosition) => (localPosition.X / Content.DrawWidth) * track.Length; public float GetBeatSnapDistanceAt(HitObject referenceObject) => throw new NotImplementedException(); public float DurationToDistance(HitObject referenceObject, double duration) => throw new NotImplementedException(); public double DistanceToDuration(HitObject referenceObject, float distance) => throw new NotImplementedException(); public double GetSnappedDurationFromDistance(HitObject referenceObject, float distance) => throw new NotImplementedException(); public float GetSnappedDistanceFromDistance(HitObject referenceObject, float distance) => throw new NotImplementedException(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace ParquetSharp.Bytes { using System; using System.Collections.Generic; using ParquetSharp.External; /** * A source of bytes capable of writing itself to an output. * A BytesInput should be consumed right away. * It is not a container. * For example if it is referring to a stream, * subsequent BytesInput reads from the stream will be incorrect * if the previous has not been consumed. * * @author Julien Le Dem * */ abstract public class BytesInput { private static readonly Log LOG = Log.getLog(typeof(BytesInput)); private static readonly bool DEBUG = false;//Log.DEBUG; private static readonly EmptyBytesInput EMPTY_BYTES_INPUT = new EmptyBytesInput(); /** * logically concatenate the provided inputs * @param inputs the inputs to concatenate * @return a concatenated input */ public static BytesInput concat(params BytesInput[] inputs) { return new SequenceBytesIn(Arrays.asList(inputs)); } /** * logically concatenate the provided inputs * @param inputs the inputs to concatenate * @return a concatenated input */ public static BytesInput concat(List<BytesInput> inputs) { return new SequenceBytesIn(inputs); } /** * @param in * @param bytes number of bytes to read * @return a BytesInput that will read that number of bytes from the stream */ public static BytesInput from(InputStream @in, int bytes) { return new StreamBytesInput(@in, bytes); } /** * @param buffer * @param length number of bytes to read * @return a BytesInput that will read the given bytes from the ByteBuffer */ public static BytesInput from(ByteBuffer buffer, int offset, int length) { return new ByteBufferBytesInput(buffer, offset, length); } /** * * @param in * @return a Bytes input that will write the given bytes */ public static BytesInput from(byte[] @in) { if (DEBUG) LOG.debug("BytesInput from array of " + @in.Length + " bytes"); return new ByteArrayBytesInput(@in, 0, @in.Length); } public static BytesInput from(byte[] @in, int offset, int length) { if (DEBUG) LOG.debug("BytesInput from array of " + length + " bytes"); return new ByteArrayBytesInput(@in, offset, length); } /** * @param intValue the int to write * @return a BytesInput that will write 4 bytes in little endian */ public static BytesInput fromInt(int intValue) { return new IntBytesInput(intValue); } /** * @param intValue the int to write * @return a BytesInput that will write var int */ public static BytesInput fromUnsignedVarInt(int intValue) { return new UnsignedVarIntBytesInput(intValue); } /** * * @param intValue the int to write */ public static BytesInput fromZigZagVarInt(int intValue) { int zigZag = (intValue << 1) ^ (intValue >> 31); return new UnsignedVarIntBytesInput(zigZag); } /** * @param arrayOut * @return a BytesInput that will write the content of the buffer */ public static BytesInput from(CapacityByteArrayOutputStream arrayOut) { return new CapacityBAOSBytesInput(arrayOut); } /** * @param baos - stream to wrap into a BytesInput * @return a BytesInput that will write the content of the buffer */ public static BytesInput from(ByteArrayOutputStream baos) { return new BAOSBytesInput(baos); } /** * @return an empty bytes input */ public static BytesInput empty() { return EMPTY_BYTES_INPUT; } /** * copies the input into a new byte array * @param bytesInput * @return */ public static BytesInput copy(BytesInput bytesInput) { return from(bytesInput.toByteArray()); } /** * writes the bytes into a stream * @param out */ abstract public void writeAllTo(OutputStream @out); /** * * @return a new byte array materializing the contents of this input */ public virtual byte[] toByteArray() { BAOS baos = new BAOS((int)size()); this.writeAllTo(baos); if (DEBUG) LOG.debug("converted " + size() + " to byteArray of " + baos.size() + " bytes"); return baos.getBuf(); } /** * * @return a new ByteBuffer materializing the contents of this input */ public virtual ByteBuffer toByteBuffer() { return ByteBuffer.wrap(toByteArray()); } /** * * @return a new InputStream materializing the contents of this input */ public InputStream toInputStream() { return new ByteBufferInputStream(toByteBuffer()); } /** * * @return the size in bytes that would be written */ abstract public long size(); sealed private class BAOS : ByteArrayOutputStream { public BAOS(int size) : base(size) { } public byte[] getBuf() { return toByteArray(); } } private class StreamBytesInput : BytesInput { private new static readonly Log LOG = Log.getLog(typeof(BytesInput.StreamBytesInput)); private readonly InputStream @in; private readonly int byteCount; internal StreamBytesInput(InputStream @in, int byteCount) { this.@in = @in; this.byteCount = byteCount; } public override void writeAllTo(OutputStream @out) { if (DEBUG) LOG.debug("write All " + byteCount + " bytes"); // TODO: more efficient @out.Write(this.toByteArray()); } public override byte[] toByteArray() { if (DEBUG) LOG.debug("read all " + byteCount + " bytes"); byte[] buf = new byte[byteCount]; @in.readFully(buf, 0, byteCount); return buf; } public override long size() { return byteCount; } } private class SequenceBytesIn : BytesInput { private static new readonly Log LOG = Log.getLog(typeof(BytesInput.SequenceBytesIn)); private readonly List<BytesInput> inputs; private readonly long _size; public SequenceBytesIn(List<BytesInput> inputs) { this.inputs = inputs; long total = 0; foreach (BytesInput input in inputs) { total += input.size(); } this._size = total; } public override void writeAllTo(OutputStream @out) { foreach (BytesInput input in inputs) { if (DEBUG) LOG.debug("write " + input.size() + " bytes to out"); if (DEBUG && input is SequenceBytesIn) LOG.debug("{"); input.writeAllTo(@out); if (DEBUG && input is SequenceBytesIn) LOG.debug("}"); } } public override long size() { return _size; } } private class IntBytesInput : BytesInput { private readonly int intValue; public IntBytesInput(int intValue) { this.intValue = intValue; } public override void writeAllTo(OutputStream @out) { BytesUtils.writeIntLittleEndian(@out, intValue); } public override ByteBuffer toByteBuffer() { return ByteBuffer.allocate(4).putInt(0, intValue); } public override long size() { return 4; } } private class UnsignedVarIntBytesInput : BytesInput { private readonly int intValue; public UnsignedVarIntBytesInput(int intValue) { this.intValue = intValue; } public override void writeAllTo(OutputStream @out) { BytesUtils.writeUnsignedVarInt(intValue, @out); } public override ByteBuffer toByteBuffer() { ByteBuffer ret = ByteBuffer.allocate((int)size()); BytesUtils.writeUnsignedVarInt(intValue, ret); return ret; } public override long size() { int s = 5 - ((Integer.numberOfLeadingZeros(intValue) + 3) / 7); return s == 0 ? 1 : s; } } sealed private class EmptyBytesInput : BytesInput { public override void writeAllTo(OutputStream @out) { } public override long size() { return 0; } public override ByteBuffer toByteBuffer() { return ByteBuffer.allocate(0); } } sealed private class CapacityBAOSBytesInput : BytesInput { private readonly CapacityByteArrayOutputStream arrayOut; internal CapacityBAOSBytesInput(CapacityByteArrayOutputStream arrayOut) { this.arrayOut = arrayOut; } public override void writeAllTo(OutputStream @out) { arrayOut.writeTo(@out); } public override long size() { return arrayOut.size(); } } private class BAOSBytesInput : BytesInput { private readonly ByteArrayOutputStream arrayOut; internal BAOSBytesInput(ByteArrayOutputStream arrayOut) { this.arrayOut = arrayOut; } public override void writeAllTo(OutputStream @out) { arrayOut.CopyTo(@out); } public override long size() { return arrayOut.size(); } } private class ByteArrayBytesInput : BytesInput { private readonly byte[] @in; private readonly int offset; private readonly int length; internal ByteArrayBytesInput(byte[] @in, int offset, int length) { this.@in = @in; this.offset = offset; this.length = length; } public override void writeAllTo(OutputStream @out) { @out.Write(@in, offset, length); } public override ByteBuffer toByteBuffer() { return ByteBuffer.wrap(@in, offset, length); } public override long size() { return length; } } private class ByteBufferBytesInput : BytesInput { private readonly ByteBuffer byteBuf; private readonly int length; private readonly int offset; internal ByteBufferBytesInput(ByteBuffer byteBuf, int offset, int length) { this.byteBuf = byteBuf; this.offset = offset; this.length = length; } public override void writeAllTo(OutputStream @out) { @out.Write(byteBuf.array(), byteBuf.arrayOffset() + offset, byteBuf.arrayOffset() + length); } public override ByteBuffer toByteBuffer() { byteBuf.position(offset); ByteBuffer buf = byteBuf.slice(); buf.limit(length); return buf; } public override long size() { return length; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.ComponentModel; using System.Threading; using Sanford.Multimedia.Midi; namespace Moritz.Midi { /// <summary> /// MidiSliders are MidiControls whose value can change gradually over time. In scores, each of these takes /// a byte argument (in the range 0..127) denoting the MSB values for the particular slider. /// Continuation characters: In addition to the msb argument, each slider text may end with a /// character which shows if and how the value subequently changes (until the next instance of the same /// slider: /// a) '-' the slider's value changes once per chord, in equal steps per chord /// b) '_' the slider's value changes once per chord, in equal steps per logical position /// c) '+' the slider's value changes continuously, in equal steps per chord /// d) '~' the slider's value changes continuously, in equal steps per logical position /// Examples: /// pan50~ pan23 pan80- pan20 /// The initial Instrument and Volume settings come from the capella file. /// All Sliders have a default value of 0, except /// volume 127 (alias v, vol) /// expression 64 (alias e, exp, expr) /// balance 64 (alias b, bal) /// pan 64 (alias p) /// pitchwheel 64 (alias pw) /// The default value is set when the control has no numeric argument. /// </summary> public abstract class MidiSlider : MidiControl { protected MidiSlider(int channel, ChannelCommand command, int msb, ControlContinuation continuation) : base(channel, command, msb) { } protected MidiSlider(int channel, ChannelCommand command, int msb, int lsb, ControlContinuation continuation) : base(channel, command, msb, lsb) { } protected MidiSlider(int channel, ControllerType controller, int msb, ControlContinuation continuation) : base(channel, controller, msb) { } } #region long (2-byte) sliders public class PitchWheel : MidiSlider { /// <summary> /// Achtung: this slider needs its lsb to be set! /// </summary> /// <param name="channel"></param> /// <param name="lsb"></param> /// <param name="continuation"></param> public PitchWheel(int channel, int lsb, ControlContinuation continuation) : base(channel, ChannelCommand.PitchWheel, 0, lsb, continuation) { } } public class ModulationWheel : MidiSlider { public ModulationWheel(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.ModulationWheel, msb, continuation) { } } public class BreathController : MidiSlider { public BreathController(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.BreathControl, msb, continuation) { } } public class FootPedal : MidiSlider { public FootPedal(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.FootPedal, msb, continuation) { } } public class PortamentoTime : MidiSlider { public PortamentoTime(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.PortamentoTime, msb, continuation) { } } public class Volume : MidiSlider { public Volume(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.Volume, msb, continuation) { // ControllerType.VolumeFine is ignored } } public class Balance : MidiSlider { public Balance(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.Balance, msb, continuation) { // ControllerType.BalanceFine is ignored. } } public class Pan : MidiSlider { public Pan(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.Pan, msb, continuation) { // ControllerType.PanFine is ignored. } } public class Expression : MidiSlider { public Expression(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.Expression, msb, continuation) { // ControllerType.ExpressionFine is ignored } } public class EffectControl1 : MidiSlider { public EffectControl1(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.EffectControl1, msb, continuation) { } } public class EffectControl2 : MidiSlider { public EffectControl2(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.EffectControl2, msb, continuation) { } } #endregion long (2-byte) sliders #region short (1-byte) sliders public class ChannelPressure : MidiSlider { public ChannelPressure(int channel, int msb, ControlContinuation continuation) : base(channel, ChannelCommand.ChannelPressure, msb, continuation) { } } public class GeneralPurposeSlider1 : MidiSlider { public GeneralPurposeSlider1(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.GeneralPurposeSlider1, msb, continuation) { } } public class GeneralPurposeSlider2 : MidiSlider { public GeneralPurposeSlider2(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.GeneralPurposeSlider2, msb, continuation) { } } public class GeneralPurposeSlider3 : MidiSlider { public GeneralPurposeSlider3(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.GeneralPurposeSlider3, msb, continuation) { } } public class GeneralPurposeSlider4 : MidiSlider { public GeneralPurposeSlider4(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.GeneralPurposeSlider4, msb, continuation) { } } public class SoundVariation : MidiSlider { public SoundVariation(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundVariation, msb, continuation) { } } public class SoundTimbre : MidiSlider { public SoundTimbre(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundTimbre, msb, continuation) { } } public class SoundReleaseTime : MidiSlider { public SoundReleaseTime(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundReleaseTime, msb, continuation) { } } public class SoundAttackTime : MidiSlider { public SoundAttackTime(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundAttackTime, msb, continuation) { } } public class SoundBrightness : MidiSlider { public SoundBrightness(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundBrightness, msb, continuation) { } } public class SoundControl6 : MidiSlider { public SoundControl6(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundControl6, msb, continuation) { } } public class SoundControl7 : MidiSlider { public SoundControl7(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundControl7, msb, continuation) { } } public class SoundControl8 : MidiSlider { public SoundControl8(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundControl8, msb, continuation) { } } public class SoundControl9 : MidiSlider { public SoundControl9(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundControl9, msb, continuation) { } } public class SoundControl10 : MidiSlider { public SoundControl10(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.SoundControl10, msb, continuation) { } } public class EffectsLevel : MidiSlider { public EffectsLevel(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.EffectsLevel, msb, continuation) { } } public class TremoloLevel : MidiSlider { public TremoloLevel(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.TremeloLevel, msb, continuation) { } } public class ChorusLevel : MidiSlider { public ChorusLevel(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.ChorusLevel, msb, continuation) { } } public class CelesteLevel : MidiSlider { public CelesteLevel(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.CelesteLevel, msb, continuation) { } } public class PhaserLevel : MidiSlider { public PhaserLevel(int channel, int msb, ControlContinuation continuation) : base(channel, ControllerType.PhaserLevel, msb, continuation) { } } #endregion short (1-byte) sliders }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; using Xunit.Sdk; namespace System.Diagnostics { /// <summary>Base class used for all tests that need to spawn a remote process.</summary> public abstract partial class RemoteExecutorTestBase : FileCleanupTestBase { /// <summary>A timeout (milliseconds) after which a wait on a remote operation should be considered a failure.</summary> public const int FailWaitTimeoutMilliseconds = 60 * 1000; /// <summary>The exit code returned when the test process exits successfully.</summary> public const int SuccessExitCode = 42; /// <summary>The name of the test console app.</summary> protected static readonly string TestConsoleApp = Path.GetFullPath("RemoteExecutorConsoleApp.exe"); /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Action method, RemoteInvokeOptions options = null) { // There's no exit code to check options = options ?? new RemoteInvokeOptions(); options.CheckExitCode = false; return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Action<string> method, string arg, RemoteInvokeOptions options = null) { // There's no exit code to check options = options ?? new RemoteInvokeOptions(); options.CheckExitCode = false; return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Action<string, string> method, string arg1, string arg2, RemoteInvokeOptions options = null) { // There's no exit code to check options = options ?? new RemoteInvokeOptions(); options.CheckExitCode = false; return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Action<string, string, string> method, string arg1, string arg2, string arg3, RemoteInvokeOptions options = null) { // There's no exit code to check options = options ?? new RemoteInvokeOptions(); options.CheckExitCode = false; return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Action<string, string, string, string> method, string arg1, string arg2, string arg3, string arg4, RemoteInvokeOptions options = null) { // There's no exit code to check options = options ?? new RemoteInvokeOptions(); options.CheckExitCode = false; return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<int> method, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<Task<int>> method, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg">The argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, Task<int>> method, string arg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, Task<int>> method, string arg1, string arg2, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg">The argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, int> method, string arg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, int> method, string arg1, string arg2, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, int> method, string arg1, string arg2, string arg3, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="arg4">The fourth argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="arg4">The fourth argument to pass to the method.</param> /// <param name="arg5">The fifth argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, string arg5, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4, arg5 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments without performing any modifications to the arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="args">The arguments to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvokeRaw(Delegate method, string unparsedArg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { unparsedArg }, options, pasteArguments: false); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="args">The arguments to pass to the method.</param> /// <param name="start">true if this function should Start the Process; false if that responsibility is left up to the caller.</param> /// <param name="psi">The ProcessStartInfo to use, or null for a default.</param> /// <param name="pasteArguments">true if this function should paste the arguments (e.g. surrounding with quotes); false if that responsibility is left up to the caller.</param> private static RemoteInvokeHandle RemoteInvoke(MethodInfo method, string[] args, RemoteInvokeOptions options, bool pasteArguments = true) { options = options ?? new RemoteInvokeOptions(); // Verify the specified method returns an int (the exit code) or nothing, // and that if it accepts any arguments, they're all strings. Assert.True(method.ReturnType == typeof(void) || method.ReturnType == typeof(int) || method.ReturnType == typeof(Task<int>)); Assert.All(method.GetParameters(), pi => Assert.Equal(typeof(string), pi.ParameterType)); // And make sure it's in this assembly. This isn't critical, but it helps with deployment to know // that the method to invoke is available because we're already running in this assembly. Type t = method.DeclaringType; Assembly a = t.GetTypeInfo().Assembly; // Start the other process and return a wrapper for it to handle its lifetime and exit checking. ProcessStartInfo psi = options.StartInfo; psi.UseShellExecute = false; if (!options.EnableProfiling) { // Profilers / code coverage tools doing coverage of the test process set environment // variables to tell the targeted process what profiler to load. We don't want the child process // to be profiled / have code coverage, so we remove these environment variables for that process // before it's started. psi.Environment.Remove("Cor_Profiler"); psi.Environment.Remove("Cor_Enable_Profiling"); psi.Environment.Remove("CoreClr_Profiler"); psi.Environment.Remove("CoreClr_Enable_Profiling"); } // If we need the host (if it exists), use it, otherwise target the console app directly. string metadataArgs = PasteArguments.Paste(new string[] { a.FullName, t.FullName, method.Name, options.ExceptionFile }, pasteFirstArgumentUsingArgV0Rules: false); string passedArgs = pasteArguments ? PasteArguments.Paste(args, pasteFirstArgumentUsingArgV0Rules: false) : string.Join(" ", args); string testConsoleAppArgs = ExtraParameter + " " + metadataArgs + " " + passedArgs; // Uap console app is globally registered. if (!File.Exists(HostRunner) && !PlatformDetection.IsUap) throw new IOException($"{HostRunner} test app isn't present in the test runtime directory."); if (options.RunAsSudo) { psi.FileName = "sudo"; psi.Arguments = HostRunner + " " + testConsoleAppArgs; } else { psi.FileName = HostRunner; psi.Arguments = testConsoleAppArgs; } // Return the handle to the process, which may or not be started return new RemoteInvokeHandle(options.Start ? Process.Start(psi) : new Process() { StartInfo = psi }, options, a.FullName, t.FullName, method.Name ); } private static MethodInfo GetMethodInfo(Delegate d) { // RemoteInvoke doesn't support marshaling state on classes associated with // the delegate supplied (often a display class of a lambda). If such fields // are used, odd errors result, e.g. NullReferenceExceptions during the remote // execution. Try to ward off the common cases by proactively failing early // if it looks like such fields are needed. if (d.Target != null) { // The only fields on the type should be compiler-defined (any fields of the compiler's own // making generally include '<' and '>', as those are invalid in C# source). Note that this logic // may need to be revised in the future as the compiler changes, as this relies on the specifics of // actually how the compiler handles lifted fields for lambdas. Type targetType = d.Target.GetType(); Assert.All( targetType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), fi => Assert.True(fi.Name.IndexOf('<') != -1, $"Field marshaling is not supported by {nameof(RemoteInvoke)}: {fi.Name}")); } return d.GetMethodInfo(); } /// <summary>A cleanup handle to the Process created for the remote invocation.</summary> public sealed class RemoteInvokeHandle : IDisposable { public RemoteInvokeHandle(Process process, RemoteInvokeOptions options, string assemblyName = null, string className = null, string methodName = null) { Process = process; Options = options; AssemblyName = assemblyName; ClassName = className; MethodName = methodName; } public int ExitCode { get { Process.WaitForExit(); return Process.ExitCode; } } public Process Process { get; set; } public RemoteInvokeOptions Options { get; private set; } public string AssemblyName { get; private set; } public string ClassName { get; private set; } public string MethodName { get; private set; } public void Dispose() { GC.SuppressFinalize(this); // before Dispose(true) in case the Dispose call throws Dispose(disposing: true); } private void Dispose(bool disposing) { Assert.True(disposing, $"A test {AssemblyName}!{ClassName}.{MethodName} forgot to Dispose() the result of RemoteInvoke()"); if (Process != null) { // A bit unorthodox to do throwing operations in a Dispose, but by doing it here we avoid // needing to do this in every derived test and keep each test much simpler. try { Assert.True(Process.WaitForExit(Options.TimeOut), $"Timed out after {Options.TimeOut}ms waiting for remote process {Process.Id}"); if (File.Exists(Options.ExceptionFile)) { throw new RemoteExecutionException(File.ReadAllText(Options.ExceptionFile)); } if (Options.CheckExitCode) { int expected = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Options.ExpectedExitCode : unchecked((sbyte)Options.ExpectedExitCode); int actual = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Process.ExitCode : unchecked((sbyte)Process.ExitCode); Assert.True(expected == actual, $"Exit code was {Process.ExitCode} but it should have been {Options.ExpectedExitCode}"); } } finally { if (File.Exists(Options.ExceptionFile)) { File.Delete(Options.ExceptionFile); } // Cleanup try { Process.Kill(); } catch { } // ignore all cleanup errors Process.Dispose(); Process = null; } } } ~RemoteInvokeHandle() { // Finalizer flags tests that omitted the explicit Dispose() call; they must have it, or they aren't // waiting on the remote execution Dispose(disposing: false); } private sealed class RemoteExecutionException : XunitException { internal RemoteExecutionException(string stackTrace) : base("Remote process failed with an unhandled exception.", stackTrace) { } } } } /// <summary>Options used with RemoteInvoke.</summary> public sealed class RemoteInvokeOptions { private bool _runAsSudo; public bool Start { get; set; } = true; public ProcessStartInfo StartInfo { get; set; } = new ProcessStartInfo(); public bool EnableProfiling { get; set; } = true; public bool CheckExitCode { get; set; } = true; public int TimeOut {get; set; } = RemoteExecutorTestBase.FailWaitTimeoutMilliseconds; public int ExpectedExitCode { get; set; } = RemoteExecutorTestBase.SuccessExitCode; public string ExceptionFile { get; } = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); public bool RunAsSudo { get { return _runAsSudo; } set { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new PlatformNotSupportedException(); } _runAsSudo = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Http.Headers; using Xunit; namespace System.Net.Http.Tests { public class AuthenticationHeaderValueTest { [Fact] public void Ctor_SetBothSchemeAndParameters_MatchExpectation() { AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Basic", "realm=\"contoso.com\""); Assert.Equal("Basic", auth.Scheme); Assert.Equal("realm=\"contoso.com\"", auth.Parameter); Assert.Throws<ArgumentException>(() => { new AuthenticationHeaderValue(null, "x"); }); Assert.Throws<ArgumentException>(() => { new AuthenticationHeaderValue("", "x"); }); Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue(" x", "x"); }); Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue("x ", "x"); }); Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue("x y", "x"); }); } [Fact] public void Ctor_SetSchemeOnly_MatchExpectation() { // Just verify that this ctor forwards the call to the overload taking 2 parameters. AuthenticationHeaderValue auth = new AuthenticationHeaderValue("NTLM"); Assert.Equal("NTLM", auth.Scheme); Assert.Null(auth.Parameter); } [Fact] public void ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly() { HttpResponseMessage response = new HttpResponseMessage(); string input = string.Empty; AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Digest", "qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\""); Assert.Equal( "Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"", auth.ToString()); response.Headers.ProxyAuthenticate.Add(auth); input += auth.ToString(); auth = new AuthenticationHeaderValue("Negotiate"); Assert.Equal("Negotiate", auth.ToString()); response.Headers.ProxyAuthenticate.Add(auth); input += ", " + auth.ToString(); auth = new AuthenticationHeaderValue("Custom", ""); // empty string should be treated like 'null'. Assert.Equal("Custom", auth.ToString()); response.Headers.ProxyAuthenticate.Add(auth); input += ", " + auth.ToString(); string result = response.Headers.ProxyAuthenticate.ToString(); Assert.Equal(input, result); } [Fact] public void Parse_GoodValues_Success() { HttpRequestMessage request = new HttpRequestMessage(); string input = " Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8 "; request.Headers.Authorization = AuthenticationHeaderValue.Parse(input); Assert.Equal(input.Trim(), request.Headers.Authorization.ToString()); } [Fact] public void TryParse_GoodValues_Success() { HttpRequestMessage request = new HttpRequestMessage(); string input = " Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",realm=\"Digest\" "; AuthenticationHeaderValue parsedValue; Assert.True(AuthenticationHeaderValue.TryParse(input, out parsedValue)); request.Headers.Authorization = parsedValue; Assert.Equal(input.Trim(), request.Headers.Authorization.ToString()); } [Fact] public void Parse_BadValues_Throws() { string input = "D\rigest qop=\"auth\",algorithm=MD5-sess,charset=utf-8,realm=\"Digest\""; Assert.Throws<FormatException>(() => { AuthenticationHeaderValue.Parse(input); }); } [Fact] public void TryParse_BadValues_False() { string input = ", Digest qop=\"auth\",nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\""; AuthenticationHeaderValue parsedValue; Assert.False(AuthenticationHeaderValue.TryParse(input, out parsedValue)); } [Fact] public void Add_BadValues_Throws() { string x = SR.net_http_message_not_success_statuscode; string input = "Digest algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\", "; HttpRequestMessage request = new HttpRequestMessage(); Assert.Throws<FormatException>(() => { request.Headers.Add(HttpKnownHeaderNames.Authorization, input); }); } [Fact] public void GetHashCode_UseSameAndDifferentAuth_SameOrDifferentHashCodes() { AuthenticationHeaderValue auth1 = new AuthenticationHeaderValue("A", "b"); AuthenticationHeaderValue auth2 = new AuthenticationHeaderValue("a", "b"); AuthenticationHeaderValue auth3 = new AuthenticationHeaderValue("A", "B"); AuthenticationHeaderValue auth4 = new AuthenticationHeaderValue("A"); AuthenticationHeaderValue auth5 = new AuthenticationHeaderValue("A", ""); AuthenticationHeaderValue auth6 = new AuthenticationHeaderValue("X", "b"); Assert.Equal(auth1.GetHashCode(), auth2.GetHashCode()); Assert.NotEqual(auth1.GetHashCode(), auth3.GetHashCode()); Assert.NotEqual(auth1.GetHashCode(), auth4.GetHashCode()); Assert.Equal(auth4.GetHashCode(), auth5.GetHashCode()); Assert.NotEqual(auth1.GetHashCode(), auth6.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentAuth_EqualOrNotEqualNoExceptions() { AuthenticationHeaderValue auth1 = new AuthenticationHeaderValue("A", "b"); AuthenticationHeaderValue auth2 = new AuthenticationHeaderValue("a", "b"); AuthenticationHeaderValue auth3 = new AuthenticationHeaderValue("A", "B"); AuthenticationHeaderValue auth4 = new AuthenticationHeaderValue("A"); AuthenticationHeaderValue auth5 = new AuthenticationHeaderValue("A", ""); AuthenticationHeaderValue auth6 = new AuthenticationHeaderValue("X", "b"); Assert.False(auth1.Equals(null)); Assert.True(auth1.Equals(auth2)); Assert.False(auth1.Equals(auth3)); Assert.False(auth1.Equals(auth4)); Assert.False(auth4.Equals(auth1)); Assert.False(auth1.Equals(auth5)); Assert.False(auth5.Equals(auth1)); Assert.True(auth4.Equals(auth5)); Assert.True(auth5.Equals(auth4)); Assert.False(auth1.Equals(auth6)); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { AuthenticationHeaderValue source = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); AuthenticationHeaderValue clone = (AuthenticationHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Scheme, clone.Scheme); Assert.Equal(source.Parameter, clone.Parameter); source = new AuthenticationHeaderValue("Kerberos"); clone = (AuthenticationHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Scheme, clone.Scheme); Assert.Null(clone.Parameter); } [Fact] public void GetAuthenticationLength_DifferentValidScenarios_AllReturnNonZero() { CallGetAuthenticationLength(" Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== ", 1, 37, new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==")); CallGetAuthenticationLength(" Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== , ", 1, 37, new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==")); CallGetAuthenticationLength(" Basic realm=\"example.com\"", 1, 25, new AuthenticationHeaderValue("Basic", "realm=\"example.com\"")); CallGetAuthenticationLength(" Basic realm=\"exam,,ple.com\",", 1, 27, new AuthenticationHeaderValue("Basic", "realm=\"exam,,ple.com\"")); CallGetAuthenticationLength(" Basic realm=\"exam,ple.com\",", 1, 26, new AuthenticationHeaderValue("Basic", "realm=\"exam,ple.com\"")); CallGetAuthenticationLength("NTLM ", 0, 7, new AuthenticationHeaderValue("NTLM")); CallGetAuthenticationLength("Digest", 0, 6, new AuthenticationHeaderValue("Digest")); CallGetAuthenticationLength("Digest,,", 0, 6, new AuthenticationHeaderValue("Digest")); CallGetAuthenticationLength("Digest a=b, c=d,,", 0, 15, new AuthenticationHeaderValue("Digest", "a=b, c=d")); CallGetAuthenticationLength("Kerberos,", 0, 8, new AuthenticationHeaderValue("Kerberos")); CallGetAuthenticationLength("Basic,NTLM", 0, 5, new AuthenticationHeaderValue("Basic")); CallGetAuthenticationLength("Digest a=b,c=\"d\", e=f, NTLM", 0, 21, new AuthenticationHeaderValue("Digest", "a=b,c=\"d\", e=f")); CallGetAuthenticationLength("Digest a = b , c = \"d\" , e = f ,NTLM", 0, 32, new AuthenticationHeaderValue("Digest", "a = b , c = \"d\" , e = f")); CallGetAuthenticationLength("Digest a = b , c = \"d\" , e = f , NTLM AbCdEf==", 0, 32, new AuthenticationHeaderValue("Digest", "a = b , c = \"d\" , e = f")); CallGetAuthenticationLength("Digest a = \"b\", c= \"d\" , e = f,NTLM AbC=,", 0, 31, new AuthenticationHeaderValue("Digest", "a = \"b\", c= \"d\" , e = f")); CallGetAuthenticationLength("Digest a=\"b\", c=d", 0, 17, new AuthenticationHeaderValue("Digest", "a=\"b\", c=d")); CallGetAuthenticationLength("Digest a=\"b\", c=d,", 0, 17, new AuthenticationHeaderValue("Digest", "a=\"b\", c=d")); CallGetAuthenticationLength("Digest a=\"b\", c=d ,", 0, 18, new AuthenticationHeaderValue("Digest", "a=\"b\", c=d")); CallGetAuthenticationLength("Digest a=\"b\", c=d ", 0, 19, new AuthenticationHeaderValue("Digest", "a=\"b\", c=d")); CallGetAuthenticationLength("Custom \"blob\", c=d,Custom2 \"blob\"", 0, 18, new AuthenticationHeaderValue("Custom", "\"blob\", c=d")); CallGetAuthenticationLength("Custom \"blob\", a=b,,,c=d,Custom2 \"blob\"", 0, 24, new AuthenticationHeaderValue("Custom", "\"blob\", a=b,,,c=d")); CallGetAuthenticationLength("Custom \"blob\", a=b,c=d,,,Custom2 \"blob\"", 0, 22, new AuthenticationHeaderValue("Custom", "\"blob\", a=b,c=d")); CallGetAuthenticationLength("Custom a=b, c=d,,,InvalidNextScheme\u670D", 0, 15, new AuthenticationHeaderValue("Custom", "a=b, c=d")); } [Fact] public void GetAuthenticationLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetAuthenticationLength(" NTLM", 0); // no leading whitespaces allowed CheckInvalidGetAuthenticationLength("Basic=", 0); CheckInvalidGetAuthenticationLength("=Basic", 0); CheckInvalidGetAuthenticationLength("Digest a=b, \u670D", 0); CheckInvalidGetAuthenticationLength("Digest a=b, c=d, \u670D", 0); CheckInvalidGetAuthenticationLength("Digest a=b, c=", 0); CheckInvalidGetAuthenticationLength("Digest a=\"b, c", 0); CheckInvalidGetAuthenticationLength("Digest a=\"b", 0); CheckInvalidGetAuthenticationLength("Digest a=b, c=\u670D", 0); CheckInvalidGetAuthenticationLength("", 0); CheckInvalidGetAuthenticationLength(null, 0); } #region Helper methods private static void CallGetAuthenticationLength(string input, int startIndex, int expectedLength, AuthenticationHeaderValue expectedResult) { object result = null; Assert.Equal(expectedLength, AuthenticationHeaderValue.GetAuthenticationLength(input, startIndex, out result)); Assert.Equal(expectedResult, result); } private static void CheckInvalidGetAuthenticationLength(string input, int startIndex) { object result = null; Assert.Equal(0, AuthenticationHeaderValue.GetAuthenticationLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.IO; using System.Text; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class ReaderTest { [Fact] public static void TestMain() { string connectionString = DataTestClass.SQL2005_Pubs; string tempTable = DataTestClass.GetUniqueName("T", "[", "]"); string tempKey = DataTestClass.GetUniqueName("K", "[", "]"); DbProviderFactory provider = SqlClientFactory.Instance; try { using (DbConnection con = provider.CreateConnection()) { con.ConnectionString = connectionString; con.Open(); using (DbCommand cmd = provider.CreateCommand()) { cmd.Connection = con; DbTransaction tx; #region <<Create temp table>> cmd.CommandText = "SELECT au_id, au_lname, au_fname, phone, address, city, state, zip, contract into " + tempTable + " from authors where au_id='UNKNOWN-ID'"; cmd.ExecuteNonQuery(); cmd.CommandText = "alter table " + tempTable + " add constraint " + tempKey + " primary key (au_id)"; cmd.ExecuteNonQuery(); #endregion tx = con.BeginTransaction(); cmd.Transaction = tx; cmd.CommandText = "insert into " + tempTable + "(au_id, au_lname, au_fname, phone, address, city, state, zip, contract) values ('876-54-3210', 'Doe', 'Jane' , '882-8080', 'One Microsoft Way', 'Redmond', 'WA', '98052', 0)"; cmd.ExecuteNonQuery(); cmd.CommandText = "insert into " + tempTable + "(au_id, au_lname, au_fname, phone, address, city, state, zip, contract) values ('876-54-3211', 'Doe', 'John' , '882-8181', NULL, NULL, NULL, NULL, 0)"; cmd.ExecuteNonQuery(); tx.Commit(); cmd.Transaction = null; string parameterName = "@p1"; DbParameter p1 = cmd.CreateParameter(); p1.ParameterName = parameterName; p1.Value = "876-54-3210"; cmd.Parameters.Add(p1); cmd.CommandText = "select * from " + tempTable + " where au_id >= " + parameterName; // Test GetValue + IsDBNull using (DbDataReader rdr = cmd.ExecuteReader()) { StringBuilder actualResult = new StringBuilder(); int currentValue = 0; string[] expectedValues = { "876-54-3210,Doe,Jane,882-8080 ,One Microsoft Way,Redmond,WA,98052,False", "876-54-3211,Doe,John,882-8181 ,(NULL),(NULL),(NULL),(NULL),False" }; while (rdr.Read()) { Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected"); for (int i = 0; i < rdr.FieldCount; i++) { if (i > 0) { actualResult.Append(","); } if (rdr.IsDBNull(i)) { actualResult.Append("(NULL)"); } else { actualResult.Append(rdr.GetValue(i)); } } DataTestClass.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data"); actualResult.Clear(); } } // Test GetFieldValue<T> + IsDBNull using (DbDataReader rdr = cmd.ExecuteReader()) { StringBuilder actualResult = new StringBuilder(); int currentValue = 0; string[] expectedValues = { "876-54-3210,Doe,Jane,882-8080 ,One Microsoft Way,Redmond,WA,98052,False", "876-54-3211,Doe,John,882-8181 ,(NULL),(NULL),(NULL),(NULL),False" }; while (rdr.Read()) { Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected"); for (int i = 0; i < rdr.FieldCount; i++) { if (i > 0) { actualResult.Append(","); } if (rdr.IsDBNull(i)) { actualResult.Append("(NULL)"); } else { if (rdr.GetFieldType(i) == typeof(bool)) { actualResult.Append(rdr.GetFieldValue<bool>(i)); } else if (rdr.GetFieldType(i) == typeof(decimal)) { actualResult.Append(rdr.GetFieldValue<decimal>(i)); } else { actualResult.Append(rdr.GetFieldValue<string>(i)); } } } DataTestClass.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data"); actualResult.Clear(); } } // Test GetFieldValueAsync<T> + IsDBNullAsync using (DbDataReader rdr = cmd.ExecuteReaderAsync().Result) { StringBuilder actualResult = new StringBuilder(); int currentValue = 0; string[] expectedValues = { "876-54-3210,Doe,Jane,882-8080 ,One Microsoft Way,Redmond,WA,98052,False", "876-54-3211,Doe,John,882-8181 ,(NULL),(NULL),(NULL),(NULL),False" }; while (rdr.ReadAsync().Result) { Assert.True(currentValue < expectedValues.Length, "ERROR: Received more values than expected"); for (int i = 0; i < rdr.FieldCount; i++) { if (i > 0) { actualResult.Append(","); } if (rdr.IsDBNullAsync(i).Result) { actualResult.Append("(NULL)"); } else { if (rdr.GetFieldType(i) == typeof(bool)) { actualResult.Append(rdr.GetFieldValueAsync<bool>(i).Result); } else if (rdr.GetFieldType(i) == typeof(decimal)) { actualResult.Append(rdr.GetFieldValueAsync<decimal>(i).Result); } else { actualResult.Append(rdr.GetFieldValueAsync<string>(i).Result); } } } DataTestClass.AssertEqualsWithDescription(expectedValues[currentValue++], actualResult.ToString(), "FAILED: Did not receive expected data"); actualResult.Clear(); } } } // GetStream byte[] correctBytes = { 0x12, 0x34, 0x56, 0x78 }; string queryString; string correctBytesAsString = "0x12345678"; queryString = string.Format("SELECT CAST({0} AS BINARY(20)), CAST({0} AS IMAGE), CAST({0} AS VARBINARY(20))", correctBytesAsString); using (var command = provider.CreateCommand()) { command.CommandText = queryString; command.Connection = con; using (var reader = command.ExecuteReader()) { reader.Read(); for (int i = 0; i < reader.FieldCount; i++) { byte[] buffer = new byte[256]; Stream stream = reader.GetStream(i); int bytesRead = stream.Read(buffer, 0, buffer.Length); for (int j = 0; j < correctBytes.Length; j++) { Assert.True(correctBytes[j] == buffer[j], "ERROR: Bytes do not match"); } } } } // GetTextReader string[] correctStrings = { "Hello World", "\uFF8A\uFF9B\uFF70\uFF9C\uFF70\uFF99\uFF84\uFF9E" }; string[] collations = { "Latin1_General_CI_AS", "Japanese_CI_AS" }; for (int j = 0; j < collations.Length; j++) { string substring = string.Format("(N'{0}' COLLATE {1})", correctStrings[j], collations[j]); queryString = string.Format("SELECT CAST({0} AS CHAR(20)), CAST({0} AS NCHAR(20)), CAST({0} AS NTEXT), CAST({0} AS NVARCHAR(20)), CAST({0} AS TEXT), CAST({0} AS VARCHAR(20))", substring); using (var command = provider.CreateCommand()) { command.CommandText = queryString; command.Connection = con; using (var reader = command.ExecuteReader()) { reader.Read(); for (int i = 0; i < reader.FieldCount; i++) { char[] buffer = new char[256]; TextReader textReader = reader.GetTextReader(i); int charsRead = textReader.Read(buffer, 0, buffer.Length); string stringRead = new string(buffer, 0, charsRead); Assert.True(stringRead == (string)reader.GetValue(i), "ERROR: Strings to not match"); } } } } } } finally { using (DbConnection con = provider.CreateConnection()) { con.ConnectionString = connectionString; con.Open(); using (DbCommand cmd = provider.CreateCommand()) { cmd.Connection = con; cmd.CommandText = "drop table " + tempTable; cmd.ExecuteNonQuery(); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GraphQL.DataLoader.Tests.Models; using GraphQL.DataLoader.Tests.Stores; using Moq; using Nito.AsyncEx; using Shouldly; using Xunit; namespace GraphQL.DataLoader.Tests { public class BatchDataLoaderTests : DataLoaderTestBase { [Fact] public void Operations_Are_Batched() { var mock = new Mock<IUsersStore>(); var users = Fake.Users.Generate(2); mock.Setup(store => store.GetUsersByIdAsync(It.IsAny<IEnumerable<int>>(), default)) .ReturnsAsync(users.ToDictionary(x => x.UserId), delay: TimeSpan.FromMilliseconds(20)); var usersStore = mock.Object; User user1 = null; User user2 = null; // Run within an async context to make sure we won't deadlock AsyncContext.Run(async () => { var loader = new BatchDataLoader<int, User>(usersStore.GetUsersByIdAsync); // Start async tasks to load by ID var result1 = loader.LoadAsync(1); var result2 = loader.LoadAsync(2); // Dispatch loading await loader.DispatchAsync(); var task1 = result1.GetResultAsync(); var task2 = result2.GetResultAsync(); // Now await tasks user1 = await task1; user2 = await task2; }); user1.ShouldNotBeNull(); user2.ShouldNotBeNull(); user1.UserId.ShouldBe(1); user2.UserId.ShouldBe(2); // This should have been called only once to load in a single batch mock.Verify(x => x.GetUsersByIdAsync(new[] { 1, 2 }, default), Times.Once); } [Fact] public void Batched_Honors_MaxBatchSize() { var mock = new Mock<IUsersStore>(); var users = Fake.Users.Generate(4); mock.Setup(store => store.GetUsersByIdAsync(It.IsAny<IEnumerable<int>>(), default)) .ReturnsAsync(() => users.ToDictionary(x => x.UserId)); var usersStore = mock.Object; User user1 = null; User user2 = null; User user3 = null; User user4 = null; User user5 = null; // Run within an async context to make sure we won't deadlock AsyncContext.Run(async () => { var loader = new BatchDataLoader<int, User>(usersStore.GetUsersByIdAsync, null, null, 2); // Start async tasks to load by ID var result1 = loader.LoadAsync(1); var result2 = loader.LoadAsync(2); var result3 = loader.LoadAsync(3); var result4 = loader.LoadAsync(4); var result5 = loader.LoadAsync(5); // Dispatch loading await loader.DispatchAsync(); var task1 = result1.GetResultAsync(); var task2 = result2.GetResultAsync(); var task3 = result3.GetResultAsync(); var task4 = result4.GetResultAsync(); var task5 = result5.GetResultAsync(); // Now await tasks user1 = await task1; user2 = await task2; user3 = await task3; user4 = await task4; user5 = await task5; }); user1.ShouldNotBeNull(); user2.ShouldNotBeNull(); user3.ShouldNotBeNull(); user4.ShouldNotBeNull(); user5.ShouldBeNull(); user1.UserId.ShouldBe(1); user2.UserId.ShouldBe(2); user3.UserId.ShouldBe(3); user4.UserId.ShouldBe(4); // This should have been called three times to load in three batch (maximum of 2 per batch) mock.Verify(x => x.GetUsersByIdAsync(new[] { 1, 2 }, default), Times.Once); mock.Verify(x => x.GetUsersByIdAsync(new[] { 3, 4 }, default), Times.Once); mock.Verify(x => x.GetUsersByIdAsync(new[] { 5 }, default), Times.Once); mock.VerifyNoOtherCalls(); } [Fact] public void Results_Are_Cached() { var mock = new Mock<IUsersStore>(); var users = Fake.Users.Generate(2); mock.Setup(store => store.GetUsersByIdAsync(It.IsAny<IEnumerable<int>>(), default)) .ReturnsAsync(() => users.ToDictionary(x => x.UserId)); var usersStore = mock.Object; User user1 = null; User user2 = null; User user3 = null; // Run within an async context to make sure we won't deadlock AsyncContext.Run(async () => { var loader = new BatchDataLoader<int, User>(usersStore.GetUsersByIdAsync); // Start async tasks to load by ID var result1 = loader.LoadAsync(1); var result2 = loader.LoadAsync(2); // Dispatch loading await loader.DispatchAsync(); var task1 = result1.GetResultAsync(); var task2 = result2.GetResultAsync(); // Now await tasks user1 = await task1; user2 = await task2; var result3 = loader.LoadAsync(1); //testing status meaningless with new design var task3 = result3.GetResultAsync(); task3.Status.ShouldBe(TaskStatus.RanToCompletion, "Task should already be complete because value comes from cache"); // This should not actually run the fetch delegate again await loader.DispatchAsync(); user3 = await task3; }); user3.ShouldBeSameAs(user1); mock.Verify(x => x.GetUsersByIdAsync(new[] { 1, 2 }, default), Times.Once); } [Fact] public void NonExistent_Key_Will_Return_Default_Value() { var mock = new Mock<IUsersStore>(); var users = Fake.Users.Generate(2); mock.Setup(store => store.GetUsersByIdAsync(It.IsAny<IEnumerable<int>>(), default)) .ReturnsAsync(() => users.ToDictionary(x => x.UserId)); var usersStore = mock.Object; var nullObjectUser = new User(); User user1 = null; User user2 = null; User user3 = null; // Run within an async context to make sure we won't deadlock AsyncContext.Run(async () => { // There is no user with the ID of 3 // 3 will not be in the returned Dictionary, so the DataLoader should use the specified default value var loader = new BatchDataLoader<int, User>(usersStore.GetUsersByIdAsync, defaultValue: nullObjectUser); // Start async tasks to load by ID var result1 = loader.LoadAsync(1); var result2 = loader.LoadAsync(2); var result3 = loader.LoadAsync(3); // Dispatch loading await loader.DispatchAsync(); var task1 = result1.GetResultAsync(); var task2 = result2.GetResultAsync(); var task3 = result3.GetResultAsync(); // Now await tasks user1 = await task1; user2 = await task2; user3 = await task3; }); user1.ShouldNotBeNull(); user2.ShouldNotBeNull(); user3.ShouldNotBeNull(); user1.UserId.ShouldBe(1); user2.UserId.ShouldBe(2); user3.ShouldBeSameAs(nullObjectUser, "The DataLoader should use the supplied default value"); } [Fact] public async Task All_Requested_Keys_Should_Be_Cached() { var mock = new Mock<IUsersStore>(); var users = Fake.Users.Generate(2); mock.Setup(store => store.GetUsersByIdAsync(It.IsAny<IEnumerable<int>>(), default)) .ReturnsAsync(() => users.ToDictionary(x => x.UserId)); var usersStore = mock.Object; var nullObjectUser = new User(); User user1 = null; User user2 = null; User user3 = null; // There is no user with the ID of 3 // 3 will not be in the returned Dictionary, so the DataLoader should use the specified default value var loader = new BatchDataLoader<int, User>(usersStore.GetUsersByIdAsync, defaultValue: nullObjectUser); // Start async tasks to load by ID var result1 = loader.LoadAsync(1); var result2 = loader.LoadAsync(2); var result3 = loader.LoadAsync(3); // Dispatch loading await loader.DispatchAsync(); var task1 = result1.GetResultAsync(); var task2 = result2.GetResultAsync(); var task3 = result3.GetResultAsync(); // Now await tasks user1 = await task1; user2 = await task2; user3 = await task3; // Load key 3 again. var result3b = loader.LoadAsync(3); //testing status is meaningless with new design var task3b = result3b.GetResultAsync(); task3b.Status.ShouldBe(TaskStatus.RanToCompletion, "Should be cached because it was requested in the first batch even though it wasn't in the result dictionary"); await loader.DispatchAsync(); var user3b = await task3b; user3.ShouldBeSameAs(nullObjectUser, "The DataLoader should use the supplied default value"); mock.Verify(x => x.GetUsersByIdAsync(new[] { 1, 2, 3 }, default), Times.Once, "Results should have been cached from first batch"); mock.VerifyNoOtherCalls(); } [Fact] public async Task ToDictionary_Exception() { var mock = new Mock<IUsersStore>(); var users = Fake.Users.Generate(2); // Set duplicate user IDs users.ForEach(u => u.UserId = 1); mock.Setup(store => store.GetUsersByIdAsync(It.IsAny<IEnumerable<int>>(), default)) .ReturnsAsync(() => users.ToDictionary(x => x.UserId)); var usersStore = mock.Object; var loader = new BatchDataLoader<int, User>(usersStore.GetUsersByIdAsync); // Start async tasks to load by ID var task1 = loader.LoadAsync(1); var task2 = loader.LoadAsync(2); // Dispatch loading //with new design, any errors would be thrown here; but this is not used by ExecutionStrategy anyway //await loader.DispatchAsync(); Exception ex = await Should.ThrowAsync<ArgumentException>(async () => { // Now await tasks var user1 = await task1.GetResultAsync(); var user2 = await task2.GetResultAsync(); }); var actualException = Should.Throw<ArgumentException>(() => { _ = new Dictionary<int, int> { { 1, 1 }, { 1, 1 } }; }); ex.Message.ShouldBe(actualException.Message); } [Fact] public async Task Failing_DataLoaders_Only_Execute_Once() { var mock = new Mock<IUsersStore>(); var users = Fake.Users.Generate(2); // Set duplicate user IDs users.ForEach(u => u.UserId = 1); mock.Setup(store => store.GetUsersByIdAsync(It.IsAny<IEnumerable<int>>(), default)) .ReturnsAsync(() => throw new ApplicationException()); var usersStore = mock.Object; var loader = new BatchDataLoader<int, User>(usersStore.GetUsersByIdAsync); // Start async tasks to load by ID var task1 = loader.LoadAsync(1); var task2 = loader.LoadAsync(2); Exception ex = await Should.ThrowAsync<ApplicationException>(async () => { // Now await tasks var user1 = await task1.GetResultAsync(); }); Exception ex2 = await Should.ThrowAsync<ApplicationException>(async () => { // Now await tasks var user2 = await task2.GetResultAsync(); }); mock.Verify(x => x.GetUsersByIdAsync(new[] { 1, 2 }, default)); mock.VerifyNoOtherCalls(); } [Fact] public async Task Keys_Are_DeDuped() { var mock = new Mock<IUsersStore>(); var users = Fake.Users.Generate(2); mock.Setup(store => store.GetUsersByIdAsync(It.IsAny<IEnumerable<int>>(), default)) .ReturnsAsync(() => users.ToDictionary(x => x.UserId)); var usersStore = mock.Object; var loader = new BatchDataLoader<int, User>(usersStore.GetUsersByIdAsync); // Start async tasks to load duplicate IDs var result1 = loader.LoadAsync(1); var result2 = loader.LoadAsync(1); // Dispatch loading await loader.DispatchAsync(); var task1 = result1.GetResultAsync(); var task2 = result2.GetResultAsync(); // Now await tasks var user1 = await task1; var user1b = await task2; user1.ShouldBeSameAs(users[0]); user1b.ShouldBeSameAs(users[0]); mock.Verify(x => x.GetUsersByIdAsync(new[] { 1 }, default), Times.Once, "The keys passed to the fetch delegate should be de-duplicated"); } [Fact] public async Task Returns_Null_For_Null_Reference_Types() { var loader = new BatchDataLoader<object, string>((_, _) => throw new Exception()); (await loader.LoadAsync(null).GetResultAsync()).ShouldBeNull(); } [Fact] public async Task Returns_Null_For_Null_Value_Types() { var loader = new BatchDataLoader<int?, string>((_, _) => throw new Exception()); (await loader.LoadAsync(null).GetResultAsync()).ShouldBeNull(); } } }
using System; using System.Net; using MbUnit.Framework; using Moq; using Subtext.Extensibility; using Subtext.Extensibility.Providers; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Email; using Subtext.Framework.Routing; namespace UnitTests.Subtext.Framework.Email { [TestFixture] public class EmailServiceTests { [Test] public void EmailCommentToBlogAuthor_WithCurrentUserIsAnAdmin_DoesNotSendEmail() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {}; var blog = new Blog {Email = "cody@example.com", UserName = "cody"}; var emailProvider = new Mock<EmailProvider>(); var context = new Mock<ISubtextContext>(); context.Setup(c => c.UrlHelper).Returns(new Mock<BlogUrlHelper>().Object); context.Setup(c => c.Blog).Returns(blog); context.Setup(c => c.User.Identity.Name).Returns("cody"); context.Setup(c => c.User.IsInRole("Admins")).Returns(true); var emailService = new EmailService(emailProvider.Object, new Mock<ITemplateEngine>().Object, context.Object); emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws( new Exception()); //act emailService.EmailCommentToBlogAuthor(comment); } [Test] public void EmailCommentToBlogAuthor_WithBlogHavingNullEmail_DoesNotSendEmail() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {}; var blog = new Blog {Email = string.Empty}; var emailProvider = new Mock<EmailProvider>(); var context = new Mock<ISubtextContext>(); context.Setup(c => c.UrlHelper).Returns(new Mock<BlogUrlHelper>().Object); context.Setup(c => c.Blog).Returns(blog); var emailService = new EmailService(emailProvider.Object, new Mock<ITemplateEngine>().Object, context.Object); emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws( new Exception()); //act emailService.EmailCommentToBlogAuthor(comment); } [Test] public void EmailCommentToBlogAuthor_WithCommentThatIsTrackback_DoesNotSendEmail() { //arrange var comment = new FeedbackItem(FeedbackType.PingTrack) {}; var blog = new Blog {Email = "foo@example.com"}; var context = new Mock<ISubtextContext>(); context.Setup(c => c.UrlHelper).Returns(new Mock<BlogUrlHelper>().Object); context.Setup(c => c.Blog).Returns(blog); var emailProvider = new Mock<EmailProvider>(); var emailService = new EmailService(emailProvider.Object, new Mock<ITemplateEngine>().Object, context.Object); emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Throws( new Exception()); //act emailService.EmailCommentToBlogAuthor(comment); } [Test] public void EmailCommentToBlogAuthor_WithComment_UsesTitleForSubject() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "the subject", FlaggedAsSpam = false}; var emailProvider = new Mock<EmailProvider>(); EmailService emailService = SetupEmailService(comment, emailProvider); string subject = null; emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback <string, string, string, string>((to, from, title, message) => subject = title); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("Comment: the subject (via the blog)", subject); } [Test] public void EmailCommentToBlogAuthor_WithCommentHavingNullSource_SendsEmail() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) { Id = 121, Author = "me", Title = "the subject", FlaggedAsSpam = false, Entry = null }; var emailProvider = new Mock<EmailProvider>(); var context = new Mock<ISubtextContext>(); context.Setup(c => c.Blog).Returns(new Blog {Title = "the blog", Email = "haacked@example.com"}); context.Setup(c => c.User.IsInRole("Admins")).Returns(false); context.Setup(c => c.UrlHelper.FeedbackUrl(It.IsAny<FeedbackItem>())).Returns((VirtualPath)null); var templateEngine = new Mock<ITemplateEngine>(); var template = new Mock<ITextTemplate>(); template.Setup(t => t.Format(It.IsAny<Object>())).Returns("whatever"); templateEngine.Setup(t => t.GetTemplate("CommentReceived")).Returns(template.Object); var emailService = new EmailService(emailProvider.Object, templateEngine.Object, context.Object); string subject = null; emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback <string, string, string, string>((to, from, title, message) => subject = title); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("Comment: the subject (via the blog)", subject); } [Test] public void EmailCommentToBlogAuthor_WithCommentFlaggedAsSpam_PrefacesSubjectWithSpamHeader() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, FlaggedAsSpam = true, Author = "me", Title = "the subject"}; var emailProvider = new Mock<EmailProvider>(); EmailService emailService = SetupEmailService(comment, emailProvider); string subject = null; emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback <string, string, string, string>((to, from, title, message) => subject = title); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("[SPAM Flagged] Comment: the subject (via the blog)", subject); } [Test] public void EmailCommentToBlogAuthor_WithCommentHavingEmail_UsesEmailAsFromEmail() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Email = "from@example.com", Author = "me", Title = "the subject", FlaggedAsSpam = true}; var emailProvider = new Mock<EmailProvider>(); emailProvider.Object.UseCommentersEmailAsFromAddress = true; emailProvider.Object.AdminEmail = "admin@example.com"; EmailService emailService = SetupEmailService(comment, emailProvider); string fromEmail = null; emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback <string, string, string, string>((to, from, title, message) => fromEmail = from); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("from@example.com", fromEmail); } [Test] public void EmailCommentToBlogAuthor_WithCommentHavingEmailButUseCommentersEmailAsFromAddressSetToFalse_UsesAdminEmailAsFromEmail () { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Email = "from@example.com", Author = "me", Title = "the subject", FlaggedAsSpam = true}; var emailProvider = new Mock<EmailProvider>(); emailProvider.Object.UseCommentersEmailAsFromAddress = false; emailProvider.Object.AdminEmail = "admin@example.com"; EmailService emailService = SetupEmailService(comment, emailProvider); string fromEmail = null; emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback <string, string, string, string>((to, from, title, message) => fromEmail = from); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("admin@example.com", fromEmail); } [Test] public void EmailCommentToBlogAuthor_WithCommentHavingNullEmail_UsesProviderEmail() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Email = null, Author = "me", Title = "the subject", FlaggedAsSpam = true}; var emailProvider = new Mock<EmailProvider>(); emailProvider.Object.AdminEmail = "admin@example.com"; EmailService emailService = SetupEmailService(comment, emailProvider); string fromEmail = null; emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback <string, string, string, string>((to, from, title, message) => fromEmail = from); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("admin@example.com", fromEmail); } private static EmailService SetupEmailService(FeedbackItem comment, Mock<EmailProvider> emailProvider) { var templateEngine = new Mock<ITemplateEngine>(); var template = new Mock<ITextTemplate>(); templateEngine.Setup(t => t.GetTemplate(It.IsAny<string>())).Returns(template.Object); template.Setup(t => t.Format(It.IsAny<object>())).Returns("message"); var urlHelper = new Mock<BlogUrlHelper>(); urlHelper.Setup(u => u.FeedbackUrl(comment)).Returns("/"); var context = new Mock<ISubtextContext>(); context.Setup(c => c.UrlHelper).Returns(urlHelper.Object); context.Setup(c => c.Blog).Returns(new Blog {Email = "test@test.com", Author = "to", Host = "localhost", Title = "the blog"}); var emailService = new EmailService(emailProvider.Object, templateEngine.Object, context.Object); return emailService; } [Test] public void EmailCommentToBlogAuthor_WithBlog_UsesBlogEmailForToEmail() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "the subject", FlaggedAsSpam = false}; var emailProvider = new Mock<EmailProvider>(); var templateEngine = new Mock<ITemplateEngine>(); var template = new Mock<ITextTemplate>(); templateEngine.Setup(t => t.GetTemplate(It.IsAny<string>())).Returns(template.Object); template.Setup(t => t.Format(It.IsAny<object>())).Returns("message"); var urlHelper = new Mock<BlogUrlHelper>(); urlHelper.Setup(u => u.FeedbackUrl(comment)).Returns("/"); var context = new Mock<ISubtextContext>(); context.Setup(c => c.UrlHelper).Returns(urlHelper.Object); context.Setup(c => c.Blog).Returns(new Blog {Email = "test@test.com", Author = "to", Host = "localhost", Title = "the blog"}); string toEmail = null; emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback <string, string, string, string>((to, from, title, message) => toEmail = to); var emailService = new EmailService(emailProvider.Object, templateEngine.Object, context.Object); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("test@test.com", toEmail); } [Test] public void EmailCommentToBlogAuthor_WithCommentFlaggedAsSpam_SetsSpamField() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "subject", FlaggedAsSpam = true}; string sentMessage = null; EmailService emailService = SetupEmailService(comment, "{spamflag}", sent => sentMessage = sent); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("Spam Flagged ", sentMessage); } [Test] public void EmailCommentToBlogAuthor_WithCommentHavingId_SetsSourceFieldWithUrlContainingId() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "subject", FlaggedAsSpam = true}; string sentMessage = null; EmailService emailService = SetupEmailService(comment, "{comment.source}", sent => sentMessage = sent); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("http://localhost/comment#121", sentMessage); } [Test] public void EmailCommentToBlogAuthor_WithEmail_SetsFromEmailAccordingly() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "subject", Email = "test@example.com"}; string sentMessage = null; EmailService emailService = SetupEmailService(comment, "{comment.email}", sent => sentMessage = sent); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("test@example.com", sentMessage); } [Test] public void EmailCommentToBlogAuthor_WithoutEmail_SetsFromEmailToNoneProvided() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "subject", Email = null}; string sentMessage = null; EmailService emailService = SetupEmailService(comment, "{comment.email}", sent => sentMessage = sent); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("none given", sentMessage); } [Test] public void EmailCommentToBlogAuthor_WithAuthor_SetsAuthorName() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "subject", Email = null}; string sentMessage = null; EmailService emailService = SetupEmailService(comment, "{comment.author}", sent => sentMessage = sent); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("me", sentMessage); } [Test] public void EmailCommentToBlogAuthor_WithSourceUrlSpecified_SetsUrl() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "subject", SourceUrl = new Uri("http://example.com/")}; string sentMessage = null; EmailService emailService = SetupEmailService(comment, "{comment.authorUrl}", sent => sentMessage = sent); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("http://example.com/", sentMessage); } [Test] public void EmailCommentToBlogAuthor_WithSourceIp_SetsIp() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "subject", IpAddress = IPAddress.Parse("127.0.0.1")}; string sentMessage = null; EmailService emailService = SetupEmailService(comment, "{comment.ip}", sent => sentMessage = sent); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("127.0.0.1", sentMessage); } [Test] public void EmailCommentToBlogAuthor_WithBodyContainingHtml_CleansHtml() { //arrange var comment = new FeedbackItem(FeedbackType.Comment) {Id = 121, Author = "me", Title = "subject", Body = "This<br />is not&lt;br /&gt;right"}; string sentMessage = null; EmailService emailService = SetupEmailService(comment, "{comment.body}", sent => sentMessage = sent); //act emailService.EmailCommentToBlogAuthor(comment); //assert Assert.AreEqual("This" + Environment.NewLine + "is not" + Environment.NewLine + "right", sentMessage); } private EmailService SetupEmailService(FeedbackItem comment, string templateText, Action<string> messageCallback) { var emailProvider = new Mock<EmailProvider>(); var templateEngine = new Mock<ITemplateEngine>(); var template = new NamedFormatTextTemplate(templateText); var urlHelper = new Mock<BlogUrlHelper>(); var context = new Mock<ISubtextContext>(); context.Setup(c => c.UrlHelper).Returns(urlHelper.Object); context.Setup(c => c.Blog).Returns(new Blog {Email = "foo@example.com", Author = "to", Host = "localhost"}); urlHelper.Setup(u => u.FeedbackUrl(comment)).Returns<FeedbackItem>(f => "/comment#" + f.Id); templateEngine.Setup(t => t.GetTemplate("CommentReceived")).Returns(template); emailProvider.Setup( e => e.Send(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback <string, string, string, string>((to, from, title, message) => messageCallback(message)); return new EmailService(emailProvider.Object, templateEngine.Object, context.Object); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_CUSTOM_TYPE_DESCRIPTOR #nullable enable using System; using System.Collections.Generic; using System.ComponentModel; using IronPython.Runtime.Types; using Microsoft.Scripting.Actions.Calls; namespace IronPython.Runtime.Operations { /// <summary> /// Helper class that all custom type descriptor implementations call for /// the bulk of their implementation. /// </summary> public static class CustomTypeDescHelpers { #region ICustomTypeDescriptor helper functions [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")] public static AttributeCollection GetAttributes(object self) { return AttributeCollection.Empty; } public static string? GetClassName(object self) { if (PythonOps.TryGetBoundAttr(DefaultContext.DefaultCLS, self, "__class__", out object? cls)) { return PythonOps.GetBoundAttr(DefaultContext.DefaultCLS, cls, "__name__").ToString(); } return null; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")] public static string? GetComponentName(object self) { return null; } public static TypeConverter GetConverter(object self) { return new TypeConv(self); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")] public static EventDescriptor? GetDefaultEvent(object self) { return null; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")] public static PropertyDescriptor? GetDefaultProperty(object self) { return null; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "editorBaseType")] public static object? GetEditor(object self, Type editorBaseType) { return null; } public static EventDescriptorCollection GetEvents(object self, Attribute[] attributes) { if (attributes == null || attributes.Length == 0) return GetEvents(self); //!!! update when we support attributes on python types // you want things w/ attributes? we don't have attributes! return EventDescriptorCollection.Empty; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")] public static EventDescriptorCollection GetEvents(object self) { return EventDescriptorCollection.Empty; } public static PropertyDescriptorCollection GetProperties(object self) { return new PropertyDescriptorCollection(GetPropertiesImpl(self, new Attribute[0])); } public static PropertyDescriptorCollection GetProperties(object self, Attribute[] attributes) { return new PropertyDescriptorCollection(GetPropertiesImpl(self, attributes)); } private static PropertyDescriptor[] GetPropertiesImpl(object self, Attribute[] attributes) { IList<object?> attrNames = PythonOps.GetAttrNames(DefaultContext.DefaultCLS, self); List<PropertyDescriptor> descrs = new List<PropertyDescriptor>(); if (attrNames != null) { foreach (object? o in attrNames) { if (!(o is string s)) continue; PythonType dt = DynamicHelpers.GetPythonType(self); dt.TryResolveSlot(DefaultContext.DefaultCLS, s, out PythonTypeSlot attrSlot); object attrVal = ObjectOps.__getattribute__(DefaultContext.DefaultCLS, self, s); Type attrType = (attrVal == null) ? typeof(NoneTypeOps) : attrVal.GetType(); if ((attrSlot != null && ShouldIncludeProperty(attrSlot, attributes)) || (attrSlot == null && ShouldIncludeInstanceMember(s, attributes))) { descrs.Add(new SuperDynamicObjectPropertyDescriptor(s, attrType, self.GetType())); } } } return descrs.ToArray(); } private static bool ShouldIncludeInstanceMember(string memberName, Attribute[] attributes) { bool include = true; foreach (Attribute attr in attributes) { if (attr.GetType() == typeof(BrowsableAttribute)) { if (memberName.StartsWith("__", StringComparison.Ordinal) && memberName.EndsWith("__", StringComparison.Ordinal)) { include = false; } } else { // unknown attribute, Python doesn't support attributes, so we // say this doesn't have that attribute. include = false; } } return include; } private static bool ShouldIncludeProperty(PythonTypeSlot attrSlot, Attribute[] attributes) { bool include = true; foreach (Attribute attr in attributes) { if (attrSlot is ReflectedProperty rp && rp.Info != null) { include &= rp.Info.IsDefined(attr.GetType(), true); } else if (attr.GetType() == typeof(BrowsableAttribute)) { if (!(attrSlot is PythonTypeUserDescriptorSlot userSlot)) { if (!(attrSlot is PythonProperty)) { include = false; } } else if (!(userSlot.Value is IPythonObject)) { include = false; } } else { // unknown attribute, Python doesn't support attributes, so we // say this doesn't have that attribute. include = false; } } return include; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "pd")] public static object GetPropertyOwner(object self, PropertyDescriptor pd) { return self; } #endregion private class SuperDynamicObjectPropertyDescriptor : PropertyDescriptor { private readonly string _name; private readonly Type _propertyType; private readonly Type _componentType; internal SuperDynamicObjectPropertyDescriptor( string name, Type propertyType, Type componentType) : base(name, null) { _name = name; _propertyType = propertyType; _componentType = componentType; } public override object GetValue(object? component) { return PythonOps.GetBoundAttr(DefaultContext.DefaultCLS, component, _name); } public override void SetValue(object? component, object? value) { PythonOps.SetAttr(DefaultContext.DefaultCLS, component, _name, value); } public override bool CanResetValue(object component) { return true; } public override Type ComponentType { get { return _componentType; } } public override bool IsReadOnly { get { return false; } } public override Type PropertyType { get { return _propertyType; } } public override void ResetValue(object component) { PythonOps.DeleteAttr(DefaultContext.DefaultCLS, component, _name); } public override bool ShouldSerializeValue(object component) { return PythonOps.TryGetBoundAttr(component, _name, out _); } } private class TypeConv : TypeConverter { private readonly object convObj; public TypeConv(object self) { convObj = self; } #region TypeConverter overrides public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) { return Converter.TryConvert(convObj, destinationType, out _); } public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return Converter.CanConvertFrom(sourceType, convObj.GetType(), NarrowingLevel.All); } public override object ConvertFrom(ITypeDescriptorContext? context, System.Globalization.CultureInfo? culture, object value) { return Converter.Convert(value, convObj.GetType()); } public override object ConvertTo(ITypeDescriptorContext? context, System.Globalization.CultureInfo? culture, object? value, Type destinationType) { return Converter.Convert(convObj, destinationType); } public override bool GetCreateInstanceSupported(ITypeDescriptorContext? context) { return false; } public override bool GetPropertiesSupported(ITypeDescriptorContext? context) { return false; } public override bool GetStandardValuesSupported(ITypeDescriptorContext? context) { return false; } public override bool IsValid(ITypeDescriptorContext? context, object? value) { return Converter.TryConvert(value, convObj.GetType(), out _); } #endregion } } } #endif
namespace IdSharp.Tagging.ID3v2 { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using zlib; internal static class Utils { static Utils() { Utils.m_ISO88591 = Encoding.GetEncoding(0x6faf); } public static long ConvertToInt64(byte[] byteArray) { long num1 = 0; for (int num2 = 0; num2 < byteArray.Length; num2++) { num1 = num1 << 8; num1 += byteArray[num2]; } return num1; } public static byte[] ConvertToUnsynchronized(byte[] data) { using (MemoryStream stream1 = new MemoryStream((int) (data.Length * 1.05))) { for (int num1 = 0; num1 < data.Length; num1++) { stream1.WriteByte(data[num1]); if (((data[num1] == 0xff) && (num1 != (data.Length - 1))) && ((data[num1 + 1] == 0) || ((data[num1 + 1] & 0xe0) == 0xe0))) { stream1.WriteByte(0); } } return stream1.ToArray(); } } private static void CopyStream(Stream input, Stream output, int size) { byte[] buffer1 = new byte[size]; input.Read(buffer1, 0, size); output.Write(buffer1, 0, size); output.Flush(); } public static Stream DecompressFrame(Stream stream, int compressedSize) { Stream stream1 = new MemoryStream(); ZOutputStream stream2 = new ZOutputStream(stream1); Utils.CopyStream(stream, stream2, compressedSize); stream1.Position = 0; return stream1; } public static byte[] Get2Bytes(short value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", value, "Value cannot be less than 0"); } return Utils.Get2Bytes((ushort) value); } public static byte[] Get2Bytes(ushort value) { return new byte[] { ((byte) ((value >> 8) & 0xff)), ((byte) (value & 0xff)) }; } public static byte[] Get4Bytes(int value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", value, "Value cannot be less than 0"); } return Utils.Get4Bytes((uint) value); } public static byte[] Get4Bytes(uint value) { return new byte[] { ((byte) ((value >> 0x18) & 0xff)), ((byte) ((value >> 0x10) & 0xff)), ((byte) ((value >> 8) & 0xff)), ((byte) (value & 0xff)) }; } public static byte[] Get8Bytes(ulong value) { return new byte[] { ((byte) ((value >> 0x38) & 0xff)), ((byte) ((value >> 0x30) & 0xff)), ((byte) ((value >> 40) & 0xff)), ((byte) ((value >> 0x20) & 0xff)), ((byte) ((value >> 0x18) & 0xff)), ((byte) ((value >> 0x10) & 0xff)), ((byte) ((value >> 8) & 0xff)), ((byte) (value & 0xff)) }; } public static byte[] GetBytesDecimal(decimal decimalValue, int bytes) { byte[] buffer1 = Utils.GetBytesMinimal((ulong) decimalValue); if (buffer1.Length == bytes) { return buffer1; } if (buffer1.Length > bytes) { byte[] buffer2 = new byte[bytes]; int num1 = buffer1.Length - bytes; for (int num2 = 0; num1 < buffer1.Length; num2++) { buffer2[num2] = buffer1[num1]; num1++; } return buffer2; } byte[] buffer3 = new byte[bytes]; int num3 = bytes - buffer1.Length; for (int num4 = 0; num3 < bytes; num4++) { buffer3[num3] = buffer1[num4]; num3++; } return buffer3; } public static byte[] GetBytesMinimal(long value) { return Utils.GetBytesMinimal((ulong) value); } public static byte[] GetBytesMinimal(ulong value) { if (value <= 0xff) { return new byte[] { ((byte) value) }; } if (value <= 0xffff) { return Utils.Get2Bytes((ushort) value); } if (value <= 0xffffffff) { return Utils.Get4Bytes((uint) value); } return Utils.Get8Bytes(value); } public static byte[] GetStringBytes(ID3v2TagVersion tagVersion, EncodingType encodingType, string value, bool isTerminated) { List<byte> list1 = new List<byte>(); switch (tagVersion) { case ID3v2TagVersion.ID3v22: { EncodingType type1 = encodingType; if (type1 == EncodingType.Unicode) { if (!string.IsNullOrEmpty(value)) { list1.Add(0xff); list1.Add(0xfe); list1.AddRange(Encoding.Unicode.GetBytes(value)); } if (isTerminated) { list1.AddRange(new byte[2]); } break; } list1.AddRange(Utils.ISO88591GetBytes(value)); if (isTerminated) { list1.Add(0); } break; } case ID3v2TagVersion.ID3v23: { EncodingType type2 = encodingType; if (type2 != EncodingType.Unicode) { list1.AddRange(Utils.ISO88591GetBytes(value)); if (isTerminated) { list1.Add(0); } break; } if (!string.IsNullOrEmpty(value)) { list1.Add(0xff); list1.Add(0xfe); list1.AddRange(Encoding.Unicode.GetBytes(value)); } if (isTerminated) { list1.AddRange(new byte[2]); } break; } case ID3v2TagVersion.ID3v24: switch (encodingType) { case EncodingType.Unicode: if (!string.IsNullOrEmpty(value)) { list1.Add(0xff); list1.Add(0xfe); list1.AddRange(Encoding.Unicode.GetBytes(value)); } if (isTerminated) { list1.AddRange(new byte[2]); } break; case EncodingType.UTF16BE: if (!string.IsNullOrEmpty(value)) { list1.AddRange(Encoding.BigEndianUnicode.GetBytes(value)); } if (isTerminated) { list1.AddRange(new byte[2]); } break; case EncodingType.UTF8: if (!string.IsNullOrEmpty(value)) { list1.AddRange(Encoding.UTF8.GetBytes(value)); } if (isTerminated) { list1.Add(0); } break; } list1.AddRange(Utils.ISO88591GetBytes(value)); if (isTerminated) { list1.Add(0); } break; default: throw new ArgumentException("Unknown tag version"); } return list1.ToArray(); } public static bool IsBitSet(byte byteToCheck, byte bitToCheck) { return (((byteToCheck >> (bitToCheck & 0x1f)) & 1) == 1); } public static byte[] ISO88591GetBytes(string value) { if (value == null) { return new byte[0]; } return Utils.m_ISO88591.GetBytes(value); } public static string ISO88591GetString(byte[] value) { if (value == null) { return string.Empty; } return Utils.m_ISO88591.GetString(value); } public static byte[] Read(Stream stream, int count) { byte[] buffer1 = new byte[count]; if (stream.Read(buffer1, 0, count) != count) { string text1 = string.Format("Attempted to read past the end of the stream when requesting {0} bytes at position {1}", count, stream.Position); Trace.WriteLine(text1); throw new InvalidDataException(text1); } return buffer1; } public static byte[] Read(Stream stream, int count, ref int bytesLeft) { bytesLeft -= count; return Utils.Read(stream, count); } public static byte ReadByte(Stream stream) { int num1 = stream.ReadByte(); if (num1 == -1) { string text1 = string.Format("Attempted to read past the end of the stream at position {0}", stream.Position); Trace.WriteLine(text1); throw new InvalidDataException(text1); } return (byte) num1; } public static byte ReadByte(Stream stream, ref int bytesLeft) { if (bytesLeft > 0) { bytesLeft -= 1; return Utils.ReadByte(stream); } string text1 = string.Format("Attempted to read past the end of the frame at position {0}", stream.Position); Trace.WriteLine(text1); throw new InvalidDataException(text1); } public static short ReadInt16(Stream stream, ref int bytesLeft) { byte[] buffer1 = Utils.Read(stream, 2); bytesLeft -= 2; return (short) ((buffer1[0] << 8) + buffer1[1]); } public static int ReadInt24(Stream stream) { byte[] buffer1 = Utils.Read(stream, 3); return (((buffer1[0] << 0x10) + (buffer1[1] << 8)) + buffer1[2]); } public static int ReadInt24Unsynchronized(Stream stream) { byte[] buffer1 = Utils.ReadUnsynchronized(stream, 3); return (((buffer1[0] << 0x10) + (buffer1[1] << 8)) + buffer1[2]); } public static int ReadInt32(Stream stream) { byte[] buffer1 = Utils.Read(stream, 4); return ((((buffer1[0] << 0x18) + (buffer1[1] << 0x10)) + (buffer1[2] << 8)) + buffer1[3]); } public static int ReadInt32SyncSafe(Stream stream) { byte[] buffer1 = Utils.Read(stream, 4); return ((((buffer1[0] << 0x15) + (buffer1[1] << 14)) + (buffer1[2] << 7)) + buffer1[3]); } public static int ReadInt32Unsynchronized(Stream stream) { byte[] buffer1 = Utils.ReadUnsynchronized(stream, 4); return ((((buffer1[0] << 0x18) + (buffer1[1] << 0x10)) + (buffer1[2] << 8)) + buffer1[3]); } public static string ReadString(EncodingType textEncoding, Stream stream, ref int bytesLeft) { string text1; if (bytesLeft > 0) { List<byte> list1 = new List<byte>(); if (textEncoding != EncodingType.ISO88591) { if (textEncoding == EncodingType.Unicode) { byte num2; byte num3; do { num2 = Utils.ReadByte(stream); list1.Add(num2); bytesLeft -= 1; if (bytesLeft == 0) { return ""; } num3 = Utils.ReadByte(stream); list1.Add(num3); bytesLeft -= 1; } while ((bytesLeft != 0) && ((num2 != 0) || (num3 != 0))); byte[] buffer1 = list1.ToArray(); if (buffer1.Length >= 2) { if ((buffer1[0] == 0xff) && (buffer1[1] == 0xfe)) { text1 = Encoding.Unicode.GetString(buffer1, 2, buffer1.Length - 2); goto Label_027D; } if ((buffer1[0] == 0xfe) && (buffer1[1] == 0xff)) { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 2, buffer1.Length - 2); goto Label_027D; } text1 = Encoding.Unicode.GetString(buffer1, 0, buffer1.Length); goto Label_027D; } text1 = Encoding.Unicode.GetString(buffer1, 0, buffer1.Length); goto Label_027D; } if (textEncoding == EncodingType.UTF16BE) { byte num4; byte num5; do { num4 = Utils.ReadByte(stream); list1.Add(num4); bytesLeft -= 1; if (bytesLeft == 0) { return ""; } num5 = Utils.ReadByte(stream); list1.Add(num5); bytesLeft -= 1; } while ((bytesLeft != 0) && ((num4 != 0) || (num5 != 0))); byte[] buffer2 = list1.ToArray(); if (buffer2.Length >= 2) { if ((buffer2[0] == 0xfe) && (buffer2[1] == 0xff)) { text1 = Encoding.BigEndianUnicode.GetString(buffer2, 2, buffer2.Length - 2); goto Label_027D; } text1 = Encoding.BigEndianUnicode.GetString(buffer2, 0, buffer2.Length); goto Label_027D; } text1 = Encoding.BigEndianUnicode.GetString(buffer2, 0, buffer2.Length); goto Label_027D; } if (textEncoding != EncodingType.UTF8) { string text2 = string.Format("Text Encoding '{0}' unknown at position {1}", textEncoding, stream.Position); Trace.WriteLine(text2); return ""; } byte num6 = Utils.ReadByte(stream); bytesLeft -= 1; if (bytesLeft != 0) { while (num6 != 0) { list1.Add(num6); num6 = Utils.ReadByte(stream); bytesLeft -= 1; if (bytesLeft == 0) { return ""; } } text1 = Encoding.UTF8.GetString(list1.ToArray()); goto Label_027D; } return ""; } byte num1 = Utils.ReadByte(stream); bytesLeft -= 1; if (bytesLeft != 0) { while (num1 != 0) { list1.Add(num1); num1 = Utils.ReadByte(stream); bytesLeft -= 1; if (bytesLeft == 0) { if (num1 != 0) { list1.Add(num1); } return Utils.ISO88591GetString(list1.ToArray()); } } text1 = Utils.ISO88591GetString(list1.ToArray()); goto Label_027D; } } return ""; Label_027D: return text1.TrimEnd(new char[1]); } public static string ReadString(EncodingType textEncoding, Stream stream, int length) { string text1; byte[] buffer1 = Utils.Read(stream, length); if (textEncoding == EncodingType.ISO88591) { text1 = Utils.ISO88591GetString(buffer1); } else if (textEncoding == EncodingType.Unicode) { if (length > 2) { if (buffer1.Length >= 2) { if ((buffer1[0] == 0xff) && (buffer1[1] == 0xfe)) { text1 = Encoding.Unicode.GetString(buffer1, 2, buffer1.Length - 2); } else if ((buffer1[0] == 0xfe) && (buffer1[1] == 0xff)) { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 2, buffer1.Length - 2); } else { text1 = Encoding.Unicode.GetString(buffer1, 0, buffer1.Length); } } else { text1 = Encoding.Unicode.GetString(buffer1, 0, buffer1.Length); } } else { text1 = ""; } } else if (textEncoding == EncodingType.UTF16BE) { if (buffer1.Length >= 2) { if ((buffer1[0] == 0xfe) && (buffer1[1] == 0xff)) { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 2, buffer1.Length - 2); } else { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 0, buffer1.Length); } } else { text1 = Encoding.BigEndianUnicode.GetString(buffer1, 0, buffer1.Length); } } else if (textEncoding == EncodingType.UTF8) { text1 = Encoding.UTF8.GetString(buffer1, 0, length); } else { string text2 = string.Format("Text Encoding '{0}' unknown at position {1}", textEncoding, stream.Position); Trace.WriteLine(text2); return ""; } return text1.TrimEnd(new char[1]); } public static byte[] ReadUnsynchronized(byte[] stream) { using (MemoryStream stream1 = new MemoryStream(stream.Length)) { int num1 = 0; int num2 = 0; while (num1 < stream.Length) { byte num3 = stream[num2++]; stream1.WriteByte(num3); if (num3 == 0xff) { num3 = stream[num2++]; if (num3 != 0) { stream1.WriteByte(num3); num1++; } } num1++; } return stream1.ToArray(); } } public static byte[] ReadUnsynchronized(Stream stream, int size) { using (MemoryStream stream1 = new MemoryStream(size)) { for (int num1 = 0; num1 < size; num1++) { byte num2 = Utils.ReadByte(stream); stream1.WriteByte(num2); if (num2 == 0xff) { num2 = Utils.ReadByte(stream); if (num2 != 0) { stream1.WriteByte(num2); num1++; } } } return stream1.ToArray(); } } public static Stream ReadUnsynchronizedStream(Stream stream, int length) { Stream stream1 = new MemoryStream(Utils.ReadUnsynchronized(stream, length), 0, length); stream1.Position = 0; return stream1; } public static void ReplaceBytes(string path, int bytesToRemove, byte[] bytesToAdd) { byte[] buffer1 = new byte[8]; Random random1 = new Random(); for (int num1 = 0; num1 < buffer1.Length; num1++) { buffer1[num1] = (byte) random1.Next(0x41, 0x5b); } string text1 = Encoding.ASCII.GetString(buffer1); string text2 = string.Format("{0}.{1}.tmp", path, text1); File.Move(path, text2); byte[] buffer2 = new byte[0x7fff]; using (FileStream stream1 = File.Open(text2, FileMode.Open, FileAccess.Read, FileShare.None)) { using (FileStream stream2 = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { stream2.Write(bytesToAdd, 0, bytesToAdd.Length); stream1.Position = bytesToRemove; for (int num2 = stream1.Read(buffer2, 0, 0x7fff); num2 > 0; num2 = stream1.Read(buffer2, 0, 0x7fff)) { stream2.Write(buffer2, 0, num2); } } } File.Delete(text2); } public static void Write(MemoryStream targetStream, byte[] byteArray) { targetStream.Write(byteArray, 0, byteArray.Length); } private static Encoding m_ISO88591; } }
// 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.ServiceModel; using System.Xml; using System.ComponentModel; namespace System.ServiceModel.Channels { public sealed class BinaryMessageEncodingBindingElement : MessageEncodingBindingElement { private int _maxReadPoolSize; private int _maxWritePoolSize; private XmlDictionaryReaderQuotas _readerQuotas; private int _maxSessionSize; private BinaryVersion _binaryVersion; private MessageVersion _messageVersion; private CompressionFormat _compressionFormat; private long _maxReceivedMessageSize; public BinaryMessageEncodingBindingElement() { _maxReadPoolSize = EncoderDefaults.MaxReadPoolSize; _maxWritePoolSize = EncoderDefaults.MaxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); EncoderDefaults.ReaderQuotas.CopyTo(_readerQuotas); _maxSessionSize = BinaryEncoderDefaults.MaxSessionSize; _binaryVersion = BinaryEncoderDefaults.BinaryVersion; _messageVersion = MessageVersion.CreateVersion(BinaryEncoderDefaults.EnvelopeVersion); _compressionFormat = EncoderDefaults.DefaultCompressionFormat; } private BinaryMessageEncodingBindingElement(BinaryMessageEncodingBindingElement elementToBeCloned) : base(elementToBeCloned) { _maxReadPoolSize = elementToBeCloned._maxReadPoolSize; _maxWritePoolSize = elementToBeCloned._maxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); elementToBeCloned._readerQuotas.CopyTo(_readerQuotas); this.MaxSessionSize = elementToBeCloned.MaxSessionSize; this.BinaryVersion = elementToBeCloned.BinaryVersion; _messageVersion = elementToBeCloned._messageVersion; this.CompressionFormat = elementToBeCloned.CompressionFormat; _maxReceivedMessageSize = elementToBeCloned._maxReceivedMessageSize; } [DefaultValue(EncoderDefaults.DefaultCompressionFormat)] public CompressionFormat CompressionFormat { get { return _compressionFormat; } set { _compressionFormat = value; } } /* public */ private BinaryVersion BinaryVersion { get { return _binaryVersion; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _binaryVersion = value; } } public override MessageVersion MessageVersion { get { return _messageVersion; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (value.Envelope != BinaryEncoderDefaults.EnvelopeVersion) { string errorMsg = SR.Format(SR.UnsupportedEnvelopeVersion, this.GetType().FullName, BinaryEncoderDefaults.EnvelopeVersion, value.Envelope); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(errorMsg)); } _messageVersion = MessageVersion.CreateVersion(BinaryEncoderDefaults.EnvelopeVersion, value.Addressing); } } [DefaultValue(EncoderDefaults.MaxReadPoolSize)] public int MaxReadPoolSize { get { return _maxReadPoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.ValueMustBePositive)); } _maxReadPoolSize = value; } } [DefaultValue(EncoderDefaults.MaxWritePoolSize)] public int MaxWritePoolSize { get { return _maxWritePoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.ValueMustBePositive)); } _maxWritePoolSize = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return _readerQuotas; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); value.CopyTo(_readerQuotas); } } [DefaultValue(BinaryEncoderDefaults.MaxSessionSize)] public int MaxSessionSize { get { return _maxSessionSize; } set { if (value < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.ValueMustBeNonNegative)); } _maxSessionSize = value; } } private void VerifyCompression(BindingContext context) { if (_compressionFormat != CompressionFormat.None) { ITransportCompressionSupport compressionSupport = context.GetInnerProperty<ITransportCompressionSupport>(); if (compressionSupport == null || !compressionSupport.IsCompressionFormatSupported(_compressionFormat)) { throw FxTrace.Exception.AsError(new NotSupportedException(SR.Format( SR.TransportDoesNotSupportCompression, _compressionFormat.ToString(), this.GetType().Name, CompressionFormat.None.ToString()))); } } } private void SetMaxReceivedMessageSizeFromTransport(BindingContext context) { TransportBindingElement transport = context.Binding.Elements.Find<TransportBindingElement>(); if (transport != null) { // We are guaranteed that a transport exists when building a binding; // Allow the regular flow/checks to happen rather than throw here // (InternalBuildChannelListener will call into the BindingContext. Validation happens there and it will throw) _maxReceivedMessageSize = transport.MaxReceivedMessageSize; } } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { VerifyCompression(context); SetMaxReceivedMessageSizeFromTransport(context); return InternalBuildChannelFactory<TChannel>(context); } public override BindingElement Clone() { return new BinaryMessageEncodingBindingElement(this); } public override MessageEncoderFactory CreateMessageEncoderFactory() { return new BinaryMessageEncoderFactory( this.MessageVersion, this.MaxReadPoolSize, this.MaxWritePoolSize, this.MaxSessionSize, this.ReaderQuotas, _maxReceivedMessageSize, this.BinaryVersion, this.CompressionFormat); } public override T GetProperty<T>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } if (typeof(T) == typeof(XmlDictionaryReaderQuotas)) { return (T)(object)_readerQuotas; } else { return base.GetProperty<T>(context); } } internal override bool IsMatch(BindingElement b) { if (!base.IsMatch(b)) return false; BinaryMessageEncodingBindingElement binary = b as BinaryMessageEncodingBindingElement; if (binary == null) return false; if (_maxReadPoolSize != binary.MaxReadPoolSize) return false; if (_maxWritePoolSize != binary.MaxWritePoolSize) return false; // compare XmlDictionaryReaderQuotas if (_readerQuotas.MaxStringContentLength != binary.ReaderQuotas.MaxStringContentLength) return false; if (_readerQuotas.MaxArrayLength != binary.ReaderQuotas.MaxArrayLength) return false; if (_readerQuotas.MaxBytesPerRead != binary.ReaderQuotas.MaxBytesPerRead) return false; if (_readerQuotas.MaxDepth != binary.ReaderQuotas.MaxDepth) return false; if (_readerQuotas.MaxNameTableCharCount != binary.ReaderQuotas.MaxNameTableCharCount) return false; if (this.MaxSessionSize != binary.MaxSessionSize) return false; if (this.CompressionFormat != binary.CompressionFormat) return false; return true; } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeReaderQuotas() { return (!EncoderDefaults.IsDefaultReaderQuotas(this.ReaderQuotas)); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeMessageVersion() { return (!_messageVersion.IsMatch(MessageVersion.Default)); } } }
// This code was generated by the Gardens Point Parser Generator // Copyright (c) Wayne Kelly, QUT 2005 // (see accompanying GPPGcopyright.rtf) using System; using System.Text; using System.Collections.Generic; using PHP.Core; using PHP.Core.Parsers.GPPG; using System.Diagnostics; namespace PHP.Library.Json { public enum Tokens {ERROR=1,EOF=2,ARRAY_OPEN=3,ARRAY_CLOSE=4,ITEMS_SEPARATOR=5,NAMEVALUE_SEPARATOR=6,OBJECT_OPEN=7,OBJECT_CLOSE=8,TRUE=9,FALSE=10,NULL=11,INTEGER=12,DOUBLE=13,STRING=14,STRING_BEGIN=15,CHARS=16,UNICODECHAR=17,ESCAPEDCHAR=18,STRING_END=19}; public partial struct SemanticValueType { public object obj; } public partial struct Position { public int FirstLine; public int FirstColumn; public int FirstOffset; public int LastLine; public int LastColumn; public int LastOffset; public Position(int firstLine, int firstColumn, int firstOffset, int lastLine, int lastColumn, int lastOffset) { this.FirstLine = firstLine; this.FirstColumn = firstColumn; this.FirstOffset = firstOffset; this.LastLine = lastLine; this.LastColumn = lastColumn; this.LastOffset = lastOffset; } } public partial class Parser: ShiftReduceParser<SemanticValueType,Position> { protected override string[] NonTerminals { get { return nonTerminals; } } private static string[] nonTerminals; protected override State[] States { get { return states; } } private static State[] states; protected override Rule[] Rules { get { return rules; } } private static Rule[] rules; protected sealed override Position CombinePositions(Position first, Position last) { return new Position(first.FirstLine, first.FirstColumn, first.FirstOffset, last.LastLine, last.LastColumn, last.LastOffset); } #region Construction static Parser() { states = new State[] { new State(0, new int[] {14,4,12,5,13,6,7,8,3,19,9,26,10,27,11,28}, new int[] {-1,1,-3,3,-4,7,-7,18}), new State(1, new int[] {2,2}), new State(2, -1), new State(3, -2), new State(4, -12), new State(5, -13), new State(6, -14), new State(7, -15), new State(8, new int[] {8,11,14,15}, new int[] {-5,9,-6,12}), new State(9, new int[] {8,10}), new State(10, -3), new State(11, -4), new State(12, new int[] {5,13,8,-6}), new State(13, new int[] {14,15}, new int[] {-5,14,-6,12}), new State(14, -5), new State(15, new int[] {6,16}), new State(16, new int[] {14,4,12,5,13,6,7,8,3,19,9,26,10,27,11,28}, new int[] {-3,17,-4,7,-7,18}), new State(17, -7), new State(18, -16), new State(19, new int[] {4,22,14,4,12,5,13,6,7,8,3,19,9,26,10,27,11,28}, new int[] {-8,20,-3,23,-4,7,-7,18}), new State(20, new int[] {4,21}), new State(21, -8), new State(22, -9), new State(23, new int[] {5,24,4,-11}), new State(24, new int[] {14,4,12,5,13,6,7,8,3,19,9,26,10,27,11,28}, new int[] {-8,25,-3,23,-4,7,-7,18}), new State(25, -10), new State(26, -17), new State(27, -18), new State(28, -19), }; rules = new Rule[20]; rules[1]=new Rule(-2, new int[]{-1,2}); rules[2]=new Rule(-1, new int[]{-3}); rules[3]=new Rule(-4, new int[]{7,-5,8}); rules[4]=new Rule(-4, new int[]{7,8}); rules[5]=new Rule(-5, new int[]{-6,5,-5}); rules[6]=new Rule(-5, new int[]{-6}); rules[7]=new Rule(-6, new int[]{14,6,-3}); rules[8]=new Rule(-7, new int[]{3,-8,4}); rules[9]=new Rule(-7, new int[]{3,4}); rules[10]=new Rule(-8, new int[]{-3,5,-8}); rules[11]=new Rule(-8, new int[]{-3}); rules[12]=new Rule(-3, new int[]{14}); rules[13]=new Rule(-3, new int[]{12}); rules[14]=new Rule(-3, new int[]{13}); rules[15]=new Rule(-3, new int[]{-4}); rules[16]=new Rule(-3, new int[]{-7}); rules[17]=new Rule(-3, new int[]{9}); rules[18]=new Rule(-3, new int[]{10}); rules[19]=new Rule(-3, new int[]{11}); nonTerminals = new string[] {"", "start", "$accept", "value", "object", "members", "pair", "array", "elements", }; } #endregion protected override void DoAction(int action) { switch (action) { case 2: // start -> value { Result = value_stack.array[value_stack.top-1].yyval.obj; } return; case 3: // object -> OBJECT_OPEN members OBJECT_CLOSE { var elements = (List<KeyValuePair<string, object>>)value_stack.array[value_stack.top-2].yyval.obj; if (decodeOptions.Assoc) { var arr = new PhpArray( elements.Count ); foreach (var item in elements) arr.Add( PHP.Core.Convert.StringToArrayKey(item.Key), item.Value ); yyval.obj = arr; } else { var std = new stdClass(context, true); std.AddRange( elements ); yyval.obj = std; } } return; case 4: // object -> OBJECT_OPEN OBJECT_CLOSE { yyval.obj = new stdClass(context, true); } return; case 5: // members -> pair ITEMS_SEPARATOR members { var elements = (List<KeyValuePair<string, object>>)value_stack.array[value_stack.top-1].yyval.obj; var result = new List<KeyValuePair<string, object>>( elements.Count + 1 ){ (KeyValuePair<string,object>)value_stack.array[value_stack.top-3].yyval.obj }; result.AddRange(elements); yyval.obj = result; } return; case 6: // members -> pair { yyval.obj = new List<KeyValuePair<string, object>>(){ (KeyValuePair<string,object>)value_stack.array[value_stack.top-1].yyval.obj }; } return; case 7: // pair -> STRING NAMEVALUE_SEPARATOR value { yyval.obj = new KeyValuePair<string,object>((string)value_stack.array[value_stack.top-3].yyval.obj, value_stack.array[value_stack.top-1].yyval.obj); } return; case 8: // array -> ARRAY_OPEN elements ARRAY_CLOSE { var elements = (List<object>)value_stack.array[value_stack.top-2].yyval.obj; var arr = new PhpArray( elements.Count ); foreach (var item in elements) arr.Add( item ); yyval.obj = arr; } return; case 9: // array -> ARRAY_OPEN ARRAY_CLOSE { yyval.obj = new PhpArray(); } return; case 10: // elements -> value ITEMS_SEPARATOR elements { var elements = (List<object>)value_stack.array[value_stack.top-1].yyval.obj; var result = new List<object>( elements.Count + 1 ){ value_stack.array[value_stack.top-3].yyval.obj }; result.AddRange(elements); yyval.obj = result; } return; case 11: // elements -> value { yyval.obj = new List<object>(){ value_stack.array[value_stack.top-1].yyval.obj }; } return; case 12: // value -> STRING {yyval.obj = value_stack.array[value_stack.top-1].yyval.obj;} return; case 13: // value -> INTEGER {yyval.obj = value_stack.array[value_stack.top-1].yyval.obj;} return; case 14: // value -> DOUBLE {yyval.obj = value_stack.array[value_stack.top-1].yyval.obj;} return; case 15: // value -> object {yyval.obj = value_stack.array[value_stack.top-1].yyval.obj;} return; case 16: // value -> array {yyval.obj = value_stack.array[value_stack.top-1].yyval.obj;} return; case 17: // value -> TRUE {yyval.obj = true;} return; case 18: // value -> FALSE {yyval.obj = false;} return; case 19: // value -> NULL {yyval.obj = null;} return; } } protected override string TerminalToString(int terminal) { if (((Tokens)terminal).ToString() != terminal.ToString()) return ((Tokens)terminal).ToString(); else return CharToString((char)terminal); } protected override int EofToken { get { return (int)Tokens.EOF; } } protected override int ErrorToken { get { return (int)Tokens.ERROR; } } private readonly ScriptContext/*!*/context; private readonly PHP.Library.JsonFormatter.DecodeOptions/*!*/decodeOptions; public Parser(ScriptContext/*!*/context, PHP.Library.JsonFormatter.DecodeOptions/*!*/decodeOptions) { System.Diagnostics.Debug.Assert(context != null && decodeOptions != null); this.context = context; this.decodeOptions = decodeOptions; } public object Result{get;private set;} } }
using Codex.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Codex { /* * Types in this file define search behaviors. Changes should be made with caution as they can affect * the mapping schema for indices and will generally need to be backward compatible. * Additions should be generally safe. * * WARNING: Changing routing key by changed input to Route() function is extremely destructive as it causes entities * to be routed to different shards and thereby invalidates most stored documents. Generally, these should never be changed * unless the entire index will be recreated. * * TODO: Maybe there should be some sort of validation on this. */ public class SearchTypes { public static readonly List<SearchType> RegisteredSearchTypes = new List<SearchType>(); public static SearchType<IDefinitionSearchModel> Definition = SearchType.Create<IDefinitionSearchModel>(RegisteredSearchTypes) .Route(ds => ds.Definition.Id.Value); //.CopyTo(ds => ds.Definition.Modifiers, ds => ds.Keywords) //.CopyTo(ds => ds.Definition.Kind, ds => ds.Kind) //.CopyTo(ds => ds.Definition.ExcludeFromDefaultSearch, ds => ds.ExcludeFromDefaultSearch) //.CopyTo(ds => ds.Definition.Kind, ds => ds.Keywords) //.CopyTo(ds => ds.Definition.ShortName, ds => ds.ShortName) ////.CopyTo(ds => ds.Language, ds => ds.Keywords) //.CopyTo(ds => ds.Definition.ProjectId, ds => ds.ProjectId) //.CopyTo(ds => ds.Definition.ProjectId, ds => ds.Keywords); public static SearchType<IReferenceSearchModel> Reference = SearchType.Create<IReferenceSearchModel>(RegisteredSearchTypes) .Route(rs => rs.Reference.Id.Value); //.CopyTo(rs => rs.Spans.First().Reference, rs => rs.Reference); public static SearchType<ITextChunkSearchModel> TextChunk = SearchType.Create<ITextChunkSearchModel>(RegisteredSearchTypes); public static SearchType<ITextSourceSearchModel> TextSource = SearchType.Create<ITextSourceSearchModel>(RegisteredSearchTypes) .Route(ss => PathUtilities.GetFileName(ss.File.Info.RepoRelativePath)); //.CopyTo(ss => ss.File.SourceFile.Content, ss => ss.Content) //.CopyTo(ss => ss.File.SourceFile.Info.RepoRelativePath, ss => ss.RepoRelativePath) //.CopyTo(ss => ss.File.ProjectId, ss => ss.ProjectId) //.CopyTo(ss => ss.File.Info.Path, ss => ss.FilePath); public static SearchType<IBoundSourceSearchModel> BoundSource = SearchType.Create<IBoundSourceSearchModel>(RegisteredSearchTypes) .Route(ss => PathUtilities.GetFileName(ss.File.Info.RepoRelativePath)); //.CopyTo(ss => ss.File.SourceFile.Content, ss => ss.Content) //.CopyTo(ss => ss.File.SourceFile.Info.RepoRelativePath, ss => ss.RepoRelativePath) //.CopyTo(ss => ss.BindingInfo.ProjectId, ss => ss.ProjectId) //.CopyTo(ss => ss.FilePath, ss => ss.FilePath); public static SearchType<ILanguageSearchModel> Language = SearchType.Create<ILanguageSearchModel>(RegisteredSearchTypes) .Route(ls => ls.Language.Name); public static SearchType<IRepositorySearchModel> Repository = SearchType.Create<IRepositorySearchModel>(RegisteredSearchTypes) .Route(rs => rs.Repository.Name); public static SearchType<IProjectSearchModel> Project = SearchType.Create<IProjectSearchModel>(RegisteredSearchTypes) .Route(sm => sm.Project.ProjectId) .Exclude(sm => sm.Project.ProjectReferences.First().Definitions); public static SearchType<ICommitSearchModel> Commit = SearchType.Create<ICommitSearchModel>(RegisteredSearchTypes); // TODO: Should these be one per file to allow mapping text files to their corresponding project for text search public static SearchType<ICommitFilesSearchModel> CommitFiles = SearchType.Create<ICommitFilesSearchModel>(RegisteredSearchTypes); public static SearchType<IProjectReferenceSearchModel> ProjectReference = SearchType.Create<IProjectReferenceSearchModel>(RegisteredSearchTypes); public static SearchType<IPropertySearchModel> Property = SearchType.Create<IPropertySearchModel>(RegisteredSearchTypes); public static SearchType<IStoredFilter> StoredFilter = SearchType.Create<IStoredFilter>(RegisteredSearchTypes); public static SearchType<IStableIdMarker> StableIdMarker = SearchType.Create<IStableIdMarker>(RegisteredSearchTypes); public static SearchType<IRegisteredEntity> RegisteredEntity = SearchType.Create<IRegisteredEntity>(RegisteredSearchTypes); } /// <summary> /// In order to compute a stable integral id for each entity. This type is used to store into a 'follow' index which /// stores entities of this type using the <see cref="ISearchEntity.Uid"/> of the corresponding search entity. Then the /// sequence number assigned by ElasticSearch is used as the shard stable id (<see cref="ISearchEntity.StableId"/>) /// for the entity. This approach is used in order to ensure that the stable id appears as an explicit field in the document rather /// which allows configuration of how the field is indexed (not true for sequence number field without code changes to ES). /// </summary> public interface IRegisteredEntity : ISearchEntity { /// <summary> /// The date in which the entity was registered (i.e. added to the store) /// </summary> DateTime DateAdded { get; set; } /// <summary> /// The id of the originating entity /// </summary> [SearchBehavior(SearchBehavior.Term)] string EntityUid { get; set; } /// <summary> /// The index of the originating entity /// </summary> [SearchBehavior(SearchBehavior.Term)] string IndexName { get; set; } } /// <summary> /// Defines a stored filter which matches entities in a particular index shard in a stable manner /// </summary> public interface IStoredFilter : ISearchEntity { /// <summary> /// The time of the last update to the stored filter /// </summary> DateTime DateUpdated { get; set; } string FullPath { get; set; } /// <summary> /// The name of the stored filter /// </summary> [SearchBehavior(SearchBehavior.Term)] string Name { get; set; } /// <summary> /// The name of the index to which the stored filter applies /// </summary> [SearchBehavior(SearchBehavior.Term)] string IndexName { get; } /// <summary> /// Stored filter bit set /// </summary> [SearchBehavior(SearchBehavior.None)] byte[] StableIds { get; } [SearchBehavior(SearchBehavior.None)] IReadOnlyList<IChildFilterReference> Children { get; } /// <summary> /// The hash of <see cref="Filter"/> /// </summary> [SearchBehavior(SearchBehavior.Term)] string FilterHash { get; } /// <summary> /// The count of elements matched by <see cref="Filter"/> /// </summary> int Cardinality { get; } } public interface IChildFilterReference { string FullPath { get; } /// <summary> /// The <see cref="ISearchEntity.Uid"/> of the child filter /// </summary> string Uid { get; } /// <summary> /// The <see cref="IStoredFilter.StableIds"/> of the child filter /// </summary> byte[] StableIds { get; } /// <summary> /// The <see cref="IStoredFilter.Cardinality"/> of the child filter /// </summary> int Cardinality { get; } } [AdapterType] public interface IGroupedStoredFilterIds { } public interface IDefinitionSearchModel : ISearchEntity { IDefinitionSymbol Definition { get; } // TODO: Not sure that this is actually needed /// <summary> /// Keywords are additional terms which can be used to find a given symbol. /// NOTE: Keywords can only be used to select from symbols which have /// a primary term match /// </summary> [SearchBehavior(SearchBehavior.NormalizedKeyword)] IReadOnlyList<string> Keywords { get; } } public interface ILanguageSearchModel : ISearchEntity { ILanguageInfo Language { get; } } public interface IReferenceSearchModel : IProjectFileScopeEntity, ISearchEntity { /// <summary> /// The reference symbol /// </summary> IReferenceSymbol Reference { get; } // TODO: Need some sort of override for searching RelatedDefinition of the // ReferenceSpan [SearchBehavior(SearchBehavior.None)] [ReadOnlyList] [CoerceGet] IReadOnlyList<ISymbolSpan> Spans { get; } /// <summary> /// Compressed list of spans /// </summary> [SearchBehavior(SearchBehavior.None)] ISymbolLineSpanList CompressedSpans { get; } } public interface ISourceSearchModelBase : ISearchEntity { /// <summary> /// Information about the source file from source control provider (may be null) /// </summary> ISourceControlFileInfo SourceControlInfo { get; } IChunkedSourceFile File { get; } } public interface IBoundSourceSearchModel : ISourceSearchModelBase { /// <summary> /// The unique identifier of the associated <see cref="ISourceFile"/> /// </summary> string TextUid { get; } /// <summary> /// The binding info /// </summary> IBoundSourceInfo BindingInfo { get; } /// <summary> /// Compressed list of classification spans /// </summary> [SearchBehavior(SearchBehavior.None)] IClassificationList CompressedClassifications { get; } /// <summary> /// Compressed list of reference spans /// </summary> [SearchBehavior(SearchBehavior.None)] IReferenceList CompressedReferences { get; } } public interface ITextSourceSearchModel : ISourceSearchModelBase { } public interface ITextChunkSearchModel : ISearchEntity { /// <summary> /// The text content. Set when the chunk IS searched /// </summary> ISourceFileContentChunk Chunk { get; } /// <summary> /// The text content. Set when the chunk IS NOT searched /// </summary> [SearchBehavior(SearchBehavior.None)] ISourceFileContentChunk RawChunk { get; } } public interface IRepositorySearchModel : ISearchEntity { IRepository Repository { get; } } public interface IProjectSearchModel : ISearchEntity { IProject Project { get; } } public interface IProjectReferenceSearchModel : IProjectScopeEntity, ISearchEntity { IReferencedProject ProjectReference { get; } } public interface ICommitSearchModel : ISearchEntity { ICommit Commit { get; } } /// <summary> /// The set of files present in the repository at a given commit. /// </summary> public interface ICommitFilesSearchModel : ICommitScopeEntity, IRepoScopeEntity, ISearchEntity { IReadOnlyList<ICommitFileLink> CommitFiles { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.InteropServices; using Xunit; namespace System.Runtime.CompilerServices { public class UnsafeTests { [Fact] public static unsafe void ReadInt32() { int expected = 10; void* address = Unsafe.AsPointer(ref expected); int ret = Unsafe.Read<int>(address); Assert.Equal(expected, ret); } [Fact] public static unsafe void WriteInt32() { int value = 10; int* address = (int*)Unsafe.AsPointer(ref value); int expected = 20; Unsafe.Write(address, expected); Assert.Equal(expected, value); Assert.Equal(expected, *address); Assert.Equal(expected, Unsafe.Read<int>(address)); } [Fact] public static unsafe void WriteBytesIntoInt32() { int value = 20; int* intAddress = (int*)Unsafe.AsPointer(ref value); byte* byteAddress = (byte*)intAddress; for (int i = 0; i < 4; i++) { Unsafe.Write(byteAddress + i, (byte)i); } Assert.Equal(0, Unsafe.Read<byte>(byteAddress)); Assert.Equal(1, Unsafe.Read<byte>(byteAddress + 1)); Assert.Equal(2, Unsafe.Read<byte>(byteAddress + 2)); Assert.Equal(3, Unsafe.Read<byte>(byteAddress + 3)); Byte4 b4 = Unsafe.Read<Byte4>(byteAddress); Assert.Equal(0, b4.B0); Assert.Equal(1, b4.B1); Assert.Equal(2, b4.B2); Assert.Equal(3, b4.B3); int expected = (b4.B3 << 24) + (b4.B2 << 16) + (b4.B1 << 8) + (b4.B0); Assert.Equal(expected, value); } [Fact] public static unsafe void LongIntoCompoundStruct() { long value = 1234567891011121314L; long* longAddress = (long*)Unsafe.AsPointer(ref value); Byte4Short2 b4s2 = Unsafe.Read<Byte4Short2>(longAddress); Assert.Equal(162, b4s2.B0); Assert.Equal(48, b4s2.B1); Assert.Equal(210, b4s2.B2); Assert.Equal(178, b4s2.B3); Assert.Equal(4340, b4s2.S4); Assert.Equal(4386, b4s2.S6); b4s2.B0 = 1; b4s2.B1 = 1; b4s2.B2 = 1; b4s2.B3 = 1; b4s2.S4 = 1; b4s2.S6 = 1; Unsafe.Write(longAddress, b4s2); long expected = 281479288520961; Assert.Equal(expected, value); Assert.Equal(expected, Unsafe.Read<long>(longAddress)); } [Fact] public static unsafe void ReadWriteDoublePointer() { int value1 = 10; int value2 = 20; int* valueAddress = (int*)Unsafe.AsPointer(ref value1); int** valueAddressPtr = &valueAddress; Unsafe.Write(valueAddressPtr, new IntPtr(&value2)); Assert.Equal(20, *(*valueAddressPtr)); Assert.Equal(20, Unsafe.Read<int>(valueAddress)); Assert.Equal(new IntPtr(valueAddress), Unsafe.Read<IntPtr>(valueAddressPtr)); Assert.Equal(20, Unsafe.Read<int>(Unsafe.Read<IntPtr>(valueAddressPtr).ToPointer())); } [Fact] public static unsafe void CopyToRef() { int value = 10; int destination = -1; Unsafe.Copy(ref destination, Unsafe.AsPointer(ref value)); Assert.Equal(10, destination); Assert.Equal(10, value); int destination2 = -1; Unsafe.Copy(ref destination2, &value); Assert.Equal(10, destination2); Assert.Equal(10, value); } [Fact] public static unsafe void CopyToVoidPtr() { int value = 10; int destination = -1; Unsafe.Copy(Unsafe.AsPointer(ref destination), ref value); Assert.Equal(10, destination); Assert.Equal(10, value); int destination2 = -1; Unsafe.Copy(&destination2, ref value); Assert.Equal(10, destination2); Assert.Equal(10, value); } [Fact] public static unsafe void SizeOf() { Assert.Equal(1, Unsafe.SizeOf<sbyte>()); Assert.Equal(1, Unsafe.SizeOf<byte>()); Assert.Equal(2, Unsafe.SizeOf<short>()); Assert.Equal(2, Unsafe.SizeOf<ushort>()); Assert.Equal(4, Unsafe.SizeOf<int>()); Assert.Equal(4, Unsafe.SizeOf<uint>()); Assert.Equal(8, Unsafe.SizeOf<long>()); Assert.Equal(8, Unsafe.SizeOf<ulong>()); Assert.Equal(4, Unsafe.SizeOf<float>()); Assert.Equal(8, Unsafe.SizeOf<double>()); Assert.Equal(4, Unsafe.SizeOf<Byte4>()); Assert.Equal(8, Unsafe.SizeOf<Byte4Short2>()); Assert.Equal(512, Unsafe.SizeOf<Byte512>()); } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockStack(int numBytes, byte value) { byte* stackPtr = stackalloc byte[numBytes]; Unsafe.InitBlock(stackPtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(stackPtr[i], value); } } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockUnmanaged(int numBytes, byte value) { IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes); byte* bytePtr = (byte*)allocatedMemory.ToPointer(); Unsafe.InitBlock(bytePtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(bytePtr[i], value); } } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockRefStack(int numBytes, byte value) { byte* stackPtr = stackalloc byte[numBytes]; Unsafe.InitBlock(ref *stackPtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(stackPtr[i], value); } } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockRefUnmanaged(int numBytes, byte value) { IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes); byte* bytePtr = (byte*)allocatedMemory.ToPointer(); Unsafe.InitBlock(ref *bytePtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(bytePtr[i], value); } } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockUnalignedStack(int numBytes, byte value) { byte* stackPtr = stackalloc byte[numBytes + 1]; stackPtr += 1; // +1 = make unaligned Unsafe.InitBlockUnaligned(stackPtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(stackPtr[i], value); } } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockUnalignedUnmanaged(int numBytes, byte value) { IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes + 1); byte* bytePtr = (byte*)allocatedMemory.ToPointer() + 1; // +1 = make unaligned Unsafe.InitBlockUnaligned(bytePtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(bytePtr[i], value); } } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockUnalignedRefStack(int numBytes, byte value) { byte* stackPtr = stackalloc byte[numBytes + 1]; stackPtr += 1; // +1 = make unaligned Unsafe.InitBlockUnaligned(ref *stackPtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(stackPtr[i], value); } } [Theory] [MemberData(nameof(InitBlockData))] public static unsafe void InitBlockUnalignedRefUnmanaged(int numBytes, byte value) { IntPtr allocatedMemory = Marshal.AllocCoTaskMem(numBytes + 1); byte* bytePtr = (byte*)allocatedMemory.ToPointer() + 1; // +1 = make unaligned Unsafe.InitBlockUnaligned(ref *bytePtr, value, (uint)numBytes); for (int i = 0; i < numBytes; i++) { Assert.Equal(bytePtr[i], value); } } public static IEnumerable<object[]> InitBlockData() { yield return new object[] { 0, 1 }; yield return new object[] { 1, 1 }; yield return new object[] { 10, 0 }; yield return new object[] { 10, 2 }; yield return new object[] { 10, 255 }; yield return new object[] { 10000, 255 }; } [Theory] [MemberData(nameof(CopyBlockData))] public static unsafe void CopyBlock(int numBytes) { byte* source = stackalloc byte[numBytes]; byte* destination = stackalloc byte[numBytes]; for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); source[i] = value; } Unsafe.CopyBlock(destination, source, (uint)numBytes); for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); Assert.Equal(value, destination[i]); Assert.Equal(source[i], destination[i]); } } [Theory] [MemberData(nameof(CopyBlockData))] public static unsafe void CopyBlockRef(int numBytes) { byte* source = stackalloc byte[numBytes]; byte* destination = stackalloc byte[numBytes]; for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); source[i] = value; } Unsafe.CopyBlock(ref destination[0], ref source[0], (uint)numBytes); for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); Assert.Equal(value, destination[i]); Assert.Equal(source[i], destination[i]); } } [Theory] [MemberData(nameof(CopyBlockData))] public static unsafe void CopyBlockUnaligned(int numBytes) { byte* source = stackalloc byte[numBytes + 1]; byte* destination = stackalloc byte[numBytes + 1]; source += 1; // +1 = make unaligned destination += 1; // +1 = make unaligned for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); source[i] = value; } Unsafe.CopyBlockUnaligned(destination, source, (uint)numBytes); for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); Assert.Equal(value, destination[i]); Assert.Equal(source[i], destination[i]); } } [Theory] [MemberData(nameof(CopyBlockData))] public static unsafe void CopyBlockUnalignedRef(int numBytes) { byte* source = stackalloc byte[numBytes + 1]; byte* destination = stackalloc byte[numBytes + 1]; source += 1; // +1 = make unaligned destination += 1; // +1 = make unaligned for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); source[i] = value; } Unsafe.CopyBlockUnaligned(ref destination[0], ref source[0], (uint)numBytes); for (int i = 0; i < numBytes; i++) { byte value = (byte)(i % 255); Assert.Equal(value, destination[i]); Assert.Equal(source[i], destination[i]); } } public static IEnumerable<object[]> CopyBlockData() { yield return new object[] { 0 }; yield return new object[] { 1 }; yield return new object[] { 10 }; yield return new object[] { 100 }; yield return new object[] { 100000 }; } [Fact] public static void As() { object o = "Hello"; Assert.Equal("Hello", Unsafe.As<string>(o)); } [Fact] public static void DangerousAs() { // Verify that As does not perform type checks object o = new object(); Assert.IsType(typeof(object), Unsafe.As<string>(o)); } [Fact] public static void ByteOffsetArray() { var a = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }; Assert.Equal(new IntPtr(0), Unsafe.ByteOffset(ref a[0], ref a[0])); Assert.Equal(new IntPtr(1), Unsafe.ByteOffset(ref a[0], ref a[1])); Assert.Equal(new IntPtr(-1), Unsafe.ByteOffset(ref a[1], ref a[0])); Assert.Equal(new IntPtr(2), Unsafe.ByteOffset(ref a[0], ref a[2])); Assert.Equal(new IntPtr(-2), Unsafe.ByteOffset(ref a[2], ref a[0])); Assert.Equal(new IntPtr(3), Unsafe.ByteOffset(ref a[0], ref a[3])); Assert.Equal(new IntPtr(4), Unsafe.ByteOffset(ref a[0], ref a[4])); Assert.Equal(new IntPtr(5), Unsafe.ByteOffset(ref a[0], ref a[5])); Assert.Equal(new IntPtr(6), Unsafe.ByteOffset(ref a[0], ref a[6])); Assert.Equal(new IntPtr(7), Unsafe.ByteOffset(ref a[0], ref a[7])); } [Fact] public static void ByteOffsetStackByte4() { var byte4 = new Byte4(); Assert.Equal(new IntPtr(0), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B0)); Assert.Equal(new IntPtr(1), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B1)); Assert.Equal(new IntPtr(-1), Unsafe.ByteOffset(ref byte4.B1, ref byte4.B0)); Assert.Equal(new IntPtr(2), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B2)); Assert.Equal(new IntPtr(-2), Unsafe.ByteOffset(ref byte4.B2, ref byte4.B0)); Assert.Equal(new IntPtr(3), Unsafe.ByteOffset(ref byte4.B0, ref byte4.B3)); Assert.Equal(new IntPtr(-3), Unsafe.ByteOffset(ref byte4.B3, ref byte4.B0)); } [Fact] public static unsafe void AsRef() { byte[] b = new byte[4] { 0x42, 0x42, 0x42, 0x42 }; fixed (byte * p = b) { ref int r = ref Unsafe.AsRef<int>(p); Assert.Equal(0x42424242, r); r = 0x0EF00EF0; Assert.Equal(0xFE, b[0] | b[1] | b[2] | b[3]); } } [Fact] public static void InAsRef() { int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 }; ref int r = ref Unsafe.AsRef<int>(a[0]); Assert.Equal(0x123, r); r = 0x42; Assert.Equal(0x42, a[0]); } [Fact] public static void RefAs() { byte[] b = new byte[4] { 0x42, 0x42, 0x42, 0x42 }; ref int r = ref Unsafe.As<byte, int>(ref b[0]); Assert.Equal(0x42424242, r); r = 0x0EF00EF0; Assert.Equal(0xFE, b[0] | b[1] | b[2] | b[3]); } [Fact] public static void RefAdd() { int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 }; ref int r1 = ref Unsafe.Add(ref a[0], 1); Assert.Equal(0x234, r1); ref int r2 = ref Unsafe.Add(ref r1, 2); Assert.Equal(0x456, r2); ref int r3 = ref Unsafe.Add(ref r2, -3); Assert.Equal(0x123, r3); } [Fact] public static unsafe void VoidPointerAdd() { int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 }; fixed (void* ptr = a) { void* r1 = Unsafe.Add<int>(ptr, 1); Assert.Equal(0x234, *(int*)r1); void* r2 = Unsafe.Add<int>(r1, 2); Assert.Equal(0x456, *(int*)r2); void* r3 = Unsafe.Add<int>(r2, -3); Assert.Equal(0x123, *(int*)r3); } fixed (void* ptr = &a[1]) { void* r0 = Unsafe.Add<int>(ptr, -1); Assert.Equal(0x123, *(int*)r0); void* r3 = Unsafe.Add<int>(ptr, 2); Assert.Equal(0x456, *(int*)r3); } } [Fact] public static void RefAddIntPtr() { int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 }; ref int r1 = ref Unsafe.Add(ref a[0], (IntPtr)1); Assert.Equal(0x234, r1); ref int r2 = ref Unsafe.Add(ref r1, (IntPtr)2); Assert.Equal(0x456, r2); ref int r3 = ref Unsafe.Add(ref r2, (IntPtr)(-3)); Assert.Equal(0x123, r3); } [Fact] public static void RefAddByteOffset() { byte[] a = new byte[] { 0x12, 0x34, 0x56, 0x78 }; ref byte r1 = ref Unsafe.AddByteOffset(ref a[0], (IntPtr)1); Assert.Equal(0x34, r1); ref byte r2 = ref Unsafe.AddByteOffset(ref r1, (IntPtr)2); Assert.Equal(0x78, r2); ref byte r3 = ref Unsafe.AddByteOffset(ref r2, (IntPtr)(-3)); Assert.Equal(0x12, r3); } [Fact] public static void RefSubtract() { string[] a = new string[] { "abc", "def", "ghi", "jkl" }; ref string r1 = ref Unsafe.Subtract(ref a[0], -2); Assert.Equal("ghi", r1); ref string r2 = ref Unsafe.Subtract(ref r1, -1); Assert.Equal("jkl", r2); ref string r3 = ref Unsafe.Subtract(ref r2, 3); Assert.Equal("abc", r3); } [Fact] public static unsafe void VoidPointerSubtract() { int[] a = new int[] { 0x123, 0x234, 0x345, 0x456 }; fixed (void* ptr = a) { void* r1 = Unsafe.Subtract<int>(ptr, -2); Assert.Equal(0x345, *(int*)r1); void* r2 = Unsafe.Subtract<int>(r1, -1); Assert.Equal(0x456, *(int*)r2); void* r3 = Unsafe.Subtract<int>(r2, 3); Assert.Equal(0x123, *(int*)r3); } fixed (void* ptr = &a[1]) { void* r0 = Unsafe.Subtract<int>(ptr, 1); Assert.Equal(0x123, *(int*)r0); void* r3 = Unsafe.Subtract<int>(ptr, -2); Assert.Equal(0x456, *(int*)r3); } } [Fact] public static void RefSubtractIntPtr() { string[] a = new string[] { "abc", "def", "ghi", "jkl" }; ref string r1 = ref Unsafe.Subtract(ref a[0], (IntPtr)(-2)); Assert.Equal("ghi", r1); ref string r2 = ref Unsafe.Subtract(ref r1, (IntPtr)(-1)); Assert.Equal("jkl", r2); ref string r3 = ref Unsafe.Subtract(ref r2, (IntPtr)3); Assert.Equal("abc", r3); } [Fact] public static void RefSubtractByteOffset() { byte[] a = new byte[] { 0x12, 0x34, 0x56, 0x78 }; ref byte r1 = ref Unsafe.SubtractByteOffset(ref a[0], (IntPtr)(-1)); Assert.Equal(0x34, r1); ref byte r2 = ref Unsafe.SubtractByteOffset(ref r1, (IntPtr)(-2)); Assert.Equal(0x78, r2); ref byte r3 = ref Unsafe.SubtractByteOffset(ref r2, (IntPtr)3); Assert.Equal(0x12, r3); } [Fact] public static void RefAreSame() { long[] a = new long[2]; Assert.True(Unsafe.AreSame(ref a[0], ref a[0])); Assert.False(Unsafe.AreSame(ref a[0], ref a[1])); } [Fact] public static unsafe void RefIsAddressGreaterThan() { int[] a = new int[2]; Assert.False(Unsafe.IsAddressGreaterThan(ref a[0], ref a[0])); Assert.False(Unsafe.IsAddressGreaterThan(ref a[0], ref a[1])); Assert.True(Unsafe.IsAddressGreaterThan(ref a[1], ref a[0])); Assert.False(Unsafe.IsAddressGreaterThan(ref a[1], ref a[1])); // The following tests ensure that we're using unsigned comparison logic Assert.False(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>((void*)(1)), ref Unsafe.AsRef<byte>((void*)(-1)))); Assert.True(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>((void*)(-1)), ref Unsafe.AsRef<byte>((void*)(1)))); Assert.True(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>((void*)(int.MinValue)), ref Unsafe.AsRef<byte>((void*)(int.MaxValue)))); Assert.False(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>((void*)(int.MaxValue)), ref Unsafe.AsRef<byte>((void*)(int.MinValue)))); Assert.False(Unsafe.IsAddressGreaterThan(ref Unsafe.AsRef<byte>(null), ref Unsafe.AsRef<byte>(null))); } [Fact] public static unsafe void RefIsAddressLessThan() { int[] a = new int[2]; Assert.False(Unsafe.IsAddressLessThan(ref a[0], ref a[0])); Assert.True(Unsafe.IsAddressLessThan(ref a[0], ref a[1])); Assert.False(Unsafe.IsAddressLessThan(ref a[1], ref a[0])); Assert.False(Unsafe.IsAddressLessThan(ref a[1], ref a[1])); // The following tests ensure that we're using unsigned comparison logic Assert.True(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>((void*)(1)), ref Unsafe.AsRef<byte>((void*)(-1)))); Assert.False(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>((void*)(-1)), ref Unsafe.AsRef<byte>((void*)(1)))); Assert.False(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>((void*)(int.MinValue)), ref Unsafe.AsRef<byte>((void*)(int.MaxValue)))); Assert.True(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>((void*)(int.MaxValue)), ref Unsafe.AsRef<byte>((void*)(int.MinValue)))); Assert.False(Unsafe.IsAddressLessThan(ref Unsafe.AsRef<byte>(null), ref Unsafe.AsRef<byte>(null))); } [Fact] public static unsafe void ReadUnaligned_ByRef_Int32() { byte[] unaligned = Int32Double.Unaligned(123456789, 3.42); int actual = Unsafe.ReadUnaligned<int>(ref unaligned[1]); Assert.Equal(123456789, actual); } [Fact] public static unsafe void ReadUnaligned_ByRef_Double() { byte[] unaligned = Int32Double.Unaligned(123456789, 3.42); double actual = Unsafe.ReadUnaligned<double>(ref unaligned[9]); Assert.Equal(3.42, actual); } [Fact] public static unsafe void ReadUnaligned_ByRef_Struct() { byte[] unaligned = Int32Double.Unaligned(123456789, 3.42); Int32Double actual = Unsafe.ReadUnaligned<Int32Double>(ref unaligned[1]); Assert.Equal(123456789, actual.Int32); Assert.Equal(3.42, actual.Double); } [Fact] public static unsafe void ReadUnaligned_Ptr_Int32() { byte[] unaligned = Int32Double.Unaligned(123456789, 3.42); fixed (byte* p = unaligned) { int actual = Unsafe.ReadUnaligned<int>(p + 1); Assert.Equal(123456789, actual); } } [Fact] public static unsafe void ReadUnaligned_Ptr_Double() { byte[] unaligned = Int32Double.Unaligned(123456789, 3.42); fixed (byte* p = unaligned) { double actual = Unsafe.ReadUnaligned<double>(p + 9); Assert.Equal(3.42, actual); } } [Fact] public static unsafe void ReadUnaligned_Ptr_Struct() { byte[] unaligned = Int32Double.Unaligned(123456789, 3.42); fixed (byte* p = unaligned) { Int32Double actual = Unsafe.ReadUnaligned<Int32Double>(p + 1); Assert.Equal(123456789, actual.Int32); Assert.Equal(3.42, actual.Double); } } [Fact] public static unsafe void WriteUnaligned_ByRef_Int32() { byte[] unaligned = new byte[sizeof(Int32Double) + 1]; Unsafe.WriteUnaligned(ref unaligned[1], 123456789); int actual = Int32Double.Aligned(unaligned).Int32; Assert.Equal(123456789, actual); } [Fact] public static unsafe void WriteUnaligned_ByRef_Double() { byte[] unaligned = new byte[sizeof(Int32Double) + 1]; Unsafe.WriteUnaligned(ref unaligned[9], 3.42); double actual = Int32Double.Aligned(unaligned).Double; Assert.Equal(3.42, actual); } [Fact] public static unsafe void WriteUnaligned_ByRef_Struct() { byte[] unaligned = new byte[sizeof(Int32Double) + 1]; Unsafe.WriteUnaligned(ref unaligned[1], new Int32Double { Int32 = 123456789, Double = 3.42 }); Int32Double actual = Int32Double.Aligned(unaligned); Assert.Equal(123456789, actual.Int32); Assert.Equal(3.42, actual.Double); } [Fact] public static unsafe void WriteUnaligned_Ptr_Int32() { byte[] unaligned = new byte[sizeof(Int32Double) + 1]; fixed (byte* p = unaligned) { Unsafe.WriteUnaligned(p + 1, 123456789); } int actual = Int32Double.Aligned(unaligned).Int32; Assert.Equal(123456789, actual); } [Fact] public static unsafe void WriteUnaligned_Ptr_Double() { byte[] unaligned = new byte[sizeof(Int32Double) + 1]; fixed (byte* p = unaligned) { Unsafe.WriteUnaligned(p + 9, 3.42); } double actual = Int32Double.Aligned(unaligned).Double; Assert.Equal(3.42, actual); } [Fact] public static unsafe void WriteUnaligned_Ptr_Struct() { byte[] unaligned = new byte[sizeof(Int32Double) + 1]; fixed (byte* p = unaligned) { Unsafe.WriteUnaligned(p + 1, new Int32Double { Int32 = 123456789, Double = 3.42 }); } Int32Double actual = Int32Double.Aligned(unaligned); Assert.Equal(123456789, actual.Int32); Assert.Equal(3.42, actual.Double); } [Fact] public static void Unbox_Int32() { object box = 42; Assert.True(Unsafe.AreSame(ref Unsafe.Unbox<int>(box), ref Unsafe.Unbox<int>(box))); Assert.Equal(42, (int)box); Assert.Equal(42, Unsafe.Unbox<int>(box)); ref int value = ref Unsafe.Unbox<int>(box); value = 84; Assert.Equal(84, (int)box); Assert.Equal(84, Unsafe.Unbox<int>(box)); Assert.Throws<InvalidCastException>(() => Unsafe.Unbox<Byte4>(box)); } [Fact] public static void Unbox_CustomValueType() { object box = new Int32Double(); Assert.Equal(0, ((Int32Double)box).Double); Assert.Equal(0, ((Int32Double)box).Int32); ref Int32Double value = ref Unsafe.Unbox<Int32Double>(box); value.Double = 42; value.Int32 = 84; Assert.Equal(42, ((Int32Double)box).Double); Assert.Equal(84, ((Int32Double)box).Int32); Assert.Throws<InvalidCastException>(() => Unsafe.Unbox<bool>(box)); } } [StructLayout(LayoutKind.Explicit)] public struct Byte4 { [FieldOffset(0)] public byte B0; [FieldOffset(1)] public byte B1; [FieldOffset(2)] public byte B2; [FieldOffset(3)] public byte B3; } [StructLayout(LayoutKind.Explicit)] public struct Byte4Short2 { [FieldOffset(0)] public byte B0; [FieldOffset(1)] public byte B1; [FieldOffset(2)] public byte B2; [FieldOffset(3)] public byte B3; [FieldOffset(4)] public short S4; [FieldOffset(6)] public short S6; } public unsafe struct Byte512 { public fixed byte Bytes[512]; } [StructLayout(LayoutKind.Explicit, Size=16)] public unsafe struct Int32Double { [FieldOffset(0)] public int Int32; [FieldOffset(8)] public double Double; public static unsafe byte[] Unaligned(int i, double d) { var aligned = new Int32Double { Int32 = i, Double = d }; var unaligned = new byte[sizeof(Int32Double) + 1]; fixed (byte* p = unaligned) { Buffer.MemoryCopy(&aligned, p + 1, sizeof(Int32Double), sizeof(Int32Double)); } return unaligned; } public static unsafe Int32Double Aligned(byte[] unaligned) { var aligned = new Int32Double(); fixed (byte* p = unaligned) { Buffer.MemoryCopy(p + 1, &aligned, sizeof(Int32Double), sizeof(Int32Double)); } return aligned; } } }
using System; using System.Collections.Generic; using System.Linq; using Signum.Entities; using Signum.Engine.Maps; using Signum.Utilities; using Signum.Utilities.Reflection; using Signum.Engine.Basics; using System.Threading; using System.Threading.Tasks; using Signum.Utilities.ExpressionTrees; using System.Diagnostics.CodeAnalysis; namespace Signum.Engine { public interface IRetriever : IDisposable { Dictionary<string, object> GetUserData(); T? Complete<T>(PrimaryKey? id, Action<T> complete) where T : Entity; T? Request<T>(PrimaryKey? id) where T : Entity; T? RequestIBA<T>(PrimaryKey? typeId, string? id) where T : class, IEntity; Lite<T>? RequestLite<T>(Lite<T>? lite) where T : class, IEntity; T? ModifiablePostRetrieving<T>(T? entity) where T : Modifiable; IRetriever? Parent { get; } void CompleteAll(); Task CompleteAllAsync(CancellationToken token); ModifiedState ModifiedState { get; } } class RealRetriever : IRetriever { Dictionary<string, object>? userData; public Dictionary<string, object> GetUserData() => userData ?? (userData = new Dictionary<string, object>()); public IRetriever? Parent { get { return null; } } public RealRetriever(EntityCache.RealEntityCache entityCache) { this.entityCache = entityCache; } EntityCache.RealEntityCache entityCache; Dictionary<(Type type, PrimaryKey id), Entity> retrieved = new Dictionary<(Type type, PrimaryKey id), Entity>(); Dictionary<Type, Dictionary<PrimaryKey, Entity>>? requests; Dictionary<(Type type, PrimaryKey id), List<Lite<IEntity>>>? liteRequests; List<Modifiable> modifiablePostRetrieving = new List<Modifiable>(); bool TryGetRequest((Type type, PrimaryKey id) key, [NotNullWhen(true)]out Entity? value) { if (requests != null && requests.TryGetValue(key.type, out var dic) && dic.TryGetValue(key.id, out value)) return true; value = null!; return false; } public T? Complete<T>(PrimaryKey? id, Action<T> complete) where T : Entity { if (id == null) return null; var tuple = (typeof(T), id.Value); if (entityCache.TryGetValue(tuple, out var result)) return (T)result; if (retrieved.TryGetValue(tuple, out result)) return (T)result; T entity; if (TryGetRequest(tuple, out result)) { entity = (T)result; requests![typeof(T)].Remove(id.Value); } else { entity = EntityCache.Construct<T>(id.Value); } retrieved.Add(tuple, entity); complete(entity); return entity; } static GenericInvoker<Func<RealRetriever, PrimaryKey?, Entity>> giRequest = new GenericInvoker<Func<RealRetriever, PrimaryKey?, Entity>>((rr, id) => rr.Request<Entity>(id)!); public T? Request<T>(PrimaryKey? id) where T : Entity { if (id == null) return null; var tuple = (type: typeof(T), id: id.Value); if (entityCache.TryGetValue(tuple, out Entity? ident)) return (T)ident; if (retrieved.TryGetValue(tuple, out ident)) return (T)ident; ICacheController? cc = Schema.Current.CacheController(typeof(T)); if (cc != null && cc.Enabled) { T entityFromCache = EntityCache.Construct<T>(id.Value); retrieved.Add(tuple, entityFromCache); //Cycles cc.Complete(entityFromCache, this); return entityFromCache; } ident = (T?)requests?.TryGetC(typeof(T))?.TryGetC(id.Value); if (ident != null) return (T)ident; T entity = EntityCache.Construct<T>(id.Value); if (requests == null) requests = new Dictionary<Type, Dictionary<PrimaryKey, Entity>>(); requests.GetOrCreate(tuple.type).Add(tuple.id, entity); return entity; } public T? RequestIBA<T>(PrimaryKey? typeId, string? id) where T : class, IEntity { if (id == null) return null; Type type = TypeLogic.IdToType[typeId!.Value]; var parsedId = PrimaryKey.Parse(id, type); return (T)(IEntity)giRequest.GetInvoker(type)(this, parsedId); } public Lite<T>? RequestLite<T>(Lite<T>? lite) where T : class, IEntity { if (lite == null) return null; ICacheController? cc = Schema.Current.CacheController(lite.EntityType); if (cc != null && cc.Enabled) { lite.SetToString(cc.TryGetToString(lite.Id) ?? ("[" + EngineMessage.EntityWithType0AndId1NotFound.NiceToString().FormatWith(lite.EntityType.NiceName(), lite.Id) + "]")); return lite; } var tuple = (type: lite.EntityType, id: lite.Id); if (liteRequests == null) liteRequests = new Dictionary<(Type type, PrimaryKey id), List<Lite<IEntity>>>(); liteRequests.GetOrCreate(tuple).Add(lite); return lite; } public T? ModifiablePostRetrieving<T>(T? modifiable) where T : Modifiable { if (modifiable != null) modifiablePostRetrieving.Add(modifiable); return modifiable; } public Task CompleteAllAsync(CancellationToken token) => CompleteAllPrivate(token); public void CompleteAll() { try { CompleteAllPrivate(null).Wait(); } catch (AggregateException ag) { var ex = ag.InnerExceptions.FirstEx(); ex.PreserveStackTrace(); throw ex; } } public async Task CompleteAllPrivate(CancellationToken? token) { retry: if (requests != null) { while (requests.Count > 0) { var group = requests.WithMax(a => a.Value.Count); var dic = group.Value; ICacheController? cc = Schema.Current.CacheController(group.Key); if (cc != null && cc.Enabled) { cc.Load(); while (dic.Count > 0) { Entity ident = dic.Values.FirstEx(); cc.Complete(ident, this); retrieved.Add((type: ident.GetType(), id: ident.Id), ident); dic.Remove(ident.Id); } } else { if (token == null) Database.RetrieveList(group.Key, dic.Keys.ToList()); else await Database.RetrieveListAsync(group.Key, dic.Keys.ToList(), token.Value); } if (dic.Count == 0) requests.Remove(group.Key); } } if (liteRequests != null) { { List<(Type type, PrimaryKey id)>? toRemove = null; foreach (var item in liteRequests) { var entity = retrieved.TryGetC(item.Key); if (entity != null) { var toStr = entity.ToString(); foreach (var lite in item.Value) lite.SetToString(toStr); if (toRemove == null) toRemove = new List<(Type type, PrimaryKey id)>(); toRemove.Add(item.Key); } } if (toRemove != null) liteRequests.RemoveRange(toRemove); } while (liteRequests.Count > 0) { var group = liteRequests.GroupBy(a => a.Key.type).FirstEx(); var dic = await giGetStrings.GetInvoker(group.Key)(group.Select(a => a.Key.id).ToList(), token); foreach (var item in group) { var toStr = dic.TryGetC(item.Key.id) ?? ("[" + EngineMessage.EntityWithType0AndId1NotFound.NiceToString().FormatWith(item.Key.type.NiceName(), item.Key.id) + "]"); foreach (var lite in item.Value) { lite.SetToString(toStr); } } liteRequests.RemoveRange(group.Select(a => a.Key)); } } var currentlyRetrieved = retrieved.Values.ToHashSet(); var currentlyModifiableRetrieved = modifiablePostRetrieving.ToHashSet(Signum.Utilities.DataStructures.ReferenceEqualityComparer<Modifiable>.Default); var ctx = new PostRetrievingContext(); foreach (var entity in currentlyRetrieved) { entity.PostRetrieving(ctx); Schema.Current.OnRetrieved(entity, ctx); entityCache.Add(entity); } foreach (var embedded in currentlyModifiableRetrieved) embedded.PostRetrieving(ctx); ModifiedState ms = ModifiedState; foreach (var entity in currentlyRetrieved) { entity.Modified = ctx.ForceModifiedState.TryGetS(entity) ?? ms; entity.IsNew = false; } foreach (var embedded in currentlyModifiableRetrieved) embedded.Modified = ctx.ForceModifiedState.TryGetS(embedded) ?? ms; if (liteRequests != null && liteRequests.Count > 0 || requests != null && requests.Count > 0 || retrieved.Count > currentlyRetrieved.Count ) // PostRetrieving could retrieve as well { retrieved.RemoveAll(a => currentlyRetrieved.Contains(a.Value)); modifiablePostRetrieving.RemoveAll(a => currentlyModifiableRetrieved.Contains(a)); goto retry; } } static readonly GenericInvoker<Func<List<PrimaryKey>, CancellationToken?, Task<Dictionary<PrimaryKey, string>>>> giGetStrings = new GenericInvoker<Func<List<PrimaryKey>, CancellationToken?, Task<Dictionary<PrimaryKey, string>>>>((ids, token) => GetStrings<Entity>(ids, token)); static async Task<Dictionary<PrimaryKey, string>> GetStrings<T>(List<PrimaryKey> ids, CancellationToken? token) where T : Entity { ICacheController? cc = Schema.Current.CacheController(typeof(T)); if (cc != null && cc.Enabled) { cc.Load(); return ids.ToDictionary(a => a, a => cc.TryGetToString(a)!); } else if (token != null) { var tasks = ids.GroupsOf(Schema.Current.Settings.MaxNumberOfParameters) .Select(gr => Database.Query<T>().Where(e => gr.Contains(e.Id)).Select(a => KeyValuePair.Create(a.Id, a.ToString())).ToListAsync(token!.Value)) .ToList(); var list = await Task.WhenAll(tasks); return list.SelectMany(li => li).ToDictionary(); } else { var dic = ids.GroupsOf(Schema.Current.Settings.MaxNumberOfParameters) .SelectMany(gr => Database.Query<T>().Where(e => gr.Contains(e.Id)).Select(a => KeyValuePair.Create(a.Id, a.ToString()))) .ToDictionaryEx(); return dic; } } public void Dispose() { entityCache.ReleaseRetriever(this); } public ModifiedState ModifiedState { get { return this.entityCache.IsSealed ? ModifiedState.Sealed : ModifiedState.Clean; } } } class ChildRetriever : IRetriever { public Dictionary<string, object> GetUserData() => this.parent.GetUserData(); EntityCache.RealEntityCache entityCache; public IRetriever parent; public IRetriever? Parent => parent; public ChildRetriever(IRetriever parent, EntityCache.RealEntityCache entityCache) { this.parent = parent; this.entityCache = entityCache; } public T? Complete<T>(PrimaryKey? id, Action<T> complete) where T : Entity { return parent.Complete<T>(id, complete); } public T? Request<T>(PrimaryKey? id) where T : Entity { return parent.Request<T>(id); } public T? RequestIBA<T>(PrimaryKey? typeId, string? id) where T : class, IEntity { return parent.RequestIBA<T>(typeId, id); } public Lite<T>? RequestLite<T>(Lite<T>? lite) where T : class, IEntity { return parent.RequestLite<T>(lite); } public T? ModifiablePostRetrieving<T>(T? entity) where T : Modifiable { return parent.ModifiablePostRetrieving(entity); } public void CompleteAll() { } public Task CompleteAllAsync(CancellationToken token) { return Task.CompletedTask; } public void Dispose() { entityCache.ReleaseRetriever(this); } public ModifiedState ModifiedState { get { return this.entityCache.IsSealed ? ModifiedState.Sealed : ModifiedState.Clean; } } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Management.Automation; using System.Xml; using System.Xml.Linq; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; namespace Trisoft.ISHRemote.Cmdlets.Settings { /// <summary> /// <para type="synopsis">This cmdlet can be used to set a configuration setting in the repository. Depending on the parameters you use, the value to set is read from different inputs. /// If you provide: /// * A metadata parameter with the fields to set, all fields and values will be read from the IshFields and set /// * A fieldname and a value, the value will be set for the given field /// * A fieldname and a filepath, the value will be read from the file and set for the given field</para> /// <para type="description">This cmdlet can be used to set a configuration setting in the repository. Depending on the parameters you use, the value to set is read from different inputs. /// If you provide: /// * A metadata parameter with the fields to set, all fields and values will be read from the IshFields and set /// * A fieldname and a value, the value will be set for the given field /// * A fieldname and a filepath, the value will be read from the file and set for the given field</para> /// </summary> /// <example> /// <code> /// New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential "Admin" /// $settingsFolderPath = 'C:\temp' /// Write-Verbose "Submitting Xml Settings from $settingsFolderPath" /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLInboxConfiguration.xml" /// Set-IshSetting -FieldName "FINBOXCONFIGURATION" -FilePath $filePath /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLBackgroundTaskConfiguration.xml" /// Set-IshSetting -FieldName "FISHBACKGROUNDTASKCONFIG" -FilePath $filePath /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLChangeTrackerConfig.xml" /// Set-IshSetting -FieldName "FISHCHANGETRACKERCONFIG" -FilePath $filePath /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLExtensionConfiguration.xml" /// Set-IshSetting -FieldName "FISHEXTENSIONCONFIG" -FilePath $filePath /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLPluginConfig.xml" /// Set-IshSetting -FieldName "FISHPLUGINCONFIGXML" -FilePath $filePath /// # Version 13.0.0 requires a status to be present before status transitions can be confirmed /// # Add-IshLovValue -LovId DSTATUS -Label "Translation In Review" -Description "Translation In Review" /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLStatusConfiguration.xml" /// Set-IshSetting -FieldName "FSTATECONFIGURATION" -FilePath $filePath /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLTranslationConfiguration.xml" /// Set-IshSetting -FieldName "FTRANSLATIONCONFIGURATION" -FilePath $filePath /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLWriteObjPluginConfig.xml" /// Set-IshSetting -FieldName "FISHWRITEOBJPLUGINCFG" -FilePath $filePath /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLPublishPluginConfiguration.xml" /// Set-IshSetting -FieldName "FISHPUBLISHPLUGINCONFIG" -FilePath $filePath /// $filePath = Join-Path -Path $settingsFolderPath -ChildPath "Admin.XMLCollectiveSpacesConfiguration.xml" /// Set-IshSetting -FieldName "FISHCOLLECTIVESPACESCFG" -FilePath $filePath /// Write-Host "Done" /// </code> /// <para>Submit all Xml Settings configuration entries from your prepared folder (or standard EnterViaUI folder).</para> /// </example> /// <example> /// <code> /// New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -PSCredential Admin /// Set-IshSetting -FieldName FISHLCURI -Value https://something/deleteThis /// </code> /// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Update CTCONFIGURATION field with the presented value.</para> /// </example> /// <example> /// <code> /// New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -PSCredential Admin /// Set-IshSetting -FieldName FISHLCURI /// </code> /// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Update CTCONFIGURATION field with the value empty string ("").</para> /// </example> /// <example> /// <code> /// New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -PSCredential Admin /// $originalValue = Get-IshSetting -FieldName FISHENABLEOUTOFDATE -ValueType Element /// Set-IshSetting -FieldName FISHENABLEOUTOFDATE -ValueType Element -Value $true /// Set-IshSetting -FieldName FISHENABLEOUTOFDATE -ValueType Element -Value $originalValue /// </code> /// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Update CTCONFIGURATION field with the value empty string ("").</para> /// </example> [Cmdlet(VerbsCommon.Set, "IshSetting", SupportsShouldProcess = true)] [OutputType(typeof(IshField))] public sealed class SetIshSetting : SettingsCmdlet { /// <summary> /// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFieldsGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ValueGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FileGroup")] [ValidateNotNullOrEmpty] public IshSession IshSession { get; set; } /// <summary> /// <para type="description">The metadata with the fields and values to set</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFieldsGroup")] [ValidateNotNull] public IshField[] Metadata { get; set; } /// <summary> /// <para type="description">The settings field to set</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ValueGroup")] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "FileGroup")] [ValidateNotNullOrEmpty] public string FieldName { get; set; } /// <summary> /// <para type="description">The value to set</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ValueGroup")] [ValidateNotNullOrEmpty] public string Value { get; set; } /// <summary> /// <para type="description">The value type</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ValueGroup")] public Enumerations.ValueType ValueType { get { return _valueType; } set { _valueType = value; } } /// <summary> /// <para type="description">File on the Windows filesystem where to read the setting from</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "FileGroup")] [ValidateNotNullOrEmpty] public string FilePath { get; set; } /// <summary> /// <para type="description">The required current metadata of the setting. This parameter can be used to avoid that users override changes done by other users. The cmdlet will check whether the fields provided in this parameter still have the same values in the repository:</para> /// <para type="description">If the metadata is still the same, the metadata will be set.</para> /// <para type="description">If the metadata is not the same anymore, an error is given and the metadata will be set.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFieldsGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ValueGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FileGroup")] [ValidateNotNullOrEmpty] public IshField[] RequiredCurrentMetadata { get; set; } #region Private fields /// <summary> /// Private fields to store the parameters and provide a default for non-mandatory parameters /// </summary> private Enumerations.ValueType _valueType = Enumerations.ValueType.Value; #endregion protected override void BeginProcessing() { if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); } if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); } WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}"); base.BeginProcessing(); } protected override void ProcessRecord() { try { IshFields metadata = new IshFields(); IshFields requiredCurrentMetadata = new IshFields(RequiredCurrentMetadata); // 1. Doing the update WriteDebug("Updating"); if (Metadata != null) { metadata = new IshFields(Metadata); } else if (FilePath != null) { //Check file exists if (!File.Exists(FilePath)) { throw new FileNotFoundException(@"File '" + FilePath + "' does not exist."); } try { // Let's try to see if it is xml first var doc = XDocument.Load(FilePath, LoadOptions.PreserveWhitespace); // ToString does not keep xml declaration <?xml, but that does not really matter as we are passing it in as string anyway (and the API removed the xml desclaration anyway) string value = doc.ToString(SaveOptions.DisableFormatting); metadata.AddField(new IshMetadataField(FieldName, Enumerations.Level.None, Enumerations.ValueType.Value, value)); } catch (Exception) { // Read it as a text file string value = String.Join(IshSession.Separator, File.ReadAllLines(FilePath)); metadata.AddField(new IshMetadataField(FieldName, Enumerations.Level.None, Enumerations.ValueType.Value, value)); } } else { Value = Value ?? ""; // if the value is not offered we presumse empty string ("") metadata.AddField(new IshMetadataField(FieldName, Enumerations.Level.None, ValueType, Value)); } if (ShouldProcess("CTCONFIGURATION")) { metadata = IshSession.IshTypeFieldSetup.ToIshMetadataFields(ISHType, metadata, Enumerations.ActionMode.Update); requiredCurrentMetadata = IshSession.IshTypeFieldSetup.ToIshRequiredCurrentMetadataFields(ISHType, requiredCurrentMetadata, Enumerations.ActionMode.Update); IshSession.Settings25.SetMetadata3(metadata.ToXml(), requiredCurrentMetadata.ToXml()); } // 2. Retrieve the updated material from the database and write it out WriteDebug("Retrieving"); var requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, metadata, Enumerations.ActionMode.Read); string xmlIshObjects = IshSession.Settings25.GetMetadata(requestedMetadata.ToXml()); var ishFieldArray = new IshObjects(xmlIshObjects).Objects[0].IshFields.Fields(); // 3. Write it WriteVerbose("returned object count[1]"); WriteObject(ishFieldArray, true); } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices.ComTypes; using Microsoft.DiaSymReader; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class MockSymUnmanagedReader : ISymUnmanagedReader, ISymUnmanagedReader2, ISymUnmanagedReader3 { private readonly ImmutableDictionary<int, MethodDebugInfoBytes> _methodDebugInfoMap; public MockSymUnmanagedReader(ImmutableDictionary<int, MethodDebugInfoBytes> methodDebugInfoMap) { _methodDebugInfoMap = methodDebugInfoMap; } public int GetMethod(int methodToken, out ISymUnmanagedMethod method) { return GetMethodByVersion(methodToken, 1, out method); } public int GetMethodByVersion(int methodToken, int version, out ISymUnmanagedMethod retVal) { Assert.Equal(1, version); MethodDebugInfoBytes info; if (!_methodDebugInfoMap.TryGetValue(methodToken, out info)) { retVal = null; return HResult.E_FAIL; } Assert.NotNull(info); retVal = info.Method; return HResult.S_OK; } public int GetSymAttribute(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { // The EE should never be calling ISymUnmanagedReader.GetSymAttribute. // In order to account for EnC updates, it should always be calling // ISymUnmanagedReader3.GetSymAttributeByVersion instead. throw ExceptionUtilities.Unreachable; } public int GetSymAttributeByVersion(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { Assert.Equal(1, version); Assert.Equal("MD2", name); MethodDebugInfoBytes info; if (!_methodDebugInfoMap.TryGetValue(methodToken, out info)) { count = 0; return HResult.S_FALSE; // This is a guess. We're not consuming it, so it doesn't really matter. } Assert.NotNull(info); info.Bytes.TwoPhaseCopy(bufferLength, out count, customDebugInformation); return HResult.S_OK; } public int GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument document) { throw new NotImplementedException(); } public int GetDocuments(int bufferLength, out int count, ISymUnmanagedDocument[] documents) { throw new NotImplementedException(); } public int GetUserEntryPoint(out int methodToken) { throw new NotImplementedException(); } public int GetVariables(int methodToken, int bufferLength, out int count, ISymUnmanagedVariable[] variables) { throw new NotImplementedException(); } public int GetGlobalVariables(int bufferLength, out int count, ISymUnmanagedVariable[] variables) { throw new NotImplementedException(); } public int GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetNamespaces(int bufferLength, out int count, ISymUnmanagedNamespace[] namespaces) { throw new NotImplementedException(); } public int Initialize(object metadataImporter, string fileName, string searchPath, IStream stream) { throw new NotImplementedException(); } public int UpdateSymbolStore(string fileName, IStream stream) { throw new NotImplementedException(); } public int ReplaceSymbolStore(string fileName, IStream stream) { throw new NotImplementedException(); } public int GetSymbolStoreFileName(int bufferLength, out int count, char[] name) { throw new NotImplementedException(); } public int GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetDocumentVersion(ISymUnmanagedDocument document, out int version, out bool isCurrent) { throw new NotImplementedException(); } public int GetMethodVersion(ISymUnmanagedMethod method, out int version) { throw new NotImplementedException(); } public int GetMethodByVersionPreRemap(int methodToken, int version, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetSymAttributePreRemap(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } public int GetMethodsInDocument(ISymUnmanagedDocument document, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetSymAttributeByVersionPreRemap(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } } internal sealed class MockSymUnmanagedMethod : ISymUnmanagedMethod { private readonly ISymUnmanagedScope _rootScope; public MockSymUnmanagedMethod(ISymUnmanagedScope rootScope) { _rootScope = rootScope; } int ISymUnmanagedMethod.GetRootScope(out ISymUnmanagedScope retVal) { retVal = _rootScope; return HResult.S_OK; } int ISymUnmanagedMethod.GetSequencePointCount(out int retVal) { retVal = 1; return HResult.S_OK; } int ISymUnmanagedMethod.GetSequencePoints(int cPoints, out int pcPoints, int[] offsets, ISymUnmanagedDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns) { pcPoints = 1; offsets[0] = 0; documents[0] = null; lines[0] = 0; columns[0] = 0; endLines[0] = 0; endColumns[0] = 0; return HResult.S_OK; } int ISymUnmanagedMethod.GetNamespace(out ISymUnmanagedNamespace retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetParameters(int cParams, out int pcParams, ISymUnmanagedVariable[] parms) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, int[] ranges) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetScopeFromOffset(int offset, out ISymUnmanagedScope retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetSourceStartEnd(ISymUnmanagedDocument[] docs, int[] lines, int[] columns, out bool retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetToken(out int pToken) { throw new NotImplementedException(); } } internal sealed class MockSymUnmanagedScope : ISymUnmanagedScope, ISymUnmanagedScope2 { private readonly ImmutableArray<ISymUnmanagedScope> _children; private readonly ImmutableArray<ISymUnmanagedNamespace> _namespaces; private readonly ISymUnmanagedConstant[] _constants; private readonly int _startOffset; private readonly int _endOffset; public MockSymUnmanagedScope(ImmutableArray<ISymUnmanagedScope> children, ImmutableArray<ISymUnmanagedNamespace> namespaces, ISymUnmanagedConstant[] constants = null, int startOffset = 0, int endOffset = 1) { _children = children; _namespaces = namespaces; _constants = constants ?? new ISymUnmanagedConstant[0]; _startOffset = startOffset; _endOffset = endOffset; } public int GetChildren(int numDesired, out int numRead, ISymUnmanagedScope[] buffer) { _children.TwoPhaseCopy(numDesired, out numRead, buffer); return HResult.S_OK; } public int GetNamespaces(int numDesired, out int numRead, ISymUnmanagedNamespace[] buffer) { _namespaces.TwoPhaseCopy(numDesired, out numRead, buffer); return HResult.S_OK; } public int GetStartOffset(out int pRetVal) { pRetVal = _startOffset; return HResult.S_OK; } public int GetEndOffset(out int pRetVal) { pRetVal = _endOffset; return HResult.S_OK; } public int GetLocalCount(out int pRetVal) { pRetVal = 0; return HResult.S_OK; } public int GetLocals(int cLocals, out int pcLocals, ISymUnmanagedVariable[] locals) { pcLocals = 0; return HResult.S_OK; } public int GetMethod(out ISymUnmanagedMethod pRetVal) { throw new NotImplementedException(); } public int GetParent(out ISymUnmanagedScope pRetVal) { throw new NotImplementedException(); } public int GetConstantCount(out int pRetVal) { pRetVal = _constants.Length; return HResult.S_OK; } public int GetConstants(int cConstants, out int pcConstants, ISymUnmanagedConstant[] constants) { pcConstants = _constants.Length; if (constants != null) { Array.Copy(_constants, constants, constants.Length); } return HResult.S_OK; } } internal sealed class MockSymUnmanagedNamespace : ISymUnmanagedNamespace { private readonly ImmutableArray<char> _nameChars; public MockSymUnmanagedNamespace(string name) { if (name != null) { var builder = ArrayBuilder<char>.GetInstance(); builder.AddRange(name); builder.AddRange('\0'); _nameChars = builder.ToImmutableAndFree(); } } int ISymUnmanagedNamespace.GetName(int numDesired, out int numRead, char[] buffer) { _nameChars.TwoPhaseCopy(numDesired, out numRead, buffer); return 0; } int ISymUnmanagedNamespace.GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces) { throw new NotImplementedException(); } int ISymUnmanagedNamespace.GetVariables(int cVars, out int pcVars, ISymUnmanagedVariable[] pVars) { throw new NotImplementedException(); } } internal delegate int GetSignatureDelegate(int bufferLength, out int count, byte[] signature); internal sealed class MockSymUnmanagedConstant : ISymUnmanagedConstant { private readonly string _name; private readonly object _value; private readonly GetSignatureDelegate _getSignature; public MockSymUnmanagedConstant(string name, object value, GetSignatureDelegate getSignature) { _name = name; _value = value; _getSignature = getSignature; } int ISymUnmanagedConstant.GetName(int bufferLength, out int count, char[] name) { count = _name.Length + 1; // + 1 for null terminator Debug.Assert((bufferLength == 0) || (bufferLength == count)); for (int i = 0; i < bufferLength - 1; i++) { name[i] = _name[i]; } return HResult.S_OK; } int ISymUnmanagedConstant.GetSignature(int bufferLength, out int count, byte[] signature) { return _getSignature(bufferLength, out count, signature); } int ISymUnmanagedConstant.GetValue(out object value) { value = _value; return HResult.S_OK; } } internal static class MockSymUnmanagedHelpers { public static void TwoPhaseCopy<T>(this ImmutableArray<T> source, int numDesired, out int numRead, T[] destination) { if (destination == null) { Assert.Equal(0, numDesired); numRead = source.IsDefault ? 0 : source.Length; } else { Assert.False(source.IsDefault); Assert.Equal(source.Length, numDesired); source.CopyTo(0, destination, 0, numDesired); numRead = numDesired; } } public static void Add2(this ArrayBuilder<byte> bytes, short s) { var shortBytes = BitConverter.GetBytes(s); Assert.Equal(2, shortBytes.Length); bytes.AddRange(shortBytes); } public static void Add4(this ArrayBuilder<byte> bytes, int i) { var intBytes = BitConverter.GetBytes(i); Assert.Equal(4, intBytes.Length); bytes.AddRange(intBytes); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UnsafeNativeMethods ** ============================================================*/ namespace Microsoft.Win32 { using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System; using System.Configuration.Assemblies; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Security.Principal; using System.Runtime.Serialization; using System.Threading; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Diagnostics.Eventing; using System.Diagnostics.Eventing.Reader; [SuppressUnmanagedCodeSecurityAttribute()] internal static class UnsafeNativeMethods { internal const String KERNEL32 = "kernel32.dll"; internal const String ADVAPI32 = "advapi32.dll"; internal const String WEVTAPI = "wevtapi.dll"; internal static readonly IntPtr NULL = IntPtr.Zero; // // Win32 IO // internal const int CREDUI_MAX_USERNAME_LENGTH = 513; // WinError.h codes: internal const int ERROR_SUCCESS = 0x0; internal const int ERROR_FILE_NOT_FOUND = 0x2; internal const int ERROR_PATH_NOT_FOUND = 0x3; internal const int ERROR_ACCESS_DENIED = 0x5; internal const int ERROR_INVALID_HANDLE = 0x6; // Can occurs when filled buffers are trying to flush to disk, but disk IOs are not fast enough. // This happens when the disk is slow and event traffic is heavy. // Eventually, there are no more free (empty) buffers and the event is dropped. internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8; internal const int ERROR_INVALID_DRIVE = 0xF; internal const int ERROR_NO_MORE_FILES = 0x12; internal const int ERROR_NOT_READY = 0x15; internal const int ERROR_BAD_LENGTH = 0x18; internal const int ERROR_SHARING_VIOLATION = 0x20; internal const int ERROR_LOCK_VIOLATION = 0x21; // 33 internal const int ERROR_HANDLE_EOF = 0x26; // 38 internal const int ERROR_FILE_EXISTS = 0x50; internal const int ERROR_INVALID_PARAMETER = 0x57; // 87 internal const int ERROR_BROKEN_PIPE = 0x6D; // 109 internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; // 122 internal const int ERROR_INVALID_NAME = 0x7B; internal const int ERROR_BAD_PATHNAME = 0xA1; internal const int ERROR_ALREADY_EXISTS = 0xB7; internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB; internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long internal const int ERROR_PIPE_BUSY = 0xE7; // 231 internal const int ERROR_NO_DATA = 0xE8; // 232 internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; // 233 internal const int ERROR_MORE_DATA = 0xEA; internal const int ERROR_NO_MORE_ITEMS = 0x103; // 259 internal const int ERROR_PIPE_CONNECTED = 0x217; // 535 internal const int ERROR_PIPE_LISTENING = 0x218; // 536 internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation internal const int ERROR_IO_PENDING = 0x3E5; // 997 internal const int ERROR_NOT_FOUND = 0x490; // 1168 // The event size is larger than the allowed maximum (64k - header). internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; // 534 internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; // 1815 // Event log specific codes: internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027; internal const int ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028; internal const int ERROR_EVT_UNRESOLVED_VALUE_INSERT = 15029; internal const int ERROR_EVT_UNRESOLVED_PARAMETER_INSERT = 15030; internal const int ERROR_EVT_MAX_INSERTS_REACHED = 15031; internal const int ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND = 15033; internal const int ERROR_MUI_FILE_NOT_FOUND = 15100; internal const int SECURITY_SQOS_PRESENT = 0x00100000; internal const int SECURITY_ANONYMOUS = 0 << 16; internal const int SECURITY_IDENTIFICATION = 1 << 16; internal const int SECURITY_IMPERSONATION = 2 << 16; internal const int SECURITY_DELEGATION = 3 << 16; internal const int GENERIC_READ = unchecked((int)0x80000000); internal const int GENERIC_WRITE = 0x40000000; internal const int STD_INPUT_HANDLE = -10; internal const int STD_OUTPUT_HANDLE = -11; internal const int STD_ERROR_HANDLE = -12; internal const int DUPLICATE_SAME_ACCESS = 0x00000002; internal const int PIPE_ACCESS_INBOUND = 1; internal const int PIPE_ACCESS_OUTBOUND = 2; internal const int PIPE_ACCESS_DUPLEX = 3; internal const int PIPE_TYPE_BYTE = 0; internal const int PIPE_TYPE_MESSAGE = 4; internal const int PIPE_READMODE_BYTE = 0; internal const int PIPE_READMODE_MESSAGE = 2; internal const int PIPE_UNLIMITED_INSTANCES = 255; internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000; internal const int FILE_SHARE_READ = 0x00000001; internal const int FILE_SHARE_WRITE = 0x00000002; internal const int FILE_ATTRIBUTE_NORMAL = 0x00000080; internal const int FILE_FLAG_OVERLAPPED = 0x40000000; internal const int OPEN_EXISTING = 3; // From WinBase.h internal const int FILE_TYPE_DISK = 0x0001; internal const int FILE_TYPE_CHAR = 0x0002; internal const int FILE_TYPE_PIPE = 0x0003; // Memory mapped file constants internal const int MEM_COMMIT = 0x1000; internal const int MEM_RESERVE = 0x2000; internal const int INVALID_FILE_SIZE = -1; internal const int PAGE_READWRITE = 0x04; internal const int PAGE_READONLY = 0x02; internal const int PAGE_WRITECOPY = 0x08; internal const int PAGE_EXECUTE_READ = 0x20; internal const int PAGE_EXECUTE_READWRITE = 0x40; internal const int FILE_MAP_COPY = 0x0001; internal const int FILE_MAP_WRITE = 0x0002; internal const int FILE_MAP_READ = 0x0004; internal const int FILE_MAP_EXECUTE = 0x0020; [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES { internal int nLength; [SecurityCritical] internal unsafe byte* pSecurityDescriptor; internal int bInheritHandle; } [DllImport(KERNEL32)] [SecurityCritical] internal static extern int GetFileType(SafeFileHandle handle); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, NativeOverlapped* lpOverlapped); // Disallow access to all non-file devices from methods that take // a String. This disallows DOS devices like "con:", "com1:", // "lpt1:", etc. Use this to avoid security problems, like allowing // a web client asking a server for "http://server/com1.aspx" and // then causing a worker process to hang. [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] private static extern SafeFileHandle CreateFile(String lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [SecurityCritical] internal static SafeFileHandle SafeCreateFile(String lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile) { SafeFileHandle handle = CreateFile(lpFileName, dwDesiredAccess, dwShareMode, securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); if (!handle.IsInvalid) { int fileType = UnsafeNativeMethods.GetFileType(handle); if (fileType != UnsafeNativeMethods.FILE_TYPE_DISK) { handle.Dispose(); throw new NotSupportedException(SR.GetString(SR.NotSupported_IONonFileDevices)); } } return handle; } // From WinBase.h internal const int SEM_FAILCRITICALERRORS = 1; [DllImport(KERNEL32, SetLastError = false)] [ResourceExposure(ResourceScope.Process)] [SecurityCritical] internal static extern int SetErrorMode(int newMode); [DllImport(KERNEL32, SetLastError = true, EntryPoint = "SetFilePointer")] [ResourceExposure(ResourceScope.None)] [SecurityCritical] private unsafe static extern int SetFilePointerWin32(SafeFileHandle handle, int lo, int* hi, int origin); [ResourceExposure(ResourceScope.None)] [SecurityCritical] internal unsafe static long SetFilePointer(SafeFileHandle handle, long offset, System.IO.SeekOrigin origin, out int hr) { hr = 0; int lo = (int)offset; int hi = (int)(offset >> 32); lo = SetFilePointerWin32(handle, lo, &hi, (int)origin); if (lo == -1 && ((hr = Marshal.GetLastWin32Error()) != 0)) return -1; return (long)(((ulong)((uint)hi)) << 32) | ((uint)lo); } // // ErrorCode & format // // Use this to translate error codes like the above into HRESULTs like // 0x80070006 for ERROR_INVALID_HANDLE internal static int MakeHRFromErrorCode(int errorCode) { return unchecked(((int)0x80070000) | errorCode); } // for win32 error message formatting private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = false)] [SecurityCritical] internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr va_list_arguments); // Gets an error message for a Win32 error code. [SecurityCritical] internal static String GetMessage(int errorCode) { StringBuilder sb = new StringBuilder(512); int result = UnsafeNativeMethods.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, UnsafeNativeMethods.NULL, errorCode, 0, sb, sb.Capacity, UnsafeNativeMethods.NULL); if (result != 0) { // result is the # of characters copied to the StringBuilder on NT, // but on Win9x, it appears to be the number of MBCS buffer. // Just give up and return the String as-is... String s = sb.ToString(); return s; } else { return "UnknownError_Num " + errorCode; } } // // SafeLibraryHandle // [DllImport(KERNEL32, CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.Machine)] [SecurityCritical] internal static extern SafeLibraryHandle LoadLibraryEx(string libFilename, IntPtr reserved, int flags); [DllImport(KERNEL32, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SecurityCritical] internal static extern bool FreeLibrary(IntPtr hModule); // // Pipe // [DllImport(KERNEL32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] [SecurityCritical] internal static extern bool CloseHandle(IntPtr handle); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern IntPtr GetCurrentProcess(); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, SafePipeHandle hSourceHandle, IntPtr hTargetProcessHandle, out SafePipeHandle lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions); [DllImport(KERNEL32)] [SecurityCritical] internal static extern int GetFileType(SafePipeHandle handle); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CreatePipe(out SafePipeHandle hReadPipe, out SafePipeHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, int nSize); [DllImport(KERNEL32, EntryPoint="CreateFile", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] [SecurityCritical] internal static extern SafePipeHandle CreateNamedPipeClient(String lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, UnsafeNativeMethods.SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] unsafe internal static extern bool ConnectNamedPipe(SafePipeHandle handle, NativeOverlapped* overlapped); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ConnectNamedPipe(SafePipeHandle handle, IntPtr overlapped); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WaitNamedPipe(String name, int timeout); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, out int lpState, IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, IntPtr lpUserName, int nMaxUserNameSize); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState, out int lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, IntPtr lpUserName, int nMaxUserNameSize); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState, IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, StringBuilder lpUserName, int nMaxUserNameSize); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, out int lpFlags, IntPtr lpOutBufferSize, IntPtr lpInBufferSize, IntPtr lpMaxInstances ); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, IntPtr lpFlags, out int lpOutBufferSize, IntPtr lpInBufferSize, IntPtr lpMaxInstances ); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, IntPtr lpFlags, IntPtr lpOutBufferSize, out int lpInBufferSize, IntPtr lpMaxInstances ); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static unsafe extern bool SetNamedPipeHandleState( SafePipeHandle hNamedPipe, int* lpMode, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout ); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DisconnectNamedPipe(SafePipeHandle hNamedPipe); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FlushFileBuffers(SafePipeHandle hNamedPipe); [DllImport(ADVAPI32, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal static extern bool RevertToSelf(); [DllImport(ADVAPI32, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal static extern bool ImpersonateNamedPipeClient(SafePipeHandle hNamedPipe); [DllImport(KERNEL32, SetLastError = true, BestFitMapping = false, CharSet = CharSet.Auto)] [SecurityCritical] internal static extern SafePipeHandle CreateNamedPipe(string pipeName, int openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, SECURITY_ATTRIBUTES securityAttributes); // Note there are two different ReadFile prototypes - this is to use // the type system to force you to not trip across a "feature" in // Win32's async IO support. You can't do the following three things // simultaneously: overlapped IO, free the memory for the overlapped // struct in a callback (or an EndRead method called by that callback), // and pass in an address for the numBytesRead parameter. // < [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] unsafe internal static extern int ReadFile(SafePipeHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] unsafe internal static extern int ReadFile(SafePipeHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero); // Note there are two different WriteFile prototypes - this is to use // the type system to force you to not trip across a "feature" in // Win32's async IO support. You can't do the following three things // simultaneously: overlapped IO, free the memory for the overlapped // struct in a callback (or an EndWrite method called by that callback), // and pass in an address for the numBytesRead parameter. // < [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] internal static unsafe extern int WriteFile(SafePipeHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] internal static unsafe extern int WriteFile(SafePipeHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] internal static extern bool SetEndOfFile(IntPtr hNamedPipe); // // ETW Methods // // // Callback // #pragma warning disable 618 // Ssytem.Core still uses SecurityRuleSet.Level1 [SecurityCritical(SecurityCriticalScope.Everything)] #pragma warning restore 618 internal unsafe delegate void EtwEnableCallback( [In] ref Guid sourceId, [In] int isEnabled, [In] byte level, [In] long matchAnyKeywords, [In] long matchAllKeywords, [In] void* filterData, [In] void* callbackContext ); // // Registration APIs // [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventRegister( [In] ref Guid providerId, [In]EtwEnableCallback enableCallback, [In]void* callbackContext, [In][Out]ref long registrationHandle ); [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern int EventUnregister([In] long registrationHandle); // // Control (Is Enabled) APIs // [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern int EventEnabled([In] long registrationHandle, [In] ref System.Diagnostics.Eventing.EventDescriptor eventDescriptor); [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventProviderEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern int EventProviderEnabled([In] long registrationHandle, [In] byte level, [In] long keywords); // // Writing (Publishing/Logging) APIs // [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventWrite( [In] long registrationHandle, [In] ref EventDescriptor eventDescriptor, [In] uint userDataCount, [In] void* userData ); // // Writing (Publishing/Logging) APIs // [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventWrite( [In] long registrationHandle, [In] EventDescriptor* eventDescriptor, [In] uint userDataCount, [In] void* userData ); [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventWriteTransfer( [In] long registrationHandle, [In] ref EventDescriptor eventDescriptor, [In] Guid* activityId, [In] Guid* relatedActivityId, [In] uint userDataCount, [In] void* userData ); [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventWriteString( [In] long registrationHandle, [In] byte level, [In] long keywords, [In] char* message ); // // ActivityId Control APIs // [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventActivityIdControl([In] int ControlCode, [In][Out] ref Guid ActivityId); // Native PERFLIB V2 Provider APIs. // [StructLayout(LayoutKind.Explicit, Size = 40)] internal struct PerfCounterSetInfoStruct { // PERF_COUNTERSET_INFO structure defined in perflib.h [FieldOffset(0)] internal Guid CounterSetGuid; [FieldOffset(16)] internal Guid ProviderGuid; [FieldOffset(32)] internal uint NumCounters; [FieldOffset(36)] internal uint InstanceType; } [StructLayout(LayoutKind.Explicit, Size = 32)] internal struct PerfCounterInfoStruct { // PERF_COUNTER_INFO structure defined in perflib.h [FieldOffset(0)] internal uint CounterId; [FieldOffset(4)] internal uint CounterType; [FieldOffset(8)] internal Int64 Attrib; [FieldOffset(16)] internal uint Size; [FieldOffset(20)] internal uint DetailLevel; [FieldOffset(24)] internal uint Scale; [FieldOffset(28)] internal uint Offset; } [StructLayout(LayoutKind.Explicit, Size = 32)] internal struct PerfCounterSetInstanceStruct { // PERF_COUNTERSET_INSTANCE structure defined in perflib.h [FieldOffset(0)] internal Guid CounterSetGuid; [FieldOffset(16)] internal uint dwSize; [FieldOffset(20)] internal uint InstanceId; [FieldOffset(24)] internal uint InstanceNameOffset; [FieldOffset(28)] internal uint InstanceNameSize; } #pragma warning disable 618 // Ssytem.Core still uses SecurityRuleSet.Level1 [SecurityCritical(SecurityCriticalScope.Everything)] #pragma warning restore 618 internal unsafe delegate uint PERFLIBREQUEST( [In] uint RequestCode, [In] void * Buffer, [In] uint BufferSize ); [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfStartProvider", CharSet = CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint PerfStartProvider( [In] ref Guid ProviderGuid, [In] PERFLIBREQUEST ControlCallback, [Out] out SafePerfProviderHandle phProvider ); [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfStopProvider", CharSet = CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint PerfStopProvider( [In] IntPtr hProvider ); [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfSetCounterSetInfo", CharSet = CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint PerfSetCounterSetInfo( [In] SafePerfProviderHandle hProvider, [In][Out] PerfCounterSetInfoStruct * pTemplate, [In] uint dwTemplateSize ); [DllImport(ADVAPI32, SetLastError = true, ExactSpelling = true, EntryPoint = "PerfCreateInstance", CharSet = CharSet.Unicode)] [SecurityCritical] internal static extern unsafe PerfCounterSetInstanceStruct* PerfCreateInstance( [In] SafePerfProviderHandle hProvider, [In] ref Guid CounterSetGuid, [In] String szInstanceName, [In] uint dwInstance ); [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfDeleteInstance", CharSet = CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint PerfDeleteInstance( [In] SafePerfProviderHandle hProvider, [In] PerfCounterSetInstanceStruct * InstanceBlock ); [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "PerfSetCounterRefValue", CharSet = CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint PerfSetCounterRefValue( [In] SafePerfProviderHandle hProvider, [In] PerfCounterSetInstanceStruct * pInstance, [In] uint CounterId, [In] void * lpAddr ); // // EventLog // [Flags] internal enum EvtQueryFlags { EvtQueryChannelPath = 0x1, EvtQueryFilePath = 0x2, EvtQueryForwardDirection = 0x100, EvtQueryReverseDirection = 0x200, EvtQueryTolerateQueryErrors = 0x1000 } [Flags] internal enum EvtSubscribeFlags { EvtSubscribeToFutureEvents = 1, EvtSubscribeStartAtOldestRecord = 2, EvtSubscribeStartAfterBookmark = 3, EvtSubscribeTolerateQueryErrors = 0x1000, EvtSubscribeStrict = 0x10000 } /// <summary> /// Evt Variant types /// </summary> internal enum EvtVariantType { EvtVarTypeNull = 0, EvtVarTypeString = 1, EvtVarTypeAnsiString = 2, EvtVarTypeSByte = 3, EvtVarTypeByte = 4, EvtVarTypeInt16 = 5, EvtVarTypeUInt16 = 6, EvtVarTypeInt32 = 7, EvtVarTypeUInt32 = 8, EvtVarTypeInt64 = 9, EvtVarTypeUInt64 = 10, EvtVarTypeSingle = 11, EvtVarTypeDouble = 12, EvtVarTypeBoolean = 13, EvtVarTypeBinary = 14, EvtVarTypeGuid = 15, EvtVarTypeSizeT = 16, EvtVarTypeFileTime = 17, EvtVarTypeSysTime = 18, EvtVarTypeSid = 19, EvtVarTypeHexInt32 = 20, EvtVarTypeHexInt64 = 21, // these types used internally EvtVarTypeEvtHandle = 32, EvtVarTypeEvtXml = 35, //Array = 128 EvtVarTypeStringArray = 129, EvtVarTypeUInt32Array = 136 } internal enum EvtMasks { EVT_VARIANT_TYPE_MASK = 0x7f, EVT_VARIANT_TYPE_ARRAY = 128 } [StructLayout(LayoutKind.Sequential)] internal struct SystemTime { [MarshalAs(UnmanagedType.U2)] public short Year; [MarshalAs(UnmanagedType.U2)] public short Month; [MarshalAs(UnmanagedType.U2)] public short DayOfWeek; [MarshalAs(UnmanagedType.U2)] public short Day; [MarshalAs(UnmanagedType.U2)] public short Hour; [MarshalAs(UnmanagedType.U2)] public short Minute; [MarshalAs(UnmanagedType.U2)] public short Second; [MarshalAs(UnmanagedType.U2)] public short Milliseconds; } [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)] #pragma warning disable 618 // Ssytem.Core still uses SecurityRuleSet.Level1 [SecurityCritical(SecurityCriticalScope.Everything)] #pragma warning restore 618 internal struct EvtVariant { [FieldOffset(0)] public UInt32 UInteger; [FieldOffset(0)] public Int32 Integer; [FieldOffset(0)] public byte UInt8; [FieldOffset(0)] public short Short; [FieldOffset(0)] public ushort UShort; [FieldOffset(0)] public UInt32 Bool; [FieldOffset(0)] public Byte ByteVal; [FieldOffset(0)] public byte SByte; [FieldOffset(0)] public UInt64 ULong; [FieldOffset(0)] public Int64 Long; [FieldOffset(0)] public Single Single; [FieldOffset(0)] public Double Double; [FieldOffset(0)] public IntPtr StringVal; [FieldOffset(0)] public IntPtr AnsiString; [FieldOffset(0)] public IntPtr SidVal; [FieldOffset(0)] public IntPtr Binary; [FieldOffset(0)] public IntPtr Reference; [FieldOffset(0)] public IntPtr Handle; [FieldOffset(0)] public IntPtr GuidReference; [FieldOffset(0)] public UInt64 FileTime; [FieldOffset(0)] public IntPtr SystemTime; [FieldOffset(0)] public IntPtr SizeT; [FieldOffset(8)] public UInt32 Count; // number of elements (not length) in bytes. [FieldOffset(12)] public UInt32 Type; } internal enum EvtEventPropertyId { EvtEventQueryIDs = 0, EvtEventPath = 1 } /// <summary> /// The query flags to get information about query /// </summary> internal enum EvtQueryPropertyId { EvtQueryNames = 0, //String; //Variant will be array of EvtVarTypeString EvtQueryStatuses = 1 //UInt32; //Variant will be Array of EvtVarTypeUInt32 } /// <summary> /// Publisher Metadata properties /// </summary> internal enum EvtPublisherMetadataPropertyId { EvtPublisherMetadataPublisherGuid = 0, // EvtVarTypeGuid EvtPublisherMetadataResourceFilePath = 1, // EvtVarTypeString EvtPublisherMetadataParameterFilePath = 2, // EvtVarTypeString EvtPublisherMetadataMessageFilePath = 3, // EvtVarTypeString EvtPublisherMetadataHelpLink = 4, // EvtVarTypeString EvtPublisherMetadataPublisherMessageID = 5, // EvtVarTypeUInt32 EvtPublisherMetadataChannelReferences = 6, // EvtVarTypeEvtHandle, ObjectArray EvtPublisherMetadataChannelReferencePath = 7, // EvtVarTypeString EvtPublisherMetadataChannelReferenceIndex = 8, // EvtVarTypeUInt32 EvtPublisherMetadataChannelReferenceID = 9, // EvtVarTypeUInt32 EvtPublisherMetadataChannelReferenceFlags = 10, // EvtVarTypeUInt32 EvtPublisherMetadataChannelReferenceMessageID = 11, // EvtVarTypeUInt32 EvtPublisherMetadataLevels = 12, // EvtVarTypeEvtHandle, ObjectArray EvtPublisherMetadataLevelName = 13, // EvtVarTypeString EvtPublisherMetadataLevelValue = 14, // EvtVarTypeUInt32 EvtPublisherMetadataLevelMessageID = 15, // EvtVarTypeUInt32 EvtPublisherMetadataTasks = 16, // EvtVarTypeEvtHandle, ObjectArray EvtPublisherMetadataTaskName = 17, // EvtVarTypeString EvtPublisherMetadataTaskEventGuid = 18, // EvtVarTypeGuid EvtPublisherMetadataTaskValue = 19, // EvtVarTypeUInt32 EvtPublisherMetadataTaskMessageID = 20, // EvtVarTypeUInt32 EvtPublisherMetadataOpcodes = 21, // EvtVarTypeEvtHandle, ObjectArray EvtPublisherMetadataOpcodeName = 22, // EvtVarTypeString EvtPublisherMetadataOpcodeValue = 23, // EvtVarTypeUInt32 EvtPublisherMetadataOpcodeMessageID = 24, // EvtVarTypeUInt32 EvtPublisherMetadataKeywords = 25, // EvtVarTypeEvtHandle, ObjectArray EvtPublisherMetadataKeywordName = 26, // EvtVarTypeString EvtPublisherMetadataKeywordValue = 27, // EvtVarTypeUInt64 EvtPublisherMetadataKeywordMessageID = 28//, // EvtVarTypeUInt32 //EvtPublisherMetadataPropertyIdEND } internal enum EvtChannelReferenceFlags { EvtChannelReferenceImported = 1 } internal enum EvtEventMetadataPropertyId { EventMetadataEventID, // EvtVarTypeUInt32 EventMetadataEventVersion, // EvtVarTypeUInt32 EventMetadataEventChannel, // EvtVarTypeUInt32 EventMetadataEventLevel, // EvtVarTypeUInt32 EventMetadataEventOpcode, // EvtVarTypeUInt32 EventMetadataEventTask, // EvtVarTypeUInt32 EventMetadataEventKeyword, // EvtVarTypeUInt64 EventMetadataEventMessageID,// EvtVarTypeUInt32 EventMetadataEventTemplate // EvtVarTypeString //EvtEventMetadataPropertyIdEND } //CHANNEL CONFIGURATION internal enum EvtChannelConfigPropertyId { EvtChannelConfigEnabled = 0, // EvtVarTypeBoolean EvtChannelConfigIsolation, // EvtVarTypeUInt32, EVT_CHANNEL_ISOLATION_TYPE EvtChannelConfigType, // EvtVarTypeUInt32, EVT_CHANNEL_TYPE EvtChannelConfigOwningPublisher, // EvtVarTypeString EvtChannelConfigClassicEventlog, // EvtVarTypeBoolean EvtChannelConfigAccess, // EvtVarTypeString EvtChannelLoggingConfigRetention, // EvtVarTypeBoolean EvtChannelLoggingConfigAutoBackup, // EvtVarTypeBoolean EvtChannelLoggingConfigMaxSize, // EvtVarTypeUInt64 EvtChannelLoggingConfigLogFilePath, // EvtVarTypeString EvtChannelPublishingConfigLevel, // EvtVarTypeUInt32 EvtChannelPublishingConfigKeywords, // EvtVarTypeUInt64 EvtChannelPublishingConfigControlGuid, // EvtVarTypeGuid EvtChannelPublishingConfigBufferSize, // EvtVarTypeUInt32 EvtChannelPublishingConfigMinBuffers, // EvtVarTypeUInt32 EvtChannelPublishingConfigMaxBuffers, // EvtVarTypeUInt32 EvtChannelPublishingConfigLatency, // EvtVarTypeUInt32 EvtChannelPublishingConfigClockType, // EvtVarTypeUInt32, EVT_CHANNEL_CLOCK_TYPE EvtChannelPublishingConfigSidType, // EvtVarTypeUInt32, EVT_CHANNEL_SID_TYPE EvtChannelPublisherList, // EvtVarTypeString | EVT_VARIANT_TYPE_ARRAY EvtChannelConfigPropertyIdEND } //LOG INFORMATION internal enum EvtLogPropertyId { EvtLogCreationTime = 0, // EvtVarTypeFileTime EvtLogLastAccessTime, // EvtVarTypeFileTime EvtLogLastWriteTime, // EvtVarTypeFileTime EvtLogFileSize, // EvtVarTypeUInt64 EvtLogAttributes, // EvtVarTypeUInt32 EvtLogNumberOfLogRecords, // EvtVarTypeUInt64 EvtLogOldestRecordNumber, // EvtVarTypeUInt64 EvtLogFull, // EvtVarTypeBoolean } internal enum EvtExportLogFlags { EvtExportLogChannelPath = 1, EvtExportLogFilePath = 2, EvtExportLogTolerateQueryErrors = 0x1000 } //RENDERING internal enum EvtRenderContextFlags { EvtRenderContextValues = 0, // Render specific properties EvtRenderContextSystem = 1, // Render all system properties (System) EvtRenderContextUser = 2 // Render all user properties (User/EventData) } internal enum EvtRenderFlags { EvtRenderEventValues = 0, // Variants EvtRenderEventXml = 1, // XML EvtRenderBookmark = 2 // Bookmark } internal enum EvtFormatMessageFlags { EvtFormatMessageEvent = 1, EvtFormatMessageLevel = 2, EvtFormatMessageTask = 3, EvtFormatMessageOpcode = 4, EvtFormatMessageKeyword = 5, EvtFormatMessageChannel = 6, EvtFormatMessageProvider = 7, EvtFormatMessageId = 8, EvtFormatMessageXml = 9 } internal enum EvtSystemPropertyId { EvtSystemProviderName = 0, // EvtVarTypeString EvtSystemProviderGuid, // EvtVarTypeGuid EvtSystemEventID, // EvtVarTypeUInt16 EvtSystemQualifiers, // EvtVarTypeUInt16 EvtSystemLevel, // EvtVarTypeUInt8 EvtSystemTask, // EvtVarTypeUInt16 EvtSystemOpcode, // EvtVarTypeUInt8 EvtSystemKeywords, // EvtVarTypeHexInt64 EvtSystemTimeCreated, // EvtVarTypeFileTime EvtSystemEventRecordId, // EvtVarTypeUInt64 EvtSystemActivityID, // EvtVarTypeGuid EvtSystemRelatedActivityID, // EvtVarTypeGuid EvtSystemProcessID, // EvtVarTypeUInt32 EvtSystemThreadID, // EvtVarTypeUInt32 EvtSystemChannel, // EvtVarTypeString EvtSystemComputer, // EvtVarTypeString EvtSystemUserID, // EvtVarTypeSid EvtSystemVersion, // EvtVarTypeUInt8 EvtSystemPropertyIdEND } //SESSION internal enum EvtLoginClass { EvtRpcLogin = 1 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal struct EvtRpcLogin { [MarshalAs(UnmanagedType.LPWStr)] public string Server; [MarshalAs(UnmanagedType.LPWStr)] public string User; [MarshalAs(UnmanagedType.LPWStr)] public string Domain; [SecurityCritical] public CoTaskMemUnicodeSafeHandle Password; public int Flags; } //SEEK [Flags] internal enum EvtSeekFlags { EvtSeekRelativeToFirst = 1, EvtSeekRelativeToLast = 2, EvtSeekRelativeToCurrent = 3, EvtSeekRelativeToBookmark = 4, EvtSeekOriginMask = 7, EvtSeekStrict = 0x10000 } [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtQuery( EventLogHandle session, [MarshalAs(UnmanagedType.LPWStr)]string path, [MarshalAs(UnmanagedType.LPWStr)]string query, int flags); //SEEK [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtSeek( EventLogHandle resultSet, long position, EventLogHandle bookmark, int timeout, [MarshalAs(UnmanagedType.I4)]EvtSeekFlags flags ); [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtSubscribe( EventLogHandle session, SafeWaitHandle signalEvent, [MarshalAs(UnmanagedType.LPWStr)]string path, [MarshalAs(UnmanagedType.LPWStr)]string query, EventLogHandle bookmark, IntPtr context, IntPtr callback, int flags); [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtNext( EventLogHandle queryHandle, int eventSize, [MarshalAs(UnmanagedType.LPArray)] IntPtr[] events, int timeout, int flags, ref int returned); [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtCancel(EventLogHandle handle); [DllImport(WEVTAPI)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtClose(IntPtr handle); /* [DllImport(WEVTAPI, EntryPoint = "EvtClose", SetLastError = true)] public static extern bool EvtClose( IntPtr eventHandle ); */ [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtGetEventInfo( EventLogHandle eventHandle, //int propertyId [MarshalAs(UnmanagedType.I4)]EvtEventPropertyId propertyId, int bufferSize, IntPtr bufferPtr, out int bufferUsed ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtGetQueryInfo( EventLogHandle queryHandle, [MarshalAs(UnmanagedType.I4)]EvtQueryPropertyId propertyId, int bufferSize, IntPtr buffer, ref int bufferRequired ); //PUBLISHER METADATA [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtOpenPublisherMetadata( EventLogHandle session, [MarshalAs(UnmanagedType.LPWStr)] string publisherId, [MarshalAs(UnmanagedType.LPWStr)] string logFilePath, int locale, int flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtGetPublisherMetadataProperty( EventLogHandle publisherMetadataHandle, [MarshalAs(UnmanagedType.I4)] EvtPublisherMetadataPropertyId propertyId, int flags, int publisherMetadataPropertyBufferSize, IntPtr publisherMetadataPropertyBuffer, out int publisherMetadataPropertyBufferUsed ); //NEW [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtGetObjectArraySize( EventLogHandle objectArray, out int objectArraySize ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtGetObjectArrayProperty( EventLogHandle objectArray, int propertyId, int arrayIndex, int flags, int propertyValueBufferSize, IntPtr propertyValueBuffer, out int propertyValueBufferUsed ); //NEW 2 [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtOpenEventMetadataEnum( EventLogHandle publisherMetadata, int flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] //public static extern IntPtr EvtNextEventMetadata( internal static extern EventLogHandle EvtNextEventMetadata( EventLogHandle eventMetadataEnum, int flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtGetEventMetadataProperty( EventLogHandle eventMetadata, [MarshalAs(UnmanagedType.I4)] EvtEventMetadataPropertyId propertyId, int flags, int eventMetadataPropertyBufferSize, IntPtr eventMetadataPropertyBuffer, out int eventMetadataPropertyBufferUsed ); //Channel Configuration Native Api [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtOpenChannelEnum( EventLogHandle session, int flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtNextChannelPath( EventLogHandle channelEnum, int channelPathBufferSize, //StringBuilder channelPathBuffer, [Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder channelPathBuffer, out int channelPathBufferUsed ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtOpenPublisherEnum( EventLogHandle session, int flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtNextPublisherId( EventLogHandle publisherEnum, int publisherIdBufferSize, [Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder publisherIdBuffer, out int publisherIdBufferUsed ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtOpenChannelConfig( EventLogHandle session, [MarshalAs(UnmanagedType.LPWStr)]String channelPath, int flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtSaveChannelConfig( EventLogHandle channelConfig, int flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtSetChannelConfigProperty( EventLogHandle channelConfig, [MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId, int flags, ref EvtVariant propertyValue ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtGetChannelConfigProperty( EventLogHandle channelConfig, [MarshalAs(UnmanagedType.I4)]EvtChannelConfigPropertyId propertyId, int flags, int propertyValueBufferSize, IntPtr propertyValueBuffer, out int propertyValueBufferUsed ); //Log Information Native Api [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtOpenLog( EventLogHandle session, [MarshalAs(UnmanagedType.LPWStr)] string path, [MarshalAs(UnmanagedType.I4)]PathType flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtGetLogInfo( EventLogHandle log, [MarshalAs(UnmanagedType.I4)]EvtLogPropertyId propertyId, int propertyValueBufferSize, IntPtr propertyValueBuffer, out int propertyValueBufferUsed ); //LOG MANIPULATION [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtExportLog( EventLogHandle session, [MarshalAs(UnmanagedType.LPWStr)]string channelPath, [MarshalAs(UnmanagedType.LPWStr)]string query, [MarshalAs(UnmanagedType.LPWStr)]string targetFilePath, int flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtArchiveExportedLog( EventLogHandle session, [MarshalAs(UnmanagedType.LPWStr)]string logFilePath, int locale, int flags ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtClearLog( EventLogHandle session, [MarshalAs(UnmanagedType.LPWStr)]string channelPath, [MarshalAs(UnmanagedType.LPWStr)]string targetFilePath, int flags ); //RENDERING [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtCreateRenderContext( Int32 valuePathsCount, [MarshalAs(UnmanagedType.LPArray,ArraySubType = UnmanagedType.LPWStr)] String[] valuePaths, [MarshalAs(UnmanagedType.I4)]EvtRenderContextFlags flags ); [DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtRender( EventLogHandle context, EventLogHandle eventHandle, EvtRenderFlags flags, int buffSize, [Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer, out int buffUsed, out int propCount ); [DllImport(WEVTAPI, EntryPoint = "EvtRender", CallingConvention = CallingConvention.Winapi, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtRender( EventLogHandle context, EventLogHandle eventHandle, EvtRenderFlags flags, int buffSize, IntPtr buffer, out int buffUsed, out int propCount ); [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)] internal struct EvtStringVariant { [MarshalAs(UnmanagedType.LPWStr),FieldOffset(0)] public string StringVal; [FieldOffset(8)] public UInt32 Count; [FieldOffset(12)] public UInt32 Type; }; [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtFormatMessage( EventLogHandle publisherMetadataHandle, EventLogHandle eventHandle, uint messageId, int valueCount, EvtStringVariant [] values, [MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags, int bufferSize, [Out, MarshalAs(UnmanagedType.LPWStr)]StringBuilder buffer, out int bufferUsed ); [DllImport(WEVTAPI, EntryPoint = "EvtFormatMessage", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtFormatMessageBuffer( EventLogHandle publisherMetadataHandle, EventLogHandle eventHandle, uint messageId, int valueCount, IntPtr values, [MarshalAs(UnmanagedType.I4)]EvtFormatMessageFlags flags, int bufferSize, IntPtr buffer, out int bufferUsed ); //SESSION [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtOpenSession( [MarshalAs(UnmanagedType.I4)]EvtLoginClass loginClass, ref EvtRpcLogin login, int timeout, int flags ); //BOOKMARK [DllImport(WEVTAPI, EntryPoint = "EvtCreateBookmark", CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtCreateBookmark( [MarshalAs(UnmanagedType.LPWStr)] string bookmarkXml ); [DllImport(WEVTAPI, CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EvtUpdateBookmark( EventLogHandle bookmark, EventLogHandle eventHandle ); // // EventLog // // // Memory Mapped File // [StructLayout(LayoutKind.Sequential)] #pragma warning disable 618 // Ssytem.Core still uses SecurityRuleSet.Level1 [SecurityCritical(SecurityCriticalScope.Everything)] #pragma warning restore 618 internal unsafe struct MEMORY_BASIC_INFORMATION { internal void* BaseAddress; internal void* AllocationBase; internal uint AllocationProtect; internal UIntPtr RegionSize; internal uint State; internal uint Protect; internal uint Type; } [StructLayout(LayoutKind.Sequential)] internal struct SYSTEM_INFO { internal int dwOemId; // This is a union of a DWORD and a struct containing 2 WORDs. internal int dwPageSize; internal IntPtr lpMinimumApplicationAddress; internal IntPtr lpMaximumApplicationAddress; internal IntPtr dwActiveProcessorMask; internal int dwNumberOfProcessors; internal int dwProcessorType; internal int dwAllocationGranularity; internal short wProcessorLevel; internal short wProcessorRevision; } [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo); [DllImport(KERNEL32, ExactSpelling = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnmapViewOfFile(IntPtr lpBaseAddress); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] internal static extern int GetFileSize( SafeMemoryMappedFileHandle hFile, out int highSize ); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] unsafe internal static extern IntPtr VirtualQuery( SafeMemoryMappedViewHandle address, ref MEMORY_BASIC_INFORMATION buffer, IntPtr sizeOfBuffer ); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] [SecurityCritical] internal static extern SafeMemoryMappedFileHandle CreateFileMapping( SafeFileHandle hFile, SECURITY_ATTRIBUTES lpAttributes, int fProtect, int dwMaximumSizeHigh, int dwMaximumSizeLow, String lpName ); [DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] unsafe internal static extern bool FlushViewOfFile( byte* lpBaseAddress, IntPtr dwNumberOfBytesToFlush ); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] [SecurityCritical] internal static extern SafeMemoryMappedFileHandle OpenFileMapping( int dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName ); [DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)] [SecurityCritical] internal static extern SafeMemoryMappedViewHandle MapViewOfFile( SafeMemoryMappedFileHandle handle, int dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, UIntPtr dwNumberOfBytesToMap ); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] unsafe internal static extern IntPtr VirtualAlloc( SafeMemoryMappedViewHandle address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode ); [SecurityCritical] internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer) { lpBuffer.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX)); return GlobalMemoryStatusExNative(ref lpBuffer); } [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, EntryPoint = "GlobalMemoryStatusEx")] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX lpBuffer); [DllImport(KERNEL32, SetLastError = true)] [SecurityCritical] internal static unsafe extern bool CancelIoEx(SafeHandle handle, NativeOverlapped* lpOverlapped); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal struct MEMORYSTATUSEX { internal uint dwLength; internal uint dwMemoryLoad; internal ulong ullTotalPhys; internal ulong ullAvailPhys; internal ulong ullTotalPageFile; internal ulong ullAvailPageFile; internal ulong ullTotalVirtual; internal ulong ullAvailVirtual; internal ulong ullAvailExtendedVirtual; } } }
// // Copyright 2012 Hakan Kjellerstrand // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.IO; using System.Text.RegularExpressions; using Google.OrTools.ConstraintSolver; public class SurvoPuzzle { // // default problem // static int default_r = 3; static int default_c = 4; static int[] default_rowsums = { 30, 18, 30 }; static int[] default_colsums = { 27, 16, 10, 25 }; static int[,] default_game = { { 0, 6, 0, 0 }, { 8, 0, 0, 0 }, { 0, 0, 3, 0 } }; // for the actual problem static int r; static int c; static int[] rowsums; static int[] colsums; static int[,] game; /** * * Solves the Survo puzzle. * See http://www.hakank.org/or-tools/survo_puzzle.py * */ private static void Solve() { Solver solver = new Solver("SurvoPuzzle"); // // data // Console.WriteLine("Problem:"); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { Console.Write(game[i, j] + " "); } Console.WriteLine(); } Console.WriteLine(); // // Decision variables // IntVar[,] x = solver.MakeIntVarMatrix(r, c, 1, r * c, "x"); IntVar[] x_flat = x.Flatten(); // // Constraints // for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { if (game[i, j] > 0) { solver.Add(x[i, j] == game[i, j]); } } } solver.Add(x_flat.AllDifferent()); // // calculate rowsums and colsums // for (int i = 0; i < r; i++) { IntVar[] row = new IntVar[c]; for (int j = 0; j < c; j++) { row[j] = x[i, j]; } solver.Add(row.Sum() == rowsums[i]); } for (int j = 0; j < c; j++) { IntVar[] col = new IntVar[r]; for (int i = 0; i < r; i++) { col[i] = x[i, j]; } solver.Add(col.Sum() == colsums[j]); } // // Search // DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_SIMPLE, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); int sol = 0; while (solver.NextSolution()) { sol++; Console.WriteLine("Solution #{0} ", sol + " "); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { Console.Write("{0} ", x[i, j].Value()); } Console.WriteLine(); } Console.WriteLine(); } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); Console.WriteLine("WallTime: {0}ms", solver.WallTime()); Console.WriteLine("Failures: {0}", solver.Failures()); Console.WriteLine("Branches: {0} ", solver.Branches()); solver.EndSearch(); } /** * * readFile() * * Reads a Survo puzzle in the following format * r * c * rowsums * olsums * data * ... * * Example: * 3 * 4 * 30,18,30 * 27,16,10,25 * 0,6,0,0 * 8,0,0,0 * 0,0,3,0 * */ private static void readFile(String file) { Console.WriteLine("readFile(" + file + ")"); TextReader inr = new StreamReader(file); r = Convert.ToInt32(inr.ReadLine()); c = Convert.ToInt32(inr.ReadLine()); rowsums = new int[r]; colsums = new int[c]; Console.WriteLine("r: " + r + " c: " + c); String[] rowsums_str = Regex.Split(inr.ReadLine(), ",\\s*"); String[] colsums_str = Regex.Split(inr.ReadLine(), ",\\s*"); Console.WriteLine("rowsums:"); for (int i = 0; i < r; i++) { Console.Write(rowsums_str[i] + " "); rowsums[i] = Convert.ToInt32(rowsums_str[i]); } Console.WriteLine("\ncolsums:"); for (int j = 0; j < c; j++) { Console.Write(colsums_str[j] + " "); colsums[j] = Convert.ToInt32(colsums_str[j]); } Console.WriteLine(); // init the game matrix and read data from file game = new int[r, c]; String str; int line_count = 0; while ((str = inr.ReadLine()) != null && str.Length > 0) { str = str.Trim(); // ignore comments // starting with either # or % if (str.StartsWith("#") || str.StartsWith("%")) { continue; } String[] this_row = Regex.Split(str, ",\\s*"); for (int j = 0; j < this_row.Length; j++) { game[line_count, j] = Convert.ToInt32(this_row[j]); } line_count++; } // end while inr.Close(); } // end readFile public static void Main(String[] args) { String file = ""; if (args.Length > 0) { file = args[0]; readFile(file); } else { r = default_r; c = default_c; game = default_game; rowsums = default_rowsums; colsums = default_colsums; } Solve(); } }
// 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. // --------------------------------------------------------------------------- // Native Format Reader // // Utilities to read native data from images, that are written by the NativeFormatWriter engine // --------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Internal.NativeFormat { internal unsafe partial struct NativePrimitiveDecoder { public static void ThrowBadImageFormatException() { Debug.Assert(false); throw new BadImageFormatException(); } public static uint DecodeUnsigned(ref byte* stream, byte* streamEnd) { if (stream >= streamEnd) ThrowBadImageFormatException(); uint value = 0; uint val = *stream; if ((val & 1) == 0) { value = (val >> 1); stream += 1; } else if ((val & 2) == 0) { if (stream + 1 >= streamEnd) ThrowBadImageFormatException(); value = (val >> 2) | (((uint)*(stream + 1)) << 6); stream += 2; } else if ((val & 4) == 0) { if (stream + 2 >= streamEnd) ThrowBadImageFormatException(); value = (val >> 3) | (((uint)*(stream + 1)) << 5) | (((uint)*(stream + 2)) << 13); stream += 3; } else if ((val & 8) == 0) { if (stream + 3 >= streamEnd) ThrowBadImageFormatException(); value = (val >> 4) | (((uint)*(stream + 1)) << 4) | (((uint)*(stream + 2)) << 12) | (((uint)*(stream + 3)) << 20); stream += 4; } else if ((val & 16) == 0) { stream += 1; value = ReadUInt32(ref stream); } else { ThrowBadImageFormatException(); return 0; } return value; } public static int DecodeSigned(ref byte* stream, byte* streamEnd) { if (stream >= streamEnd) ThrowBadImageFormatException(); int value = 0; int val = *(stream); if ((val & 1) == 0) { value = ((sbyte)val) >> 1; stream += 1; } else if ((val & 2) == 0) { if (stream + 1 >= streamEnd) ThrowBadImageFormatException(); value = (val >> 2) | (((int)*(sbyte*)(stream + 1)) << 6); stream += 2; } else if ((val & 4) == 0) { if (stream + 2 >= streamEnd) ThrowBadImageFormatException(); value = (val >> 3) | (((int)*(stream + 1)) << 5) | (((int)*(sbyte*)(stream + 2)) << 13); stream += 3; } else if ((val & 8) == 0) { if (stream + 3 >= streamEnd) ThrowBadImageFormatException(); value = (val >> 4) | (((int)*(stream + 1)) << 4) | (((int)*(stream + 2)) << 12) | (((int)*(sbyte*)(stream + 3)) << 20); stream += 4; } else if ((val & 16) == 0) { stream += 1; value = (int)ReadUInt32(ref stream); } else { ThrowBadImageFormatException(); return 0; } return value; } public static ulong DecodeUnsignedLong(ref byte* stream, byte* streamEnd) { if (stream >= streamEnd) ThrowBadImageFormatException(); ulong value = 0; byte val = *stream; if ((val & 31) != 31) { value = DecodeUnsigned(ref stream, streamEnd); } else if ((val & 32) == 0) { stream += 1; value = ReadUInt64(ref stream); } else { ThrowBadImageFormatException(); return 0; } return value; } public static long DecodeSignedLong(ref byte* stream, byte* streamEnd) { if (stream >= streamEnd) ThrowBadImageFormatException(); long value = 0; byte val = *stream; if ((val & 31) != 31) { value = DecodeSigned(ref stream, streamEnd); } else if ((val & 32) == 0) { stream += 1; value = (long)ReadUInt64(ref stream); } else { ThrowBadImageFormatException(); return 0; } return value; } public static void SkipInteger(ref byte* stream) { byte val = *stream; if ((val & 1) == 0) { stream += 1; } else if ((val & 2) == 0) { stream += 2; } else if ((val & 4) == 0) { stream += 3; } else if ((val & 8) == 0) { stream += 4; } else if ((val & 16) == 0) { stream += 5; } else if ((val & 32) == 0) { stream += 9; } else { ThrowBadImageFormatException(); } } } internal unsafe partial class NativeReader { private readonly byte* _base; private readonly uint _size; public NativeReader(byte* base_, uint size) { // Limit the maximum blob size to prevent buffer overruns triggered by boundary integer overflows if (size >= UInt32.MaxValue / 4) ThrowBadImageFormatException(); Debug.Assert(base_ <= base_ + size); _base = base_; _size = size; } public uint Size { get { return _size; } } public uint AddressToOffset(IntPtr address) { Debug.Assert((byte*)address >= _base); Debug.Assert((byte*)address <= _base + _size); return (uint)((byte*)address - _base); } public IntPtr OffsetToAddress(uint offset) { Debug.Assert(offset < _size); return new IntPtr(_base + offset); } public void ThrowBadImageFormatException() { Debug.Assert(false); throw new BadImageFormatException(); } private uint EnsureOffsetInRange(uint offset, uint lookAhead) { if ((int)offset < 0 || offset + lookAhead >= _size) ThrowBadImageFormatException(); return offset; } public byte ReadUInt8(uint offset) { EnsureOffsetInRange(offset, 0); byte* data = _base + offset; return NativePrimitiveDecoder.ReadUInt8(ref data); } public ushort ReadUInt16(uint offset) { EnsureOffsetInRange(offset, 1); byte* data = _base + offset; return NativePrimitiveDecoder.ReadUInt16(ref data); } public uint ReadUInt32(uint offset) { EnsureOffsetInRange(offset, 3); byte* data = _base + offset; return NativePrimitiveDecoder.ReadUInt32(ref data); } public ulong ReadUInt64(uint offset) { EnsureOffsetInRange(offset, 7); byte* data = _base + offset; return NativePrimitiveDecoder.ReadUInt64(ref data); } public unsafe float ReadFloat(uint offset) { EnsureOffsetInRange(offset, 3); byte* data = _base + offset; return NativePrimitiveDecoder.ReadFloat(ref data); } public double ReadDouble(uint offset) { EnsureOffsetInRange(offset, 7); byte* data = _base + offset; return NativePrimitiveDecoder.ReadDouble(ref data); } public uint DecodeUnsigned(uint offset, out uint value) { EnsureOffsetInRange(offset, 0); byte* data = _base + offset; value = NativePrimitiveDecoder.DecodeUnsigned(ref data, _base + _size); return (uint)(data - _base); } public uint DecodeSigned(uint offset, out int value) { EnsureOffsetInRange(offset, 0); byte* data = _base + offset; value = NativePrimitiveDecoder.DecodeSigned(ref data, _base + _size); return (uint)(data - _base); } public uint DecodeUnsignedLong(uint offset, out ulong value) { EnsureOffsetInRange(offset, 0); byte* data = _base + offset; value = NativePrimitiveDecoder.DecodeUnsignedLong(ref data, _base + _size); return (uint)(data - _base); } public uint DecodeSignedLong(uint offset, out long value) { EnsureOffsetInRange(offset, 0); byte* data = _base + offset; value = NativePrimitiveDecoder.DecodeSignedLong(ref data, _base + _size); return (uint)(data - _base); } public uint SkipInteger(uint offset) { EnsureOffsetInRange(offset, 0); byte* data = _base + offset; NativePrimitiveDecoder.SkipInteger(ref data); return (uint)(data - _base); } } internal partial struct NativeParser { private readonly NativeReader _reader; private uint _offset; public NativeParser(NativeReader reader, uint offset) { _reader = reader; _offset = offset; } public bool IsNull { get { return _reader == null; } } public NativeReader Reader { get { return _reader; } } public uint Offset { get { return _offset; } set { Debug.Assert(value < _reader.Size); _offset = value; } } public void ThrowBadImageFormatException() { _reader.ThrowBadImageFormatException(); } public byte GetUInt8() { byte val = _reader.ReadUInt8(_offset); _offset += 1; return val; } public uint GetUnsigned() { uint value; _offset = _reader.DecodeUnsigned(_offset, out value); return value; } public ulong GetUnsignedLong() { ulong value; _offset = _reader.DecodeUnsignedLong(_offset, out value); return value; } public int GetSigned() { int value; _offset = _reader.DecodeSigned(_offset, out value); return value; } public uint GetRelativeOffset() { uint pos = _offset; int delta; _offset = _reader.DecodeSigned(_offset, out delta); return pos + (uint)delta; } public void SkipInteger() { _offset = _reader.SkipInteger(_offset); } public NativeParser GetParserFromRelativeOffset() { return new NativeParser(_reader, GetRelativeOffset()); } public uint GetSequenceCount() { return GetUnsigned(); } } internal struct NativeHashtable { private NativeReader _reader; private uint _baseOffset; private uint _bucketMask; private byte _entryIndexSize; public NativeHashtable(NativeParser parser) { uint header = parser.GetUInt8(); _reader = parser.Reader; _baseOffset = parser.Offset; int numberOfBucketsShift = (int)(header >> 2); if (numberOfBucketsShift > 31) _reader.ThrowBadImageFormatException(); _bucketMask = (uint)((1 << numberOfBucketsShift) - 1); byte entryIndexSize = (byte)(header & 3); if (entryIndexSize > 2) _reader.ThrowBadImageFormatException(); _entryIndexSize = entryIndexSize; } public bool IsNull { get { return _reader == null; } } // // The enumerator does not conform to the regular C# enumerator pattern to avoid paying // its performance penalty (allocation, multiple calls per iteration) // public struct Enumerator { private NativeParser _parser; private uint _endOffset; private byte _lowHashcode; internal Enumerator(NativeParser parser, uint endOffset, byte lowHashcode) { _parser = parser; _endOffset = endOffset; _lowHashcode = lowHashcode; } public NativeParser GetNext() { while (_parser.Offset < _endOffset) { byte lowHashcode = _parser.GetUInt8(); if (lowHashcode == _lowHashcode) { return _parser.GetParserFromRelativeOffset(); } // The entries are sorted by hashcode within the bucket. It allows us to terminate the lookup prematurely. if (lowHashcode > _lowHashcode) { _endOffset = _parser.Offset; // Ensure that extra call to GetNext returns null parser again break; } _parser.SkipInteger(); } return new NativeParser(); } } public struct AllEntriesEnumerator { private NativeHashtable _table; private NativeParser _parser; private uint _currentBucket; private uint _endOffset; internal AllEntriesEnumerator(NativeHashtable table) { _table = table; _currentBucket = 0; _parser = _table.GetParserForBucket(_currentBucket, out _endOffset); } public NativeParser GetNext() { for (;;) { while (_parser.Offset < _endOffset) { byte lowHashcode = _parser.GetUInt8(); return _parser.GetParserFromRelativeOffset(); } if (_currentBucket >= _table._bucketMask) return new NativeParser(); _currentBucket++; _parser = _table.GetParserForBucket(_currentBucket, out _endOffset); } } } private NativeParser GetParserForBucket(uint bucket, out uint endOffset) { uint start, end; if (_entryIndexSize == 0) { uint bucketOffset = _baseOffset + bucket; start = _reader.ReadUInt8(bucketOffset); end = _reader.ReadUInt8(bucketOffset + 1); } else if (_entryIndexSize == 1) { uint bucketOffset = _baseOffset + 2 * bucket; start = _reader.ReadUInt16(bucketOffset); end = _reader.ReadUInt16(bucketOffset + 2); } else { uint bucketOffset = _baseOffset + 4 * bucket; start = _reader.ReadUInt32(bucketOffset); end = _reader.ReadUInt32(bucketOffset + 4); } endOffset = end + _baseOffset; return new NativeParser(_reader, _baseOffset + start); } // The recommended code pattern to perform lookup is: // // var lookup = t.Lookup(TypeHashingAlgorithms.ComputeGenericInstanceHashCode(genericTypeDefinitionHandle, genericTypeArgumentHandles)); // NativeParser typeParser; // while (!(typeParser = lookup.GetNext()).IsNull) // { // typeParser.GetTypeSignatureKind(out index); // ... create RuntimeTypeHandle from the external reference RVAs at [index] // ... compare if RuntimeTypeHandle is an instance of pair (genericTypeDefinitionHandle, genericTypeArgumentHandles) // } // public Enumerator Lookup(int hashcode) { uint endOffset; uint bucket = ((uint)hashcode >> 8) & _bucketMask; NativeParser parser = GetParserForBucket(bucket, out endOffset); return new Enumerator(parser, endOffset, (byte)hashcode); } public AllEntriesEnumerator EnumerateAllEntries() { return new AllEntriesEnumerator(this); } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace Microsoft.Tools.ServiceModel.WsatConfig { using System; using System.Text; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Globalization; using System.Diagnostics; using System.Security; using System.Security.Permissions; using System.Security.Cryptography; using System.Security.AccessControl; using Microsoft.Win32; // In theory we could abstract this class out and provide concrete implementation for config from different // sources, in practice we didn't do that for historical code reasons class WsatConfiguration { const string TransactionBridgeRegistryValue = "{BFFECCA7-4069-49F9-B5AB-7CCBB078ED91}"; const string TransactionBridge30RegistryValue = "{EEC5DCCA-05DC-4B46-8AF7-2881C1635AEA}"; internal const bool DefaultNetworkSupport = false; internal const uint DefaultHttpsPort = 443; internal const SourceLevels DefaultTraceLevel = SourceLevels.Warning; internal const bool DefaultActivityPropagation = false; internal const bool DefaultActivityTracing = false; internal const uint DefaultDefaultTimeout = 60; internal const uint DefaultMaxTimeout = 3600; internal const bool DefaultTracingPii = false; internal string[] DefaultX509GlobalAcl = { string.Empty }; internal string[] DefaultKerberosGlobalAcl = { @"NT AUTHORITY\Authenticated Users" }; const X509Certificate2 DefaultX509CertificateIdentity = null; WsatConfiguration previousConfig; FirewallWrapper firewallWrapper; string machineName; string virtualServer; ConfigurationProvider wsatConfigProvider; ConfigurationProvider msdtcConfigProvider; bool isClusterRemoteNode = false; uint httpsPort = DefaultHttpsPort; uint defaultTimeout = DefaultDefaultTimeout; uint maxTimeout = DefaultMaxTimeout; SourceLevels diagnosticTraceLevel = DefaultTraceLevel; bool activityPropagation = DefaultActivityPropagation; bool activityTracing = DefaultActivityTracing; bool tracePii = DefaultTracingPii; bool transactionBridgeEnabled = false; bool transactionBridge30Enabled = false; X509Certificate2 certificate = DefaultX509CertificateIdentity; string[] allowedCertificates = null; string[] kerberosGlobalAcl = null; bool minimalWrite = false; string[] clusterNodes = null; SafeHResource hClusterDtcResource; [SecurityCritical] internal WsatConfiguration(string machineName, string virtualServer, WsatConfiguration previousConfig, bool minimalWrite) { this.MachineName = machineName; this.minimalWrite = minimalWrite; this.firewallWrapper = new FirewallWrapper(); this.previousConfig = previousConfig; this.virtualServer = virtualServer; if (previousConfig == null) { this.allowedCertificates = DefaultX509GlobalAcl; this.kerberosGlobalAcl = DefaultKerberosGlobalAcl; } else { CopyConfigurationData(previousConfig, this); } if (MsdtcClusterUtils.IsClusterServer(MachineName)) { this.hClusterDtcResource = MsdtcClusterUtils.GetTransactionManagerClusterResource(VirtualServer, out clusterNodes); if (hClusterDtcResource == null || hClusterDtcResource.IsInvalid) { if (!string.IsNullOrEmpty(VirtualServer)) { throw new WsatAdminException(WsatAdminErrorCode.CANNOT_FIND_CLUSTER_VIRTUAL_SERVER, SR.GetString(SR.ErrorCanNotFindVirtualServer)); } } } InitializeConfigurationProvider(); } void CopyConfigurationData(WsatConfiguration src, WsatConfiguration dest) { dest.TransactionBridgeEnabled = src.TransactionBridgeEnabled; dest.TransactionBridge30Enabled = src.TransactionBridge30Enabled; dest.HttpsPort = src.HttpsPort; dest.X509Certificate = src.X509Certificate; dest.KerberosGlobalAcl = src.KerberosGlobalAcl; dest.X509GlobalAcl = src.X509GlobalAcl; dest.DefaultTimeout = src.DefaultTimeout; dest.MaxTimeout = src.MaxTimeout; dest.TraceLevel = src.TraceLevel; dest.ActivityPropagation = src.ActivityPropagation; dest.ActivityTracing = src.ActivityTracing; dest.TracePii = src.TracePii; dest.MachineName = src.MachineName; dest.IsClusterRemoteNode = src.IsClusterRemoteNode; dest.VirtualServer = src.VirtualServer; } internal MsdtcWrapper GetMsdtcWrapper() { return MsdtcWrapper.GetWrapper(MachineName, VirtualServer, this.msdtcConfigProvider); } // A cluster node can spawn remote processes to setup other nodes. // Is this a node of cluster, but not the originating one? internal bool IsClusterRemoteNode { get { return this.isClusterRemoteNode; } set { this.isClusterRemoteNode = value; } } internal bool IsClustered { get { return (hClusterDtcResource != null && !hClusterDtcResource.IsInvalid); } } internal string MachineName { get { return string.IsNullOrEmpty(this.machineName) ? string.Empty : machineName; } set { this.machineName = value; } } internal string VirtualServer { get { return this.virtualServer; } set { this.virtualServer = value; } } internal bool TransactionBridgeEnabled { get { return this.transactionBridgeEnabled; } set { this.transactionBridgeEnabled = value; } } internal bool TransactionBridge30Enabled { get { return this.transactionBridge30Enabled; } set { this.transactionBridge30Enabled = value; } } internal uint HttpsPort { get { return this.httpsPort; } set { this.httpsPort = value; } } internal SourceLevels TraceLevel { get { return this.diagnosticTraceLevel; } set { this.diagnosticTraceLevel = value; } } internal uint DefaultTimeout { get { return this.defaultTimeout; } set { this.defaultTimeout = value; } } internal uint MaxTimeout { get { return this.maxTimeout; } set { this.maxTimeout = value; } } internal bool ActivityTracing { get { return this.activityTracing; } set { this.activityTracing = value; } } internal bool ActivityPropagation { get { return this.activityPropagation; } set { this.activityPropagation = value; } } internal bool TracePii { get { return this.tracePii; } set { this.tracePii = value; } } internal string[] X509GlobalAcl { get { return this.allowedCertificates; } set { if (value == null) { this.allowedCertificates = new string[] { }; } else { this.allowedCertificates = value; } } } internal string[] KerberosGlobalAcl { get { return kerberosGlobalAcl; } set { if (value == null) { this.kerberosGlobalAcl = new string[] { }; } else { this.kerberosGlobalAcl = value; } } } internal X509Certificate2 X509Certificate { get { return this.certificate; } set { this.certificate = value; } } internal void ValidateThrow() { if (this.TransactionBridgeEnabled) { // rule: WS-AT network support requires MSDTC network transaction to be enabled // GetNetworkTransactionAccess fails if current remote cluster node does not take ownership if (!IsClusterRemoteNode) { MsdtcWrapper wrapper = this.GetMsdtcWrapper(); if (!wrapper.GetNetworkTransactionAccess()) { throw new WsatAdminException(WsatAdminErrorCode.MSDTC_NETWORK_ACCESS_DISABLED, SR.GetString(SR.ErrorMsdtcNetworkAccessDisabled)); } } // rule: HTTPS port must be in range 1-65535 if (this.HttpsPort < 1) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_HTTPS_PORT, SR.GetString(SR.ErrorHttpsPortRange)); } // rule: local endpoint certificate must be specified and valid ValidateIdentityCertificateThrow(this.X509Certificate, !Utilities.IsLocalMachineName(MachineName)); // rule: default timeout should be in range 1-3600 if (this.DefaultTimeout < 1 || this.DefaultTimeout > 3600) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_DEFTIMEOUT_ARGUMENT, SR.GetString(SR.ErrorDefaultTimeoutRange)); } // rule: max timeout be in range 0-3600 if (this.MaxTimeout > 3600) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_MAXTIMEOUT_ARGUMENT, SR.GetString(SR.ErrorMaximumTimeoutRange)); } } } void InitializeConfigurationProvider() { if (IsClustered) { this.msdtcConfigProvider = new ClusterRegistryConfigurationProvider(this.hClusterDtcResource, GetClusterMstdcRegistryKey()); this.wsatConfigProvider = new ClusterRegistryConfigurationProvider(this.hClusterDtcResource, WsatKeys.WsatClusterRegKey); } else { this.msdtcConfigProvider = new RegistryConfigurationProvider(RegistryHive.LocalMachine, WsatKeys.MsdtcRegKey, MachineName); this.wsatConfigProvider = new RegistryConfigurationProvider(RegistryHive.LocalMachine, WsatKeys.WsatRegKey, MachineName); } } // // LH: Cluster\Resources\GUID_OF_DTC\MSDTCPrivate\MSDTC // W2k3: Cluster\Resources\GUID_OF_DTC\SOME_GUID\, here SOME_GUID is the default value of GUID_OF_DTC\DataPointer\ // string GetClusterMstdcRegistryKey() { Debug.Assert(IsClustered); if (Utilities.OSMajor > 5) { return WsatKeys.MsdtcClusterRegKey_OS6; } ClusterRegistryConfigurationProvider clusterReg = new ClusterRegistryConfigurationProvider(this.hClusterDtcResource, WsatKeys.MsdtcClusterDataPointerRegKey_OS5); using (clusterReg) { //the default value string subKey = clusterReg.ReadString(string.Empty, string.Empty); if (!string.IsNullOrEmpty(subKey)) { return subKey; } } RegistryExceptionHelper registryExceptionHelper = new RegistryExceptionHelper(WsatKeys.MsdtcClusterDataPointerRegKey_OS5); throw registryExceptionHelper.CreateRegistryAccessException(null); } [SecurityCritical] internal void LoadFromRegistry() { string value = msdtcConfigProvider.ReadString(WsatKeys.TransactionBridgeRegKey, null); TransactionBridgeEnabled = Utilities.SafeCompare(value, TransactionBridgeRegistryValue); TransactionBridge30Enabled = Utilities.SafeCompare(value, TransactionBridge30RegistryValue); HttpsPort = wsatConfigProvider.ReadUInt32(WsatKeys.RegistryEntryHttpsPort, DefaultHttpsPort); X509Certificate = CertificateManager.GetCertificateFromThumbprint( wsatConfigProvider.ReadString(WsatKeys.RegistryEntryX509CertificateIdentity, string.Empty), MachineName); KerberosGlobalAcl = wsatConfigProvider.ReadMultiString(WsatKeys.RegistryEntryKerberosGlobalAcl, DefaultKerberosGlobalAcl); X509GlobalAcl = wsatConfigProvider.ReadMultiString(WsatKeys.RegistryEntryX509GlobalAcl, DefaultX509GlobalAcl); TraceLevel = (SourceLevels)wsatConfigProvider.ReadUInt32(WsatKeys.RegistryEntryTraceLevel, (uint)DefaultTraceLevel); #pragma warning disable 429 ActivityTracing = wsatConfigProvider.ReadUInt32(WsatKeys.RegistryEntryActivityTracing, (DefaultActivityTracing ? 1 : 0)) != 0; ActivityPropagation = wsatConfigProvider.ReadUInt32(WsatKeys.RegistryEntryPropagateActivity, (DefaultActivityPropagation ? 1 : 0)) != 0; TracePii = wsatConfigProvider.ReadUInt32(WsatKeys.RegistryEntryTracingPii, (DefaultTracingPii ? 1 : 0)) != 0; #pragma warning restore 429 DefaultTimeout = wsatConfigProvider.ReadUInt32(WsatKeys.RegistryEntryDefTimeout, DefaultDefaultTimeout); MaxTimeout = wsatConfigProvider.ReadUInt32(WsatKeys.RegistryEntryMaxTimeout, DefaultMaxTimeout); } internal bool IsLocalMachine { get { return !IsClustered && Utilities.IsLocalMachineName(this.MachineName); } } // The code should align with the ValidateIdentityCertificate implementation in // src\TransactionBridge\Microsoft\Transactions\Wsat\protocol\Configuration.cs internal static void ValidateIdentityCertificateThrow(X509Certificate2 cert, bool remoteCert) { // I wish we had system-defined constants for these. We don't. const string KeyUsage = "2.5.29.15"; const string EnhancedKeyUsage = "2.5.29.37"; const string ClientAuthentication = "1.3.6.1.5.5.7.3.2"; const string ServerAuthentication = "1.3.6.1.5.5.7.3.1"; X509Certificate2 identity = cert; // 0) The certificate should be present if (identity == null) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_SSL_CERTIFICATE, SR.GetString(SR.ErrorMissingSSLCert)); } if (remoteCert) { return; // the following info is not accurate for remote cert, so we do not bother to check them } // 1) A certificate identity must have a private key if (!identity.HasPrivateKey) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_SSL_CERTIFICATE, SR.GetString(SR.ErrorSSLCertHasNoPrivateKey)); } // 2) A certificate identity must have an accessible private key try { // Yes, this property throws on error... AsymmetricAlgorithm privateKey = identity.PrivateKey; } catch (CryptographicException e) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_SSL_CERTIFICATE, SR.GetString(SR.ErrorSSLCertCanNotAccessPrivateKey), e); } // 3) If a "Key Usage" extension is present, it must allow "Key Encipherment" // 4) If a "Key Usage" extension is present, it must allow "Digital Signature" X509KeyUsageExtension keyUsage = (X509KeyUsageExtension)identity.Extensions[KeyUsage]; if (keyUsage != null) { const X509KeyUsageFlags required = X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature; if ((keyUsage.KeyUsages & required) != required) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_SSL_CERTIFICATE, SR.GetString(SR.ErrorSSLCertDoesNotSupportKeyEnciphermentOrDsig)); } } X509EnhancedKeyUsageExtension enhancedKeyUsage = (X509EnhancedKeyUsageExtension)identity.Extensions[EnhancedKeyUsage]; if (enhancedKeyUsage != null) { // 5) If an "Enhanced Key Usage" extension is present, it must allow "Client Authentication" if (enhancedKeyUsage.EnhancedKeyUsages[ClientAuthentication] == null) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_SSL_CERTIFICATE, SR.GetString(SR.ErrorSSLCertDoesNotSupportClientAuthentication)); } // 6) If an "Enhanced Key Usage" extension is present, it must allow "Server Authentication" if (enhancedKeyUsage.EnhancedKeyUsages[ServerAuthentication] == null) { throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_SSL_CERTIFICATE, SR.GetString(SR.ErrorSSLCertDoesNotSupportServerAuthentication)); } } } void UpdateClusterNodesPorts(bool restart) { if (clusterNodes != null) { foreach (string node in clusterNodes) { if (Utilities.SafeCompare(node, Utilities.LocalHostName)) { UpdatePorts(); UpdateCertificatePrivateKeyAccess(); } else { //Explicitly not to restart DTC on remote cluster node, actually restart will be ignored anyway. SaveRemote(node, false, true); } } } } void RestartHelper(bool restart) { if (restart) { try { MsdtcWrapper msdtc = this.GetMsdtcWrapper(); msdtc.RestartDtcService(); } catch (WsatAdminException) { throw; } #pragma warning suppress 56500 catch (Exception e) { if (Utilities.IsCriticalException(e)) { throw; } throw new WsatAdminException(WsatAdminErrorCode.DTC_RESTART_ERROR, SR.GetString(SR.ErrorRestartMSDTC), e); } } } internal void Save(bool restart) { if (IsLocalMachine) { Utilities.Log("Save - LocalMachine"); // Single local machine: // 1. Update local SSL binding // 2. Update URL ACL // 3. Update firewall port status // 4. Update the endpoint cert's private key permission // 5. Save to local registry UpdatePorts(); UpdateCertificatePrivateKeyAccess(); SaveToRegistry(); RestartHelper(restart); } else if (IsClusterRemoteNode) { Utilities.Log("Save - Cluster Remote Node"); // Cluster remote node machine: // DO NOT save to cluster registry, DO NOT restart DTC // 1. Update SSL binding on the node // 2. Update URL ACL on the node // 3. Update firewall port status on the node // 4. Update the endpoint cert's private key permission UpdatePorts(); UpdateCertificatePrivateKeyAccess(); } else if (IsClustered) // the orignating cluster node { Utilities.Log("Save - Cluster"); // Cluster originating node machine: // 1. Update SSL binding on each node // 2. Update URL ACL on each node // 3. Update firewall port status on each remote node // 4. Update the endpoint cert's private key permission on each remote node // 5. Save to cluster registry UpdateClusterNodesPorts(restart); SaveToRegistry(); RestartHelper(restart); } else { Utilities.Log("Save - Remote"); // Remote machine: // 1. Save to remote registry // 2. Update SSL binding on remote machine // 3. Update URL ACL on remote machine // 4. Update firewall port status on remote machine // 5. Update the endpoint cert's private key permission on remote machine SaveRemote(restart, false); } CopyConfigurationData(this, previousConfig); } void SaveRemote(bool restart, bool clusterRemoteNode) { System.Diagnostics.Debug.Assert(!(IsLocalMachine || IsClustered)); SaveRemote(MachineName, restart, clusterRemoteNode); } void SaveRemote(string machineName, bool restart, bool clusterRemoteNode) { string portString = null; string endpointCertString = null; string accountsString = null; string accountsCertsString = null; string defaultTimeoutString = null; string maxTimeoutString = null; string traceLevelString = null; string traceActivityString = null; string tracePropString = null; string tracePiiString = null; // Performance is not a concern here so we just do plain string concatenation string networkEnabledString = " -" + CommandLineOption.Network + ":" + (this.TransactionBridgeEnabled ? CommandLineOption.Enable : CommandLineOption.Disable); string virtualServerString = null; if (!string.IsNullOrEmpty(VirtualServer)) { virtualServerString = " -" + CommandLineOption.ClusterVirtualServer + ":" + "\"" + VirtualServer + "\""; } if (this.TransactionBridgeEnabled) { portString = " -" + CommandLineOption.Port + ":" + this.HttpsPort; endpointCertString = this.X509Certificate == null ? "" : " -" + CommandLineOption.EndpointCert + ":" + this.X509Certificate.Thumbprint; accountsString = " -" + CommandLineOption.Accounts + ":" + BuildAccountsArgument(); accountsCertsString = " -" + CommandLineOption.AccountsCerts + ":" + BuildAccountsCertsArgument(); defaultTimeoutString = " -" + CommandLineOption.DefaultTimeout + ":" + this.DefaultTimeout.ToString(CultureInfo.InvariantCulture); traceLevelString = " -" + CommandLineOption.TraceLevel + ":" + ((uint)this.TraceLevel).ToString(CultureInfo.InvariantCulture); traceActivityString = " -" + CommandLineOption.TraceActivity + ":" + (this.ActivityTracing ? CommandLineOption.Enable : CommandLineOption.Disable); tracePropString = " -" + CommandLineOption.TraceProp + ":" + (this.ActivityPropagation ? CommandLineOption.Enable : CommandLineOption.Disable); tracePiiString = " -" + CommandLineOption.TracePii + ":" + (this.TracePii ? CommandLineOption.Enable : CommandLineOption.Disable); maxTimeoutString = " -" + CommandLineOption.MaxTimeout + ":" + this.MaxTimeout.ToString(CultureInfo.InvariantCulture); } string arguments = networkEnabledString + virtualServerString + portString + endpointCertString + accountsString + accountsCertsString + defaultTimeoutString + maxTimeoutString + traceLevelString + traceActivityString + tracePropString + tracePiiString; if (clusterRemoteNode) { arguments += " -" + CommandLineOption.ClusterRemoteNode + ":" + CommandLineOption.Enable; } if (restart) { arguments += " -" + CommandLineOption.Restart; } Utilities.Log("Remote command arguments: " + arguments); RemoteHelper remote = new RemoteHelper(machineName); remote.ExecuteWsatProcess(arguments); } string BuildAccountsCertsArgument() { string result = string.Empty; if (this.X509GlobalAcl != null && this.X509GlobalAcl.Length > 0) { result += "\"" + this.X509GlobalAcl[0] + "\""; for (int i = 1; i < this.X509GlobalAcl.Length; ++i) { result += ",\"" + this.X509GlobalAcl[i] + "\""; } } return result; } string BuildAccountsArgument() { string result = string.Empty; if (this.KerberosGlobalAcl != null && this.KerberosGlobalAcl.Length > 0) { result += "\"" + this.KerberosGlobalAcl[0] + "\""; for (int i = 1; i < this.KerberosGlobalAcl.Length; ++i) { result += ",\"" + this.KerberosGlobalAcl[i] + "\""; } } return result; } void UpdateCertificatePrivateKeyAccess() { if (previousConfig == null) { AddCertificatePrivateKeyAccess(X509Certificate); } else if (X509Certificate != previousConfig.X509Certificate) { RemoveCertificatePrivateKeyAccess(previousConfig.X509Certificate); AddCertificatePrivateKeyAccess(X509Certificate); } } // This method could throw any exception, because RSACryptoServiceProvider ctor could do so // We will escalate the exceptions to the callers who will be more sensible on how to deal with them void CommitCryptoKeySecurity(CspKeyContainerInfo info, CryptoKeySecurity keySec) { CspParameters cspParams = new CspParameters( info.ProviderType, info.ProviderName, info.KeyContainerName); cspParams.CryptoKeySecurity = keySec; // Important flag, or the security setting will silently fail cspParams.Flags = CspProviderFlags.UseMachineKeyStore; // The RSACryptoServiceProvider ctor will automatically apply DACLs set in CSP's securtiy info new RSACryptoServiceProvider(cspParams); } void RemoveCertificatePrivateKeyAccess(X509Certificate2 cert) { if (cert != null && cert.HasPrivateKey) { try { AsymmetricAlgorithm key = cert.PrivateKey; // Only RSA provider is supported here if (key is RSACryptoServiceProvider) { RSACryptoServiceProvider prov = key as RSACryptoServiceProvider; CspKeyContainerInfo info = prov.CspKeyContainerInfo; CryptoKeySecurity keySec = info.CryptoKeySecurity; SecurityIdentifier ns = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); AuthorizationRuleCollection rules = keySec.GetAccessRules(true, false, typeof(SecurityIdentifier)); foreach (AuthorizationRule rule in rules) { CryptoKeyAccessRule keyAccessRule = (CryptoKeyAccessRule)rule; if (keyAccessRule.AccessControlType == AccessControlType.Allow && (int)(keyAccessRule.CryptoKeyRights & CryptoKeyRights.GenericRead) != 0) { SecurityIdentifier sid = keyAccessRule.IdentityReference as SecurityIdentifier; if (ns.Equals(sid)) { CryptoKeyAccessRule nsReadRule = new CryptoKeyAccessRule(ns, CryptoKeyRights.GenericRead, AccessControlType.Allow); keySec.RemoveAccessRule(nsReadRule); CommitCryptoKeySecurity(info, keySec); break; } } } } } #pragma warning suppress 56500 catch (Exception e) { // CommitCryptoKeySecurity can actually throw any exception, // so the safest way here is to catch a generic exception while throw on critical ones if (Utilities.IsCriticalException(e)) { throw; } throw new WsatAdminException(WsatAdminErrorCode.CANNOT_UPDATE_PRIVATE_KEY_PERM, SR.GetString(SR.ErrorUpdateCertPrivateKeyPerm), e); } } } void AddCertificatePrivateKeyAccess(X509Certificate2 cert) { if (cert != null && cert.HasPrivateKey) { try { AsymmetricAlgorithm key = cert.PrivateKey; // Only RSA provider is supported here if (key is RSACryptoServiceProvider) { RSACryptoServiceProvider prov = key as RSACryptoServiceProvider; CspKeyContainerInfo info = prov.CspKeyContainerInfo; CryptoKeySecurity keySec = info.CryptoKeySecurity; SecurityIdentifier ns = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); // Just add a rule, exisitng settings will be merged CryptoKeyAccessRule rule = new CryptoKeyAccessRule(ns, CryptoKeyRights.GenericRead, AccessControlType.Allow); keySec.AddAccessRule(rule); CommitCryptoKeySecurity(info, keySec); } } #pragma warning suppress 56500 catch (Exception e) { // CommitCryptoKeySecurity can actually throw any exception, // so the safest way here is to catch a generic exception while throw on critical ones if (Utilities.IsCriticalException(e)) { throw; } throw new WsatAdminException(WsatAdminErrorCode.CANNOT_UPDATE_PRIVATE_KEY_PERM, SR.GetString(SR.ErrorUpdateCertPrivateKeyPerm), e); } } } void SaveToRegistry() { if (!this.minimalWrite || this.previousConfig == null || this.TransactionBridgeEnabled != this.previousConfig.TransactionBridgeEnabled || (this.previousConfig.TransactionBridge30Enabled && !this.TransactionBridgeEnabled) ) { msdtcConfigProvider.WriteString( WsatKeys.TransactionBridgeRegKey, this.TransactionBridgeEnabled ? TransactionBridgeRegistryValue : string.Empty); } if (!this.minimalWrite || this.previousConfig == null || this.TraceLevel != this.previousConfig.TraceLevel) { wsatConfigProvider.WriteUInt32(WsatKeys.RegistryEntryTraceLevel, (uint)this.TraceLevel); } if (!this.minimalWrite || this.previousConfig == null || this.ActivityTracing != this.previousConfig.ActivityTracing) { wsatConfigProvider.WriteUInt32(WsatKeys.RegistryEntryActivityTracing, (this.ActivityTracing ? 1u : 0)); } if (!this.minimalWrite || this.previousConfig == null || this.ActivityPropagation != this.previousConfig.ActivityPropagation) { wsatConfigProvider.WriteUInt32(WsatKeys.RegistryEntryPropagateActivity, (this.ActivityPropagation ? 1u : 0)); } if (!this.minimalWrite || this.previousConfig == null || this.TracePii != this.previousConfig.TracePii) { wsatConfigProvider.WriteUInt32(WsatKeys.RegistryEntryTracingPii, (this.TracePii ? 1u : 0)); } if (!this.minimalWrite || this.previousConfig == null || this.DefaultTimeout != this.previousConfig.DefaultTimeout) { wsatConfigProvider.WriteUInt32(WsatKeys.RegistryEntryDefTimeout, (uint)this.DefaultTimeout); } if (!this.minimalWrite || this.previousConfig == null || this.MaxTimeout != this.previousConfig.MaxTimeout) { wsatConfigProvider.WriteUInt32(WsatKeys.RegistryEntryMaxTimeout, (uint)this.MaxTimeout); } if (!this.minimalWrite || this.previousConfig == null || this.X509GlobalAcl != this.previousConfig.X509GlobalAcl) { wsatConfigProvider.WriteMultiString(WsatKeys.RegistryEntryX509GlobalAcl, this.X509GlobalAcl); } if (!this.minimalWrite || this.previousConfig == null || this.X509Certificate != this.previousConfig.X509Certificate) { wsatConfigProvider.WriteString(WsatKeys.RegistryEntryX509CertificateIdentity, (this.X509Certificate == null ? string.Empty : this.X509Certificate.Thumbprint)); } if (!this.minimalWrite || this.previousConfig == null || this.HttpsPort != this.previousConfig.HttpsPort) { wsatConfigProvider.WriteUInt32(WsatKeys.RegistryEntryHttpsPort, this.HttpsPort); } if (!this.minimalWrite || this.previousConfig == null || this.KerberosGlobalAcl != this.previousConfig.KerberosGlobalAcl) { wsatConfigProvider.WriteMultiString(WsatKeys.RegistryEntryKerberosGlobalAcl, this.KerberosGlobalAcl); } if (IsClustered || IsLocalMachine) { wsatConfigProvider.AdjustRegKeyPermission(); } } void UpdateUrlAclReservation() { WsatServiceAddress wsatServiceAddress; if (this.previousConfig != null) { wsatServiceAddress = new WsatServiceAddress(this.previousConfig.HttpsPort); wsatServiceAddress.FreeWsatServiceAddress(); } if (this.TransactionBridgeEnabled) { wsatServiceAddress = new WsatServiceAddress(this.HttpsPort); wsatServiceAddress.ReserveWsatServiceAddress(); } } void UpdateSSLBinding() { WsatServiceCertificate wsatServiceCertificate; if (this.previousConfig != null && this.previousConfig.X509Certificate != null) { wsatServiceCertificate = new WsatServiceCertificate(this.previousConfig.X509Certificate, previousConfig.HttpsPort); wsatServiceCertificate.UnbindSSLCertificate(); } if (this.TransactionBridgeEnabled && this.X509Certificate != null) { wsatServiceCertificate = new WsatServiceCertificate(this.X509Certificate, HttpsPort); wsatServiceCertificate.BindSSLCertificate(); } } void UpdateFirewallPort() { FirewallWrapper firewallWrapper = new FirewallWrapper(); firewallWrapper.RemoveHttpsPort((int)this.previousConfig.HttpsPort); if (this.TransactionBridgeEnabled) { firewallWrapper.AddHttpsPort((int)this.HttpsPort); } } // update the ports for the SSL Binding, URL ACL Reservation and Firewall void UpdatePorts() { UpdateFirewallPort(); UpdateUrlAclReservation(); UpdateSSLBinding(); } #if WSAT_CMDLINE public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(SR.GetString(SR.ConfigNetworkSupport, Utilities.GetEnabledStatusString(this.TransactionBridgeEnabled || this.TransactionBridge30Enabled))); if (this.TransactionBridgeEnabled || this.TransactionBridge30Enabled) { sb.Append(SR.GetString(SR.ConfigHTTPSPort, this.HttpsPort)); sb.Append(SR.GetString(SR.ConfigIdentityCertificate, this.X509Certificate == null ? SR.GetString(SR.ConfigNone) : this.X509Certificate.Thumbprint)); sb.Append(SR.GetString(SR.ConfigKerberosGACL)); if (this.KerberosGlobalAcl == null || this.KerberosGlobalAcl.Length < 1) { sb.AppendLine(SR.GetString(SR.ConfigNone)); } else { int i = 0; foreach (string ace in this.KerberosGlobalAcl) { if (i++ > 0) { sb.Append(SR.GetString(SR.ConfigACEPrefix)); } sb.AppendLine(ace); } } sb.Append(SR.GetString(SR.ConfigAcceptedCertificates)); if (this.X509GlobalAcl == null || this.X509GlobalAcl.Length < 1) { sb.AppendLine(SR.GetString(SR.ConfigNone)); } else { int i = 0; foreach (string cert in this.X509GlobalAcl) { if (i++ > 0) { sb.Append(SR.GetString(SR.ConfigAcceptedCertPrefix)); } sb.AppendLine(cert); } } sb.Append(SR.GetString(SR.ConfigDefaultTimeout, this.DefaultTimeout)); sb.Append(SR.GetString(SR.ConfigMaximumTimeout, this.MaxTimeout)); SourceLevels level = this.TraceLevel; if (level != SourceLevels.All) { level = level & ~SourceLevels.ActivityTracing; } sb.Append(SR.GetString(SR.ConfigTraceLevel, level)); sb.Append(SR.GetString(SR.ConfigActivityTracing, Utilities.GetEnabledStatusString(this.ActivityTracing))); sb.Append(SR.GetString(SR.ConfigActivityProp, Utilities.GetEnabledStatusString(this.ActivityPropagation))); sb.Append(SR.GetString(SR.ConfigPiiTracing, Utilities.GetEnabledStatusString(this.TracePii))); MsdtcWrapper msdtc = this.GetMsdtcWrapper(); if (!msdtc.GetNetworkTransactionAccess()) { sb.Append(Environment.NewLine); sb.Append(SR.GetString(SR.ConfigWarningNetworkDTCAccessIsDisabled)); } } else { // When network support is disabled, the only setting that still matters is the MaxTimeout sb.Append(SR.GetString(SR.ConfigMaximumTimeoutWhenNetworkDisabled, this.MaxTimeout)); } return sb.ToString(); } #endif } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Security { using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Net; using System.Security.Authentication.ExtendedProtection; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.ServiceModel.Security.Tokens; public class ServiceCredentialsSecurityTokenManager : SecurityTokenManager, IEndpointIdentityProvider { ServiceCredentials parent; public ServiceCredentialsSecurityTokenManager(ServiceCredentials parent) { if (parent == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent"); } this.parent = parent; } public ServiceCredentials ServiceCredentials { get { return parent; } } public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version) { if (version == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version"); } MessageSecurityTokenVersion wsVersion = version as MessageSecurityTokenVersion; if (wsVersion != null) { SamlSerializer samlSerializer = null; if (parent.IssuedTokenAuthentication != null) samlSerializer = parent.IssuedTokenAuthentication.SamlSerializer; else samlSerializer = new SamlSerializer(); return new WSSecurityTokenSerializer(wsVersion.SecurityVersion, wsVersion.TrustVersion, wsVersion.SecureConversationVersion, wsVersion.EmitBspRequiredAttributes, samlSerializer, parent.SecureConversationAuthentication.SecurityStateEncoder, parent.SecureConversationAuthentication.SecurityContextClaimTypes); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateSerializerForVersion, version))); } } protected SecurityTokenAuthenticator CreateSecureConversationTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, bool preserveBootstrapTokens, out SecurityTokenResolver sctResolver) { SecurityBindingElement securityBindingElement = recipientRequirement.SecurityBindingElement; if (securityBindingElement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenAuthenticatorRequiresSecurityBindingElement, recipientRequirement)); } bool isCookieMode = !recipientRequirement.SupportSecurityContextCancellation; LocalServiceSecuritySettings localServiceSettings = securityBindingElement.LocalServiceSettings; IMessageFilterTable<EndpointAddress> endpointFilterTable = recipientRequirement.GetPropertyOrDefault<IMessageFilterTable<EndpointAddress>>(ServiceModelSecurityTokenRequirement.EndpointFilterTableProperty, null); if (!isCookieMode) { sctResolver = new SecurityContextSecurityTokenResolver(Int32.MaxValue, false); // remember this authenticator for future reference SecuritySessionSecurityTokenAuthenticator authenticator = new SecuritySessionSecurityTokenAuthenticator(); authenticator.BootstrapSecurityBindingElement = SecurityUtils.GetIssuerSecurityBindingElement(recipientRequirement); authenticator.IssuedSecurityTokenParameters = recipientRequirement.GetProperty<SecurityTokenParameters>(ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty); authenticator.IssuedTokenCache = (ISecurityContextSecurityTokenCache)sctResolver; authenticator.IssuerBindingContext = recipientRequirement.GetProperty<BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty); authenticator.KeyEntropyMode = securityBindingElement.KeyEntropyMode; authenticator.ListenUri = recipientRequirement.ListenUri; authenticator.SecurityAlgorithmSuite = recipientRequirement.SecurityAlgorithmSuite; authenticator.SessionTokenLifetime = TimeSpan.MaxValue; authenticator.KeyRenewalInterval = securityBindingElement.LocalServiceSettings.SessionKeyRenewalInterval; authenticator.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(recipientRequirement, this); authenticator.EndpointFilterTable = endpointFilterTable; authenticator.MaximumConcurrentNegotiations = localServiceSettings.MaxStatefulNegotiations; authenticator.NegotiationTimeout = localServiceSettings.NegotiationTimeout; authenticator.PreserveBootstrapTokens = preserveBootstrapTokens; return authenticator; } else { sctResolver = new SecurityContextSecurityTokenResolver(localServiceSettings.MaxCachedCookies, true, localServiceSettings.MaxClockSkew); AcceleratedTokenAuthenticator authenticator = new AcceleratedTokenAuthenticator(); authenticator.BootstrapSecurityBindingElement = SecurityUtils.GetIssuerSecurityBindingElement(recipientRequirement); authenticator.KeyEntropyMode = securityBindingElement.KeyEntropyMode; authenticator.EncryptStateInServiceToken = true; authenticator.IssuedSecurityTokenParameters = recipientRequirement.GetProperty<SecurityTokenParameters>(ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty); authenticator.IssuedTokenCache = (ISecurityContextSecurityTokenCache)sctResolver; authenticator.IssuerBindingContext = recipientRequirement.GetProperty<BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty); authenticator.ListenUri = recipientRequirement.ListenUri; authenticator.SecurityAlgorithmSuite = recipientRequirement.SecurityAlgorithmSuite; authenticator.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(recipientRequirement, this); authenticator.SecurityStateEncoder = parent.SecureConversationAuthentication.SecurityStateEncoder; authenticator.KnownTypes = parent.SecureConversationAuthentication.SecurityContextClaimTypes; authenticator.PreserveBootstrapTokens = preserveBootstrapTokens; // local security quotas authenticator.MaximumCachedNegotiationState = localServiceSettings.MaxStatefulNegotiations; authenticator.NegotiationTimeout = localServiceSettings.NegotiationTimeout; authenticator.ServiceTokenLifetime = localServiceSettings.IssuedCookieLifetime; authenticator.MaximumConcurrentNegotiations = localServiceSettings.MaxStatefulNegotiations; // audit settings authenticator.AuditLogLocation = recipientRequirement.AuditLogLocation; authenticator.SuppressAuditFailure = recipientRequirement.SuppressAuditFailure; authenticator.MessageAuthenticationAuditLevel = recipientRequirement.MessageAuthenticationAuditLevel; authenticator.EndpointFilterTable = endpointFilterTable; return authenticator; } } SecurityTokenAuthenticator CreateSpnegoSecurityTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, out SecurityTokenResolver sctResolver) { SecurityBindingElement securityBindingElement = recipientRequirement.SecurityBindingElement; if (securityBindingElement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenAuthenticatorRequiresSecurityBindingElement, recipientRequirement)); } bool isCookieMode = !recipientRequirement.SupportSecurityContextCancellation; LocalServiceSecuritySettings localServiceSettings = securityBindingElement.LocalServiceSettings; sctResolver = new SecurityContextSecurityTokenResolver(localServiceSettings.MaxCachedCookies, true); ExtendedProtectionPolicy extendedProtectionPolicy = null; recipientRequirement.TryGetProperty<ExtendedProtectionPolicy>(ServiceModelSecurityTokenRequirement.ExtendedProtectionPolicy, out extendedProtectionPolicy); SpnegoTokenAuthenticator authenticator = new SpnegoTokenAuthenticator(); authenticator.ExtendedProtectionPolicy = extendedProtectionPolicy; authenticator.AllowUnauthenticatedCallers = parent.WindowsAuthentication.AllowAnonymousLogons; authenticator.ExtractGroupsForWindowsAccounts = parent.WindowsAuthentication.IncludeWindowsGroups; authenticator.IsClientAnonymous = false; authenticator.EncryptStateInServiceToken = isCookieMode; authenticator.IssuedSecurityTokenParameters = recipientRequirement.GetProperty<SecurityTokenParameters>(ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty); authenticator.IssuedTokenCache = (ISecurityContextSecurityTokenCache)sctResolver; authenticator.IssuerBindingContext = recipientRequirement.GetProperty<BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty); authenticator.ListenUri = recipientRequirement.ListenUri; authenticator.SecurityAlgorithmSuite = recipientRequirement.SecurityAlgorithmSuite; authenticator.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(recipientRequirement, this); authenticator.SecurityStateEncoder = parent.SecureConversationAuthentication.SecurityStateEncoder; authenticator.KnownTypes = parent.SecureConversationAuthentication.SecurityContextClaimTypes; // if the SPNEGO is being done in mixed-mode, the nego blobs are from an anonymous client and so there size bound needs to be enforced. if (securityBindingElement is TransportSecurityBindingElement) { authenticator.MaxMessageSize = SecurityUtils.GetMaxNegotiationBufferSize(authenticator.IssuerBindingContext); } // local security quotas authenticator.MaximumCachedNegotiationState = localServiceSettings.MaxStatefulNegotiations; authenticator.NegotiationTimeout = localServiceSettings.NegotiationTimeout; authenticator.ServiceTokenLifetime = localServiceSettings.IssuedCookieLifetime; authenticator.MaximumConcurrentNegotiations = localServiceSettings.MaxStatefulNegotiations; // audit settings authenticator.AuditLogLocation = recipientRequirement.AuditLogLocation; authenticator.SuppressAuditFailure = recipientRequirement.SuppressAuditFailure; authenticator.MessageAuthenticationAuditLevel = recipientRequirement.MessageAuthenticationAuditLevel; return authenticator; } SecurityTokenAuthenticator CreateTlsnegoClientX509TokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement) { RecipientServiceModelSecurityTokenRequirement clientX509Requirement = new RecipientServiceModelSecurityTokenRequirement(); clientX509Requirement.TokenType = SecurityTokenTypes.X509Certificate; clientX509Requirement.KeyUsage = SecurityKeyUsage.Signature; clientX509Requirement.ListenUri = recipientRequirement.ListenUri; clientX509Requirement.KeyType = SecurityKeyType.AsymmetricKey; clientX509Requirement.SecurityBindingElement = recipientRequirement.SecurityBindingElement; SecurityTokenResolver dummy; return this.CreateSecurityTokenAuthenticator(clientX509Requirement, out dummy); } SecurityTokenProvider CreateTlsnegoServerX509TokenProvider(RecipientServiceModelSecurityTokenRequirement recipientRequirement) { RecipientServiceModelSecurityTokenRequirement serverX509Requirement = new RecipientServiceModelSecurityTokenRequirement(); serverX509Requirement.TokenType = SecurityTokenTypes.X509Certificate; serverX509Requirement.KeyUsage = SecurityKeyUsage.Exchange; serverX509Requirement.ListenUri = recipientRequirement.ListenUri; serverX509Requirement.KeyType = SecurityKeyType.AsymmetricKey; serverX509Requirement.SecurityBindingElement = recipientRequirement.SecurityBindingElement; return this.CreateSecurityTokenProvider(serverX509Requirement); } SecurityTokenAuthenticator CreateTlsnegoSecurityTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, bool requireClientCertificate, out SecurityTokenResolver sctResolver) { SecurityBindingElement securityBindingElement = recipientRequirement.SecurityBindingElement; if (securityBindingElement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenAuthenticatorRequiresSecurityBindingElement, recipientRequirement)); } bool isCookieMode = !recipientRequirement.SupportSecurityContextCancellation; LocalServiceSecuritySettings localServiceSettings = securityBindingElement.LocalServiceSettings; sctResolver = new SecurityContextSecurityTokenResolver(localServiceSettings.MaxCachedCookies, true); TlsnegoTokenAuthenticator authenticator = new TlsnegoTokenAuthenticator(); authenticator.IsClientAnonymous = !requireClientCertificate; if (requireClientCertificate) { authenticator.ClientTokenAuthenticator = this.CreateTlsnegoClientX509TokenAuthenticator(recipientRequirement); authenticator.MapCertificateToWindowsAccount = this.ServiceCredentials.ClientCertificate.Authentication.MapClientCertificateToWindowsAccount; } authenticator.EncryptStateInServiceToken = isCookieMode; authenticator.IssuedSecurityTokenParameters = recipientRequirement.GetProperty<SecurityTokenParameters>(ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty); authenticator.IssuedTokenCache = (ISecurityContextSecurityTokenCache)sctResolver; authenticator.IssuerBindingContext = recipientRequirement.GetProperty<BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty); authenticator.ListenUri = recipientRequirement.ListenUri; authenticator.SecurityAlgorithmSuite = recipientRequirement.SecurityAlgorithmSuite; authenticator.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(recipientRequirement, this); authenticator.SecurityStateEncoder = parent.SecureConversationAuthentication.SecurityStateEncoder; authenticator.KnownTypes = parent.SecureConversationAuthentication.SecurityContextClaimTypes; authenticator.ServerTokenProvider = CreateTlsnegoServerX509TokenProvider(recipientRequirement); // local security quotas authenticator.MaximumCachedNegotiationState = localServiceSettings.MaxStatefulNegotiations; authenticator.NegotiationTimeout = localServiceSettings.NegotiationTimeout; authenticator.ServiceTokenLifetime = localServiceSettings.IssuedCookieLifetime; authenticator.MaximumConcurrentNegotiations = localServiceSettings.MaxStatefulNegotiations; // if the TLSNEGO is being done in mixed-mode, the nego blobs are from an anonymous client and so there size bound needs to be enforced. if (securityBindingElement is TransportSecurityBindingElement) { authenticator.MaxMessageSize = SecurityUtils.GetMaxNegotiationBufferSize(authenticator.IssuerBindingContext); } // audit settings authenticator.AuditLogLocation = recipientRequirement.AuditLogLocation; authenticator.SuppressAuditFailure = recipientRequirement.SuppressAuditFailure; authenticator.MessageAuthenticationAuditLevel = recipientRequirement.MessageAuthenticationAuditLevel; return authenticator; } X509SecurityTokenAuthenticator CreateClientX509TokenAuthenticator() { X509ClientCertificateAuthentication authentication = parent.ClientCertificate.Authentication; return new X509SecurityTokenAuthenticator(authentication.GetCertificateValidator(), authentication.MapClientCertificateToWindowsAccount, authentication.IncludeWindowsGroups); } SamlSecurityTokenAuthenticator CreateSamlTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, out SecurityTokenResolver outOfBandTokenResolver) { if (recipientRequirement == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("recipientRequirement"); Collection<SecurityToken> outOfBandTokens = new Collection<SecurityToken>(); if (parent.ServiceCertificate.Certificate != null) { outOfBandTokens.Add(new X509SecurityToken(parent.ServiceCertificate.Certificate)); } List<SecurityTokenAuthenticator> supportingAuthenticators = new List<SecurityTokenAuthenticator>(); if ((parent.IssuedTokenAuthentication.KnownCertificates != null) && (parent.IssuedTokenAuthentication.KnownCertificates.Count > 0)) { for (int i = 0; i < parent.IssuedTokenAuthentication.KnownCertificates.Count; ++i) { outOfBandTokens.Add(new X509SecurityToken(parent.IssuedTokenAuthentication.KnownCertificates[i])); } } X509CertificateValidator validator = parent.IssuedTokenAuthentication.GetCertificateValidator(); supportingAuthenticators.Add(new X509SecurityTokenAuthenticator(validator)); if (parent.IssuedTokenAuthentication.AllowUntrustedRsaIssuers) { supportingAuthenticators.Add(new RsaSecurityTokenAuthenticator()); } outOfBandTokenResolver = (outOfBandTokens.Count > 0) ? SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection<SecurityToken>(outOfBandTokens), false) : null; SamlSecurityTokenAuthenticator ssta; if ((recipientRequirement.SecurityBindingElement == null) || (recipientRequirement.SecurityBindingElement.LocalServiceSettings == null)) { ssta = new SamlSecurityTokenAuthenticator(supportingAuthenticators); } else { ssta = new SamlSecurityTokenAuthenticator(supportingAuthenticators, recipientRequirement.SecurityBindingElement.LocalServiceSettings.MaxClockSkew); } // set audience uri restrictions ssta.AudienceUriMode = parent.IssuedTokenAuthentication.AudienceUriMode; IList<string> allowedAudienceUris = ssta.AllowedAudienceUris; if (parent.IssuedTokenAuthentication.AllowedAudienceUris != null) { for (int i = 0; i < parent.IssuedTokenAuthentication.AllowedAudienceUris.Count; i++) allowedAudienceUris.Add(parent.IssuedTokenAuthentication.AllowedAudienceUris[i]); } if (recipientRequirement.ListenUri != null) { allowedAudienceUris.Add(recipientRequirement.ListenUri.AbsoluteUri); } return ssta; } X509SecurityTokenProvider CreateServerX509TokenProvider() { if (parent.ServiceCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ServiceCertificateNotProvidedOnServiceCredentials))); } SecurityUtils.EnsureCertificateCanDoKeyExchange(parent.ServiceCertificate.Certificate); return new ServiceX509SecurityTokenProvider(parent.ServiceCertificate.Certificate); } protected bool IsIssuedSecurityTokenRequirement(SecurityTokenRequirement requirement) { return (requirement != null && requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.IssuerAddressProperty)); } public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver) { if (tokenRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement"); } string tokenType = tokenRequirement.TokenType; outOfBandTokenResolver = null; SecurityTokenAuthenticator result = null; if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement) { // this is the uncorrelated duplex case in which the server is asking for // an authenticator to validate its provisioned client certificate if (tokenType == SecurityTokenTypes.X509Certificate && tokenRequirement.KeyUsage == SecurityKeyUsage.Exchange) { return new X509SecurityTokenAuthenticator(X509CertificateValidator.None, false); } } RecipientServiceModelSecurityTokenRequirement recipientRequirement = tokenRequirement as RecipientServiceModelSecurityTokenRequirement; if (recipientRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateAuthenticatorForRequirement, tokenRequirement))); } if (tokenType == SecurityTokenTypes.X509Certificate) { result = CreateClientX509TokenAuthenticator(); } else if (tokenType == SecurityTokenTypes.Kerberos) { result = new KerberosSecurityTokenAuthenticatorWrapper( new KerberosSecurityTokenAuthenticator(parent.WindowsAuthentication.IncludeWindowsGroups)); } else if (tokenType == SecurityTokenTypes.UserName) { if (parent.UserNameAuthentication.UserNamePasswordValidationMode == UserNamePasswordValidationMode.Windows) { if (parent.UserNameAuthentication.CacheLogonTokens) { result = new WindowsUserNameCachingSecurityTokenAuthenticator(parent.UserNameAuthentication.IncludeWindowsGroups, parent.UserNameAuthentication.MaxCachedLogonTokens, parent.UserNameAuthentication.CachedLogonTokenLifetime); } else { result = new WindowsUserNameSecurityTokenAuthenticator(parent.UserNameAuthentication.IncludeWindowsGroups); } } else { result = new CustomUserNameSecurityTokenAuthenticator(parent.UserNameAuthentication.GetUserNamePasswordValidator()); } } else if (tokenType == SecurityTokenTypes.Rsa) { result = new RsaSecurityTokenAuthenticator(); } else if (tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego) { result = CreateTlsnegoSecurityTokenAuthenticator(recipientRequirement, false, out outOfBandTokenResolver); } else if (tokenType == ServiceModelSecurityTokenTypes.MutualSslnego) { result = CreateTlsnegoSecurityTokenAuthenticator(recipientRequirement, true, out outOfBandTokenResolver); } else if (tokenType == ServiceModelSecurityTokenTypes.Spnego) { result = CreateSpnegoSecurityTokenAuthenticator(recipientRequirement, out outOfBandTokenResolver); } else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation) { result = CreateSecureConversationTokenAuthenticator(recipientRequirement, false, out outOfBandTokenResolver); } else if ((tokenType == SecurityTokenTypes.Saml) || (tokenType == SecurityXXX2005Strings.SamlTokenType) || (tokenType == SecurityJan2004Strings.SamlUri) || (tokenType == null && IsIssuedSecurityTokenRequirement(recipientRequirement))) { result = CreateSamlTokenAuthenticator(recipientRequirement, out outOfBandTokenResolver); } if (result == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateAuthenticatorForRequirement, tokenRequirement))); return result; } SecurityTokenProvider CreateLocalSecurityTokenProvider(RecipientServiceModelSecurityTokenRequirement recipientRequirement) { string tokenType = recipientRequirement.TokenType; SecurityTokenProvider result = null; if (tokenType == SecurityTokenTypes.X509Certificate) { result = CreateServerX509TokenProvider(); } else if (tokenType == ServiceModelSecurityTokenTypes.SspiCredential) { // if Transport Security, AuthenicationSchemes.Basic will look at parent.UserNameAuthentication settings. AuthenticationSchemes authenticationScheme; bool authenticationSchemeIdentified = recipientRequirement.TryGetProperty<AuthenticationSchemes>(ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty, out authenticationScheme); if (authenticationSchemeIdentified && authenticationScheme.IsSet(AuthenticationSchemes.Basic) && authenticationScheme.IsNotSet(AuthenticationSchemes.Digest | AuthenticationSchemes.Ntlm | AuthenticationSchemes.Negotiate)) { // create security token provider even when basic and Anonymous are enabled. result = new SspiSecurityTokenProvider(null, parent.UserNameAuthentication.IncludeWindowsGroups, false); } else { if (authenticationSchemeIdentified && authenticationScheme.IsSet(AuthenticationSchemes.Basic) && parent.WindowsAuthentication.IncludeWindowsGroups != parent.UserNameAuthentication.IncludeWindowsGroups) { // Ensure there are no inconsistencies when Basic and (Digest and/or Ntlm and/or Negotiate) are both enabled throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenProviderIncludeWindowsGroupsInconsistent, (AuthenticationSchemes)authenticationScheme - AuthenticationSchemes.Basic, parent.UserNameAuthentication.IncludeWindowsGroups, parent.WindowsAuthentication.IncludeWindowsGroups))); } result = new SspiSecurityTokenProvider(null, parent.WindowsAuthentication.IncludeWindowsGroups, parent.WindowsAuthentication.AllowAnonymousLogons); } } return result; } SecurityTokenProvider CreateUncorrelatedDuplexSecurityTokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement) { string tokenType = initiatorRequirement.TokenType; SecurityTokenProvider result = null; if (tokenType == SecurityTokenTypes.X509Certificate) { SecurityKeyUsage keyUsage = initiatorRequirement.KeyUsage; if (keyUsage == SecurityKeyUsage.Exchange) { if (parent.ClientCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ClientCertificateNotProvidedOnServiceCredentials))); } result = new X509SecurityTokenProvider(parent.ClientCertificate.Certificate); } else { // this is a request for the server's own cert for signing result = CreateServerX509TokenProvider(); } } return result; } public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement requirement) { if (requirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requirement"); } RecipientServiceModelSecurityTokenRequirement recipientRequirement = requirement as RecipientServiceModelSecurityTokenRequirement; SecurityTokenProvider result = null; if (recipientRequirement != null) { result = CreateLocalSecurityTokenProvider(recipientRequirement); } else if (requirement is InitiatorServiceModelSecurityTokenRequirement) { result = CreateUncorrelatedDuplexSecurityTokenProvider((InitiatorServiceModelSecurityTokenRequirement)requirement); } if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateProviderForRequirement, requirement))); } return result; } public virtual EndpointIdentity GetIdentityOfSelf(SecurityTokenRequirement tokenRequirement) { if (tokenRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement"); } if (tokenRequirement is RecipientServiceModelSecurityTokenRequirement) { string tokenType = tokenRequirement.TokenType; if (tokenType == SecurityTokenTypes.X509Certificate || tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || tokenType == ServiceModelSecurityTokenTypes.MutualSslnego) { if (parent.ServiceCertificate.Certificate != null) { return EndpointIdentity.CreateX509CertificateIdentity(parent.ServiceCertificate.Certificate); } } else if (tokenType == SecurityTokenTypes.Kerberos || tokenType == ServiceModelSecurityTokenTypes.Spnego) { return SecurityUtils.CreateWindowsIdentity(); } else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation) { SecurityBindingElement securityBindingElement = ((RecipientServiceModelSecurityTokenRequirement)tokenRequirement).SecureConversationSecurityBindingElement; if (securityBindingElement != null) { if (securityBindingElement == null || securityBindingElement is TransportSecurityBindingElement) { return null; } SecurityTokenParameters bootstrapProtectionParameters = (securityBindingElement is SymmetricSecurityBindingElement) ? ((SymmetricSecurityBindingElement)securityBindingElement).ProtectionTokenParameters : ((AsymmetricSecurityBindingElement)securityBindingElement).RecipientTokenParameters; SecurityTokenRequirement bootstrapRequirement = new RecipientServiceModelSecurityTokenRequirement(); bootstrapProtectionParameters.InitializeSecurityTokenRequirement(bootstrapRequirement); return GetIdentityOfSelf(bootstrapRequirement); } } } return null; } internal class KerberosSecurityTokenAuthenticatorWrapper : CommunicationObjectSecurityTokenAuthenticator { KerberosSecurityTokenAuthenticator innerAuthenticator; System.IdentityModel.SafeFreeCredentials credentialsHandle = null; public KerberosSecurityTokenAuthenticatorWrapper(KerberosSecurityTokenAuthenticator innerAuthenticator) { this.innerAuthenticator = innerAuthenticator; } public override void OnOpening() { base.OnOpening(); if (this.credentialsHandle == null) { this.credentialsHandle = SecurityUtils.GetCredentialsHandle("Kerberos", null, true); } } public override void OnClose(TimeSpan timeout) { base.OnClose(timeout); FreeCredentialsHandle(); } public override void OnAbort() { base.OnAbort(); FreeCredentialsHandle(); } void FreeCredentialsHandle() { if (this.credentialsHandle != null) { this.credentialsHandle.Close(); this.credentialsHandle = null; } } protected override bool CanValidateTokenCore(SecurityToken token) { return this.innerAuthenticator.CanValidateToken(token); } internal ReadOnlyCollection<IAuthorizationPolicy> ValidateToken(SecurityToken token, ChannelBinding channelBinding, ExtendedProtectionPolicy protectionPolicy) { KerberosReceiverSecurityToken kerberosToken = (KerberosReceiverSecurityToken)token; kerberosToken.Initialize(this.credentialsHandle, channelBinding, protectionPolicy); return this.innerAuthenticator.ValidateToken(kerberosToken); } protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token) { return ValidateToken(token, null, null); } } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using Newtonsoft.Json.Utilities; using System.IO; using System.Globalization; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON array. /// </summary> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from Text" /> /// </example> public class JArray : JContainer, IList<JToken> { private readonly List<JToken> _values = new List<JToken>(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _values; } } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return JTokenType.Array; } } /// <summary> /// Initializes a new instance of the <see cref="JArray"/> class. /// </summary> public JArray() { } /// <summary> /// Initializes a new instance of the <see cref="JArray"/> class from another <see cref="JArray"/> object. /// </summary> /// <param name="other">A <see cref="JArray"/> object to copy from.</param> public JArray(JArray other) : base(other) { } /// <summary> /// Initializes a new instance of the <see cref="JArray"/> class with the specified content. /// </summary> /// <param name="content">The contents of the array.</param> public JArray(params object[] content) : this((object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JArray"/> class with the specified content. /// </summary> /// <param name="content">The contents of the array.</param> public JArray(object content) { Add(content); } internal override bool DeepEquals(JToken node) { JArray t = node as JArray; return (t != null && ContentsEqual(t)); } internal override JToken CloneToken() { return new JArray(this); } /// <summary> /// Loads an <see cref="JArray"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JArray"/>.</param> /// <returns>A <see cref="JArray"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JArray Load(JsonReader reader) { if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader."); } while (reader.TokenType == JsonToken.Comment) { reader.Read(); } if (reader.TokenType != JsonToken.StartArray) throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); JArray a = new JArray(); a.SetLineInfo(reader as IJsonLineInfo); a.ReadTokenFrom(reader); return a; } /// <summary> /// Load a <see cref="JArray"/> from a string that contains JSON. /// </summary> /// <param name="json">A <see cref="String"/> that contains JSON.</param> /// <returns>A <see cref="JArray"/> populated from the string that contains JSON.</returns> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from Text" /> /// </example> public static new JArray Parse(string json) { JsonReader reader = new JsonTextReader(new StringReader(json)); JArray a = Load(reader); if (reader.Read() && reader.TokenType != JsonToken.Comment) throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); return a; } /// <summary> /// Creates a <see cref="JArray"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JArray"/>.</param> /// <returns>A <see cref="JArray"/> with the values of the specified object</returns> public static new JArray FromObject(object o) { return FromObject(o, JsonSerializer.CreateDefault()); } /// <summary> /// Creates a <see cref="JArray"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JArray"/>.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param> /// <returns>A <see cref="JArray"/> with the values of the specified object</returns> public static new JArray FromObject(object o, JsonSerializer jsonSerializer) { JToken token = FromObjectInternal(o, jsonSerializer); if (token.Type != JTokenType.Array) throw new ArgumentException("Object serialized to {0}. JArray instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); return (JArray)token; } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartArray(); for (int i = 0; i < _values.Count; i++) { _values[i].WriteTo(writer, converters); } writer.WriteEndArray(); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Accessed JArray values with invalid key value: {0}. Array position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); return GetItem((int)key); } set { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Set JArray values with invalid key value: {0}. Array position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); SetItem((int)key, value); } } /// <summary> /// Gets or sets the <see cref="Newtonsoft.Json.Linq.JToken"/> at the specified index. /// </summary> /// <value></value> public JToken this[int index] { get { return GetItem(index); } set { SetItem(index, value); } } #region IList<JToken> Members /// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> public int IndexOf(JToken item) { return IndexOfItem(item); } /// <summary> /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception> public void Insert(int index, JToken item) { InsertItem(index, item, false); } /// <summary> /// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception> public void RemoveAt(int index) { RemoveItemAt(index); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. /// </returns> public IEnumerator<JToken> GetEnumerator() { return Children().GetEnumerator(); } #endregion #region ICollection<JToken> Members /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public void Add(JToken item) { Add((object)item); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception> public void Clear() { ClearItems(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> public bool Contains(JToken item) { return ContainsItem(item); } /// <summary> /// Copies to. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">Index of the array.</param> public void CopyTo(JToken[] array, int arrayIndex) { CopyItemsTo(array, arrayIndex); } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only. /// </summary> /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.</returns> public bool IsReadOnly { get { return false; } } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public bool Remove(JToken item) { return RemoveItem(item); } #endregion internal override int GetDeepHashCode() { return ContentsHashCode(); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { using System; using System.Diagnostics.Contracts; // // This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar // is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day // every fourth year. //* //* Calendar support range: //* Calendar Minimum Maximum //* ========== ========== ========== //* Gregorian 0001/01/01 9999/12/31 //* Julia 0001/01/03 9999/10/19 [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class JulianCalendar : Calendar { public static readonly int JulianEra = 1; private const int DatePartYear = 0; private const int DatePartDayOfYear = 1; private const int DatePartMonth = 2; private const int DatePartDay = 3; // Number of days in a non-leap year private const int JulianDaysPerYear = 365; // Number of days in 4 years private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1; //internal static Calendar m_defaultInstance; private static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; // Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19 // keep it as variable field for serialization compat. internal int MaxYear = 9999; [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Julian calendar. // [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of JulianCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ /* internal static Calendar GetDefaultInstance() { if (m_defaultInstance == null) { m_defaultInstance = new JulianCalendar(); } return (m_defaultInstance); } */ // Construct an instance of gregorian calendar. public JulianCalendar() { // There is no system setting of TwoDigitYear max, so set the value here. twoDigitYearMax = 2029; } internal override int ID { get { return (CAL_JULIAN); } } static internal void CheckEraRange(int era) { if (era != CurrentEra && era != JulianEra) { throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } } internal void CheckYearEraRange(int year, int era) { CheckEraRange(era); if (year <= 0 || year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } } static internal void CheckMonthRange(int month) { if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); } } /*=================================GetDefaultInstance========================== **Action: Check for if the day value is valid. **Returns: **Arguments: **Exceptions: **Notes: ** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make ** sure year/month values are correct. ============================================================================*/ static internal void CheckDayRange(int year, int month, int day) { if (year == 1 && month == 1) { // The mimimum supported Julia date is Julian 0001/01/03. if (day < 3) { throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay")); } } bool isLeapYear = (year % 4) == 0; int[] days = isLeapYear ? DaysToMonth366 : DaysToMonth365; int monthDays = days[month] - days[month - 1]; if (day < 1 || day > monthDays) { throw new ArgumentOutOfRangeException( "day", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, monthDays)); } } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. static internal int GetDatePart(long ticks, int part) { // Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001. // The following line convert Gregorian ticks to Julian ticks. long julianTicks = ticks + TicksPerDay * 2; // n = number of days since 1/1/0001 int n = (int)(julianTicks / TicksPerDay); // y4 = number of whole 4-year periods within 100-year period int y4 = n / JulianDaysPer4Years; // n = day number within 4-year period n -= y4 * JulianDaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / JulianDaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * JulianDaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3); int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } // Returns the tick count corresponding to the given year, month, and day. static internal long DateToTicks(int year, int month, int day) { int[] days = (year % 4 == 0)? DaysToMonth366: DaysToMonth365; int y = year - 1; int n = y * 365 + y / 4 + days[month - 1] + day - 1; // Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar. // Therefore, we subtract two days in the following to convert the ticks in JulianCalendar // to ticks in Gregorian calendar. return ((n - 2) * TicksPerDay); } public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), -120000, 120000)); } Contract.EndContractBlock(); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } public override int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } public override int GetDaysInMonth(int year, int month, int era) { CheckYearEraRange(year, era); CheckMonthRange(month); int[] days = (year % 4 == 0) ? DaysToMonth366: DaysToMonth365; return (days[month] - days[month - 1]); } public override int GetDaysInYear(int year, int era) { // Year/Era range is done in IsLeapYear(). return (IsLeapYear(year, era) ? 366:365); } public override int GetEra(DateTime time) { return (JulianEra); } public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } public override int[] Eras { get { return (new int[] {JulianEra}); } } public override int GetMonthsInYear(int year, int era) { CheckYearEraRange(year, era); return (12); } public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } public override bool IsLeapDay(int year, int month, int day, int era) { CheckMonthRange(month); // Year/Era range check is done in IsLeapYear(). if (IsLeapYear(year, era)) { CheckDayRange(year, month, day); return (month == 2 && day == 29); } CheckDayRange(year, month, day); return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { CheckYearEraRange(year, era); return (0); } public override bool IsLeapMonth(int year, int month, int era) { CheckYearEraRange(year, era); CheckMonthRange(month); return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { CheckYearEraRange(year, era); return (year % 4 == 0); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { CheckYearEraRange(year, era); CheckMonthRange(month); CheckDayRange(year, month, day); if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1)); } if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60) { return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks); } else { throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond")); } } public override int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 99, MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"), 1, MaxYear)); } return (base.ToFourDigitYear(year)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class represents settings specified by de jure or // de facto standards for a particular country/region. In // contrast to CultureInfo, the RegionInfo does not represent // preferences of the user and does not depend on the user's // language or culture. // // //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; namespace System.Globalization { public class RegionInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // // // Name of this region (ie: es-US): serialized, the field used for deserialization // internal String _name; // // The CultureData instance that we are going to read data from. // internal CultureData _cultureData; // // The RegionInfo for our current region // internal static volatile RegionInfo s_currentRegionInfo; //////////////////////////////////////////////////////////////////////// // // RegionInfo Constructors // // Note: We prefer that a region be created with a full culture name (ie: en-US) // because otherwise the native strings won't be right. // // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// public RegionInfo(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, nameof(name)); } // // For CoreCLR we only want the region names that are full culture names // _cultureData = CultureData.GetCultureDataForRegion(name, true); if (_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, name), nameof(name)); // Not supposed to be neutral if (_cultureData.IsNeutralCulture) throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), nameof(name)); SetName(name); } public RegionInfo(int culture) { if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture); } if (culture == CultureInfo.LOCALE_NEUTRAL) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CustomCultureCannotBePassedByNumber, culture), nameof(culture)); } _cultureData = CultureData.GetCultureData(culture, true); _name = _cultureData.SREGIONNAME; if (_cultureData.IsNeutralCulture) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } } internal RegionInfo(CultureData cultureData) { _cultureData = cultureData; _name = _cultureData.SREGIONNAME; } private void SetName(string name) { // Use the name of the region we found _name = _cultureData.SREGIONNAME; } //////////////////////////////////////////////////////////////////////// // // GetCurrentRegion // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// public static RegionInfo CurrentRegion { get { RegionInfo temp = s_currentRegionInfo; if (temp == null) { temp = new RegionInfo(CultureInfo.CurrentCulture._cultureData); // Need full name for custom cultures temp._name = temp._cultureData.SREGIONNAME; s_currentRegionInfo = temp; } return temp; } } //////////////////////////////////////////////////////////////////////// // // GetName // // Returns the name of the region (ie: en-US) // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already"); return (_name); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the name of the region in English. (ie: United States) // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { get { return (_cultureData.SENGCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetDisplayName // // Returns the display name (localized) of the region. (ie: United States // if the current UI language is en-US) // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { get { return (_cultureData.SLOCALIZEDCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the native name of the region. (ie: Deutschland) // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual String NativeName { get { return (_cultureData.SNATIVECOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // TwoLetterISORegionName // // Returns the two letter ISO region name (ie: US) // //////////////////////////////////////////////////////////////////////// public virtual String TwoLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterISORegionName // // Returns the three letter ISO region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME2); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsRegionName // // Returns the three letter windows region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsRegionName { get { // ThreeLetterWindowsRegionName is really same as ThreeLetterISORegionName return ThreeLetterISORegionName; } } //////////////////////////////////////////////////////////////////////// // // IsMetric // // Returns true if this region uses the metric measurement system // //////////////////////////////////////////////////////////////////////// public virtual bool IsMetric { get { int value = _cultureData.IMEASURE; return (value == 0); } } public virtual int GeoId { get { return (_cultureData.IGEOID); } } //////////////////////////////////////////////////////////////////////// // // CurrencyEnglishName // // English name for this region's currency, ie: Swiss Franc // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyEnglishName { get { return (_cultureData.SENGLISHCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencyNativeName // // Native name for this region's currency, ie: Schweizer Franken // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyNativeName { get { return (_cultureData.SNATIVECURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencySymbol // // Currency Symbol for this locale, ie: Fr. or $ // //////////////////////////////////////////////////////////////////////// public virtual String CurrencySymbol { get { return (_cultureData.SCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // ISOCurrencySymbol // // ISO Currency Symbol for this locale, ie: CHF // //////////////////////////////////////////////////////////////////////// public virtual String ISOCurrencySymbol { get { return (_cultureData.SINTLSYMBOL); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same RegionInfo as the current instance. // // RegionInfos are considered equal if and only if they have the same name // (ie: en-US) // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { RegionInfo that = value as RegionInfo; if (that != null) { return this.Name.Equals(that.Name); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for RegionInfo // A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the Region, ie: es-US // //////////////////////////////////////////////////////////////////////// public override String ToString() { return (Name); } } }
// GameLayer.cs // // Author(s) // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2012 s. Delcroix // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using Microsoft.Xna.Framework; using CocosSharp; namespace Jumpy { public class GameLayer : MainLayer { public enum Bonus : int { Bonus5 = 0, Bonus10, Bonus50, Bonus100, NumBonuses } int score; int currentPlatformTag; bool gameSuspended; int numPlatforms = 10; int minPlatformStep = 50; int maxPlatformStep = 300; int minBonusStep = 20; int maxBonusStep = 50; int platformTopPadding = 10; bool birdLookingRight; CCPoint bird_pos; Vector2 bird_vel; Vector2 bird_acc; public static CCScene Scene { get { var scene = new CCScene(); var layer = new GameLayer(); scene.AddChild(layer); return scene; } } public GameLayer() { gameSuspended = true; var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; InitPlatforms(); var bird = new CCSprite(batchnode.Texture, new CCRect(608, 16, 44, 32)); batchnode.AddChild(bird, 4, (int)Tags.Bird); CCSprite bonus; for (int i = 0; i < (int)Bonus.NumBonuses; i++) { bonus = new CCSprite(batchnode.Texture, new CCRect(608 + i * 32, 256, 25, 25)); batchnode.AddChild(bonus, 4, (int)Tags.BomusStart + i); bonus.Visible = false; } var scoreLabel = new CCLabelBMFont("0", "Fonts/bitmapFont.fnt"); scoreLabel.Position = new CCPoint(160, 430); AddChild(scoreLabel, 5, (int)Tags.ScoreLabel); } CCEventListenerTouchOneByOne touchListener; public override void OnEnter() { base.OnEnter(); Schedule(Step); #if WINDOWS || MACOS //AccelerometerEnabled = false; //TouchEnabled = true; //TouchMode = CCTouchMode.OneByOne; touchListener = new CCEventListenerTouchOneByOne(); touchListener.OnTouchBegan = OnTouchBegan; touchListener.OnTouchMoved = OnTouchMoved; touchListener.OnTouchEnded = OnTouchEnded; #else AccelerometerEnabled = true; SingleTouchEnabled = false; #endif //IsAccelerometerEnabled = true; // CCDirector.SharedDirector.Accelerometer.SetDelegate(new AccelerometerDelegate(DidAccelerate); StartGame(); } //public override void TouchEnded(CCTouch touch) //{ //} private void OnTouchEnded(CCTouch arg1, CCEvent arg2) { float accel_filter = 0.1f; float ax = ConvertTouchToNodeSpace(arg1).X - ConvertToNodeSpace(arg1.PreviousLocationInView).X; ax /= 500; bird_vel.X = bird_vel.X * accel_filter + (float)ax * (1.0f - accel_filter) * 500.0f; } private void OnTouchMoved(CCTouch arg1, CCEvent arg2) { } private bool OnTouchBegan(CCTouch arg1, CCEvent arg2) { return (true); } public override void OnExit() { base.OnExit(); EventDispatcher.RemoveEventListener(touchListener); } void InitPlatforms() { currentPlatformTag = (int)Tags.PlatformsStart; while (currentPlatformTag < (int)Tags.PlatformsStart + numPlatforms) { InitPlatform(); currentPlatformTag++; } ResetPlatforms(); } private Random ran = new Random(); void InitPlatform() { CCRect rect; switch (ran.Next() % 2) { case 0: rect = new CCRect(608, 64, 102, 36); break; default: rect = new CCRect(608, 128, 90, 32); break; } var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; var platform = new CCSprite(batchnode.Texture, rect); batchnode.AddChild(platform, 3, currentPlatformTag); } float currentPlatformY; float currentMaxPlatformStep; int currentBonusPlatformIndex; int currentBonusType; int platformCount; void ResetPlatforms() { currentPlatformY = -1; currentPlatformTag = (int)Tags.PlatformsStart; currentMaxPlatformStep = 60.0f; currentBonusPlatformIndex = 0; currentBonusType = 0; platformCount = 0; while (currentPlatformTag < (int)Tags.PlatformsStart + numPlatforms) { ResetPlatform(); currentPlatformTag++; } } void ResetPlatform() { if (currentPlatformY < 0) { currentPlatformY = 30.0f; } else { currentPlatformY += ran.Next() % (int)(currentMaxPlatformStep - minPlatformStep) + minPlatformStep; if (currentMaxPlatformStep < maxPlatformStep) { currentMaxPlatformStep += 0.5f; } } var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; var platform = batchnode.GetChildByTag(currentPlatformTag) as CCSprite; if (ran.Next() % 2 == 1) platform.ScaleX = -1.0f; float x; var size = platform.ContentSize; if (currentPlatformY == 30.0f) { x = 160.0f; } else { x = ran.Next() % (320 - (int)size.Width) + size.Width / 2; } platform.Position = new CCPoint(x, currentPlatformY); platformCount++; if (platformCount == currentBonusPlatformIndex) { var bonus = batchnode.GetChildByTag((int)Tags.BomusStart + currentBonusType) as CCSprite; bonus.Position = new CCPoint(x, currentPlatformY + 30); bonus.Visible = true; } } void StartGame() { score = 0; ResetClouds(); ResetPlatforms(); ResetBird(); ResetBonus(); // UIApplication.SharedApplication.IdleTimerDisabled=true; gameSuspended = false; ; } void ResetBird() { var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; var bird = batchnode.GetChildByTag((int)Tags.Bird) as CCSprite; bird_pos.X = 160; bird_pos.Y = 160; bird.Position = bird_pos; bird_vel.X = 0; bird_vel.Y = 0; bird_acc.X = 0; bird_acc.Y = -550.0f; birdLookingRight = true; bird.ScaleX = 1.0f; } void ResetBonus() { var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; var bonus = batchnode.GetChildByTag((int)Tags.BomusStart + currentBonusType) as CCSprite; bonus.Visible = false; currentBonusPlatformIndex += ran.Next() % (maxBonusStep - minBonusStep) + minBonusStep; if (score < 10000) { currentBonusType = 0; } else if (score < 50000) { currentBonusType = ran.Next() % 2; } else if (score < 100000) { currentBonusType = ran.Next() % 3; } else { currentBonusType = ran.Next() % 2 + 2; } } protected override void Step(float dt) { base.Step(dt); if (gameSuspended) return; var batchnode = GetChildByTag((int)Tags.SpriteManager) as CCSpriteBatchNode; var bird = batchnode.GetChildByTag((int)Tags.Bird) as CCSprite; var particles = GetChildByTag((int)Tags.Particles) as CCParticleSystem; bird_pos.X += bird_vel.X * dt; if (bird_vel.X < -30.0f && birdLookingRight) { birdLookingRight = false; bird.ScaleX = -1.0f; } else if (bird_vel.X > 30.0f && !birdLookingRight) { birdLookingRight = true; bird.ScaleX = 1.0f; } var bird_size = bird.ContentSize; float max_x = 320 - bird_size.Width / 2; float min_x = 0 + bird_size.Width / 2; if (bird_pos.X > max_x) bird_pos.X = max_x; if (bird_pos.X < min_x) bird_pos.X = min_x; bird_vel.Y += bird_acc.Y * dt; bird_pos.Y += bird_vel.Y * dt; var bonus = batchnode.GetChildByTag((int)Tags.BomusStart + currentBonusType); if (bonus.Visible) { var bonus_pos = bonus.Position; float range = 20.0f; if (bird_pos.X > bonus_pos.X - range && bird_pos.X < bonus_pos.Y + range && bird_pos.Y > bonus_pos.Y - range && bird_pos.Y < bonus_pos.Y + range) { switch (currentBonusType) { case (int)Bonus.Bonus5: score += 5000; break; case (int)Bonus.Bonus10: score += 10000; break; case (int)Bonus.Bonus50: score += 50000; break; case (int)Bonus.Bonus100: score += 100000; break; } var scorelabel = GetChildByTag((int)Tags.ScoreLabel) as CCLabelBMFont; scorelabel.Text = score.ToString(); var a1 = new CCScaleTo(.2f, 1.5f, .08f); var a2 = new CCScaleTo(.2f, 1f, 1f); var a3 = new CCSequence(a1, a2, a1, a2, a1, a2); scorelabel.RunAction(a3); ResetBonus(); } } int t; if (bird_vel.Y < 0) { t = (int)Tags.PlatformsStart; for (t = (int)Tags.PlatformsStart; t < (int)Tags.PlatformsStart + numPlatforms; t++) { var platform = batchnode.GetChildByTag(t) as CCSprite; var platform_size = platform.ContentSize; var platform_pos = platform.Position; max_x = platform_pos.X - platform_size.Width / 2 - 10; min_x = platform_pos.X + platform_size.Width / 2 + 10; float min_y = platform_pos.Y + (platform_size.Height + bird_size.Height) / 2 - platformTopPadding; if (bird_pos.X > max_x && bird_pos.X < min_x && bird_pos.Y > platform_pos.Y && bird_pos.Y < min_y) { Jump(); } } if (bird_pos.Y < -bird_size.Height / 2) { ShowHighScores(); } } else if (bird_pos.Y > 240) { float delta = bird_pos.Y - 240; bird_pos.Y = 240; currentPlatformY -= delta; for (t = (int)Tags.CloudsStart; t < (int)Tags.CloudsStart + numClouds; t++) { var cloud = batchnode.GetChildByTag(t) as CCSprite; var pos = cloud.Position; pos.Y -= delta * cloud.ScaleY * 0.8f; if (pos.Y < -cloud.ContentSize.Height / 2) { currentCloudTag = t; ResetCloud(); } else { cloud.Position = pos; } } for (t = (int)Tags.PlatformsStart; t < (int)Tags.PlatformsStart + numPlatforms; t++) { var platform = batchnode.GetChildByTag(t) as CCSprite; var pos = platform.Position; pos = new CCPoint(pos.X, pos.Y - delta); if (pos.Y < -platform.ContentSize.Height / 2) { currentPlatformTag = t; ResetPlatform(); } else { platform.Position = pos; } } if (bonus.Visible) { var pos = bonus.Position; pos.Y -= delta; if (pos.Y < -bonus.ContentSize.Height / 2) { ResetBonus(); //[self resetBonus]; } else { bonus.Position = pos; } } score += (int)delta; var scoreLabel = GetChildByTag((int)Tags.ScoreLabel) as CCLabelBMFont; scoreLabel.Text = score.ToString(); } bird.Position = bird_pos; if (particles != null) { var particle_pos = new CCPoint(bird_pos.X, bird_pos.Y - 17); particles.Position = particle_pos; } } void Jump() { bird_vel.Y = 400.0f + Math.Abs(bird_vel.X); var old_part = GetChildByTag((int)Tags.Particles); if (old_part != null) RemoveChild(old_part, true); var particle = new CCParticleFireworks(bird_pos); //particle.Position = bird_pos; particle.Gravity = new CCPoint(0, -5000); particle.Duration = .3f; AddChild(particle, -1, (int)Tags.Particles); } void HandleAccelerate(CCAcceleration acceleration) { if (gameSuspended) return; float accel_filter = 0.1f; bird_vel.X = bird_vel.X * accel_filter + (float)acceleration.X * (1.0f - accel_filter) * 500.0f; } void ShowHighScores() { gameSuspended = true; Director.ReplaceScene(new CCTransitionFade(1, HighScoreLayer.Scene(score), new CCColor3B(255, 255, 255))); } } //public class AccelerometerDelegate : ICCAccelerometerDelegate //{ // public virtual void DidAccelerate(CCAcceleration pAccelerationValue) // { // } //} }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using PrimerProObjects; using PrimerProLocalization; using GenLib; namespace PrimerProForms { /// <summary> /// Summary description for FormToneWL. /// </summary> public class FormToneWL : System.Windows.Forms.Form { private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnSO; private System.Windows.Forms.Label labTone; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private CheckedListBox clbTones; private Button btnUncheck; private Button btnCheck; //private ToneWLSearch m_Search; //WordList Tone Search private ArrayList m_SelectedTones; private SearchOptions m_SearchOptions; private PSTable m_PSTable; private LocalizationTable m_Table; public FormToneWL(Settings s) { // // Required for Windows Form Designer support // InitializeComponent(); GraphemeInventory gi = s.GraphemeInventory; m_PSTable = s.PSTable; Font fnt = s.OptionSettings.GetDefaultFont(); for (int i = 0; i < gi.ToneCount(); i++) { this.clbTones.Items.Add(gi.GetTone(i).Symbol); } this.clbTones.Font = fnt; m_Table = null; } public FormToneWL(Settings s, LocalizationTable table) { // // Required for Windows Form Designer support // InitializeComponent(); GraphemeInventory gi = s.GraphemeInventory; m_PSTable = s.PSTable; Font fnt = s.OptionSettings.GetDefaultFont(); for (int i = 0; i < gi.ToneCount(); i++) { this.clbTones.Items.Add(gi.GetTone(i).Symbol); } this.clbTones.Font = fnt; m_Table = table; this.UpdateFormForLocalization(table); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormToneWL)); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnSO = new System.Windows.Forms.Button(); this.labTone = new System.Windows.Forms.Label(); this.clbTones = new System.Windows.Forms.CheckedListBox(); this.btnUncheck = new System.Windows.Forms.Button(); this.btnCheck = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnOK // this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnOK.Location = new System.Drawing.Point(292, 255); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(100, 32); this.btnOK.TabIndex = 5; this.btnOK.Text = "OK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnCancel.Location = new System.Drawing.Point(410, 255); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(100, 32); this.btnCancel.TabIndex = 6; this.btnCancel.Text = "Cancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnSO // this.btnSO.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnSO.Location = new System.Drawing.Point(242, 32); this.btnSO.Name = "btnSO"; this.btnSO.Size = new System.Drawing.Size(200, 32); this.btnSO.TabIndex = 2; this.btnSO.Text = "&Search Options"; this.btnSO.Click += new System.EventHandler(this.btnSO_Click); // // labTone // this.labTone.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labTone.Location = new System.Drawing.Point(24, 32); this.labTone.Name = "labTone"; this.labTone.Size = new System.Drawing.Size(177, 32); this.labTone.TabIndex = 0; this.labTone.Text = "Select Tones to find"; this.labTone.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // clbTones // this.clbTones.CheckOnClick = true; this.clbTones.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.clbTones.FormattingEnabled = true; this.clbTones.HorizontalScrollbar = true; this.clbTones.Location = new System.Drawing.Point(27, 67); this.clbTones.Name = "clbTones"; this.clbTones.Size = new System.Drawing.Size(174, 232); this.clbTones.TabIndex = 1; this.clbTones.TabStop = false; // // btnUncheck // this.btnUncheck.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnUncheck.Location = new System.Drawing.Point(410, 120); this.btnUncheck.Name = "btnUncheck"; this.btnUncheck.Size = new System.Drawing.Size(150, 32); this.btnUncheck.TabIndex = 4; this.btnUncheck.Text = "&Uncheck All"; this.btnUncheck.UseVisualStyleBackColor = true; this.btnUncheck.Click += new System.EventHandler(this.btnUncheck_Click); // // btnCheck // this.btnCheck.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnCheck.Location = new System.Drawing.Point(242, 120); this.btnCheck.Name = "btnCheck"; this.btnCheck.Size = new System.Drawing.Size(150, 32); this.btnCheck.TabIndex = 3; this.btnCheck.Text = "&Check All"; this.btnCheck.UseVisualStyleBackColor = true; this.btnCheck.Click += new System.EventHandler(this.btnCheck_Click); // // FormToneWL // this.AcceptButton = this.btnOK; this.AutoScaleBaseSize = new System.Drawing.Size(6, 15); this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(586, 314); this.Controls.Add(this.btnUncheck); this.Controls.Add(this.btnCheck); this.Controls.Add(this.clbTones); this.Controls.Add(this.btnSO); this.Controls.Add(this.labTone); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "FormToneWL"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Tone Search"; this.ResumeLayout(false); } #endregion public ArrayList SelectedTones { get { return m_SelectedTones; } } public SearchOptions SearchOptions { get { return m_SearchOptions; } } private void btnOK_Click(object sender, System.EventArgs e) { if (this.clbTones.CheckedItems.Count > 0) { string strTone = ""; m_SelectedTones = new ArrayList(); foreach (object obj in clbTones.CheckedItems) { strTone = obj.ToString(); m_SelectedTones.Add(strTone); } } } private void btnCancel_Click(object sender, System.EventArgs e) { m_SelectedTones = null; this.Close(); } private void btnSO_Click(object sender, System.EventArgs e) { SearchOptions so = new SearchOptions(m_PSTable); CodeTable ct = (CodeTable) m_PSTable; //FormSearchOptions form = new FormSearchOptions(ct, false, false); FormSearchOptions form = new FormSearchOptions(ct, false, false, m_Table); DialogResult dr= form.ShowDialog(); if (dr == DialogResult.OK) { so.PS = form.PSTE; so.IsRootOnly = form.IsRootOnly; so.IsIdenticalVowelsInRoot = form.IsIdenticalVowelsInRoot; so.IsIdenticalVowelsInWord = form.IsIdenticalVowelsInWord; so.IsBrowseView = form.IsBrowseView; so.WordCVShape = form.WordCVShape; so.RootCVShape = form.RootCVShape; so.MinSyllables = form.MinSyllables; so.MaxSyllables = form.MaxSyllables; so.WordPosition = form.WordPosition; so.RootPosition = form.RootPosition; m_SearchOptions = so; } } private void btnCheck_Click(object sender, EventArgs e) { for (int i = 0; i < clbTones.Items.Count; i++) clbTones.SetItemChecked(i, true); clbTones.Show(); } private void btnUncheck_Click(object sender, EventArgs e) { for (int i = 0; i < clbTones.Items.Count; i++) clbTones.SetItemChecked(i, false); clbTones.Show(); } private void UpdateFormForLocalization(LocalizationTable table) { string strText = ""; strText = table.GetForm("FormToneWLT"); if (strText != "") this.Text = strText; strText = table.GetForm("FormToneWL0"); if (strText != "") this.labTone.Text = strText; strText = table.GetForm("FormToneWL2"); if (strText != "") this.btnSO.Text = strText; strText = table.GetForm("FormToneWL3"); if (strText != "") this.btnCheck.Text = strText; strText = table.GetForm("FormToneWL4"); if (strText != "") this.btnUncheck.Text = strText; strText = table.GetForm("FormToneWL5"); if (strText != "") this.btnOK.Text = strText; strText = table.GetForm("FormToneWL6"); if (strText != "") this.btnCancel.Text = strText; return; } } }
// 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. //---------------------------------------------------------------------------------------- // // Description: // Analyze the current project inputs, the compiler state file and local reference // cache, determine which xaml files require to recompile. // //--------------------------------------------------------------------------------------- using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Microsoft.Build.Tasks.Windows; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using MS.Utility; namespace MS.Internal.Tasks { // // Keep different categories of recompilation. // [Flags] internal enum RecompileCategory : byte { NoRecompile = 0x00, ApplicationFile = 0x01, ModifiedPages = 0x02, PagesWithLocalType = 0x04, ContentFiles = 0x08, All = 0x0F } // <summary> // IncrementalCompileAnalyzer // </summary> internal class IncrementalCompileAnalyzer { // <summary> // ctor of IncrementalCompileAnalyzer // </summary> internal IncrementalCompileAnalyzer(MarkupCompilePass1 mcPass1) { _mcPass1 = mcPass1; _analyzeResult = RecompileCategory.NoRecompile; } #region internal methods // // Analyze the input files based on the compiler cache files. // // Put the analyze result in _analyzeResult and other related data fields, // such as RecompileMarkupPages, RecompileApplicationFile, etc. // // If analyze is failed somehow, throw exception. // internal void AnalyzeInputFiles() { // // First: Detect if the entire project requires re-compile. // // // If the compiler state file doesn't exist, recompile all the xaml files. // if (!CompilerState.StateFileExists()) { _analyzeResult = RecompileCategory.All; } else { // Load the compiler state file. CompilerState.LoadStateInformation(); // if PresenationBuildTasks.dll is changed last build, rebuild the entire project for sure. if (IsFileChanged(Assembly.GetExecutingAssembly().Location) || IsFileListChanged(_mcPass1.ExtraBuildControlFiles)) { _analyzeResult = RecompileCategory.All; } else { // // Any one single change in below list would request completely re-compile. // if (IsSettingModified(CompilerState.References, _mcPass1.ReferencesCache) || IsSettingModified(CompilerState.ApplicationFile, _mcPass1.ApplicationFile) || IsSettingModified(CompilerState.RootNamespace, _mcPass1.RootNamespace) || IsSettingModified(CompilerState.AssemblyName, _mcPass1.AssemblyName) || IsSettingModified(CompilerState.AssemblyVersion, _mcPass1.AssemblyVersion) || IsSettingModified(CompilerState.AssemblyPublicKeyToken, _mcPass1.AssemblyPublicKeyToken) || IsSettingModified(CompilerState.OutputType, _mcPass1.OutputType) || IsSettingModified(CompilerState.Language, _mcPass1.Language) || IsSettingModified(CompilerState.LanguageSourceExtension, _mcPass1.LanguageSourceExtension) || IsSettingModified(CompilerState.OutputPath, _mcPass1.OutputPath) || IsSettingModified(CompilerState.LocalizationDirectivesToLocFile, _mcPass1.LocalizationDirectivesToLocFile)) { _analyzeResult = RecompileCategory.All; } else { if (_mcPass1.IsApplicationTarget) { // // When application definition file is modified, it could potentially change the application // class name, it then has impact on all other xaml file compilation, so recompile the entire // project for this case. // if (TaskFileService.Exists(_mcPass1.ApplicationFile) && IsFileChanged(_mcPass1.ApplicationFile)) { _analyzeResult = RecompileCategory.All; } } // // If any one referenced assembly is updated since last build, the entire project needs to recompile. // if (IsFileListChanged(_mcPass1.References)) { _analyzeResult = RecompileCategory.All; } } } } if (_analyzeResult == RecompileCategory.All) { UpdateFileListForCleanbuild(); return; } // // The entire project recompilation should have already been handled when code goes here. // Now, Detect the individual xaml files which require to recompile. // if (_mcPass1.IsApplicationTarget) { if (IsSettingModified(CompilerState.ContentFiles, _mcPass1.ContentFilesCache)) { _analyzeResult |= RecompileCategory.ContentFiles; } // if HostInBrowser setting is changed, it would affect the application file compilation only. if (IsSettingModified(CompilerState.HostInBrowser, _mcPass1.HostInBrowser)) { _analyzeResult |= RecompileCategory.ApplicationFile; } if (IsSettingModified(CompilerState.SplashImage, _mcPass1.SplashImageName)) { _analyzeResult |= RecompileCategory.ApplicationFile; } } // // If code files are changed, or Define flags are changed, it would affect the xaml file with local types. // // If previous build didn't have such local-ref-xaml files, don't bother to do further check for this. // if (CompilerLocalReference.CacheFileExists()) { if (IsSettingModified(CompilerState.DefineConstants, _mcPass1.DefineConstants) || IsSettingModified(CompilerState.SourceCodeFiles, _mcPass1.SourceCodeFilesCache) || IsFileListChanged(_mcPass1.SourceCodeFiles) ) { _analyzeResult |= RecompileCategory.PagesWithLocalType; } } List<FileUnit> modifiedXamlFiles = new List<FileUnit>(); // // Detect if any .xaml page is updated since last build // if (ListIsNotEmpty(_mcPass1.PageMarkup)) { // // If the PageMarkup file number or hashcode is changed, it would affect // the xaml files with local types. // // This check is necessary for the senario that a xaml file is removed and the // removed xaml file could be referenced by other xaml files with local types. // if (IsSettingModified(CompilerState.PageMarkup, _mcPass1.PageMarkupCache)) { if (CompilerLocalReference.CacheFileExists()) { _analyzeResult |= RecompileCategory.PagesWithLocalType; } } // Below code detects which individual xaml files are modified since last build. for (int i = 0; i < _mcPass1.PageMarkup.Length; i++) { ITaskItem taskItem = _mcPass1.PageMarkup[i]; string fileName = taskItem.ItemSpec; string filepath = Path.GetFullPath(fileName); string linkAlias = taskItem.GetMetadata(SharedStrings.Link); string logicalName = taskItem.GetMetadata(SharedStrings.LogicalName); if (IsFileChanged(filepath)) { // add this file to the modified file list. modifiedXamlFiles.Add(new FileUnit(filepath, linkAlias, logicalName)); } else { // A previously generated xaml file (with timestamp earlier than of the cache file) // could be added to the project. This means that the above check for time stamp // will skip compiling the newly added xaml file. We save the name all the xaml // files we previously built to the cache file. Retrieve that list and see if // this xaml file is already in it. If so, we'll skip compiling this xaml file, // else, this xaml file was just added to the project and thus compile it. if (!CompilerState.PageMarkupFileNames.Contains(fileName)) { modifiedXamlFiles.Add(new FileUnit(filepath, linkAlias, logicalName)); } } } if (modifiedXamlFiles.Count > 0) { _analyzeResult |= RecompileCategory.ModifiedPages; if (CompilerLocalReference.CacheFileExists()) { _analyzeResult |= RecompileCategory.PagesWithLocalType; } } } // Check for the case where a required Pass2 wasn't run, e.g. because the build was aborted, // or because the Compile target was run inside VS. // If that happened, let's recompile the local-type pages, which will force Pass2 to run. if (CompilerState.Pass2Required && CompilerLocalReference.CacheFileExists()) { _analyzeResult |= RecompileCategory.PagesWithLocalType; } UpdateFileListForIncrementalBuild(modifiedXamlFiles); } #endregion #region internal properties // // Keep the AnlyzeResult. // internal RecompileCategory AnalyzeResult { get { return _analyzeResult; } } // // Keep a list of markup pages which require to recompile // internal FileUnit[] RecompileMarkupPages { get { return _recompileMarkupPages; } } // // Application file which requires re-compile. // If the value is String.Empty, the appdef file is not required // to recompile. // internal FileUnit RecompileApplicationFile { get { return _recompileApplicationFile; } } internal string[] ContentFiles { get { return _contentFiles; } } #endregion #region private properties and methods private CompilerState CompilerState { get { return _mcPass1.CompilerState; } } private CompilerLocalReference CompilerLocalReference { get { return _mcPass1.CompilerLocalReference; } } private ITaskFileService TaskFileService { get { return _mcPass1.TaskFileService; } } private DateTime LastCompileTime { get { DateTime nonSet = new DateTime(0); if (_lastCompileTime == nonSet) { _lastCompileTime = TaskFileService.GetLastChangeTime(CompilerState.CacheFilePath); } return _lastCompileTime; } } // // Compare two strings. // private bool IsSettingModified(string textSource, string textTarget) { bool IsSettingModified; bool isSrcEmpty = String.IsNullOrEmpty(textSource); bool istgtEmpty = String.IsNullOrEmpty(textTarget); if (isSrcEmpty != istgtEmpty) { IsSettingModified = true; } else { if (isSrcEmpty) // Both source and target strings are empty. { IsSettingModified = false; } else // Both source and target strings are not empty. { IsSettingModified = String.Compare(textSource, textTarget, StringComparison.OrdinalIgnoreCase) == 0 ? false : true; } } return IsSettingModified; } // // Generate new list of files that require to recompile for incremental build based on _analyzeResult // private void UpdateFileListForIncrementalBuild(List<FileUnit> modifiedXamlFiles) { List<FileUnit> recompiledXaml = new List<FileUnit>(); bool recompileApp = false; int numLocalTypeXamls = 0; if ((_analyzeResult & RecompileCategory.ContentFiles) == RecompileCategory.ContentFiles) { RecompileContentFiles(); } if ((_analyzeResult & RecompileCategory.ApplicationFile) == RecompileCategory.ApplicationFile) { recompileApp = true; } if ((_analyzeResult & RecompileCategory.PagesWithLocalType) == RecompileCategory.PagesWithLocalType && TaskFileService.IsRealBuild) { CompilerLocalReference.LoadCacheFile(); if (CompilerLocalReference.LocalApplicationFile != null) { // Application file contains local types, it will be recompiled. recompileApp = true; } if (ListIsNotEmpty(CompilerLocalReference.LocalMarkupPages)) { numLocalTypeXamls = CompilerLocalReference.LocalMarkupPages.Length; for (int i = 0; i < CompilerLocalReference.LocalMarkupPages.Length; i++) { LocalReferenceFile localRefFile = CompilerLocalReference.LocalMarkupPages[i]; recompiledXaml.Add(new FileUnit( localRefFile.FilePath, localRefFile.LinkAlias, localRefFile.LogicalName)); } } } if ((_analyzeResult & RecompileCategory.ModifiedPages) == RecompileCategory.ModifiedPages) { // If the xaml is already in the local-type-ref xaml file list, don't add a duplicate file path to recompiledXaml list. for (int i = 0; i < modifiedXamlFiles.Count; i++) { FileUnit xamlfile = modifiedXamlFiles[i]; bool addToList; addToList = true; if (numLocalTypeXamls > 0) { for (int j = 0; j < numLocalTypeXamls; j++) { if (String.Compare(xamlfile.Path, CompilerLocalReference.LocalMarkupPages[j].FilePath, StringComparison.OrdinalIgnoreCase) == 0) { addToList = false; break; } } } if (addToList) { recompiledXaml.Add(xamlfile); } } } if (recompiledXaml.Count > 0) { _recompileMarkupPages = recompiledXaml.ToArray(); } // Set ApplicationFile appropriatelly for this incremental build. ProcessApplicationFile(recompileApp); } // // To recompile all the xaml files ( including page and application file). // Transfer all the xaml files to the recompileMarkupPages. // private void UpdateFileListForCleanbuild() { if (ListIsNotEmpty(_mcPass1.PageMarkup)) { int count = _mcPass1.PageMarkup.Length; _recompileMarkupPages = new FileUnit[count]; for (int i = 0; i < count; i++) { ITaskItem taskItem = _mcPass1.PageMarkup[i]; _recompileMarkupPages[i] = new FileUnit( Path.GetFullPath(taskItem.ItemSpec), taskItem.GetMetadata(SharedStrings.Link), taskItem.GetMetadata(SharedStrings.LogicalName)); } } RecompileContentFiles(); ProcessApplicationFile(true); } // // Content files are only for Application target type. // private void RecompileContentFiles() { if (!_mcPass1.IsApplicationTarget) return; if (_contentFiles == null) { if (ListIsNotEmpty(_mcPass1.ContentFiles)) { string curDir = Directory.GetCurrentDirectory() + "\\"; int count = _mcPass1.ContentFiles.Length; _contentFiles = new string[count]; for (int i = 0; i < count; i++) { string fullPath = Path.GetFullPath(_mcPass1.ContentFiles[i].ItemSpec); string relContentFilePath = TaskHelper.GetRootRelativePath(curDir, fullPath); if (String.IsNullOrEmpty(relContentFilePath)) { relContentFilePath = Path.GetFileName(fullPath); } _contentFiles[i] = relContentFilePath; } } } } // // Handle Application definition xaml file and Application Class name. // recompile parameter indicates whether or not to recompile the appdef file. // If the appdef file is not recompiled, a specially handling is required to // take application class name from previous build. // private void ProcessApplicationFile(bool recompile) { if (!_mcPass1.IsApplicationTarget) { return; } if (recompile) { // // Take whatever setting in _mcPass1 task. // if (_mcPass1.ApplicationMarkup != null && _mcPass1.ApplicationMarkup.Length > 0 && _mcPass1.ApplicationMarkup[0] != null) { ITaskItem taskItem = _mcPass1.ApplicationMarkup[0]; _recompileApplicationFile = new FileUnit( _mcPass1.ApplicationFile, taskItem.GetMetadata(SharedStrings.Link), taskItem.GetMetadata(SharedStrings.LogicalName)); } else { _recompileApplicationFile = FileUnit.Empty; } } else { _recompileApplicationFile = FileUnit.Empty; } } // // Detect if at least one file in the same item list has changed since last build. // private bool IsFileListChanged(ITaskItem[] fileList) { bool isChanged = false; if (ListIsNotEmpty(fileList)) { for (int i = 0; i < fileList.Length; i++) { if (IsFileChanged(fileList[i].ItemSpec)) { isChanged = true; break; } } } return isChanged; } // // Detect if the input file was changed since last build. // private bool IsFileChanged(string inputFile) { bool isChanged = false; DateTime dtFile; dtFile = TaskFileService.GetLastChangeTime(inputFile); if (dtFile > LastCompileTime) { isChanged = true; } return isChanged; } // A helper to detect if the list is not empty. private bool ListIsNotEmpty(object [] list) { bool isNotEmpty = false; if (list != null && list.Length > 0) { isNotEmpty = true; } return isNotEmpty; } #endregion #region private data private MarkupCompilePass1 _mcPass1; private RecompileCategory _analyzeResult; private DateTime _lastCompileTime = new DateTime(0); private FileUnit[] _recompileMarkupPages = null; private FileUnit _recompileApplicationFile = FileUnit.Empty; private string[] _contentFiles = null; #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventHub { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ConsumerGroupsOperations. /// </summary> public static partial class ConsumerGroupsOperationsExtensions { /// <summary> /// Creates or updates an Event Hubs consumer group as a nested resource within /// a Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='consumerGroupName'> /// The consumer group name /// </param> /// <param name='parameters'> /// Parameters supplied to create or update a consumer group resource. /// </param> public static ConsumerGroup CreateOrUpdate(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, ConsumerGroup parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an Event Hubs consumer group as a nested resource within /// a Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='consumerGroupName'> /// The consumer group name /// </param> /// <param name='parameters'> /// Parameters supplied to create or update a consumer group resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConsumerGroup> CreateOrUpdateAsync(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, ConsumerGroup parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a consumer group from the specified Event Hub and resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='consumerGroupName'> /// The consumer group name /// </param> public static void Delete(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName) { operations.DeleteAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a consumer group from the specified Event Hub and resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='consumerGroupName'> /// The consumer group name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets a description for the specified consumer group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='consumerGroupName'> /// The consumer group name /// </param> public static ConsumerGroup Get(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName) { return operations.GetAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets a description for the specified consumer group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='consumerGroupName'> /// The consumer group name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ConsumerGroup> GetAsync(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string consumerGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, consumerGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the consumer groups in a Namespace. An empty feed is returned if /// no consumer group exists in the Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> public static IPage<ConsumerGroup> ListByEventHub(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName) { return operations.ListByEventHubAsync(resourceGroupName, namespaceName, eventHubName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the consumer groups in a Namespace. An empty feed is returned if /// no consumer group exists in the Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ConsumerGroup>> ListByEventHubAsync(this IConsumerGroupsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEventHubWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the consumer groups in a Namespace. An empty feed is returned if /// no consumer group exists in the Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ConsumerGroup> ListByEventHubNext(this IConsumerGroupsOperations operations, string nextPageLink) { return operations.ListByEventHubNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the consumer groups in a Namespace. An empty feed is returned if /// no consumer group exists in the Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ConsumerGroup>> ListByEventHubNextAsync(this IConsumerGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByEventHubNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using Autofac; using Autofac.Extensions.DependencyInjection; using Common.Log; using Lykke.AzureQueueIntegration; using Lykke.Common.ApiLibrary.Middleware; using Lykke.Common.ApiLibrary.Swagger; using Lykke.Logs; using Lykke.SettingsReader; using Lykke.SlackNotification.AzureQueue; using Lykke.SlackNotifications; using MarginTrading.Backend.Core; using MarginTrading.Backend.Core.MatchingEngines; using MarginTrading.Backend.Core.Settings; using MarginTrading.Backend.Filters; using MarginTrading.Backend.Infrastructure; using MarginTrading.Backend.Middleware; using MarginTrading.Backend.Modules; using MarginTrading.Backend.Services; using MarginTrading.Backend.Services.Infrastructure; using MarginTrading.Backend.Services.MatchingEngines; using MarginTrading.Backend.Services.Modules; using MarginTrading.Backend.Services.Quotes; using MarginTrading.Backend.Services.Settings; using MarginTrading.Backend.Services.TradingConditions; using MarginTrading.Common.Extensions; using MarginTrading.Common.Json; using MarginTrading.Common.Modules; using MarginTrading.Common.Services; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using GlobalErrorHandlerMiddleware = MarginTrading.Backend.Middleware.GlobalErrorHandlerMiddleware; using LogLevel = Microsoft.Extensions.Logging.LogLevel; #pragma warning disable 1591 namespace MarginTrading.Backend { public class Startup { public IConfigurationRoot Configuration { get; } public IHostingEnvironment Environment { get; } public IContainer ApplicationContainer { get; set; } public Startup(IHostingEnvironment env) { Configuration = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddDevJson(env) .AddEnvironmentVariables() .Build(); Environment = env; } public IServiceProvider ConfigureServices(IServiceCollection services) { var loggerFactory = new LoggerFactory() .AddConsole(LogLevel.Error) .AddDebug(LogLevel.Error); services.AddSingleton(loggerFactory); services.AddLogging(); services.AddSingleton(Configuration); services.AddMvc(options => options.Filters.Add(typeof(MarginTradingEnabledFilter))) .AddJsonOptions( options => { options.SerializerSettings.Converters = SerializerSettings.GetDefaultConverters(); }); services.AddAuthentication(KeyAuthOptions.AuthenticationScheme) .AddScheme<KeyAuthOptions, KeyAuthHandler>(KeyAuthOptions.AuthenticationScheme, "", options => { }); var isLive = Configuration.IsLive(); services.AddSwaggerGen(options => { options.DefaultLykkeConfiguration("v1", $"MarginTrading_Api_{Configuration.ServerType()}"); options.OperationFilter<ApiKeyHeaderOperationFilter>(); }); var builder = new ContainerBuilder(); var envSuffix = !string.IsNullOrEmpty(Configuration["Env"]) ? "." + Configuration["Env"] : ""; var mtSettings = Configuration.LoadSettings<MtBackendSettings>() .Nested(s => { var inner = isLive ? s.MtBackend.MarginTradingLive : s.MtBackend.MarginTradingDemo; inner.IsLive = isLive; inner.Env = Configuration.ServerType() + envSuffix; return s; }); var settings = mtSettings.Nested(s => isLive ? s.MtBackend.MarginTradingLive : s.MtBackend.MarginTradingDemo); var riskInformingSettings = mtSettings.Nested(s => isLive ? s.RiskInformingSettings : s.RiskInformingSettingsDemo); Console.WriteLine($"IsLive: {settings.CurrentValue.IsLive}"); SetupLoggers(services, mtSettings, settings); RegisterModules(builder, mtSettings, settings, Environment, riskInformingSettings); builder.Populate(services); ApplicationContainer = builder.Build(); MtServiceLocator.FplService = ApplicationContainer.Resolve<IFplService>(); MtServiceLocator.AccountUpdateService = ApplicationContainer.Resolve<IAccountUpdateService>(); MtServiceLocator.AccountsCacheService = ApplicationContainer.Resolve<IAccountsCacheService>(); MtServiceLocator.SwapCommissionService = ApplicationContainer.Resolve<ICommissionService>(); MtServiceLocator.OvernightSwapService = ApplicationContainer.Resolve<IOvernightSwapService>(); return new AutofacServiceProvider(ApplicationContainer); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime) { app.UseMiddleware<GlobalErrorHandlerMiddleware>(); app.UseMiddleware<MaintenanceModeMiddleware>(); app.UseAuthentication(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUi(); appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose()); var application = app.ApplicationServices.GetService<Application>(); var settings = app.ApplicationServices.GetService<MarginSettings>(); appLifetime.ApplicationStarted.Register(() => { if (!string.IsNullOrEmpty(settings.ApplicationInsightsKey)) { TelemetryConfiguration.Active.InstrumentationKey = settings.ApplicationInsightsKey; } LogLocator.CommonLog?.WriteMonitorAsync("", "", $"{Configuration.ServerType()} Started"); }); appLifetime.ApplicationStopping.Register(() => { LogLocator.CommonLog?.WriteMonitorAsync("", "", $"{Configuration.ServerType()} Terminating"); application.StopApplication(); } ); } private void RegisterModules(ContainerBuilder builder, IReloadingManager<MtBackendSettings> mtSettings, IReloadingManager<MarginSettings> settings, IHostingEnvironment environment, IReloadingManager<RiskInformingSettings> riskInformingSettings) { builder.RegisterModule(new BaseServicesModule(mtSettings.CurrentValue, LogLocator.CommonLog)); builder.RegisterModule(new BackendSettingsModule(mtSettings.CurrentValue, settings)); builder.RegisterModule(new BackendRepositoriesModule(settings, LogLocator.CommonLog)); builder.RegisterModule(new EventModule()); builder.RegisterModule(new CacheModule()); builder.RegisterModule(new ManagersModule()); builder.RegisterModule(new ServicesModule(riskInformingSettings)); builder.RegisterModule(new BackendServicesModule(mtSettings.CurrentValue, settings.CurrentValue, environment, LogLocator.CommonLog)); builder.RegisterModule(new MarginTradingCommonModule()); builder.RegisterModule(new ExternalServicesModule(mtSettings, LogLocator.CommonLog)); builder.RegisterModule(new BackendMigrationsModule()); builder.RegisterBuildCallback(c => c.Resolve<AccountAssetsManager>()); builder.RegisterBuildCallback(c => c.Resolve<OrderBookSaveService>()); builder.RegisterBuildCallback(c => c.Resolve<MicrographManager>()); builder.RegisterBuildCallback(c => c.Resolve<QuoteCacheService>()); builder.RegisterBuildCallback(c => c.Resolve<AccountManager>()); // note the order here is important! builder.RegisterBuildCallback(c => c.Resolve<OrderCacheManager>()); builder.RegisterBuildCallback(c => c.Resolve<PendingOrdersCleaningService>()); builder.RegisterBuildCallback(c => c.Resolve<IOvernightSwapService>()); } private static void SetupLoggers(IServiceCollection services, IReloadingManager<MtBackendSettings> mtSettings, IReloadingManager<MarginSettings> settings) { var consoleLogger = new LogToConsole(); var azureQueue = new AzureQueueSettings { ConnectionString = mtSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString, QueueName = mtSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName }; var commonSlackService = services.UseSlackNotificationsSenderViaAzureQueue(azureQueue, consoleLogger); var slackService = new MtSlackNotificationsSender(commonSlackService, "MT Backend", settings.CurrentValue.Env); services.AddSingleton<ISlackNotificationsSender>(slackService); services.AddSingleton<IMtSlackNotificationsSender>(slackService); // Order of logs registration is important - UseLogToAzureStorage() registers ILog in container. // Last registration wins. LogLocator.RequestsLog = services.UseLogToAzureStorage(settings.Nested(s => s.Db.LogsConnString), slackService, "MarginTradingBackendRequestsLog", consoleLogger); LogLocator.CommonLog = services.UseLogToAzureStorage(settings.Nested(s => s.Db.LogsConnString), slackService, "MarginTradingBackendLog", consoleLogger); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using TABS_UserControls.resources.code.BAL; using TABS_UserControls.resources.code.DAL; using System.Collections.Generic; namespace TABS_UserControls.usercontrols { public partial class job_board : System.Web.UI.UserControl { #region Variable Declarations private JobClass JobsBAL = new JobClass(); private tabs_admin TabsAdminBAL = new tabs_admin(); #endregion #region Event Handlers protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // Bind Categories BindCategories(); // Bind Job Types BindTypes(); // Bind Locations BindLocations(); // Bind Salary BindSalary(); // Bind CalendarYear Types BindCalendarYearTypes(); // See if we're coming back from a job detail page if (!String.IsNullOrEmpty(Request.QueryString["results"])) { // Get the DataTable DataTable dt = (DataTable)Session["TABS_JobBoard_DataTable"]; BindGrid(dt); pnlSearch.Visible = false; pnlResults.Visible = true; } else { // Check for any jobs if (JobsBAL.GetJobs().Rows.Count.Equals(0)) { // Show "no jobs" panel. pnlSearch.Visible = false; pnlResults.Visible = false; pnlNoResults.Visible = true; } } } } protected void btnSearch_Click(object sender, EventArgs e) { // Job Categories List<int> jobCategoryTypeIds = new List<int>(); for (int i = 0; i < cblJobCategories.Items.Count; i++) { if (cblJobCategories.Items[i].Selected) { jobCategoryTypeIds.Add(Convert.ToInt32(cblJobCategories.Items[i].Value)); } } // Job Types List<int> jobTypeIds = new List<int>(); for (int i = 0; i < cblJobTypes.Items.Count; i++) { if (cblJobTypes.Items[i].Selected) { jobTypeIds.Add(Convert.ToInt32(cblJobTypes.Items[i].Value)); } } // Calendar Year Types List<int> calendarYearTypeIds = new List<int>(); for (int i = 0; i < cblCalendarYear.Items.Count; i++) { if (cblCalendarYear.Items[i].Selected) { calendarYearTypeIds.Add(Convert.ToInt32(cblCalendarYear.Items[i].Value)); } } // Salaries List<int> salaryIds = new List<int>(); if (cbSalaryUnspecified.Checked) { salaryIds.Add(Convert.ToInt32(ddlSalary.Items.FindByText("Not Specified").Value)); } salaryIds.Add(Convert.ToInt32(ddlSalary.SelectedValue)); // Locations List<int> locationIds = new List<int>(); for (int i = 0; i < lbStates.Items.Count; i++) { if (lbStates.Items[i].Selected) { locationIds.Add(Convert.ToInt32(lbStates.Items[i].Value)); } } // Keywords string keywords = Utility.GetCleanString(tbKeywords.Text); keywords = String.IsNullOrEmpty(keywords) ? "|||" : keywords; // Search JobsDataset._tabs_JobsDataTable dt = JobsBAL.SearchJobs(jobCategoryTypeIds, keywords, jobTypeIds, calendarYearTypeIds, salaryIds, locationIds); // Bind Obout grid BindGrid(dt); pnlSearch.Visible = false; pnlResults.Visible = true; } protected void btnReset_Click(object sender, EventArgs e) { // Clear out any selections cblJobCategories.SelectedIndex = -1; tbKeywords.Text = string.Empty; cblJobTypes.SelectedIndex = -1; cblCalendarYear.SelectedIndex = -1; ddlSalary.SelectedIndex = -1; cbSalaryUnspecified.Checked = false; lbStates.SelectedIndex = -1; } protected void btnBackToSearch_Click(object sender, EventArgs e) { pnlSearch.Visible = true; pnlResults.Visible = false; } #endregion #region Methods private void BindCategories() { JobsDataset._tabs_JobCategoriesDataTable dt = JobsBAL.GetJobCategories(); cblJobCategories.DataSource = dt; cblJobCategories.DataBind(); } private void BindTypes() { JobsDataset._tabs_JobTypesDataTable dt = JobsBAL.GetJobTypes(); cblJobTypes.DataSource = dt; cblJobTypes.DataBind(); } private void BindLocations() { // Only get locations where there are jobs JobsDataset._tabs_JobsDataTable dtJobs = JobsBAL.GetJobs(); tabs_admin_dataset._tabs_schoolsDataTable dtSchools = null; tabs_admin_dataset._tabs_statesDataTable dtState = null; tabs_admin_dataset._tabs_statesDataTable dtStates = new tabs_admin_dataset._tabs_statesDataTable(); Hashtable htLocations = new Hashtable(); for (int i = 0; i < dtJobs.Rows.Count; i++) { dtSchools = TabsAdminBAL.getSchoolByID(dtJobs[i].SchoolId); dtState = TabsAdminBAL.GetState(dtSchools[0].stateid); if (!dtStates.Rows.Contains(dtState[0].stateid)) { DataRow dr = dtStates.NewRow(); dr["state"] = dtState[0].state; dr["stateid"] = dtState[0].stateid; dtStates.Rows.Add(dr); } } lbStates.DataSource = dtStates; lbStates.DataBind(); } private void BindSalary() { JobsDataset._tabs_JobSalariesDataTable dt = JobsBAL.GetJobSalaries(); ddlSalary.DataSource = dt; ddlSalary.DataBind(); } private void BindCalendarYearTypes() { JobsDataset._tabs_CalendarYearTypesDataTable dt = JobsBAL.GetCalendarYearTypes(); cblCalendarYear.DataSource = dt; cblCalendarYear.DataBind(); } private void BindGrid(DataTable dt) { // Store the DataTable in Session Session["TABS_JobBoard_DataTable"] = dt; gridResults.DataSource = dt; gridResults.DataBind(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { public partial struct ImmutableArray<T> { /// <summary> /// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/> /// instance without allocating memory. /// </summary> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))] public sealed class Builder : IList<T>, IReadOnlyList<T> { /// <summary> /// The backing array for the builder. /// </summary> private T[] _elements; /// <summary> /// The number of initialized elements in the array. /// </summary> private int _count; /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> /// <param name="capacity">The initial capacity of the internal array.</param> internal Builder(int capacity) { Requires.Range(capacity >= 0, nameof(capacity)); _elements = new T[capacity]; _count = 0; } /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> internal Builder() : this(8) { } /// <summary> /// Get and sets the length of the internal array. When set the internal array is /// reallocated to the given capacity if it is not already the specified length. /// </summary> public int Capacity { get { return _elements.Length; } set { if (value < _count) { throw new ArgumentException(SR.CapacityMustBeGreaterThanOrEqualToCount, paramName: nameof(value)); } if (value != _elements.Length) { if (value > 0) { var temp = new T[value]; if (_count > 0) { Array.Copy(_elements, 0, temp, 0, _count); } _elements = temp; } else { _elements = ImmutableArray<T>.Empty.array; } } } } /// <summary> /// Gets or sets the length of the builder. /// </summary> /// <remarks> /// If the value is decreased, the array contents are truncated. /// If the value is increased, the added elements are initialized to the default value of type <typeparamref name="T"/>. /// </remarks> public int Count { get { return _count; } set { Requires.Range(value >= 0, nameof(value)); if (value < _count) { // truncation mode // Clear the elements of the elements that are effectively removed. // PERF: Array.Clear works well for big arrays, // but may have too much overhead with small ones (which is the common case here) if (_count - value > 64) { Array.Clear(_elements, value, _count - value); } else { for (int i = value; i < this.Count; i++) { _elements[i] = default(T); } } } else if (value > _count) { // expansion this.EnsureCapacity(value); } _count = value; } } private static void ThrowIndexOutOfRangeException() => throw new IndexOutOfRangeException(); /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> /// <exception cref="IndexOutOfRangeException"> /// </exception> public T this[int index] { get { if (index >= this.Count) { ThrowIndexOutOfRangeException(); } return _elements[index]; } set { if (index >= this.Count) { ThrowIndexOutOfRangeException(); } _elements[index] = value; } } #if FEATURE_ITEMREFAPI /// <summary> /// Gets a read-only reference to the element at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> /// <exception cref="IndexOutOfRangeException"> /// </exception> public ref readonly T ItemRef(int index) { if (index >= this.Count) { ThrowIndexOutOfRangeException(); } return ref this._elements[index]; } #endif /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool ICollection<T>.IsReadOnly { get { return false; } } /// <summary> /// Returns an immutable copy of the current contents of this collection. /// </summary> /// <returns>An immutable array.</returns> public ImmutableArray<T> ToImmutable() { return new ImmutableArray<T>(this.ToArray()); } /// <summary> /// Extracts the internal array as an <see cref="ImmutableArray{T}"/> and replaces it /// with a zero length array. /// </summary> /// <exception cref="InvalidOperationException">When <see cref="ImmutableArray{T}.Builder.Count"/> doesn't /// equal <see cref="ImmutableArray{T}.Builder.Capacity"/>.</exception> public ImmutableArray<T> MoveToImmutable() { if (Capacity != Count) { throw new InvalidOperationException(SR.CapacityMustEqualCountOnMove); } T[] temp = _elements; _elements = ImmutableArray<T>.Empty.array; _count = 0; return new ImmutableArray<T>(temp); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> public void Clear() { this.Count = 0; } /// <summary> /// Inserts an item to the <see cref="IList{T}"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="IList{T}"/>.</param> public void Insert(int index, T item) { Requires.Range(index >= 0 && index <= this.Count, nameof(index)); this.EnsureCapacity(this.Count + 1); if (index < this.Count) { Array.Copy(_elements, index, _elements, index + 1, this.Count - index); } _count++; _elements[index] = item; } /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> public void Add(T item) { int newCount = _count + 1; this.EnsureCapacity(newCount); _elements[_count] = item; _count = newCount; } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(IEnumerable<T> items) { Requires.NotNull(items, nameof(items)); int count; if (items.TryGetCount(out count)) { this.EnsureCapacity(this.Count + count); if (items.TryCopyTo(_elements, _count)) { _count += count; return; } } foreach (var item in items) { this.Add(item); } } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(params T[] items) { Requires.NotNull(items, nameof(items)); var offset = this.Count; this.Count += items.Length; Array.Copy(items, 0, _elements, offset, items.Length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange<TDerived>(TDerived[] items) where TDerived : T { Requires.NotNull(items, nameof(items)); var offset = this.Count; this.Count += items.Length; Array.Copy(items, 0, _elements, offset, items.Length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> /// <param name="length">The number of elements from the source array to add.</param> public void AddRange(T[] items, int length) { Requires.NotNull(items, nameof(items)); Requires.Range(length >= 0 && length <= items.Length, nameof(length)); var offset = this.Count; this.Count += length; Array.Copy(items, 0, _elements, offset, length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(ImmutableArray<T> items) { this.AddRange(items, items.Length); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> /// <param name="length">The number of elements from the source array to add.</param> public void AddRange(ImmutableArray<T> items, int length) { Requires.Range(length >= 0, nameof(length)); if (items.array != null) { this.AddRange(items.array, length); } } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T { if (items.array != null) { this.AddRange(items.array); } } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange(Builder items) { Requires.NotNull(items, nameof(items)); this.AddRange(items._elements, items.Count); } /// <summary> /// Adds the specified items to the end of the array. /// </summary> /// <param name="items">The items.</param> public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T { Requires.NotNull(items, nameof(items)); this.AddRange(items._elements, items.Count); } /// <summary> /// Removes the specified element. /// </summary> /// <param name="element">The element.</param> /// <returns>A value indicating whether the specified element was found and removed from the collection.</returns> public bool Remove(T element) { int index = this.IndexOf(element); if (index >= 0) { this.RemoveAt(index); return true; } return false; } /// <summary> /// Removes the <see cref="IList{T}"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> public void RemoveAt(int index) { Requires.Range(index >= 0 && index < this.Count, nameof(index)); if (index < this.Count - 1) { Array.Copy(_elements, index + 1, _elements, index, this.Count - index - 1); } this.Count--; } /// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> public bool Contains(T item) { return this.IndexOf(item) >= 0; } /// <summary> /// Creates a new array with the current contents of this Builder. /// </summary> public T[] ToArray() { if (this.Count == 0) { return Empty.array; } T[] result = new T[this.Count]; Array.Copy(_elements, 0, result, 0, this.Count); return result; } /// <summary> /// Copies the current contents to the specified array. /// </summary> /// <param name="array">The array to copy to.</param> /// <param name="index">The starting index of the target array.</param> public void CopyTo(T[] array, int index) { Requires.NotNull(array, nameof(array)); Requires.Range(index >= 0 && index + this.Count <= array.Length, nameof(index)); Array.Copy(_elements, 0, array, index, this.Count); } /// <summary> /// Resizes the array to accommodate the specified capacity requirement. /// </summary> /// <param name="capacity">The required capacity.</param> private void EnsureCapacity(int capacity) { if (_elements.Length < capacity) { int newCapacity = Math.Max(_elements.Length * 2, capacity); Array.Resize(ref _elements, newCapacity); } } /// <summary> /// Determines the index of a specific item in the <see cref="IList{T}"/>. /// </summary> /// <param name="item">The object to locate in the <see cref="IList{T}"/>.</param> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> [Pure] public int IndexOf(T item) { return this.IndexOf(item, 0, _count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int IndexOf(T item, int startIndex) { return this.IndexOf(item, startIndex, this.Count - startIndex, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int IndexOf(T item, int startIndex, int count) { return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer"> /// The equality comparer to use in the search. /// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used. /// </param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer) { if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex)); Requires.Range(count >= 0 && startIndex + count <= this.Count, nameof(count)); equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; if (equalityComparer == EqualityComparer<T>.Default) { return Array.IndexOf(_elements, item, startIndex, count); } else { for (int i = startIndex; i < startIndex + count; i++) { if (equalityComparer.Equals(_elements[i], item)) { return i; } } return -1; } } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item) { if (this.Count == 0) { return -1; } return this.LastIndexOf(item, this.Count - 1, this.Count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item, int startIndex) { if (this.Count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex)); return this.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item, int startIndex, int count) { return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches the array for the specified item in reverse. /// </summary> /// <param name="item">The item to search for.</param> /// <param name="startIndex">The index at which to begin the search.</param> /// <param name="count">The number of elements to search.</param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns> [Pure] public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer) { if (count == 0 && startIndex == 0) { return -1; } Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex)); Requires.Range(count >= 0 && startIndex - count + 1 >= 0, nameof(count)); equalityComparer = equalityComparer ?? EqualityComparer<T>.Default; if (equalityComparer == EqualityComparer<T>.Default) { return Array.LastIndexOf(_elements, item, startIndex, count); } else { for (int i = startIndex; i >= startIndex - count + 1; i--) { if (equalityComparer.Equals(item, _elements[i])) { return i; } } return -1; } } /// <summary> /// Reverses the order of elements in the collection. /// </summary> public void Reverse() { // The non-generic Array.Reverse is not used because it does not perform // well for non-primitive value types. // If/when a generic Array.Reverse<T> becomes available, the below code // can be deleted and replaced with a call to Array.Reverse<T>. int i = 0; int j = _count - 1; T[] array = _elements; while (i < j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } } /// <summary> /// Sorts the array. /// </summary> public void Sort() { if (Count > 1) { Array.Sort(_elements, 0, this.Count, Comparer<T>.Default); } } /// <summary> /// Sorts the elements in the entire array using /// the specified <see cref="Comparison{T}"/>. /// </summary> /// <param name="comparison"> /// The <see cref="Comparison{T}"/> to use when comparing elements. /// </param> /// <exception cref="ArgumentNullException"><paramref name="comparison"/> is null.</exception> [Pure] public void Sort(Comparison<T> comparison) { Requires.NotNull(comparison, nameof(comparison)); if (Count > 1) { // Array.Sort does not have an overload that takes both bounds and a Comparison. // We could special case _count == _elements.Length in order to try to avoid // the IComparer allocation, but the Array.Sort overload that takes a Comparison // allocates such an IComparer internally, anyway. Array.Sort(_elements, 0, _count, Comparer<T>.Create(comparison)); } } /// <summary> /// Sorts the array. /// </summary> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public void Sort(IComparer<T> comparer) { if (Count > 1) { Array.Sort(_elements, 0, _count, comparer); } } /// <summary> /// Sorts the array. /// </summary> /// <param name="index">The index of the first element to consider in the sort.</param> /// <param name="count">The number of elements to include in the sort.</param> /// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param> public void Sort(int index, int count, IComparer<T> comparer) { // Don't rely on Array.Sort's argument validation since our internal array may exceed // the bounds of the publicly addressable region. Requires.Range(index >= 0, nameof(index)); Requires.Range(count >= 0 && index + count <= this.Count, nameof(count)); if (count > 1) { Array.Sort(_elements, index, count, comparer); } } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> public IEnumerator<T> GetEnumerator() { for (int i = 0; i < this.Count; i++) { yield return this[i]; } } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator for the contents of the array. /// </summary> /// <returns>An enumerator.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Adds items to this collection. /// </summary> /// <typeparam name="TDerived">The type of source elements.</typeparam> /// <param name="items">The source array.</param> /// <param name="length">The number of elements to add to this array.</param> private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T { this.EnsureCapacity(this.Count + length); var offset = this.Count; this.Count += length; var nodes = _elements; for (int i = 0; i < length; i++) { nodes[offset + i] = items[i]; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Threading; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { internal class EventLogInternal : IDisposable, ISupportInitialize { private EventLogEntryCollection entriesCollection; internal string logName; // used in monitoring for event postings. private int lastSeenCount; // holds the machine we're on, or null if it's the local machine internal readonly string machineName; // the delegate to call when an event arrives internal EntryWrittenEventHandler onEntryWrittenHandler; // holds onto the handle for reading private SafeEventLogReadHandle readHandle; // the source name - used only when writing internal readonly string sourceName; // holds onto the handle for writing private SafeEventLogWriteHandle writeHandle; private string logDisplayName; // cache system state variables // the initial size of the buffer (it can be made larger if necessary) private const int BUF_SIZE = 40000; // the number of bytes in the cache that belong to entries (not necessarily // the same as BUF_SIZE, because the cache only holds whole entries) private int bytesCached; // the actual cache buffer private byte[] cache; // the number of the entry at the beginning of the cache private int firstCachedEntry = -1; // the number of the entry that we got out of the cache most recently private int lastSeenEntry; // where that entry was private int lastSeenPos; //support for threadpool based deferred execution private ISynchronizeInvoke synchronizingObject; // the EventLog object that publicly exposes this instance. private readonly EventLog parent; private const string EventLogKey = "SYSTEM\\CurrentControlSet\\Services\\EventLog"; internal const string DllName = "EventLogMessages.dll"; private const string eventLogMutexName = "netfxeventlog.1.0"; private const int SecondsPerDay = 60 * 60 * 24; private const int DefaultMaxSize = 512 * 1024; private const int DefaultRetention = 7 * SecondsPerDay; private const int Flag_notifying = 0x1; // keeps track of whether we're notifying our listeners - to prevent double notifications private const int Flag_forwards = 0x2; // whether the cache contains entries in forwards order (true) or backwards (false) private const int Flag_initializing = 0x4; internal const int Flag_monitoring = 0x8; private const int Flag_registeredAsListener = 0x10; private const int Flag_writeGranted = 0x20; private const int Flag_disposed = 0x100; private const int Flag_sourceVerified = 0x200; private BitVector32 boolFlags = new BitVector32(); private Hashtable messageLibraries; private readonly static Hashtable listenerInfos = new Hashtable(StringComparer.OrdinalIgnoreCase); private Object m_InstanceLockObject; private Object InstanceLockObject { get { if (m_InstanceLockObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref m_InstanceLockObject, o, null); } return m_InstanceLockObject; } } private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } public EventLogInternal(string logName, string machineName) : this(logName, machineName, "", null) { } public EventLogInternal(string logName, string machineName, string source) : this(logName, machineName, source, null) { } public EventLogInternal(string logName, string machineName, string source, EventLog parent) { //look out for invalid log names if (logName == null) throw new ArgumentNullException(nameof(logName)); if (!ValidLogName(logName, true)) throw new ArgumentException(SR.BadLogName); if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); this.machineName = machineName; this.logName = logName; this.sourceName = source; readHandle = null; writeHandle = null; boolFlags[Flag_forwards] = true; this.parent = parent; } public EventLogEntryCollection Entries { get { string currentMachineName = this.machineName; if (entriesCollection == null) entriesCollection = new EventLogEntryCollection(this); return entriesCollection; } } internal int EntryCount { get { if (!IsOpenForRead) OpenForRead(this.machineName); int count; bool success = UnsafeNativeMethods.GetNumberOfEventLogRecords(readHandle, out count); if (!success) throw SharedUtils.CreateSafeWin32Exception(); return count; } } private bool IsOpen { get { return readHandle != null || writeHandle != null; } } private bool IsOpenForRead { get { return readHandle != null; } } private bool IsOpenForWrite { get { return writeHandle != null; } } public string LogDisplayName { get { if (logDisplayName != null) return logDisplayName; string currentMachineName = this.machineName; if (GetLogName(currentMachineName) != null) { RegistryKey logkey = null; try { // we figure out what logs are on the machine by looking in the registry. logkey = GetLogRegKey(currentMachineName, false); if (logkey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, GetLogName(currentMachineName), currentMachineName)); string resourceDll = (string)logkey.GetValue("DisplayNameFile"); if (resourceDll == null) logDisplayName = GetLogName(currentMachineName); else { int resourceId = (int)logkey.GetValue("DisplayNameID"); logDisplayName = FormatMessageWrapper(resourceDll, (uint)resourceId, null); if (logDisplayName == null) logDisplayName = GetLogName(currentMachineName); } } finally { logkey?.Close(); } } return logDisplayName; } } public string Log { get { string currentMachineName = this.machineName; return GetLogName(currentMachineName); } } private string GetLogName(string currentMachineName) { if ((logName == null || logName.Length == 0) && sourceName != null && sourceName.Length != 0) { logName = EventLog._InternalLogNameFromSourceName(sourceName, currentMachineName); } return logName; } public string MachineName { get { return this.machineName; } } public long MaximumKilobytes { get { string currentMachineName = this.machineName; object val = GetLogRegValue(currentMachineName, "MaxSize"); if (val != null) { int intval = (int)val; // cast to an int first to unbox return ((uint)intval) / 1024; // then convert to kilobytes } // 512k is the default value return 0x200; } set { string currentMachineName = this.machineName; // valid range is 64 KB to 4 GB if (value < 64 || value > 0x3FFFC0 || value % 64 != 0) throw new ArgumentOutOfRangeException("MaximumKilobytes", SR.MaximumKilobytesOutOfRange); long regvalue = value * 1024; // convert to bytes int i = unchecked((int)regvalue); using (RegistryKey logkey = GetLogRegKey(currentMachineName, true)) logkey.SetValue("MaxSize", i, RegistryValueKind.DWord); } } internal Hashtable MessageLibraries { get { if (messageLibraries == null) messageLibraries = new Hashtable(StringComparer.OrdinalIgnoreCase); return messageLibraries; } } public OverflowAction OverflowAction { get { string currentMachineName = this.machineName; object retentionobj = GetLogRegValue(currentMachineName, "Retention"); if (retentionobj != null) { int retention = (int)retentionobj; if (retention == 0) return OverflowAction.OverwriteAsNeeded; else if (retention == -1) return OverflowAction.DoNotOverwrite; else return OverflowAction.OverwriteOlder; } // default value as listed in MSDN return OverflowAction.OverwriteOlder; } } public int MinimumRetentionDays { get { string currentMachineName = this.machineName; object retentionobj = GetLogRegValue(currentMachineName, "Retention"); if (retentionobj != null) { int retention = (int)retentionobj; if (retention == 0 || retention == -1) return retention; else return (int)(((double)retention) / SecondsPerDay); } return 7; } } public bool EnableRaisingEvents { get { string currentMachineName = this.machineName; return boolFlags[Flag_monitoring]; } set { string currentMachineName = this.machineName; if (parent.ComponentDesignMode) this.boolFlags[Flag_monitoring] = value; else { if (value) StartRaisingEvents(currentMachineName, GetLogName(currentMachineName)); else StopRaisingEvents(/*currentMachineName,*/ GetLogName(currentMachineName)); } } } private int OldestEntryNumber { get { if (!IsOpenForRead) OpenForRead(this.machineName); int num; bool success = UnsafeNativeMethods.GetOldestEventLogRecord(readHandle, out num); if (!success) throw SharedUtils.CreateSafeWin32Exception(); if (num == 0) num = 1; return num; } } internal SafeEventLogReadHandle ReadHandle { get { if (!IsOpenForRead) OpenForRead(this.machineName); return readHandle; } } public ISynchronizeInvoke SynchronizingObject { get { string currentMachineName = this.machineName; if (this.synchronizingObject == null && parent.ComponentDesignMode) { IDesignerHost host = (IDesignerHost)parent.ComponentGetService(typeof(IDesignerHost)); if (host != null) { object baseComponent = host.RootComponent; if (baseComponent != null && baseComponent is ISynchronizeInvoke) this.synchronizingObject = (ISynchronizeInvoke)baseComponent; } } return this.synchronizingObject; } set { this.synchronizingObject = value; } } public string Source { get { string currentMachineName = this.machineName; return sourceName; } } private static void AddListenerComponent(EventLogInternal component, string compMachineName, string compLogName) { lock (InternalSyncObject) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::AddListenerComponent(" + compLogName + ")"); LogListeningInfo info = (LogListeningInfo)listenerInfos[compLogName]; if (info != null) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::AddListenerComponent: listener already active."); info.listeningComponents.Add(component); return; } info = new LogListeningInfo(); info.listeningComponents.Add(component); info.handleOwner = new EventLogInternal(compLogName, compMachineName); // tell the event log system about it info.waitHandle = new AutoResetEvent(false); bool success = UnsafeNativeMethods.NotifyChangeEventLog(info.handleOwner.ReadHandle, info.waitHandle.SafeWaitHandle); if (!success) throw new InvalidOperationException(SR.CantMonitorEventLog, SharedUtils.CreateSafeWin32Exception()); info.registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(info.waitHandle, new WaitOrTimerCallback(StaticCompletionCallback), info, -1, false); listenerInfos[compLogName] = info; } } public event EntryWrittenEventHandler EntryWritten { add { string currentMachineName = this.machineName; onEntryWrittenHandler += value; } remove { string currentMachineName = this.machineName; onEntryWrittenHandler -= value; } } public void BeginInit() { string currentMachineName = this.machineName; if (boolFlags[Flag_initializing]) throw new InvalidOperationException(SR.InitTwice); boolFlags[Flag_initializing] = true; if (boolFlags[Flag_monitoring]) StopListening(GetLogName(currentMachineName)); } public void Clear() { string currentMachineName = this.machineName; if (!IsOpenForRead) OpenForRead(currentMachineName); bool success = UnsafeNativeMethods.ClearEventLog(readHandle, NativeMethods.NullHandleRef); if (!success) { // Ignore file not found errors. ClearEventLog seems to try to delete the file where the event log is // stored. If it can't find it, it gives an error. int error = Marshal.GetLastWin32Error(); if (error != NativeMethods.ERROR_FILE_NOT_FOUND) throw SharedUtils.CreateSafeWin32Exception(); } // now that we've cleared the event log, we need to re-open our handles, because // the internal state of the event log has changed. Reset(currentMachineName); } public void Close() { Close(this.machineName); } private void Close(string currentMachineName) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Close"); //Trace("Close", "Closing the event log"); if (readHandle != null) { try { readHandle.Close(); } catch (IOException) { throw SharedUtils.CreateSafeWin32Exception(); } readHandle = null; //Trace("Close", "Closed read handle"); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Close: closed read handle"); } if (writeHandle != null) { try { writeHandle.Close(); } catch (IOException) { throw SharedUtils.CreateSafeWin32Exception(); } writeHandle = null; //Trace("Close", "Closed write handle"); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Close: closed write handle"); } if (boolFlags[Flag_monitoring]) StopRaisingEvents(/*currentMachineName,*/ GetLogName(currentMachineName)); if (messageLibraries != null) { foreach (SafeLibraryHandle handle in messageLibraries.Values) handle.Close(); messageLibraries = null; } boolFlags[Flag_sourceVerified] = false; } private void CompletionCallback(object context) { if (boolFlags[Flag_disposed]) { // This object has been disposed previously, ignore firing the event. return; } Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: starting at " + lastSeenCount.ToString(CultureInfo.InvariantCulture)); lock (InstanceLockObject) { if (boolFlags[Flag_notifying]) { // don't do double notifications. Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: aborting because we're already notifying."); return; } boolFlags[Flag_notifying] = true; } int i = lastSeenCount; try { int oldest = OldestEntryNumber; int count = EntryCount + oldest; // Ensure lastSeenCount is within bounds. This deals with the case where the event log has been cleared between // notifications. if (lastSeenCount < oldest || lastSeenCount > count) { lastSeenCount = oldest; i = lastSeenCount; } Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: OldestEntryNumber is " + OldestEntryNumber + ", EntryCount is " + EntryCount); while (i < count) { while (i < count) { EventLogEntry entry = GetEntryWithOldest(i); if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) this.SynchronizingObject.BeginInvoke(this.onEntryWrittenHandler, new object[] { this, new EntryWrittenEventArgs(entry) }); else onEntryWrittenHandler(this, new EntryWrittenEventArgs(entry)); i++; } oldest = OldestEntryNumber; count = EntryCount + oldest; } } catch (Exception e) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: Caught exception notifying event handlers: " + e.ToString()); } try { // if the user cleared the log while we were receiving events, the call to GetEntryWithOldest above could have // thrown an exception and i could be too large. Make sure we don't set lastSeenCount to something bogus. int newCount = EntryCount + OldestEntryNumber; if (i > newCount) lastSeenCount = newCount; else lastSeenCount = i; Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: finishing at " + lastSeenCount.ToString(CultureInfo.InvariantCulture)); } catch (Win32Exception e) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::CompletionStatusChanged: Caught exception updating last entry number: " + e.ToString()); } lock (InstanceLockObject) { boolFlags[Flag_notifying] = false; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } internal void Dispose(bool disposing) { try { if (disposing) { //Dispose unmanaged and managed resources if (IsOpen) { Close(); } // This is probably unnecessary if (readHandle != null) { readHandle.Close(); readHandle = null; } if (writeHandle != null) { writeHandle.Close(); writeHandle = null; } } } finally { messageLibraries = null; this.boolFlags[Flag_disposed] = true; } } public void EndInit() { string currentMachineName = this.machineName; boolFlags[Flag_initializing] = false; if (boolFlags[Flag_monitoring]) StartListening(currentMachineName, GetLogName(currentMachineName)); } internal string FormatMessageWrapper(string dllNameList, uint messageNum, string[] insertionStrings) { if (dllNameList == null) return null; if (insertionStrings == null) insertionStrings = new string[0]; string[] listDll = dllNameList.Split(';'); // Find first mesage in DLL list foreach (string dllName in listDll) { if (dllName == null || dllName.Length == 0) continue; SafeLibraryHandle hModule = null; if (IsOpen) { hModule = MessageLibraries[dllName] as SafeLibraryHandle; if (hModule == null || hModule.IsInvalid) { hModule = Interop.Kernel32.LoadLibraryExW(dllName, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE); MessageLibraries[dllName] = hModule; } } else { hModule = Interop.Kernel32.LoadLibraryExW(dllName, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE); } if (hModule.IsInvalid) continue; string msg = null; try { msg = EventLog.TryFormatMessage(hModule, messageNum, insertionStrings); } finally { if (!IsOpen) { hModule.Close(); } } if (msg != null) { return msg; } } return null; } internal EventLogEntry[] GetAllEntries() { // we could just call getEntryAt() on all the entries, but it'll be faster // if we grab multiple entries at once. string currentMachineName = this.machineName; if (!IsOpenForRead) OpenForRead(currentMachineName); EventLogEntry[] entries = new EventLogEntry[EntryCount]; int idx = 0; int oldestEntry = OldestEntryNumber; int bytesRead; int minBytesNeeded; int error = 0; while (idx < entries.Length) { byte[] buf = new byte[BUF_SIZE]; bool success = UnsafeNativeMethods.ReadEventLog(readHandle, NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ, oldestEntry + idx, buf, buf.Length, out bytesRead, out minBytesNeeded); if (!success) { error = Marshal.GetLastWin32Error(); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "Error from ReadEventLog is " + error.ToString(CultureInfo.InvariantCulture)); if (error == Interop.Kernel32.ERROR_INSUFFICIENT_BUFFER || error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) { if (error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) { Reset(currentMachineName); } // try again with a bigger buffer if necessary else if (minBytesNeeded > buf.Length) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "Increasing buffer size from " + buf.Length.ToString(CultureInfo.InvariantCulture) + " to " + minBytesNeeded.ToString(CultureInfo.InvariantCulture) + " bytes"); buf = new byte[minBytesNeeded]; } success = UnsafeNativeMethods.ReadEventLog(readHandle, NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ, oldestEntry + idx, buf, buf.Length, out bytesRead, out minBytesNeeded); if (!success) break; } else { break; } error = 0; } entries[idx] = new EventLogEntry(buf, 0, this); int sum = IntFrom(buf, 0); idx++; while (sum < bytesRead && idx < entries.Length) { entries[idx] = new EventLogEntry(buf, sum, this); sum += IntFrom(buf, sum); idx++; } } if (idx != entries.Length) { if (error != 0) throw new InvalidOperationException(SR.CantRetrieveEntries, SharedUtils.CreateSafeWin32Exception(error)); else throw new InvalidOperationException(SR.CantRetrieveEntries); } return entries; } private int GetCachedEntryPos(int entryIndex) { if (cache == null || (boolFlags[Flag_forwards] && entryIndex < firstCachedEntry) || (!boolFlags[Flag_forwards] && entryIndex > firstCachedEntry) || firstCachedEntry == -1) { // the index falls before anything we have in the cache, or the cache // is not yet valid return -1; } while (lastSeenEntry < entryIndex) { lastSeenEntry++; if (boolFlags[Flag_forwards]) { lastSeenPos = GetNextEntryPos(lastSeenPos); if (lastSeenPos >= bytesCached) break; } else { lastSeenPos = GetPreviousEntryPos(lastSeenPos); if (lastSeenPos < 0) break; } } while (lastSeenEntry > entryIndex) { lastSeenEntry--; if (boolFlags[Flag_forwards]) { lastSeenPos = GetPreviousEntryPos(lastSeenPos); if (lastSeenPos < 0) break; } else { lastSeenPos = GetNextEntryPos(lastSeenPos); if (lastSeenPos >= bytesCached) break; } } if (lastSeenPos >= bytesCached) { // we ran past the end. move back to the last one and return -1 lastSeenPos = GetPreviousEntryPos(lastSeenPos); if (boolFlags[Flag_forwards]) lastSeenEntry--; else lastSeenEntry++; return -1; } else if (lastSeenPos < 0) { // we ran past the beginning. move back to the first one and return -1 lastSeenPos = 0; if (boolFlags[Flag_forwards]) lastSeenEntry++; else lastSeenEntry--; return -1; } else { // we found it. return lastSeenPos; } } internal EventLogEntry GetEntryAt(int index) { EventLogEntry entry = GetEntryAtNoThrow(index); if (entry == null) throw new ArgumentException(SR.Format(SR.IndexOutOfBounds, index.ToString(CultureInfo.CurrentCulture))); return entry; } internal EventLogEntry GetEntryAtNoThrow(int index) { if (!IsOpenForRead) OpenForRead(this.machineName); if (index < 0 || index >= EntryCount) return null; index += OldestEntryNumber; EventLogEntry entry = null; try { entry = GetEntryWithOldest(index); } catch (InvalidOperationException) { } return entry; } private EventLogEntry GetEntryWithOldest(int index) { EventLogEntry entry = null; int entryPos = GetCachedEntryPos(index); if (entryPos >= 0) { entry = new EventLogEntry(cache, entryPos, this); return entry; } string currentMachineName = this.machineName; int flags = 0; if (GetCachedEntryPos(index + 1) < 0) { flags = NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ; boolFlags[Flag_forwards] = true; } else { flags = NativeMethods.BACKWARDS_READ | NativeMethods.SEEK_READ; boolFlags[Flag_forwards] = false; } cache = new byte[BUF_SIZE]; int bytesRead; int minBytesNeeded; bool success = UnsafeNativeMethods.ReadEventLog(readHandle, flags, index, cache, cache.Length, out bytesRead, out minBytesNeeded); if (!success) { int error = Marshal.GetLastWin32Error(); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "Error from ReadEventLog is " + error.ToString(CultureInfo.InvariantCulture)); if (error == Interop.Kernel32.ERROR_INSUFFICIENT_BUFFER || error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) { if (error == NativeMethods.ERROR_EVENTLOG_FILE_CHANGED) { byte[] tempcache = cache; Reset(currentMachineName); cache = tempcache; } else { // try again with a bigger buffer. if (minBytesNeeded > cache.Length) { cache = new byte[minBytesNeeded]; } } success = UnsafeNativeMethods.ReadEventLog(readHandle, NativeMethods.FORWARDS_READ | NativeMethods.SEEK_READ, index, cache, cache.Length, out bytesRead, out minBytesNeeded); } if (!success) { throw new InvalidOperationException(SR.Format(SR.CantReadLogEntryAt, index.ToString(CultureInfo.CurrentCulture)), SharedUtils.CreateSafeWin32Exception()); } } bytesCached = bytesRead; firstCachedEntry = index; lastSeenEntry = index; lastSeenPos = 0; return new EventLogEntry(cache, 0, this); } internal static RegistryKey GetEventLogRegKey(string machine, bool writable) { RegistryKey lmkey = null; try { if (machine.Equals(".")) { lmkey = Registry.LocalMachine; } else { lmkey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine); } if (lmkey != null) return lmkey.OpenSubKey(EventLogKey, writable); } finally { lmkey?.Close(); } return null; } private RegistryKey GetLogRegKey(string currentMachineName, bool writable) { string logname = GetLogName(currentMachineName); if (!ValidLogName(logname, false)) throw new InvalidOperationException(SR.BadLogName); RegistryKey eventkey = null; RegistryKey logkey = null; try { eventkey = GetEventLogRegKey(currentMachineName, false); if (eventkey == null) throw new InvalidOperationException(SR.Format(SR.RegKeyMissingShort, EventLogKey, currentMachineName)); logkey = eventkey.OpenSubKey(logname, writable); if (logkey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, logname, currentMachineName)); } finally { eventkey?.Close(); } return logkey; } private object GetLogRegValue(string currentMachineName, string valuename) { RegistryKey logkey = null; try { logkey = GetLogRegKey(currentMachineName, false); if (logkey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, GetLogName(currentMachineName), currentMachineName)); object val = logkey.GetValue(valuename); return val; } finally { logkey?.Close(); } } private int GetNextEntryPos(int pos) { return pos + IntFrom(cache, pos); } private int GetPreviousEntryPos(int pos) { return pos - IntFrom(cache, pos - 4); } internal static string GetDllPath(string machineName) { return Path.Combine(SharedUtils.GetLatestBuildDllDirectory(machineName), DllName); } private static int IntFrom(byte[] buf, int offset) { // assumes Little Endian byte order. return (unchecked((int)0xFF000000) & (buf[offset + 3] << 24)) | (0xFF0000 & (buf[offset + 2] << 16)) | (0xFF00 & (buf[offset + 1] << 8)) | (0xFF & (buf[offset])); } public void ModifyOverflowPolicy(OverflowAction action, int retentionDays) { string currentMachineName = this.machineName; if (action < OverflowAction.DoNotOverwrite || action > OverflowAction.OverwriteOlder) throw new InvalidEnumArgumentException("action", (int)action, typeof(OverflowAction)); // this is a long because in the if statement we may need to store values as // large as UInt32.MaxValue - 1. This would overflow an int. long retentionvalue = (long)action; if (action == OverflowAction.OverwriteOlder) { if (retentionDays < 1 || retentionDays > 365) throw new ArgumentOutOfRangeException(SR.RentionDaysOutOfRange); retentionvalue = (long)retentionDays * SecondsPerDay; } using (RegistryKey logkey = GetLogRegKey(currentMachineName, true)) logkey.SetValue("Retention", retentionvalue, RegistryValueKind.DWord); } private void OpenForRead(string currentMachineName) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::OpenForRead"); if (this.boolFlags[Flag_disposed]) throw new ObjectDisposedException(GetType().Name); string logname = GetLogName(currentMachineName); if (logname == null || logname.Length == 0) throw new ArgumentException(SR.MissingLogProperty); if (!EventLog.Exists(logname, currentMachineName)) // do not open non-existing Log [alexvec] throw new InvalidOperationException(SR.Format(SR.LogDoesNotExists, logname, currentMachineName)); // Clean up cache variables. // The initilizing code is put here to guarantee, that first read of events // from log file will start by filling up the cache buffer. lastSeenEntry = 0; lastSeenPos = 0; bytesCached = 0; firstCachedEntry = -1; SafeEventLogReadHandle handle = SafeEventLogReadHandle.OpenEventLog(currentMachineName, logname); if (handle.IsInvalid) { Win32Exception e = null; if (Marshal.GetLastWin32Error() != 0) { e = SharedUtils.CreateSafeWin32Exception(); } throw new InvalidOperationException(SR.Format(SR.CantOpenLog, logname.ToString(), currentMachineName, e?.Message ?? "")); } readHandle = handle; } private void OpenForWrite(string currentMachineName) { //Cannot allocate the writeHandle if the object has been disposed, since finalization has been suppressed. if (this.boolFlags[Flag_disposed]) throw new ObjectDisposedException(GetType().Name); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::OpenForWrite"); if (sourceName == null || sourceName.Length == 0) throw new ArgumentException(SR.NeedSourceToOpen); SafeEventLogWriteHandle handle = SafeEventLogWriteHandle.RegisterEventSource(currentMachineName, sourceName); if (handle.IsInvalid) { Win32Exception e = null; if (Marshal.GetLastWin32Error() != 0) { e = SharedUtils.CreateSafeWin32Exception(); } throw new InvalidOperationException(SR.Format(SR.CantOpenLogAccess, sourceName), e); } writeHandle = handle; } public void RegisterDisplayName(string resourceFile, long resourceId) { string currentMachineName = this.machineName; using (RegistryKey logkey = GetLogRegKey(currentMachineName, true)) { logkey.SetValue("DisplayNameFile", resourceFile, RegistryValueKind.ExpandString); logkey.SetValue("DisplayNameID", resourceId, RegistryValueKind.DWord); } } private void Reset(string currentMachineName) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::Reset"); // save the state we're in now bool openRead = IsOpenForRead; bool openWrite = IsOpenForWrite; bool isMonitoring = boolFlags[Flag_monitoring]; bool isListening = boolFlags[Flag_registeredAsListener]; // close everything down Close(currentMachineName); cache = null; // and get us back into the same state as before if (openRead) OpenForRead(currentMachineName); if (openWrite) OpenForWrite(currentMachineName); if (isListening) StartListening(currentMachineName, GetLogName(currentMachineName)); boolFlags[Flag_monitoring] = isMonitoring; } [HostProtection(Synchronization = true)] private static void RemoveListenerComponent(EventLogInternal component, string compLogName) { lock (InternalSyncObject) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::RemoveListenerComponent(" + compLogName + ")"); LogListeningInfo info = (LogListeningInfo)listenerInfos[compLogName]; Debug.Assert(info != null); // remove the requested component from the list. info.listeningComponents.Remove(component); if (info.listeningComponents.Count != 0) return; // if that was the last interested compononent, destroy the handles and stop listening. info.handleOwner.Dispose(); //Unregister the thread pool wait handle info.registeredWaitHandle.Unregister(info.waitHandle); // close the handle info.waitHandle.Close(); listenerInfos[compLogName] = null; } } private void StartListening(string currentMachineName, string currentLogName) { // make sure we don't fire events for entries that are already there Debug.Assert(!boolFlags[Flag_registeredAsListener], "StartListening called with boolFlags[Flag_registeredAsListener] true."); lastSeenCount = EntryCount + OldestEntryNumber; Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::StartListening: lastSeenCount = " + lastSeenCount); AddListenerComponent(this, currentMachineName, currentLogName); boolFlags[Flag_registeredAsListener] = true; } private void StartRaisingEvents(string currentMachineName, string currentLogName) { if (!boolFlags[Flag_initializing] && !boolFlags[Flag_monitoring] && !parent.ComponentDesignMode) { StartListening(currentMachineName, currentLogName); } boolFlags[Flag_monitoring] = true; } private static void StaticCompletionCallback(object context, bool wasSignaled) { LogListeningInfo info = (LogListeningInfo)context; if (info == null) return; // get a snapshot of the components to fire the event on EventLogInternal[] interestedComponents; lock (InternalSyncObject) { interestedComponents = (EventLogInternal[])info.listeningComponents.ToArray(typeof(EventLogInternal)); } Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::StaticCompletionCallback: notifying " + interestedComponents.Length + " components."); for (int i = 0; i < interestedComponents.Length; i++) { try { if (interestedComponents[i] != null) { interestedComponents[i].CompletionCallback(null); } } catch (ObjectDisposedException) { // The EventLog that was registered to listen has been disposed. Nothing much we can do here // we don't want to propigate this error up as it will likely be unhandled and will cause the app // to crash. Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "EventLog::StaticCompletionCallback: ignored an ObjectDisposedException"); } } } private void StopListening(/*string currentMachineName,*/ string currentLogName) { Debug.Assert(boolFlags[Flag_registeredAsListener], "StopListening called without StartListening."); RemoveListenerComponent(this, currentLogName); boolFlags[Flag_registeredAsListener] = false; } private void StopRaisingEvents(/*string currentMachineName,*/ string currentLogName) { if (!boolFlags[Flag_initializing] && boolFlags[Flag_monitoring] && !parent.ComponentDesignMode) { StopListening(currentLogName); } boolFlags[Flag_monitoring] = false; } private static bool CharIsPrintable(char c) { UnicodeCategory uc = Char.GetUnicodeCategory(c); return (!(uc == UnicodeCategory.Control) || (uc == UnicodeCategory.Format) || (uc == UnicodeCategory.LineSeparator) || (uc == UnicodeCategory.ParagraphSeparator) || (uc == UnicodeCategory.OtherNotAssigned)); } internal static bool ValidLogName(string logName, bool ignoreEmpty) { if (logName.Length == 0 && !ignoreEmpty) return false; //any space, backslash, asterisk, or question mark is bad //any non-printable characters are also bad foreach (char c in logName) if (!CharIsPrintable(c) || (c == '\\') || (c == '*') || (c == '?')) return false; return true; } private void VerifyAndCreateSource(string sourceName, string currentMachineName) { if (boolFlags[Flag_sourceVerified]) return; if (!EventLog.SourceExists(sourceName, currentMachineName, true)) { Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { SharedUtils.EnterMutex(eventLogMutexName, ref mutex); if (!EventLog.SourceExists(sourceName, currentMachineName, true)) { if (GetLogName(currentMachineName) == null) this.logName = "Application"; // we automatically add an entry in the registry if there's not already // one there for this source EventLog.CreateEventSource(new EventSourceCreationData(sourceName, GetLogName(currentMachineName), currentMachineName)); // The user may have set a custom log and tried to read it before trying to // write. Due to a quirk in the event log API, we would have opened the Application // log to read (because the custom log wasn't there). Now that we've created // the custom log, we should close so that when we re-open, we get a read // handle on the _new_ log instead of the Application log. Reset(currentMachineName); } else { string rightLogName = EventLog.LogNameFromSourceName(sourceName, currentMachineName); string currentLogName = GetLogName(currentMachineName); if (rightLogName != null && currentLogName != null && String.Compare(rightLogName, currentLogName, StringComparison.OrdinalIgnoreCase) != 0) throw new ArgumentException(SR.Format(SR.LogSourceMismatch, Source.ToString(), currentLogName, rightLogName)); } } finally { if (mutex != null) { mutex.ReleaseMutex(); mutex.Close(); } } } else { string rightLogName = EventLog._InternalLogNameFromSourceName(sourceName, currentMachineName); string currentLogName = GetLogName(currentMachineName); if (rightLogName != null && currentLogName != null && String.Compare(rightLogName, currentLogName, StringComparison.OrdinalIgnoreCase) != 0) throw new ArgumentException(SR.Format(SR.LogSourceMismatch, Source.ToString(), currentLogName, rightLogName)); } boolFlags[Flag_sourceVerified] = true; } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, byte[] rawData) { if (eventID < 0 || eventID > ushort.MaxValue) throw new ArgumentException(SR.Format(SR.EventID, eventID.ToString(), 0, ushort.MaxValue)); if (Source.Length == 0) throw new ArgumentException(SR.NeedSourceToWrite); if (!Enum.IsDefined(typeof(EventLogEntryType), type)) throw new InvalidEnumArgumentException(nameof(type), (int)type, typeof(EventLogEntryType)); string currentMachineName = machineName; if (!boolFlags[Flag_writeGranted]) { boolFlags[Flag_writeGranted] = true; } VerifyAndCreateSource(sourceName, currentMachineName); // now that the source has been hooked up to our DLL, we can use "normal" // (message-file driven) logging techniques. // Our DLL has 64K different entries; all of them just display the first // insertion string. InternalWriteEvent((uint)eventID, (ushort)category, type, new string[] { message }, rawData, currentMachineName); } public void WriteEvent(EventInstance instance, byte[] data, params Object[] values) { if (instance == null) throw new ArgumentNullException(nameof(instance)); if (Source.Length == 0) throw new ArgumentException(SR.NeedSourceToWrite); string currentMachineName = machineName; if (!boolFlags[Flag_writeGranted]) { boolFlags[Flag_writeGranted] = true; } VerifyAndCreateSource(Source, currentMachineName); string[] strings = null; if (values != null) { strings = new string[values.Length]; for (int i = 0; i < values.Length; i++) { if (values[i] != null) strings[i] = values[i].ToString(); else strings[i] = String.Empty; } } InternalWriteEvent((uint)instance.InstanceId, (ushort)instance.CategoryId, instance.EntryType, strings, data, currentMachineName); } private void InternalWriteEvent(uint eventID, ushort category, EventLogEntryType type, string[] strings, byte[] rawData, string currentMachineName) { // check arguments if (strings == null) strings = new string[0]; if (strings.Length >= 256) throw new ArgumentException(SR.TooManyReplacementStrings); for (int i = 0; i < strings.Length; i++) { if (strings[i] == null) strings[i] = String.Empty; // make sure the strings aren't too long. MSDN says each string has a limit of 32k (32768) characters, but // experimentation shows that it doesn't like anything larger than 32766 if (strings[i].Length > 32766) throw new ArgumentException(SR.LogEntryTooLong); } if (rawData == null) rawData = new byte[0]; if (Source.Length == 0) throw new ArgumentException(SR.NeedSourceToWrite); if (!IsOpenForWrite) OpenForWrite(currentMachineName); // pin each of the strings in memory IntPtr[] stringRoots = new IntPtr[strings.Length]; GCHandle[] stringHandles = new GCHandle[strings.Length]; GCHandle stringsRootHandle = GCHandle.Alloc(stringRoots, GCHandleType.Pinned); try { for (int strIndex = 0; strIndex < strings.Length; strIndex++) { stringHandles[strIndex] = GCHandle.Alloc(strings[strIndex], GCHandleType.Pinned); stringRoots[strIndex] = stringHandles[strIndex].AddrOfPinnedObject(); } byte[] sid = null; // actually report the event bool success = UnsafeNativeMethods.ReportEvent(writeHandle, (short)type, category, eventID, sid, (short)strings.Length, rawData.Length, new HandleRef(this, stringsRootHandle.AddrOfPinnedObject()), rawData); if (!success) { // Trace("WriteEvent", "Throwing Win32Exception"); throw SharedUtils.CreateSafeWin32Exception(); } } finally { // now free the pinned strings for (int i = 0; i < strings.Length; i++) { if (stringHandles[i].IsAllocated) stringHandles[i].Free(); } stringsRootHandle.Free(); } } private class LogListeningInfo { public EventLogInternal handleOwner; public RegisteredWaitHandle registeredWaitHandle; public WaitHandle waitHandle; public ArrayList listeningComponents = new ArrayList(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Threading; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Portable; using Apache.Ignite.Core.Transactions; /// <summary> /// Managed environment. Acts as a gateway for native code. /// </summary> [StructLayout(LayoutKind.Sequential)] internal static class ExceptionUtils { /** NoClassDefFoundError fully-qualified class name which is important during startup phase. */ private const string ClsNoClsDefFoundErr = "java.lang.NoClassDefFoundError"; /** NoSuchMethodError fully-qualified class name which is important during startup phase. */ private const string ClsNoSuchMthdErr = "java.lang.NoSuchMethodError"; /** InteropCachePartialUpdateException. */ private const string ClsCachePartialUpdateErr = "org.apache.ignite.internal.processors.platform.cache.PlatformCachePartialUpdateException"; /** Map with predefined exceptions. */ private static readonly IDictionary<string, ExceptionFactoryDelegate> EXS = new Dictionary<string, ExceptionFactoryDelegate>(); /** Exception factory delegate. */ private delegate Exception ExceptionFactoryDelegate(string msg); /// <summary> /// Static initializer. /// </summary> static ExceptionUtils() { // Common Java exceptions mapped to common .Net exceptions. EXS["java.lang.IllegalArgumentException"] = m => new ArgumentException(m); EXS["java.lang.IllegalStateException"] = m => new InvalidOperationException(m); EXS["java.lang.UnsupportedOperationException"] = m => new NotImplementedException(m); EXS["java.lang.InterruptedException"] = m => new ThreadInterruptedException(m); // Generic Ignite exceptions. EXS["org.apache.ignite.IgniteException"] = m => new IgniteException(m); EXS["org.apache.ignite.IgniteCheckedException"] = m => new IgniteException(m); // Cluster exceptions. EXS["org.apache.ignite.cluster.ClusterGroupEmptyException"] = m => new ClusterGroupEmptyException(m); EXS["org.apache.ignite.cluster.ClusterTopologyException"] = m => new ClusterTopologyException(m); // Compute exceptions. EXS["org.apache.ignite.compute.ComputeExecutionRejectedException"] = m => new ComputeExecutionRejectedException(m); EXS["org.apache.ignite.compute.ComputeJobFailoverException"] = m => new ComputeJobFailoverException(m); EXS["org.apache.ignite.compute.ComputeTaskCancelledException"] = m => new ComputeTaskCancelledException(m); EXS["org.apache.ignite.compute.ComputeTaskTimeoutException"] = m => new ComputeTaskTimeoutException(m); EXS["org.apache.ignite.compute.ComputeUserUndeclaredException"] = m => new ComputeUserUndeclaredException(m); // Cache exceptions. EXS["javax.cache.CacheException"] = m => new CacheException(m); EXS["javax.cache.integration.CacheLoaderException"] = m => new CacheStoreException(m); EXS["javax.cache.integration.CacheWriterException"] = m => new CacheStoreException(m); EXS["javax.cache.processor.EntryProcessorException"] = m => new CacheEntryProcessorException(m); EXS["org.apache.ignite.cache.CacheAtomicUpdateTimeoutException"] = m => new CacheAtomicUpdateTimeoutException(m); // Transaction exceptions. EXS["org.apache.ignite.transactions.TransactionOptimisticException"] = m => new TransactionOptimisticException(m); EXS["org.apache.ignite.transactions.TransactionTimeoutException"] = m => new TransactionTimeoutException(m); EXS["org.apache.ignite.transactions.TransactionRollbackException"] = m => new TransactionRollbackException(m); EXS["org.apache.ignite.transactions.TransactionHeuristicException"] = m => new TransactionHeuristicException(m); // Security exceptions. EXS["org.apache.ignite.IgniteAuthenticationException"] = m => new SecurityException(m); EXS["org.apache.ignite.plugin.security.GridSecurityException"] = m => new SecurityException(m); } /// <summary> /// Creates exception according to native code class and message. /// </summary> /// <param name="clsName">Exception class name.</param> /// <param name="msg">Exception message.</param> /// <param name="reader">Error data reader.</param> public static Exception GetException(string clsName, string msg, PortableReaderImpl reader = null) { ExceptionFactoryDelegate ctor; if (EXS.TryGetValue(clsName, out ctor)) return ctor(msg); if (ClsNoClsDefFoundErr.Equals(clsName)) return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " + "variable?): " + msg); if (ClsNoSuchMthdErr.Equals(clsName)) return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " + "variable?): " + msg); if (ClsCachePartialUpdateErr.Equals(clsName)) return ProcessCachePartialUpdateException(msg, reader); return new IgniteException("Java exception occurred [class=" + clsName + ", message=" + msg + ']'); } /// <summary> /// Process cache partial update exception. /// </summary> /// <param name="msg">Message.</param> /// <param name="reader">Reader.</param> /// <returns></returns> private static Exception ProcessCachePartialUpdateException(string msg, PortableReaderImpl reader) { if (reader == null) return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available.")); bool dataExists = reader.ReadBoolean(); Debug.Assert(dataExists); if (reader.ReadBoolean()) { bool keepPortable = reader.ReadBoolean(); PortableReaderImpl keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepPortable); try { return new CachePartialUpdateException(msg, ReadNullableList(keysReader)); } catch (Exception e) { // Failed to deserialize data. return new CachePartialUpdateException(msg, e); } } // Was not able to write keys. string innerErrCls = reader.ReadString(); string innerErrMsg = reader.ReadString(); Exception innerErr = GetException(innerErrCls, innerErrMsg); return new CachePartialUpdateException(msg, innerErr); } /// <summary> /// Create JVM initialization exception. /// </summary> /// <param name="clsName">Class name.</param> /// <param name="msg">Message.</param> /// <returns>Exception.</returns> public static Exception GetJvmInitializeException(string clsName, string msg) { if (clsName != null) return new IgniteException("Failed to initialize JVM.", GetException(clsName, msg)); if (msg != null) return new IgniteException("Failed to initialize JVM: " + msg); return new IgniteException("Failed to initialize JVM."); } /// <summary> /// Reads nullable list. /// </summary> /// <param name="reader">Reader.</param> /// <returns>List.</returns> private static List<object> ReadNullableList(PortableReaderImpl reader) { if (!reader.ReadBoolean()) return null; var size = reader.ReadInt(); var list = new List<object>(size); for (int i = 0; i < size; i++) list.Add(reader.ReadObject<object>()); return list; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the LabMotivoRepeticionScreening class. /// </summary> [Serializable] public partial class LabMotivoRepeticionScreeningCollection : ActiveList<LabMotivoRepeticionScreening, LabMotivoRepeticionScreeningCollection> { public LabMotivoRepeticionScreeningCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>LabMotivoRepeticionScreeningCollection</returns> public LabMotivoRepeticionScreeningCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { LabMotivoRepeticionScreening o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the LAB_MotivoRepeticionScreening table. /// </summary> [Serializable] public partial class LabMotivoRepeticionScreening : ActiveRecord<LabMotivoRepeticionScreening>, IActiveRecord { #region .ctors and Default Settings public LabMotivoRepeticionScreening() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public LabMotivoRepeticionScreening(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public LabMotivoRepeticionScreening(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public LabMotivoRepeticionScreening(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("LAB_MotivoRepeticionScreening", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdMotivoRepeticionScreening = new TableSchema.TableColumn(schema); colvarIdMotivoRepeticionScreening.ColumnName = "idMotivoRepeticionScreening"; colvarIdMotivoRepeticionScreening.DataType = DbType.Int32; colvarIdMotivoRepeticionScreening.MaxLength = 0; colvarIdMotivoRepeticionScreening.AutoIncrement = true; colvarIdMotivoRepeticionScreening.IsNullable = false; colvarIdMotivoRepeticionScreening.IsPrimaryKey = true; colvarIdMotivoRepeticionScreening.IsForeignKey = false; colvarIdMotivoRepeticionScreening.IsReadOnly = false; colvarIdMotivoRepeticionScreening.DefaultSetting = @""; colvarIdMotivoRepeticionScreening.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMotivoRepeticionScreening); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.String; colvarDescripcion.MaxLength = 500; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = false; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("LAB_MotivoRepeticionScreening",schema); } } #endregion #region Props [XmlAttribute("IdMotivoRepeticionScreening")] [Bindable(true)] public int IdMotivoRepeticionScreening { get { return GetColumnValue<int>(Columns.IdMotivoRepeticionScreening); } set { SetColumnValue(Columns.IdMotivoRepeticionScreening, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.LabSolicitudScreeningRepeticionCollection colLabSolicitudScreeningRepeticionRecords; public DalSic.LabSolicitudScreeningRepeticionCollection LabSolicitudScreeningRepeticionRecords { get { if(colLabSolicitudScreeningRepeticionRecords == null) { colLabSolicitudScreeningRepeticionRecords = new DalSic.LabSolicitudScreeningRepeticionCollection().Where(LabSolicitudScreeningRepeticion.Columns.IdMotivoRepeticion, IdMotivoRepeticionScreening).Load(); colLabSolicitudScreeningRepeticionRecords.ListChanged += new ListChangedEventHandler(colLabSolicitudScreeningRepeticionRecords_ListChanged); } return colLabSolicitudScreeningRepeticionRecords; } set { colLabSolicitudScreeningRepeticionRecords = value; colLabSolicitudScreeningRepeticionRecords.ListChanged += new ListChangedEventHandler(colLabSolicitudScreeningRepeticionRecords_ListChanged); } } void colLabSolicitudScreeningRepeticionRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colLabSolicitudScreeningRepeticionRecords[e.NewIndex].IdMotivoRepeticion = IdMotivoRepeticionScreening; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varDescripcion) { LabMotivoRepeticionScreening item = new LabMotivoRepeticionScreening(); item.Descripcion = varDescripcion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdMotivoRepeticionScreening,string varDescripcion) { LabMotivoRepeticionScreening item = new LabMotivoRepeticionScreening(); item.IdMotivoRepeticionScreening = varIdMotivoRepeticionScreening; item.Descripcion = varDescripcion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdMotivoRepeticionScreeningColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdMotivoRepeticionScreening = @"idMotivoRepeticionScreening"; public static string Descripcion = @"descripcion"; } #endregion #region Update PK Collections public void SetPKValues() { if (colLabSolicitudScreeningRepeticionRecords != null) { foreach (DalSic.LabSolicitudScreeningRepeticion item in colLabSolicitudScreeningRepeticionRecords) { if (item.IdMotivoRepeticion != IdMotivoRepeticionScreening) { item.IdMotivoRepeticion = IdMotivoRepeticionScreening; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colLabSolicitudScreeningRepeticionRecords != null) { colLabSolicitudScreeningRepeticionRecords.SaveAll(); } } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using HtcSharp.HttpModule.Http.Abstractions.Internal; using Microsoft.Extensions.Primitives; namespace HtcSharp.HttpModule.Http.Abstractions { // SourceTools-Start // Remote-File C:\ASP\src\Http\Http.Abstractions\src\HostString.cs // Start-At-Remote-Line 11 // SourceTools-End /// <summary> /// Represents the host portion of a URI can be used to construct URI's properly formatted and encoded for use in /// HTTP headers. /// </summary> public readonly struct HostString : IEquatable<HostString> { private readonly string _value; /// <summary> /// Creates a new HostString without modification. The value should be Unicode rather than punycode, and may have a port. /// IPv4 and IPv6 addresses are also allowed, and also may have ports. /// </summary> /// <param name="value"></param> public HostString(string value) { _value = value; } /// <summary> /// Creates a new HostString from its host and port parts. /// </summary> /// <param name="host">The value should be Unicode rather than punycode. IPv6 addresses must use square braces.</param> /// <param name="port">A positive, greater than 0 value representing the port in the host string.</param> public HostString(string host, int port) { if (host == null) { throw new ArgumentNullException(nameof(host)); } if (port <= 0) { throw new ArgumentOutOfRangeException(nameof(port), Resources.Exception_PortMustBeGreaterThanZero); } int index; if (host.IndexOf('[') == -1 && (index = host.IndexOf(':')) >= 0 && index < host.Length - 1 && host.IndexOf(':', index + 1) >= 0) { // IPv6 without brackets ::1 is the only type of host with 2 or more colons host = $"[{host}]"; } _value = host + ":" + port.ToString(CultureInfo.InvariantCulture); } /// <summary> /// Returns the original value from the constructor. /// </summary> public string Value { get { return _value; } } public bool HasValue { get { return !string.IsNullOrEmpty(_value); } } /// <summary> /// Returns the value of the host part of the value. The port is removed if it was present. /// IPv6 addresses will have brackets added if they are missing. /// </summary> /// <returns>The host portion of the value.</returns> public string Host { get { GetParts(_value, out var host, out var port); return host.ToString(); } } /// <summary> /// Returns the value of the port part of the host, or <value>null</value> if none is found. /// </summary> /// <returns>The port portion of the value.</returns> public int? Port { get { GetParts(_value, out var host, out var port); if (!StringSegment.IsNullOrEmpty(port) && int.TryParse(port.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out var p)) { return p; } return null; } } /// <summary> /// Returns the value as normalized by ToUriComponent(). /// </summary> /// <returns>The value as normalized by <see cref="ToUriComponent"/>.</returns> public override string ToString() { return ToUriComponent(); } /// <summary> /// Returns the value properly formatted and encoded for use in a URI in a HTTP header. /// Any Unicode is converted to punycode. IPv6 addresses will have brackets added if they are missing. /// </summary> /// <returns>The <see cref="HostString"/> value formated for use in a URI or HTTP header.</returns> public string ToUriComponent() { if (string.IsNullOrEmpty(_value)) { return string.Empty; } int i; for (i = 0; i < _value.Length; ++i) { if (!HostStringHelper.IsSafeHostStringChar(_value[i])) { break; } } if (i != _value.Length) { GetParts(_value, out var host, out var port); var mapping = new IdnMapping(); var encoded = mapping.GetAscii(host.Buffer, host.Offset, host.Length); return StringSegment.IsNullOrEmpty(port) ? encoded : string.Concat(encoded, ":", port.ToString()); } return _value; } /// <summary> /// Creates a new HostString from the given URI component. /// Any punycode will be converted to Unicode. /// </summary> /// <param name="uriComponent">The URI component string to create a <see cref="HostString"/> from.</param> /// <returns>The <see cref="HostString"/> that was created.</returns> public static HostString FromUriComponent(string uriComponent) { if (!string.IsNullOrEmpty(uriComponent)) { int index; if (uriComponent.IndexOf('[') >= 0) { // IPv6 in brackets [::1], maybe with port } else if ((index = uriComponent.IndexOf(':')) >= 0 && index < uriComponent.Length - 1 && uriComponent.IndexOf(':', index + 1) >= 0) { // IPv6 without brackets ::1 is the only type of host with 2 or more colons } else if (uriComponent.IndexOf("xn--", StringComparison.Ordinal) >= 0) { // Contains punycode if (index >= 0) { // Has a port string port = uriComponent.Substring(index); var mapping = new IdnMapping(); uriComponent = mapping.GetUnicode(uriComponent, 0, index) + port; } else { var mapping = new IdnMapping(); uriComponent = mapping.GetUnicode(uriComponent); } } } return new HostString(uriComponent); } /// <summary> /// Creates a new HostString from the host and port of the give Uri instance. /// Punycode will be converted to Unicode. /// </summary> /// <param name="uri">The <see cref="Uri"/> to create a <see cref="HostString"/> from.</param> /// <returns>The <see cref="HostString"/> that was created.</returns> public static HostString FromUriComponent(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } return new HostString(uri.GetComponents( UriComponents.NormalizedHost | // Always convert punycode to Unicode. UriComponents.HostAndPort, UriFormat.Unescaped)); } /// <summary> /// Matches the host portion of a host header value against a list of patterns. /// The host may be the encoded punycode or decoded unicode form so long as the pattern /// uses the same format. /// </summary> /// <param name="value">Host header value with or without a port.</param> /// <param name="patterns">A set of pattern to match, without ports.</param> /// <remarks> /// The port on the given value is ignored. The patterns should not have ports. /// The patterns may be exact matches like "example.com", a top level wildcard "*" /// that matches all hosts, or a subdomain wildcard like "*.example.com" that matches /// "abc.example.com:443" but not "example.com:443". /// Matching is case insensitive. /// </remarks> /// <returns><code>true</code> if <paramref name="value"/> matches any of the patterns.</returns> public static bool MatchesAny(StringSegment value, IList<StringSegment> patterns) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (patterns == null) { throw new ArgumentNullException(nameof(patterns)); } // Drop the port GetParts(value, out var host, out var port); for (int i = 0; i < port.Length; i++) { if (port[i] < '0' || '9' < port[i]) { throw new FormatException($"The given host value '{value}' has a malformed port."); } } var count = patterns.Count; for (int i = 0; i < count; i++) { var pattern = patterns[i]; if (pattern == "*") { return true; } if (StringSegment.Equals(pattern, host, StringComparison.OrdinalIgnoreCase)) { return true; } // Sub-domain wildcards: *.example.com if (pattern.StartsWith("*.", StringComparison.Ordinal) && host.Length >= pattern.Length) { // .example.com var allowedRoot = pattern.Subsegment(1); var hostRoot = host.Subsegment(host.Length - allowedRoot.Length); if (hostRoot.Equals(allowedRoot, StringComparison.OrdinalIgnoreCase)) { return true; } } } return false; } /// <summary> /// Compares the equality of the Value property, ignoring case. /// </summary> /// <param name="other">The <see cref="HostString"/> to compare against.</param> /// <returns><code>true</code> if they have the same value.</returns> public bool Equals(HostString other) { if (!HasValue && !other.HasValue) { return true; } return string.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Compares against the given object only if it is a HostString. /// </summary> /// <param name="obj">The <see cref="object"/> to compare against.</param> /// <returns><code>true</code> if they have the same value.</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return !HasValue; } return obj is HostString && Equals((HostString)obj); } /// <summary> /// Gets a hash code for the value. /// </summary> /// <returns>The hash code as an <see cref="int"/>.</returns> public override int GetHashCode() { return (HasValue ? StringComparer.OrdinalIgnoreCase.GetHashCode(_value) : 0); } /// <summary> /// Compares the two instances for equality. /// </summary> /// <param name="left">The left parameter.</param> /// <param name="right">The right parameter.</param> /// <returns><code>true</code> if both <see cref="HostString"/>'s have the same value.</returns> public static bool operator ==(HostString left, HostString right) { return left.Equals(right); } /// <summary> /// Compares the two instances for inequality. /// </summary> /// <param name="left">The left parameter.</param> /// <param name="right">The right parameter.</param> /// <returns><code>true</code> if both <see cref="HostString"/>'s values are not equal.</returns> public static bool operator !=(HostString left, HostString right) { return !left.Equals(right); } /// <summary> /// Parses the current value. IPv6 addresses will have brackets added if they are missing. /// </summary> /// <param name="value">The value to get the parts of.</param> /// <param name="host">The portion of the <paramref name="value"/> which represents the host.</param> /// <param name="port">The portion of the <paramref name="value"/> which represents the port.</param> private static void GetParts(StringSegment value, out StringSegment host, out StringSegment port) { int index; port = null; host = null; if (StringSegment.IsNullOrEmpty(value)) { return; } else if ((index = value.IndexOf(']')) >= 0) { // IPv6 in brackets [::1], maybe with port host = value.Subsegment(0, index + 1); // Is there a colon and at least one character? if (index + 2 < value.Length && value[index + 1] == ':') { port = value.Subsegment(index + 2); } } else if ((index = value.IndexOf(':')) >= 0 && index < value.Length - 1 && value.IndexOf(':', index + 1) >= 0) { // IPv6 without brackets ::1 is the only type of host with 2 or more colons host = $"[{value}]"; port = null; } else if (index >= 0) { // Has a port host = value.Subsegment(0, index); port = value.Subsegment(index + 1); } else { host = value; port = null; } } } }