context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Diagnostics.CodeAnalysis; namespace Konscious.Security.Cryptography { using System.Text; using Xunit; [SuppressMessage("Microsoft.Naming", "CA1707")] public class Argon2CoreTests { [Fact] public void Initialize_BuildTheCorrectHashForJustPAndS() { var subject = new Argon2iCore(128); subject.DegreeOfParallelism = 4; subject.Iterations = 5; subject.MemorySize = 128; subject.Salt = new byte[] { 0xf7, 0x19, 0x2b, 0xa7, 0xff, 0xb8, 0xca, 0xdc, 0x67, 0x51, 0xed, 0xa0, 0x08, 0x1d, 0x9d, 0x95, 0x0b, 0x10, 0xe4, 0x32, 0x23, 0xef, 0x30, 0x07, 0x39, 0xc6, 0xbc, 0xad, 0x36, 0xda, 0x08, 0xeb, 0x03, 0x3b, 0xab, 0x98, 0x32, 0x06, 0x7d, 0x39, 0x6f, 0x81, 0x72, 0x24, 0xff, 0x58, 0x41, 0xe6, 0x33, 0x5d, 0xf7, 0xe7, 0x56, 0xf7, 0xaf, 0x32, 0xfa, 0xd8, 0x72, 0x78, 0xac, 0x63, 0xda, 0xd1 }; var expected = new byte[] { 0x12, 0xcb, 0x36, 0xfa, 0x63, 0x8e, 0xcf, 0xee, 0xb8, 0x55, 0x0e, 0xbb, 0x73, 0xfb, 0x01, 0x81, 0x95, 0xfb, 0x6f, 0x64, 0xd9, 0xb8, 0x84, 0x27, 0x67, 0xd1, 0xb3, 0xe1, 0xc8, 0xbb, 0x16, 0x24, 0xa8, 0x5e, 0x27, 0xa5, 0x63, 0x13, 0x51, 0x0f, 0x25, 0x4b, 0x82, 0xc9, 0x9a, 0x00, 0xdb, 0xe1, 0x7a, 0xe0, 0xfc, 0x7f, 0x6e, 0x7a, 0x41, 0x14, 0x17, 0x9a, 0xb8, 0xe2, 0x79, 0x5c, 0x85, 0x55 }; var actual = subject.Initialize(Encoding.UTF8.GetBytes("P@ssw0rd!$")); Assert.Equal(expected, actual); } [Fact] public void Initialize_BuildTheCorrectHashForPAndSWithSecret() { var subject = new Argon2iCore(128); subject.DegreeOfParallelism = 4; subject.Iterations = 5; subject.MemorySize = 128; subject.Secret = Encoding.UTF8.GetBytes("In1ti@lS3cr3T 1234"); subject.Salt = new byte[] { 0xf7, 0x19, 0x2b, 0xa7, 0xff, 0xb8, 0xca, 0xdc, 0x67, 0x51, 0xed, 0xa0, 0x08, 0x1d, 0x9d, 0x95, 0x0b, 0x10, 0xe4, 0x32, 0x23, 0xef, 0x30, 0x07, 0x39, 0xc6, 0xbc, 0xad, 0x36, 0xda, 0x08, 0xeb, 0x03, 0x3b, 0xab, 0x98, 0x32, 0x06, 0x7d, 0x39, 0x6f, 0x81, 0x72, 0x24, 0xff, 0x58, 0x41, 0xe6, 0x33, 0x5d, 0xf7, 0xe7, 0x56, 0xf7, 0xaf, 0x32, 0xfa, 0xd8, 0x72, 0x78, 0xac, 0x63, 0xda, 0xd1 }; var expected = new byte[] { 0xb7, 0x33, 0x03, 0xff, 0x3f, 0xe7, 0x16, 0x46, 0x03, 0x15, 0x8e, 0xf5, 0x17, 0xe4, 0x79, 0xd2, 0x7f, 0xf6, 0x73, 0xbf, 0x01, 0x5f, 0xfa, 0xe6, 0x72, 0x13, 0x33, 0xb4, 0xff, 0x4f, 0xa3, 0x60, 0x4b, 0x53, 0x7c, 0xa5, 0xe0, 0x2b, 0xe4, 0x06, 0xce, 0x9e, 0x9e, 0xa3, 0x27, 0x9c, 0x6e, 0x26, 0x39, 0x11, 0xa3, 0x36, 0xa8, 0x4d, 0xdd, 0xaf, 0x33, 0x9d, 0xe2, 0xd1, 0x77, 0x99, 0x08, 0x30 }; var actual = subject.Initialize(Encoding.UTF8.GetBytes("P@ssw0rd!$")); Assert.Equal(expected, actual); } [Fact] public void Initialize_BuildTheCorrectHashForWeirdSizes() { var subject = new Argon2iCore(47); subject.DegreeOfParallelism = 7; subject.Iterations = 7; subject.MemorySize = 1024; subject.Salt = new byte[] { 0xf7, 0x19, 0x2b, 0xa7, 0xff, 0xb8, 0xca, 0xdc, 0x67, 0x51, 0xed, 0xa0, 0x08, 0x1d, 0x9d, 0x95, 0x0b, 0x10, 0xe4, 0x32, 0x23, 0xef, 0x30, 0x07, 0x39, 0xc6, 0xbc, 0xad, 0x36, 0xda, 0x08, 0xeb, 0x03, 0x3b, 0xab, 0x98, 0x32, 0x06, 0x7d, 0x39, 0x6f, 0x81, 0x72, 0x24, 0xff, 0x58, 0x41, 0xe6, 0x33, 0x5d, 0xf7, 0xe7, 0x56, 0xf7, 0xaf, 0x32, 0xfa, 0xd8, 0x72, 0x78, 0xac, 0x63, 0xda, 0xd1 }; var expected = new byte[] { 0x18, 0xac, 0xca, 0x56, 0x86, 0x20, 0xb3, 0x75, 0xf9, 0x90, 0x24, 0x72, 0x4a, 0x50, 0xa5, 0xff, 0x39, 0xee, 0x34, 0x70, 0x8f, 0xdc, 0xfa, 0xfb, 0xbb, 0x59, 0xbe, 0xd5, 0xca, 0x78, 0x6f, 0x95, 0xca, 0xd8, 0x3a, 0x8c, 0x9d, 0x2b, 0xd1, 0x5e, 0x73, 0xea, 0xb4, 0x73, 0xc5, 0x4d, 0xfb, 0x07, 0x34, 0xb8, 0x08, 0x2c, 0xdd, 0xec, 0x9f, 0x5f, 0xe2, 0x48, 0xd1, 0x38, 0x93, 0x12, 0xfd, 0x6f }; var actual = subject.Initialize(Encoding.UTF8.GetBytes("#S3cr3t+Ke4$")); Assert.Equal(expected, actual); } [Fact] public void Initialize_BuildTheCorrectHashForPAndSWithSecretAndAD() { var subject = new Argon2iCore(128); subject.DegreeOfParallelism = 4; subject.Iterations = 5; subject.MemorySize = 128; subject.Secret = Encoding.UTF8.GetBytes("In1ti@lS3cr3T 1234"); subject.AssociatedData = new byte[] { 0x4b, 0x53, 0x7c, 0xa5, 0xe0, 0x2b, 0xe4, 0x06, 0xce, 0x9e, 0x9e, 0xa3, 0x27, 0x9c, 0x6e, 0x26 }; subject.Salt = new byte[] { 0xf7, 0x19, 0x2b, 0xa7, 0xff, 0xb8, 0xca, 0xdc, 0x67, 0x51, 0xed, 0xa0, 0x08, 0x1d, 0x9d, 0x95, 0x0b, 0x10, 0xe4, 0x32, 0x23, 0xef, 0x30, 0x07, 0x39, 0xc6, 0xbc, 0xad, 0x36, 0xda, 0x08, 0xeb, 0x03, 0x3b, 0xab, 0x98, 0x32, 0x06, 0x7d, 0x39, 0x6f, 0x81, 0x72, 0x24, 0xff, 0x58, 0x41, 0xe6, 0x33, 0x5d, 0xf7, 0xe7, 0x56, 0xf7, 0xaf, 0x32, 0xfa, 0xd8, 0x72, 0x78, 0xac, 0x63, 0xda, 0xd1 }; var expected = new byte[] { 0x54, 0xaa, 0x5a, 0x9a, 0x69, 0x7f, 0x69, 0xdf, 0xd2, 0xf1, 0xdb, 0x33, 0xb8, 0xf4, 0xa3, 0xa5, 0x82, 0x5e, 0x34, 0x5a, 0x0a, 0xb0, 0xe8, 0x5c, 0x84, 0x31, 0x09, 0x80, 0xd8, 0x71, 0xab, 0xad, 0x85, 0x14, 0x88, 0x2a, 0xfd, 0x69, 0x85, 0x1b, 0x54, 0x6c, 0x37, 0x99, 0xba, 0x87, 0x95, 0x81, 0xb3, 0x6e, 0x44, 0xf3, 0x13, 0xf9, 0x1d, 0xe3, 0x26, 0xed, 0xb6, 0x39, 0xf0, 0x21, 0xf8, 0x7f }; var actual = subject.Initialize(Encoding.UTF8.GetBytes("P@ssw0rd!$")); Assert.Equal(expected, actual); } [Fact] public async void InitializeLanes_BuildsInitialLanesCorrectly() { var subject = new Argon2iCore(128); subject.DegreeOfParallelism = 2; subject.Iterations = 5; subject.MemorySize = 16; subject.Salt = new byte[] { 0x69, 0xf8, 0xf7, 0x5e, 0x68, 0x9d, 0x10, 0xe8, 0x75, 0xf2, 0x94, 0x2f, 0xa5, 0xb0, 0x6e, 0x36, 0x9b, 0x89, 0x24, 0x43, 0x6e, 0xad, 0x8c, 0x81, 0xc5, 0x3a, 0x84, 0xfe, 0x05, 0xc6, 0x1e, 0x90, 0x63, 0x62, 0x58, 0xcd, 0x11, 0xae, 0x3f, 0x68, 0xd0, 0x9e, 0xd2, 0x52, 0x0c, 0xc3, 0xe5, 0xc3, 0xb3, 0x88, 0x52, 0x97, 0x56, 0x7d, 0xcd, 0xd9, 0x0e, 0x67, 0x7d, 0x09, 0x08, 0x0c, 0x2b, 0x9a }; var expected00 = new ulong[] { 0x3127bfce73a8a49eUL, 0x8bf2093ec0fbfd28UL, 0x6e2ddbd012c3a096UL, 0x5fafb594148598e3UL, 0x3dfb96e1781a7cf8UL, 0x34621adcefc2dbe8UL, 0x536d87ad2f720554UL, 0x01c0598be369df21UL, 0x6f253038b6c8a9fcUL, 0x0d97673913c22c43UL, 0x5319ca244e7cfe7aUL, 0x372d3b32bcf26addUL, 0x808fff65f30da51cUL, 0xf073157457548aacUL, 0xe835687ca32841c3UL, 0x019b5399bf5fc2a3UL, 0x1eee11941369cdcbUL, 0x110c6a3b6febf9f8UL, 0xd862629e96fb4aaeUL, 0xe074c69bac3d0626UL, 0x8c651c06368f64daUL, 0xa7ab521b32874a6bUL, 0xe5e9d2990cd8a260UL, 0xb5554374c8604559UL, 0x0533d04f5519815cUL, 0x9fc667b4f970df73UL, 0x16b518e93b487893UL, 0x70bbb2e89d60456cUL, 0x682e159206bf2625UL, 0x721a95082ab1726cUL, 0xb128cd7d096b07d9UL, 0x83eebb0eadef156fUL, 0x620f410459bb585bUL, 0x83b989248dd35244UL, 0xfe684b77e63583ccUL, 0x486009c0c1d932a3UL, 0x740b7daf2455f62fUL, 0xf34558a4f2e319dfUL, 0x678579bcd61c0e35UL, 0x37ef3a1c5a696967UL, 0x5ae6eae58262a759UL, 0x5bd4e3035fb25fa6UL, 0xb59cf8db51cc1160UL, 0xa22e44bc7d74712cUL, 0x419ff488a9b76124UL, 0xc9374af699de145bUL, 0x2ef3398697f2951cUL, 0x3e21fa5ccfe9d976UL, 0xd669b7e4254be2c5UL, 0x49eb4ad0242d0b48UL, 0x4d9da909b6c17010UL, 0x4da74c64475b6076UL, 0x91418a11dba98ec0UL, 0x7839c2034c11738fUL, 0xce094fa88651abc7UL, 0xc2bfa72bc3ed4106UL, 0x70bc0e0182c12657UL, 0x99ed30b3d28144edUL, 0xc3841311ca44c887UL, 0xd618c52b4d152a23UL, 0x27f6a8e3b7fcd9deUL, 0x0db0fec6c0fbee23UL, 0x1d5f7a446d8a3a01UL, 0x7317ac34ab2272caUL, 0x5382c607fa4a31e2UL, 0x20f5acbdd8471f20UL, 0xce2abc9c8ef060ecUL, 0xa084e26c3fd09721UL, 0x0729cb77ea17d73fUL, 0xcdf67832b7869cd2UL, 0xe627f0f3ff161c9dUL, 0x9d62be6099439727UL, 0x567d2e47ec7879a3UL, 0x739d4d043e8ea74dUL, 0xa166e7f41fc71196UL, 0x9df8862e2a6c7cc9UL, 0x4b24832ebdeeab8aUL, 0x0da19d0f6e7d9101UL, 0xed156ed715447ec5UL, 0x705937e7d1a82fb0UL, 0xbc0d5da2ceb4534eUL, 0x7f0fdd6ef1918b35UL, 0xd50b0d3250b33e52UL, 0xecc0378743f69182UL, 0x5fdaa5fc5c286142UL, 0xe743a8a515c8f007UL, 0x1850b288ba12cdfaUL, 0x421059d8f29dc871UL, 0xc8e77a502c579e4eUL, 0xe17e813763e011a8UL, 0x915716dab8b8a1ceUL, 0xdf136d321a9050d4UL, 0x19b8f5d7a9e1b3c8UL, 0x50ca78026b5545ebUL, 0xe1ff70c89c43d4feUL, 0xe3a42a6e522b822eUL, 0x58d40ffce6667b98UL, 0x33a7a1bc326aea10UL, 0xbc7b0100222ca1a9UL, 0xfe127449c94a001cUL, 0xca2b369322a6c661UL, 0x2f33453bc62ad471UL, 0x2e2d2e0695b4627fUL, 0x46e4144c6b298126UL, 0xe550c799900e5ecfUL, 0x432215ef7bd56d5fUL, 0x9276b83c49e28d98UL, 0x12f3bf8112853699UL, 0x07797c71f568ca1dUL, 0x58d7d2e4e141a40fUL, 0xc62e0ffb2efb90ccUL, 0x31c6f62dc7795c64UL, 0x9d7106c4a1efe709UL, 0xb0e1c169e638def6UL, 0x3ff4f4416bbec88dUL, 0xf2a7cc5e158c8bd9UL, 0x460beec0f388db3fUL, 0x102b3ee7f709e102UL, 0xe9f24dcb49beebaeUL, 0xd9267f914e205fc9UL, 0xbafd5f9429b9c6d8UL, 0x7a479f3d848193c8UL, 0x5b59288f408c0f95UL, 0xa43fd470a4324b24UL, 0x26ed98390047473dUL, 0xf5864cd386a3df6dUL, 0x948c57d223d6b63eUL, 0x352bd5900a0c78dcUL }; var expected01 = new ulong[] { 0x6ecb0e82c305a8b1UL, 0xd5e15e619ba7e908UL, 0x3949135e482d28b2UL, 0x0f2d53536b0629c8UL, 0x9423174fa5da006aUL, 0xcdef4ec1f741b2f1UL, 0x11a500b5a6ba5ad6UL, 0xfc3c73f2182a3207UL, 0x0d419066868d04e2UL, 0xf41df430ca1deb4cUL, 0xc0fac627fccac8e4UL, 0x0a993ba4ba02a02aUL, 0xea6e6d507437d83eUL, 0x838ce720da09dca0UL, 0xf677a31e45f40e54UL, 0xd91c251f03fd1105UL, 0xf3a3622074a74c92UL, 0x144a2eb6be533f7eUL, 0x9301f4ff7e79257cUL, 0x403ac4e52d43a088UL, 0x9396db10f7720e84UL, 0x064136e50719e913UL, 0x9191a3316f114275UL, 0xd00a7041da54bae4UL, 0x97eafb749c47519eUL, 0x49768687e276b647UL, 0xc185cd914f360c49UL, 0xaaaf3fcd95d1a1aaUL, 0x1c6c00a3863af67fUL, 0xcb22d9ce096f2f21UL, 0x82aff4b1aa5edeacUL, 0xb27c058e0dbf7836UL, 0x4a1462a63808c840UL, 0x11ae09fd0f6c1d7dUL, 0x0829afffb9193ee7UL, 0x963deb4d9517b139UL, 0x01b11722d6c3cd8dUL, 0x7e489873dbef1da0UL, 0xf86c9ab02dff9d27UL, 0xd1c97ed9b54ff878UL, 0x062994f814364255UL, 0x71c1fcc33f73df0eUL, 0xad7158fe1d9a0f26UL, 0x5b91a7e9b619248eUL, 0xf9a21e5b8351c85eUL, 0xef7947068318c098UL, 0xd38ce63b06b6444cUL, 0x803f186462142580UL, 0x2155286d1d5a7e52UL, 0xbbb187ec23d4b084UL, 0x3ed8172fb113ff50UL, 0xa93c8feb842f5cacUL, 0xf268ee76c1c47032UL, 0x9dd60023a7f787b2UL, 0x023a6130fdb79d7eUL, 0xf3b4e3ff56cd10d4UL, 0x5125a9c1e864063cUL, 0x440904150dc5d202UL, 0xcaf7297bb99e2245UL, 0x470437bfef84d66cUL, 0x69e6721bb2251e8aUL, 0x26a7fc3100835cf9UL, 0x9c1b901a2bc1b19eUL, 0xf3b9ccf4b55e1a15UL, 0xd53ca80df854908cUL, 0xe19913464caed8c1UL, 0x45eebb56d4767743UL, 0x89e05fb09b9b595aUL, 0xe7ac307534734e13UL, 0xb902f5dbbd0198f9UL, 0xf48a8a8209196226UL, 0xb52813700e5f1478UL, 0x6e99bfe86d98fb7bUL, 0xb3ef90b39b03e1e8UL, 0x1a4b5da515554573UL, 0x149b9b52d158b9e4UL, 0xe8200623809c9cadUL, 0xff5817fc6d6087b7UL, 0x45a92883c1d0aae8UL, 0xcdcbafef103d241cUL, 0x3035af3dc9f144f5UL, 0x84a6b50f01926074UL, 0x218e6c77f06a8afdUL, 0x62065de09c07ea85UL, 0xa3b15c4a54a051f9UL, 0x71e03c12514102feUL, 0xb0b64366f9cfa367UL, 0x93c7e3ce298533b7UL, 0xa867eeec462e15d2UL, 0x91bf55b5006ae340UL, 0x9c0b386daaad9d4aUL, 0x220efd735f58b41cUL, 0xfe00a7de37c7d5e4UL, 0x0d485cb52f73adf1UL, 0x018e5414e448f06cUL, 0xa2ddcad262041b64UL, 0x8f97379373521a27UL, 0xd837bf5ad5c0c25dUL, 0xc219c62d50660416UL, 0xfd1a59deac35edbdUL, 0x51f9f0663c9a9f0dUL, 0x6878bc402ef55cf1UL, 0x86d7acc833beb55eUL, 0xdaba7e48d54e7f0eUL, 0x689006186f9603b4UL, 0xf39f59ee5f11b637UL, 0x3225cce538f311efUL, 0xc7890b2221558d5fUL, 0xe1aa16084fb7d68eUL, 0xd948d9d9d178b24fUL, 0xa3743146fe9aa8a5UL, 0x612eb05f997d94eeUL, 0x4292f28db8996e96UL, 0x9948828e81f87bf8UL, 0x502e5e0f0b45d668UL, 0xb453f860bd5b4462UL, 0x6ab5a117f1a8fcceUL, 0x9acc5b7fc54179c2UL, 0x5b21e508c5d9393bUL, 0x5656d57d0ed1b2d7UL, 0xdfe138ee684ead02UL, 0x9c837d027f385239UL, 0xd74f0589cbeb0b98UL, 0x595093e3daa4e698UL, 0x82511c12d74ca499UL, 0xb9738260cd43826bUL, 0x08eada4f93816301UL, 0x450c9e92591775fcUL }; var expected10 = new ulong[] { 0x4064ab7401a367caUL, 0xd6efc13fdbe1a6dbUL, 0x791a942f8e183ed2UL, 0x1201685e055ae4f9UL, 0x9bce6806914174a3UL, 0xa2525312462cc956UL, 0x168ad5e6356239b7UL, 0x8fd19d11c1a20997UL, 0x3a29d386c25b7b41UL, 0xfdfd4e820b93d84aUL, 0x9ffb414431f180deUL, 0x2ab43fea0e59dc3bUL, 0xd9f939886e95aa3cUL, 0x2ce29da0009c5f38UL, 0x7a17603155147f45UL, 0xd6409e4d993f354cUL, 0xf7c292775ff7b6f1UL, 0xcba283e99c3ed928UL, 0x482ef73f88eef9dbUL, 0x47a430ec00fcabc8UL, 0x75dbcd077a20060aUL, 0x0fc5200fed7b7bc7UL, 0x46102c34bee65c8aUL, 0xf6a08bcb5ad74d68UL, 0xd712bdf08d4f2478UL, 0xc7892ec5681a0ab0UL, 0x1a0a0630f4cc9fb9UL, 0x48815436bef7c4b6UL, 0xa1cf9d4dd990a76fUL, 0xa56c2f8e839c2746UL, 0xd84ddf240c3f2b13UL, 0x7d9f21fe54adbdd2UL, 0x031aff3c6f358f1bUL, 0xd3905d6c86296eccUL, 0xf40b0c27fc91b9eaUL, 0x5a24b5e2d2901ba0UL, 0x7683449d4bc847bbUL, 0xc54dd281a3331482UL, 0x8f6f8b5eb73ac077UL, 0xb99ec55de9c532a0UL, 0xaedee0c7e55059e2UL, 0x2f9377a41ed485c5UL, 0x72eafb538ce583e8UL, 0xb5eb93c6165b8646UL, 0x3ff0af70673c327fUL, 0x6d502fc8fa40ca57UL, 0x95704e86a52e87ebUL, 0x712710607c339b1bUL, 0x4566ccfacebc3617UL, 0xce14cd117bd7f7dcUL, 0xd5b93e54d1aa8edbUL, 0xfb553e8168ebdca5UL, 0x0b0df7a642918c4aUL, 0xf50b1c338bf67d97UL, 0x8e7ce5186eaab38fUL, 0x5dcc06af0cf93ec3UL, 0x1b855433540288aeUL, 0xdfd1af20dfa87f78UL, 0x1464f39c3785d0bfUL, 0xa2e03e5fe551d9e6UL, 0xc99e8ff5a184f47dUL, 0xc3d8d3499413d699UL, 0x3dc5450867069861UL, 0x94a6226df3f12313UL, 0x3a69a11f65bafb67UL, 0x9a94a4b9d83052f5UL, 0xf20772e21f991c71UL, 0xadeb3fe1a1ccdea2UL, 0x6ad761dc5abe2a3aUL, 0xb880c1f9941726cdUL, 0xcd18ae74c66653eaUL, 0xfd9649c87ac6a3e3UL, 0x1d714aac1332fc78UL, 0xe0ee41d8707e48a0UL, 0x641e9effe4ea00a5UL, 0x17b5cfb868dc453aUL, 0x8d1e8f293280a696UL, 0xaee633ab32395cb8UL, 0xdfa3de545ff4528fUL, 0xfab54c8b5670c2fdUL, 0xf461d9ff88f74c93UL, 0x3b208c41f684c266UL, 0x578efa62fc110f78UL, 0xe64b0339d174d8fbUL, 0x8cb8a33be3020ffaUL, 0x6f66ca2d33ef34bbUL, 0x6194d0f714651ed1UL, 0x95e12f904fe7dda0UL, 0x91ef1fba242c29bcUL, 0x18176705d7283327UL, 0x7098d6ad81900c2eUL, 0x0580d1a8599fb21aUL, 0x84015d1bced4928aUL, 0xe46b6e4139e0977aUL, 0x257f0a22ec11bc1dUL, 0xf5e77f203820003cUL, 0xb44e275b35122504UL, 0xce539392f7cb6811UL, 0xc17004461d88d904UL, 0xaf297010d0164476UL, 0x2a5aac33a5f94629UL, 0xec6e36a8c1ca866dUL, 0xf52df2b470d42a86UL, 0xf051a672800eef43UL, 0x7723121ac94338e5UL, 0x3af80606c98faf7fUL, 0x8188bd55cd1c720bUL, 0x2170721a4d22531fUL, 0xb3c84442774bd366UL, 0xf6da1fd02d87d577UL, 0x2f691c91dc7bb727UL, 0xfe2d97b8992db9dcUL, 0x21728d8b2174002bUL, 0xf8eecef0ce2b3edaUL, 0xb0a1ba60d4946faaUL, 0x52cdcf8cc003eb62UL, 0xc7ef8697e7c26ab3UL, 0x6c20031b94e16920UL, 0xfa828735ed3cb8faUL, 0x296aefde709e6f60UL, 0xac2a9cf3d2e660cbUL, 0x078f7026fcc3facaUL, 0x220e8822b80b65e0UL, 0xac648f3472b75d22UL, 0xa12c577eb7633db3UL, 0x05d93c9c97fdee11UL, 0xd1e71104fd4ae8e0UL, 0x0d3a54142ccbec2eUL }; var expected11 = new ulong[] { 0x0d5455fb29afdb26UL, 0x665b4aafc468cce3UL, 0x2497c4907ba41570UL, 0x67883c5259bd80ebUL, 0x18c2b8eac7e0aafcUL, 0x1c6aee5c0a117fb9UL, 0x6adbbb9258fe3f3cUL, 0x7f42d49115f2d634UL, 0x873ecd17b6a0f313UL, 0xca035bf63dae9f91UL, 0xe86cd53af10ace54UL, 0x1e7230e3fb5d3e2fUL, 0x2077d1cdaedff2faUL, 0x102a0c29393308d0UL, 0xadae96c5c319f8cdUL, 0x3efbbd2ceaa694d3UL, 0xf90e7e77ee374716UL, 0x1a1389e16ee4f939UL, 0x413ddbcc102483ccUL, 0x5c73d57e9e7004feUL, 0xcecb86a979e1397fUL, 0xb908ae9f6ffdf374UL, 0xc13b87d96b5f719dUL, 0x86f08b6503879e95UL, 0x2fbdcb1cd4478120UL, 0x309fedcb1ad4dac7UL, 0xff247a8590cd7d06UL, 0xfb473c30a2e8c7cdUL, 0xf1d4f539d390d328UL, 0xbe4dfb38213213d0UL, 0x982a24ff77b3c0d2UL, 0xfecafa7b23f48875UL, 0xe8f19aa11703b398UL, 0x9e722bd401a61813UL, 0x41946bfeab21d25bUL, 0x49b3d1d4c01db24fUL, 0x4486ca528c7cbc82UL, 0xa55781c5f787ca3aUL, 0x4efa0d3e9383637dUL, 0x2c4ecd72302d444aUL, 0xb8b92f75e4c83363UL, 0x37d55d033d712e49UL, 0x7229bc73b695ebbeUL, 0x4be0daf4f5b04a4fUL, 0xac8718efefcfebbdUL, 0x09536b7ad0c6d87eUL, 0x2d5c064b115d73cbUL, 0xeda4f1ca9446361aUL, 0xf69f4afb12a4b8e1UL, 0x0ae04cbbf18a594bUL, 0xfeb4a9c7938d55eaUL, 0x62864daf547d0089UL, 0x964f33f96aea10e8UL, 0x041261ada2203a4dUL, 0xaa1d648492c362b5UL, 0xd9e909a61dff9859UL, 0x4003017994045585UL, 0x729cfbb22af630c7UL, 0xd165175002bc805eUL, 0x035e7ebbb2131851UL, 0xa86aecfc9a9b2adaUL, 0xa5becf9df02bd95cUL, 0x98d7d4e6d42bcf2cUL, 0xc2d4732f12f69191UL, 0x2a5b2c75ac464a87UL, 0xca6b0d4e8c1a1e36UL, 0x5f47747f88d012aeUL, 0xe5cb06e47ec52a18UL, 0xc10484d36ffb9009UL, 0xbb867ad3547cd9f6UL, 0x5e31b5d31def1ca1UL, 0x9e6ccd313604b382UL, 0x96d7b7a48a608728UL, 0x5b56c0a31cf8c59aUL, 0xf00df56d57682e80UL, 0xda0d7259c356ae4aUL, 0xed479fe50bbe5412UL, 0xa5c77f5549e9e6fcUL, 0x1164e76c428eb388UL, 0x178237111cbb14bdUL, 0x0a58c78ae91af8b6UL, 0x2d50a9920193838aUL, 0xc1556b371364fca7UL, 0x5da67f7a6bb836d0UL, 0xe41c25ffe2a32e58UL, 0xd6948ef3d8b5d544UL, 0x90ca547c7ad047c4UL, 0x2d2c1ba47159d370UL, 0xe7f44b48651760ebUL, 0xddaed69e7d4a1fa8UL, 0x1bcd924d1bc68f05UL, 0x74d50c178408ab0bUL, 0xc4df4db85b5d7285UL, 0x14926f0fecc3bf36UL, 0x2c796b006e41e92dUL, 0xaecdc2d1ce26491dUL, 0x2606173c65f273deUL, 0x3b65d6d4e6847d28UL, 0x907720f7772ed470UL, 0x256fa14a354c1304UL, 0x0be4aad94c7dffceUL, 0xa042440bb9f7557eUL, 0xc0cd069c4cef85d4UL, 0xc07c8601b20d5647UL, 0x2e6c906d4880dd27UL, 0x736b8c75e5765acfUL, 0xc9468e4cd9cfc7a5UL, 0xc9881c5ac58c8193UL, 0x9ce1d1a8573663bfUL, 0x5d97131ce7db872eUL, 0x858abc0cff42cbe6UL, 0x8966c871421606d7UL, 0x5b45a2d33827f1e9UL, 0xb3058993bdaf35bfUL, 0x14115152887d0319UL, 0x2a504362a04c472bUL, 0x70f4c117d593cc79UL, 0xb19768bfef91cff6UL, 0x8a310a753d2e6877UL, 0x001c29be4afea7aeUL, 0x231054402f69f427UL, 0xe01258eebe5f8ed8UL, 0x571c28935e68ebe4UL, 0x60f3148b1d546b2dUL, 0x1d87c04eb73098c2UL, 0xea0d944662c15303UL, 0x24f79172017ffaa1UL, 0x4d855aad955058daUL }; var actual = await subject.InitializeLanes(Encoding.UTF8.GetBytes("P@ssw0rd!$")).ConfigureAwait(false); Assert.Equal(expected00, actual[0][0]); Assert.Equal(expected01, actual[0][1]); Assert.Equal(expected10, actual[1][0]); Assert.Equal(expected11, actual[1][1]); } [Fact] public async void Hash_HashesAnArgon2dThingWithSalt() { var subject = new Argon2dCore(128); subject.DegreeOfParallelism = 2; subject.Iterations = 5; subject.MemorySize = 16; subject.Salt = new byte[] { 0xf7, 0x19, 0x2b, 0xa7, 0xff, 0xb8, 0xca, 0xdc, 0x67, 0x51, 0xed, 0xa0, 0x08, 0x1d, 0x9d, 0x95, 0x0b, 0x10, 0xe4, 0x32, 0x23, 0xef, 0x30, 0x07, 0x39, 0xc6, 0xbc, 0xad, 0x36, 0xda, 0x08, 0xeb, 0x03, 0x3b, 0xab, 0x98, 0x32, 0x06, 0x7d, 0x39, 0x6f, 0x81, 0x72, 0x24, 0xff, 0x58, 0x41, 0xe6, 0x33, 0x5d, 0xf7, 0xe7, 0x56, 0xf7, 0xaf, 0x32, 0xfa, 0xd8, 0x72, 0x78, 0xac, 0x63, 0xda, 0xd1 }; var expected = new byte[] { 0xed, 0x33, 0x02, 0x8b, 0x15, 0x1a, 0xa2, 0x75, 0x83, 0x06, 0x27, 0x08, 0x76, 0x2e, 0x2c, 0x68, 0x01, 0x04, 0xa1, 0xea, 0xcb, 0xf5, 0xff, 0x8e, 0xb3, 0xd5, 0xa9, 0x77, 0x22, 0x3c, 0x48, 0xa7, 0x0c, 0xea, 0xa1, 0x01, 0x58, 0xd2, 0x79, 0x16, 0x53, 0x67, 0x9c, 0x32, 0x70, 0x65, 0x9e, 0x50, 0x9b, 0x05, 0x90, 0x12, 0xd5, 0x21, 0x2f, 0xbc, 0xd9, 0x06, 0xfb, 0xb1, 0x05, 0x38, 0x5a, 0x9b, 0xb3, 0xc0, 0xd6, 0xd5, 0x2d, 0x2f, 0x75, 0x7f, 0x53, 0x77, 0x08, 0x86, 0xe3, 0x3a, 0x23, 0x5f, 0x43, 0x5e, 0xcc, 0x7c, 0x79, 0x0a, 0xbc, 0xd2, 0xa6, 0xae, 0xbd, 0xef, 0xe1, 0x6c, 0xd4, 0x60, 0x37, 0x54, 0x2c, 0x59, 0x49, 0x15, 0x26, 0x4c, 0xed, 0x61, 0x72, 0xd5, 0x24, 0x74, 0x86, 0x28, 0xdc, 0xa3, 0xe6, 0xc5, 0x99, 0x2a, 0x33, 0x3c, 0x64, 0x07, 0xe1, 0x4f, 0x8e, 0xe1, 0x43, 0xdd }; var actual = await subject.Hash(Encoding.UTF8.GetBytes("P@ssw0rd!$")).ConfigureAwait(false); Assert.Equal(expected, actual); } [Fact] public async void Hash_HashesAnArgon2iThingWithSalt() { var subject = new Argon2iCore(128); subject.DegreeOfParallelism = 2; subject.Iterations = 5; subject.MemorySize = 16; subject.Salt = new byte[] { 0xf7, 0x19, 0x2b, 0xa7, 0xff, 0xb8, 0xca, 0xdc, 0x67, 0x51, 0xed, 0xa0, 0x08, 0x1d, 0x9d, 0x95, 0x0b, 0x10, 0xe4, 0x32, 0x23, 0xef, 0x30, 0x07, 0x39, 0xc6, 0xbc, 0xad, 0x36, 0xda, 0x08, 0xeb, 0x03, 0x3b, 0xab, 0x98, 0x32, 0x06, 0x7d, 0x39, 0x6f, 0x81, 0x72, 0x24, 0xff, 0x58, 0x41, 0xe6, 0x33, 0x5d, 0xf7, 0xe7, 0x56, 0xf7, 0xaf, 0x32, 0xfa, 0xd8, 0x72, 0x78, 0xac, 0x63, 0xda, 0xd1 }; var expected = new byte[] { 0x59, 0xc2, 0x50, 0x75, 0x1a, 0x9d, 0xe4, 0x5f, 0x71, 0x0d, 0xc3, 0x1f, 0xe5, 0xfe, 0xc0, 0x51, 0xfc, 0x73, 0x94, 0x8a, 0x27, 0xda, 0x14, 0x26, 0xed, 0x9f, 0xe4, 0x68, 0x9c, 0xe3, 0x30, 0x92, 0x2f, 0x6b, 0xbf, 0x62, 0x45, 0x31, 0xa1, 0x86, 0xf1, 0xe7, 0xd5, 0x83, 0xb7, 0x5a, 0x12, 0x57, 0x01, 0xf0, 0x2a, 0x5e, 0xca, 0x1e, 0x39, 0x14, 0xba, 0xc2, 0x85, 0x31, 0xb0, 0x0b, 0xc1, 0xa0, 0x3a, 0xef, 0x1c, 0xc5, 0xd6, 0x05, 0xe8, 0x3c, 0x7a, 0xd8, 0x1e, 0xff, 0xab, 0x36, 0xc0, 0x82, 0x66, 0xe3, 0x96, 0xe4, 0xdf, 0x87, 0x0a, 0x0e, 0x80, 0xbf, 0x1b, 0xc4, 0x90, 0x9e, 0x75, 0x25, 0xa5, 0x67, 0xba, 0xd8, 0x50, 0x4d, 0xa9, 0x38, 0x4c, 0xa1, 0x65, 0x4b, 0x7c, 0x18, 0x8a, 0xcc, 0x65, 0x4b, 0xca, 0x04, 0x0f, 0x6e, 0xe5, 0xf7, 0xa2, 0x70, 0x2a, 0x84, 0x4b, 0x3e, 0x2f, 0xcd }; var actual = await subject.Hash(Encoding.UTF8.GetBytes("P@ssw0rd!$")).ConfigureAwait(false); Assert.Equal(expected, actual); } } }
// TODO: Logging. using System; using System.Collections; using Patterns.Logging; namespace SocketHttpListener.Net { public sealed class HttpListener : IDisposable { AuthenticationSchemes auth_schemes; HttpListenerPrefixCollection prefixes; AuthenticationSchemeSelector auth_selector; string realm; bool ignore_write_exceptions; bool unsafe_ntlm_auth; bool listening; bool disposed; Hashtable registry; // Dictionary<HttpListenerContext,HttpListenerContext> Hashtable connections; private ILogger _logger; private string _certificateLocation; public Action<HttpListenerContext> OnContext { get; set; } public HttpListener(ILogger logger, string certificateLocation) { _logger = logger; _certificateLocation = certificateLocation; prefixes = new HttpListenerPrefixCollection(logger, this); registry = new Hashtable(); connections = Hashtable.Synchronized(new Hashtable()); auth_schemes = AuthenticationSchemes.Anonymous; } // TODO: Digest, NTLM and Negotiate require ControlPrincipal public AuthenticationSchemes AuthenticationSchemes { get { return auth_schemes; } set { CheckDisposed(); auth_schemes = value; } } public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate { get { return auth_selector; } set { CheckDisposed(); auth_selector = value; } } public bool IgnoreWriteExceptions { get { return ignore_write_exceptions; } set { CheckDisposed(); ignore_write_exceptions = value; } } public bool IsListening { get { return listening; } } public static bool IsSupported { get { return true; } } public HttpListenerPrefixCollection Prefixes { get { CheckDisposed(); return prefixes; } } // TODO: use this public string Realm { get { return realm; } set { CheckDisposed(); realm = value; } } public bool UnsafeConnectionNtlmAuthentication { get { return unsafe_ntlm_auth; } set { CheckDisposed(); unsafe_ntlm_auth = value; } } internal string CertificateLocation { get { return _certificateLocation; } } public void Abort() { if (disposed) return; if (!listening) { return; } Close(true); } public void Close() { if (disposed) return; if (!listening) { disposed = true; return; } Close(true); disposed = true; } void Close(bool force) { CheckDisposed(); EndPointManager.RemoveListener(_logger, this); Cleanup(force); } void Cleanup(bool close_existing) { lock (registry) { if (close_existing) { // Need to copy this since closing will call UnregisterContext ICollection keys = registry.Keys; var all = new HttpListenerContext[keys.Count]; keys.CopyTo(all, 0); registry.Clear(); for (int i = all.Length - 1; i >= 0; i--) all[i].Connection.Close(true); } lock (connections.SyncRoot) { ICollection keys = connections.Keys; var conns = new HttpConnection[keys.Count]; keys.CopyTo(conns, 0); connections.Clear(); for (int i = conns.Length - 1; i >= 0; i--) conns[i].Close(true); } } } internal AuthenticationSchemes SelectAuthenticationScheme(HttpListenerContext context) { if (AuthenticationSchemeSelectorDelegate != null) return AuthenticationSchemeSelectorDelegate(context.Request); else return auth_schemes; } public void Start() { CheckDisposed(); if (listening) return; EndPointManager.AddListener(_logger, this); listening = true; } public void Stop() { CheckDisposed(); listening = false; Close(false); } void IDisposable.Dispose() { if (disposed) return; Close(true); //TODO: Should we force here or not? disposed = true; } internal void CheckDisposed() { if (disposed) throw new ObjectDisposedException(GetType().ToString()); } internal void RegisterContext(HttpListenerContext context) { if (OnContext != null && IsListening) { OnContext(context); } lock (registry) registry[context] = context; } internal void UnregisterContext(HttpListenerContext context) { lock (registry) registry.Remove(context); } internal void AddConnection(HttpConnection cnc) { connections[cnc] = cnc; } internal void RemoveConnection(HttpConnection cnc) { connections.Remove(cnc); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using System.Reflection; namespace Ecosim.SceneData { public abstract class Question { public string body; public bool opened; public bool answersOpened; public List<Answer> answers; public abstract void Save (XmlTextWriter writer, Scene scene); public abstract void Load (XmlTextReader reader, Scene scene); public abstract void UpdateReferences (Scene scene); } public abstract class Answer { public string body; public string feedback; public bool useFeedback; public bool opened; public bool feedbackOpened; public abstract void Save (XmlTextWriter writer, Scene scene); public abstract void Load (XmlTextReader reader, Scene scene); public abstract void UpdateReferences (Scene scene); } public class MPCQuestion : Question { public class MPCAnswer : Answer { public const string XML_ELEMENT = "answer"; public bool startFromBeginning; public int moneyGained; public int score; public bool allowRetry; public MPCAnswer () { body = "New answer"; feedback = "Feedback"; moneyGained = 0; score = 0; startFromBeginning = false; allowRetry = false; } override public void Save (XmlTextWriter writer, Scene scene) { writer.WriteStartElement (XML_ELEMENT); writer.WriteAttributeString ("body", body); writer.WriteAttributeString ("feedback", feedback); writer.WriteAttributeString ("usefb", useFeedback.ToString().ToLower()); writer.WriteAttributeString ("startover", startFromBeginning.ToString().ToLower()); writer.WriteAttributeString ("money", moneyGained.ToString()); writer.WriteAttributeString ("score", score.ToString()); writer.WriteAttributeString ("allowretry", allowRetry.ToString().ToLower()); writer.WriteEndElement (); } override public void Load (XmlTextReader reader, Scene scene) { body = reader.GetAttribute ("body"); feedback = reader.GetAttribute ("feedback"); useFeedback = bool.Parse (reader.GetAttribute ("usefb")); startFromBeginning = bool.Parse (reader.GetAttribute ("startover")); moneyGained = int.Parse (reader.GetAttribute ("money")); score = int.Parse (reader.GetAttribute ("score")); allowRetry = bool.Parse (reader.GetAttribute ("allowretry")); if (!reader.IsEmptyElement) { while (reader.Read ()) { XmlNodeType nt = reader.NodeType; if (nt == XmlNodeType.Element) { /*switch (reader.Name.ToLower ()) { case "" : break; }*/ } else if (nt == XmlNodeType.EndElement && reader.Name.ToLower () == XML_ELEMENT) { break; } } } } override public void UpdateReferences (Scene scene) { } } public const string XML_ELEMENT = "mpc"; public MPCQuestion () { this.answers = new List<Answer> (); this.answers.Add (new MPCAnswer ()); this.answers.Add (new MPCAnswer ()); this.body = "New multiple choice question"; } override public void Save (XmlTextWriter writer, Scene scene) { writer.WriteStartElement (XML_ELEMENT); writer.WriteAttributeString ("body", body); foreach (Answer a in answers) { a.Save (writer, scene); } writer.WriteEndElement (); } override public void Load (XmlTextReader reader, Scene scene) { this.answers = new List<Answer> (); body = reader.GetAttribute ("body"); if (!reader.IsEmptyElement) { while (reader.Read ()) { XmlNodeType nt = reader.NodeType; if (nt == XmlNodeType.Element) { switch (reader.Name.ToLower ()) { case MPCAnswer.XML_ELEMENT : MPCAnswer a = new MPCAnswer(); a.Load (reader, scene); this.answers.Add (a); break; } } else if (nt == XmlNodeType.EndElement && reader.Name.ToLower () == XML_ELEMENT) { break; } } } } override public void UpdateReferences (Scene scene) { foreach (MPCAnswer a in answers) { a.UpdateReferences (scene); } } } public class OpenQuestion : Question { public class OpenAnswer : Answer { public const string XML_ELEMENT = "answer"; public bool useMaxChars; public int maxChars; public bool copyToReport; public List<int> reportIndices; public bool reportIndicesOpened; public OpenAnswer () { body = "Write your answer"; feedback = "Feedback"; maxChars = 0; useMaxChars = false; copyToReport = false; reportIndices = new List<int>(); reportIndices.Add (1); } override public void Save (XmlTextWriter writer, Scene scene) { writer.WriteStartElement (XML_ELEMENT); writer.WriteAttributeString ("body", body); writer.WriteAttributeString ("feedback", feedback); writer.WriteAttributeString ("usefb", useFeedback.ToString().ToLower()); writer.WriteAttributeString ("usemaxchars", useMaxChars.ToString().ToLower()); writer.WriteAttributeString ("maxchars", maxChars.ToString()); writer.WriteAttributeString ("copytoreport", copyToReport.ToString().ToLower()); string reportIndicesStr = ""; foreach (int i in reportIndices) { reportIndicesStr += i.ToString() + ","; } reportIndicesStr = reportIndicesStr.TrimEnd (','); writer.WriteAttributeString ("copytoreports", reportIndicesStr); writer.WriteEndElement (); } override public void Load (XmlTextReader reader, Scene scene) { body = reader.GetAttribute ("body"); feedback = reader.GetAttribute ("feedback"); useFeedback = bool.Parse (reader.GetAttribute ("usefb")); maxChars = int.Parse (reader.GetAttribute ("maxchars")); useMaxChars = bool.Parse (reader.GetAttribute ("usemaxchars")); copyToReport = bool.Parse (reader.GetAttribute ("copytoreport")); string indicesStr = reader.GetAttribute ("copytoreports"); string[] indices = indicesStr.Split (','); reportIndices = new List<int> (); if (indicesStr.Length > 0) { foreach (string i in indices) { int idx = 0; if (int.TryParse (i, out idx)) { reportIndices.Add (idx); } } } if (!reader.IsEmptyElement) { while (reader.Read ()) { XmlNodeType nt = reader.NodeType; if (nt == XmlNodeType.Element) { /*switch (reader.Name.ToLower ()) { case "" : break; }*/ } else if (nt == XmlNodeType.EndElement && reader.Name.ToLower () == XML_ELEMENT) { break; } } } } override public void UpdateReferences (Scene scene) { } } public const string XML_ELEMENT = "open"; public OpenQuestion () { answers = new List<Answer> (); answers.Add (new OpenAnswer()); this.body = "New open question"; } override public void Save (XmlTextWriter writer, Scene scene) { writer.WriteStartElement (XML_ELEMENT); writer.WriteAttributeString ("body", body); foreach (Answer a in answers) { a.Save (writer, scene); } writer.WriteEndElement (); } override public void Load (XmlTextReader reader, Scene scene) { this.body = reader.GetAttribute ("body"); this.answers = new List<Answer> (); if (!reader.IsEmptyElement) { while (reader.Read ()) { XmlNodeType nt = reader.NodeType; if (nt == XmlNodeType.Element) { switch (reader.Name.ToLower ()) { case OpenAnswer.XML_ELEMENT : OpenAnswer a = new OpenAnswer (); a.Load (reader, scene); this.answers.Add (a); break; } } else if (nt == XmlNodeType.EndElement && reader.Name.ToLower () == XML_ELEMENT) { break; } } } } override public void UpdateReferences (Scene scene) { foreach (Answer a in answers) { a.UpdateReferences (scene); } } } public class Questionnaire : ReportBase { public const string XML_ELEMENT = "questionnaire"; private Scene scene; // TODO: All todo's mean they have to be processed in the Editor interface public bool useRequiredScore; public int requiredScore; public bool useReqScoreFeedback; public string reqScoreFeedback; public bool usePassedFeedback; public bool useFailedFeedback; public string passedFeedback; public string failedFeedback; public bool startOverOnFailed; public List<Question> questions; public bool useBudget; public bool useBudgetFeedback; public string budgetFeedback; public bool useResultsPage; public bool questionsOpened; public bool reqScoreOpened; public bool reqScoreFeedbackOpened; public bool budgetOpened; public bool budgetFeedbackOpened; public bool passedFeedbackOpened; public bool failedFeedbackOpened; public int currentQuestionIndex; public Questionnaire () : base() { this.questions = new List<Question>(); this.name = "New questionnaire"; this.requiredScore = 100; this.passedFeedback = "Passed"; this.failedFeedback = "Failed"; this.budgetFeedback = "Explanation"; this.reqScoreFeedback = "Explanation"; this.currentQuestionIndex = 0; this.useResultsPage = true; this.showHeader = true; } public Questionnaire Copy () { Questionnaire copy = new Questionnaire (); FieldInfo[] fields = this.GetType ().GetFields (BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance); foreach (FieldInfo fi in fields) { fi.SetValue (copy, fi.GetValue (this)); } FieldInfo[] baseFields = typeof (ReportBase).GetFields (BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance); foreach (FieldInfo fi in baseFields) { fi.SetValue (copy, fi.GetValue (this)); } return copy; } public static Questionnaire Load (XmlTextReader reader, Scene scene) { Questionnaire q = new Questionnaire (); q.LoadBase (reader, scene); q.useRequiredScore = bool.Parse (reader.GetAttribute ("usereqscore")); q.requiredScore = int.Parse (reader.GetAttribute ("reqscore")); q.useReqScoreFeedback = bool.Parse (reader.GetAttribute ("usereqscorefb")); q.reqScoreFeedback = reader.GetAttribute ("reqscorefb"); q.usePassedFeedback = bool.Parse (reader.GetAttribute ("usepassedfb")); q.useFailedFeedback = bool.Parse (reader.GetAttribute ("usefailedfb")); q.passedFeedback = reader.GetAttribute ("passedfb"); q.failedFeedback = reader.GetAttribute ("failedfb"); q.startOverOnFailed = bool.Parse (reader.GetAttribute ("failstartover")); q.useBudget = bool.Parse (reader.GetAttribute ("usebudget")); q.useBudgetFeedback = bool.Parse (reader.GetAttribute ("usebudgetfb")); q.budgetFeedback = reader.GetAttribute ("budgetfb"); if (!string.IsNullOrEmpty (reader.GetAttribute ("useresultspg"))) { q.useResultsPage = bool.Parse (reader.GetAttribute ("useresultspg")); } if (!reader.IsEmptyElement) { while (reader.Read ()) { XmlNodeType nt = reader.NodeType; if (nt == XmlNodeType.Element) { switch (reader.Name.ToLower ()) { case OpenQuestion.XML_ELEMENT : { OpenQuestion newQ = new OpenQuestion (); newQ.Load (reader, scene); q.questions.Add (newQ); } break; case MPCQuestion.XML_ELEMENT: { MPCQuestion newQ = new MPCQuestion (); newQ.Load (reader, scene); q.questions.Add (newQ); } break; } } else if (nt == XmlNodeType.EndElement && reader.Name.ToLower () == XML_ELEMENT) { break; } } } return q; } public void Save (XmlTextWriter writer, Scene scene) { writer.WriteStartElement (XML_ELEMENT); this.SaveBase (writer, scene); writer.WriteAttributeString ("usereqscore", useRequiredScore.ToString().ToLower()); writer.WriteAttributeString ("reqscore", requiredScore.ToString()); writer.WriteAttributeString ("usereqscorefb", useReqScoreFeedback.ToString().ToLower()); writer.WriteAttributeString ("reqscorefb", reqScoreFeedback.ToString()); writer.WriteAttributeString ("usepassedfb", usePassedFeedback.ToString().ToLower()); writer.WriteAttributeString ("usefailedfb", useFailedFeedback.ToString().ToLower()); writer.WriteAttributeString ("passedfb", passedFeedback); writer.WriteAttributeString ("failedfb", failedFeedback); writer.WriteAttributeString ("failstartover", startOverOnFailed.ToString().ToLower()); writer.WriteAttributeString ("usebudget", useBudget.ToString().ToLower()); writer.WriteAttributeString ("usebudgetfb", useBudgetFeedback.ToString().ToLower()); writer.WriteAttributeString ("budgetfb", budgetFeedback.ToString()); writer.WriteAttributeString ("useresultspg", useResultsPage.ToString().ToLower ()); foreach (Question q in this.questions) { q.Save (writer, scene); } writer.WriteEndElement (); } public override void UpdateReferences (Scene scene) { foreach (Question q in this.questions) { q.UpdateReferences (scene); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using DryIoc; using FluentValidation; using FluentValidation.Results; using Maple.Core; using Maple.Domain; using Microsoft.VisualStudio.TestTools.UnitTesting; using NSubstitute; namespace Maple.Test.ViewModels { [TestClass, TestCategory("PlaylistTests")] public class PlaylistTests { private static TestContext _context; private static ValidationResult _defaultValidationResult; [ClassInitialize] public static void ClassInitialize(TestContext context) { _context = context; _defaultValidationResult = new ValidationResult(Enumerable.Empty<ValidationFailure>()); } [TestMethod] public async Task Playlist_ShouldRunConstructorWithoutErrors() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var model = _context.CreateModelPlaylist(); var playlist = container.CreatePlaylist(model); Assert.AreEqual(_context.FullyQualifiedTestClassName, playlist.CreatedBy); Assert.AreEqual(_context.FullyQualifiedTestClassName, playlist.UpdatedBy); Assert.AreEqual(4, playlist.Count); Assert.AreEqual($"Description for {_context.FullyQualifiedTestClassName} Playlist", playlist.Description); Assert.AreEqual(false, playlist.HasErrors); Assert.AreEqual(1, playlist.Id); Assert.AreEqual(false, playlist.IsBusy); Assert.AreEqual(false, playlist.IsChanged); Assert.AreEqual(false, playlist.IsDeleted); Assert.AreEqual(false, playlist.IsNew); Assert.AreEqual(false, playlist.IsSelected); Assert.AreEqual(false, playlist.IsShuffeling); Assert.AreEqual(4, playlist.Items.Count); Assert.AreEqual(model, playlist.Model); Assert.AreEqual(PrivacyStatus.None, playlist.PrivacyStatus); Assert.AreEqual(RepeatMode.None, playlist.RepeatMode); Assert.AreEqual(playlist[0], playlist.SelectedItem); Assert.AreEqual(1, playlist.Sequence); Assert.AreEqual($"Title for {_context.FullyQualifiedTestClassName} Playlist", playlist.Title); Assert.IsNotNull(playlist.View); Assert.IsNotNull(playlist.ClearCommand); Assert.IsNotNull(playlist.LoadFromFileCommand); Assert.IsNotNull(playlist.LoadFromFolderCommand); Assert.IsNotNull(playlist.LoadFromUrlCommand); Assert.IsNotNull(playlist.RemoveCommand); Assert.IsNotNull(playlist.RemoveRangeCommand); } [TestMethod] public async Task Playlist_ShouldThrowForEmptyModel() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); Assert.ThrowsException<ArgumentNullException>(() => container.CreatePlaylist(default(PlaylistModel))); } [TestMethod] public async Task Playlist_ShouldThrowForEmptyContainer() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); Assert.ThrowsException<ArgumentNullException>(() => new Playlist(null, container.Resolve<IValidator<Playlist>>(), container.Resolve<IDialogViewModel>(), container.Resolve<IMediaItemMapper>(), _context.CreateModelPlaylist())); } [TestMethod] public async Task Playlist_ShouldThrowForEmptyValidator() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); Assert.ThrowsException<ArgumentNullException>(() => new Playlist(container.Resolve<ViewModelServiceContainer>(), null, container.Resolve<IDialogViewModel>(), container.Resolve<IMediaItemMapper>(), _context.CreateModelPlaylist())); } [TestMethod] public async Task Playlist_ShouldThrowForEmptyViewModel() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); Assert.ThrowsException<ArgumentNullException>(() => new Playlist(container.Resolve<ViewModelServiceContainer>(), container.Resolve<IValidator<Playlist>>(), null, container.Resolve<IMediaItemMapper>(), _context.CreateModelPlaylist())); } [TestMethod] public async Task Playlist_ShouldThrowForEmptyMediaItemMapper() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); Assert.ThrowsException<ArgumentNullException>(() => new Playlist(container.Resolve<ViewModelServiceContainer>(), container.Resolve<IValidator<Playlist>>(), container.Resolve<IDialogViewModel>(), null, _context.CreateModelPlaylist())); } [TestMethod] public async Task Playlist_ShouldRunClear() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.AreEqual(4, playlist.Count); playlist.Clear(); Assert.AreEqual(0, playlist.Count); } [TestMethod] public async Task Playlist_ShouldAdd() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var mediaItem = container.CreateMediaItem(_context.CreateModelMediaItem()); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.AreEqual(4, playlist.Count); playlist.Add(mediaItem); Assert.AreEqual(5, playlist.Count); } [TestMethod] public async Task Playlist_ShouldThrowAddForNull() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.ThrowsException<ArgumentNullException>(() => playlist.Add(null)); } [TestMethod] public async Task Playlist_ShouldAddRange() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var mediaItems = new[] { container.CreateMediaItem(_context.CreateModelMediaItem()), container.CreateMediaItem(_context.CreateModelMediaItem()), container.CreateMediaItem(_context.CreateModelMediaItem()), }; var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.AreEqual(4, playlist.Count); playlist.AddRange(mediaItems); Assert.AreEqual(7, playlist.Count); } [TestMethod] public async Task Playlist_ShouldHandleAddRangeForEmptyCollection() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var mediaItems = new List<MediaItem>(); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.AreEqual(4, playlist.Count); playlist.AddRange(mediaItems); Assert.AreEqual(4, playlist.Count); } [TestMethod] public async Task Playlist_ShouldThrowAddRangeForNull() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.AreEqual(4, playlist.Count); Assert.ThrowsException<ArgumentNullException>(() => playlist.AddRange(null)); } [TestMethod] public async Task Playlist_ShouldHandleAddRangeForDuplicateEntries() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var mediaItem = container.CreateMediaItem(_context.CreateModelMediaItem()); var mediaItems = new[] { mediaItem, mediaItem, mediaItem, }; var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.AreEqual(4, playlist.Count); playlist.AddRange(mediaItems); Assert.AreEqual(7, playlist.Count); } [TestMethod] public async Task Playlist_ShouldRemove() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.AreEqual(4, playlist.Count); playlist.Remove(playlist[0]); Assert.AreEqual(3, playlist.Count); } [TestMethod] public async Task Playlist_ShouldThrowRemoveForNull() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.ThrowsException<ArgumentNullException>(() => playlist.Remove(null)); } [TestMethod] public async Task Playlist_ShouldRemoveRange() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); var mediaItems = new[] { playlist[0], playlist[1], playlist[2], }; Assert.AreEqual(4, playlist.Count); playlist.RemoveRange(mediaItems); Assert.AreEqual(1, playlist.Count); } [TestMethod] public async Task Playlist_ShouldThrowRemoveRangeForNull() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); Assert.ThrowsException<ArgumentNullException>(() => playlist.RemoveRange(null)); } [TestMethod] public async Task Playlist_ShouldHandleRemoveRangeForSameItem() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); var mediaItems = new[] { playlist[0], playlist[0], playlist[0], }; Assert.AreEqual(4, playlist.Count); playlist.RemoveRange(mediaItems); Assert.AreEqual(3, playlist.Count); } [TestMethod] public async Task Playlist_ShouldHandleRemoveRangeForUnknownItem() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); var mediaItems = new List<MediaItem>() { container.CreateMediaItem(new MediaItemModel()), }; Assert.AreEqual(4, playlist.Count); playlist.RemoveRange(mediaItems); Assert.AreEqual(4, playlist.Count); } [TestMethod] public async Task Playlist_ShouldHandleRemoveRangeForUnknownItems() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); var mediaItems = new[] { container.CreateMediaItem(new MediaItemModel()), container.CreateMediaItem(new MediaItemModel()), container.CreateMediaItem(new MediaItemModel()), }; Assert.AreEqual(4, playlist.Count); playlist.RemoveRange(mediaItems); Assert.AreEqual(4, playlist.Count); } [TestMethod] public async Task Playlist_ShouldHandleRemoveRangeForEmptyCollection() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); var mediaItems = new List<MediaItem>(); Assert.AreEqual(4, playlist.Count); playlist.RemoveRange(mediaItems); Assert.AreEqual(4, playlist.Count); } [TestMethod] public async Task Playlist_ShouldRunNext() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); playlist.RepeatMode = RepeatMode.None; var mediaItem = playlist.Next(); Assert.IsNotNull(mediaItem); Assert.AreEqual(playlist[1], mediaItem); Assert.AreNotEqual(playlist.SelectedItem, mediaItem); } [TestMethod] public async Task Playlist_ShouldRunNextWithRepeatModeNone() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); playlist.RepeatMode = RepeatMode.None; playlist.SelectedItem = playlist[3]; var mediaItem = playlist.Next(); Assert.IsNull(mediaItem); } [TestMethod] public async Task Playlist_ShouldRunNextWithRepeatModeAll() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); playlist.RepeatMode = RepeatMode.All; playlist.SelectedItem = playlist[3]; var mediaItem = playlist.Next(); Assert.IsNotNull(mediaItem); Assert.AreEqual(playlist[0], mediaItem); } [TestMethod] public async Task Playlist_ShouldRunNextWithRepeatModeAllWhileShuffeling() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); playlist.RepeatMode = RepeatMode.All; playlist.IsShuffeling = true; playlist.SelectedItem = playlist[3]; var mediaItem = playlist.Next(); Assert.IsNotNull(mediaItem); Assert.AreNotEqual(playlist.SelectedItem, mediaItem); } [TestMethod] public async Task Playlist_ShouldRunNextWithRepeatModeNoneWhileShuffeling() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); playlist.RepeatMode = RepeatMode.None; playlist.IsShuffeling = true; playlist.SelectedItem = playlist[3]; var mediaItem = playlist.Next(); Assert.IsNotNull(mediaItem); Assert.AreNotEqual(playlist.SelectedItem, mediaItem); } [TestMethod] public async Task Playlist_ShouldRunNextWithRepeatModeSingleWhileShuffeling() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); playlist.RepeatMode = RepeatMode.Single; playlist.IsShuffeling = true; var mediaItem = playlist.Next(); Assert.IsNotNull(mediaItem); Assert.AreEqual(playlist[0], mediaItem); Assert.AreEqual(playlist.SelectedItem, mediaItem); } [TestMethod] public async Task Playlist_ShouldRunNextWithRepeatModeSingle() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); playlist.RepeatMode = RepeatMode.Single; var mediaItem = playlist.Next(); Assert.IsNotNull(mediaItem); Assert.AreEqual(playlist[0], mediaItem); Assert.AreEqual(playlist.SelectedItem, mediaItem); } [TestMethod] public async Task Playlist_ShouldRunPrevious() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); var messenger = container.Resolve<IMessenger>(); messenger.Publish(new PlayingMediaItemMessage(this, playlist[0], playlist.Id)); messenger.Publish(new PlayingMediaItemMessage(this, playlist[1], playlist.Id)); messenger.Publish(new PlayingMediaItemMessage(this, playlist[2], playlist.Id)); var previous = playlist.Previous(); Assert.AreEqual(playlist[2], previous); Assert.AreEqual(true, previous.IsSelected); Assert.AreEqual(1, playlist.Items.Where(p => p.IsSelected).Count()); previous = playlist.Previous(); Assert.AreEqual(playlist[1], previous); Assert.AreEqual(true, previous.IsSelected); Assert.AreEqual(1, playlist.Items.Where(p => p.IsSelected).Count()); previous = playlist.Previous(); Assert.AreEqual(playlist[0], previous); Assert.AreEqual(true, previous.IsSelected); Assert.AreEqual(1, playlist.Items.Where(p => p.IsSelected).Count()); previous = playlist.Previous(); Assert.AreEqual(null, previous); Assert.AreEqual(0, playlist.Items.Where(p => p.IsSelected).Count()); previous = playlist.Previous(); Assert.AreEqual(null, previous); Assert.AreEqual(0, playlist.Items.Where(p => p.IsSelected).Count()); } [TestMethod] public async Task Playlist_ShouldRaiseSelectionChanging() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var messenger = Substitute.For<IMessenger>(); container.UseInstance(typeof(IMessenger), messenger, IfAlreadyRegistered: IfAlreadyRegistered.Replace); Assert.AreEqual(messenger, container.Resolve<IMessenger>()); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); messenger.ClearReceivedCalls(); playlist.SelectedItem = playlist[1]; messenger.Received(1).Publish(NSubstitute.Arg.Any<ViewModelSelectionChangingMessage<MediaItem>>()); } [TestMethod] public async Task Playlist_ShouldRaiseSelectionChanged() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var messenger = Substitute.For<IMessenger>(); container.UseInstance(typeof(IMessenger), messenger, IfAlreadyRegistered: IfAlreadyRegistered.Replace); Assert.AreEqual(messenger, container.Resolve<IMessenger>()); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); messenger.ClearReceivedCalls(); playlist.SelectedItem = playlist[1]; messenger.Received(1).Publish(NSubstitute.Arg.Any<ViewModelSelectionChangedMessage<MediaItem>>()); } [TestMethod] public async Task Playlist_ShouldSynchronizeItemsWithModelWhenRemovingSelectedItem() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var model = _context.CreateModelPlaylist(); var playlist = container.CreatePlaylist(model); var selectedModel = playlist.SelectedItem.Model; var next = playlist.Next(); Assert.AreEqual(model.MediaItems.Count, playlist.Count); playlist.Remove(playlist.SelectedItem); Assert.AreEqual(3, playlist.Count); Assert.AreEqual(true, selectedModel.IsDeleted); Assert.AreEqual(next, playlist.SelectedItem); } [TestMethod] public async Task Playlist_ShouldSynchronizeItemsWithModelWhenRemoving() { var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var model = _context.CreateModelPlaylist(); var playlist = container.CreatePlaylist(model); var mediaItem1 = playlist[1]; var mediaItem2 = playlist[2]; var mediaItem3 = playlist[3]; Assert.AreEqual(model.MediaItems.Count, playlist.Count); playlist.Remove(mediaItem1); Assert.AreEqual(3, playlist.Count); Assert.AreEqual(true, mediaItem1.IsDeleted); playlist.RemoveRange(new[] { mediaItem2, mediaItem3 }); Assert.AreEqual(1, playlist.Count); Assert.AreEqual(true, mediaItem2.IsDeleted); Assert.AreEqual(true, mediaItem3.IsDeleted); } [TestMethod] public async Task Playlist_ShouldAddItemsFromFileDialog() { var tokenSource = new CancellationTokenSource(1000); var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var mediaItems = new[] { container.CreateMediaItem(new MediaItemModel()), container.CreateMediaItem(new MediaItemModel()), container.CreateMediaItem(new MediaItemModel()), }; var dialogViewModel = Substitute.For<IDialogViewModel>(); dialogViewModel.ShowMediaItemSelectionDialog(NSubstitute.Arg.Any<FileSystemBrowserOptions>(), NSubstitute.Arg.Any<CancellationToken>()).Returns((true, mediaItems)); container.UseInstance(typeof(IDialogViewModel), dialogViewModel, IfAlreadyRegistered: IfAlreadyRegistered.Replace); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); foreach (var item in mediaItems) Assert.AreEqual(false, playlist.Items.Contains(item)); await playlist.LoadFromFileCommand.ExecuteAsync(tokenSource.Token).ConfigureAwait(false); foreach (var item in mediaItems) Assert.AreEqual(true, playlist.Items.Contains(item)); } [TestMethod] public async Task Playlist_ShouldAddItemsFromFolderDialog() { var tokenSource = new CancellationTokenSource(1000); var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var mediaItems = new[] { container.CreateMediaItem(new MediaItemModel()), container.CreateMediaItem(new MediaItemModel()), container.CreateMediaItem(new MediaItemModel()), }; var dialogViewModel = Substitute.For<IDialogViewModel>(); dialogViewModel.ShowMediaItemFolderSelectionDialog(NSubstitute.Arg.Any<FileSystemFolderBrowserOptions>(), NSubstitute.Arg.Any<CancellationToken>()).Returns((true, mediaItems)); container.UseInstance(typeof(IDialogViewModel), dialogViewModel, IfAlreadyRegistered: IfAlreadyRegistered.Replace); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); foreach (var item in mediaItems) Assert.AreEqual(false, playlist.Items.Contains(item)); await playlist.LoadFromFolderCommand.ExecuteAsync(tokenSource.Token).ConfigureAwait(false); foreach (var item in mediaItems) Assert.AreEqual(true, playlist.Items.Contains(item)); } [TestMethod] public async Task Playlist_ShouldAddItemsFromUrlDialog() { var tokenSource = new CancellationTokenSource(1000); var container = await DependencyInjectionFactory.Get().ConfigureAwait(false); var mediaItems = new[] { container.CreateMediaItem(new MediaItemModel()), container.CreateMediaItem(new MediaItemModel()), container.CreateMediaItem(new MediaItemModel()), }; var dialogViewModel = Substitute.For<IDialogViewModel>(); dialogViewModel.ShowUrlParseDialog(NSubstitute.Arg.Any<CancellationToken>()).Returns((mediaItems)); container.UseInstance(typeof(IDialogViewModel), dialogViewModel, IfAlreadyRegistered: IfAlreadyRegistered.Replace); var playlist = container.CreatePlaylist(_context.CreateModelPlaylist()); foreach (var item in mediaItems) Assert.AreEqual(false, playlist.Items.Contains(item)); await playlist.LoadFromUrlCommand.ExecuteAsync(tokenSource.Token).ConfigureAwait(false); foreach (var item in mediaItems) Assert.AreEqual(true, playlist.Items.Contains(item)); } } }
namespace Caliburn.ShellFramework.Services { using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Markup; using Core; using Core.Logging; using PresentationFramework; using PresentationFramework.ApplicationModel; using PresentationFramework.Screens; using PresentationFramework.Views; /// <summary> /// The default implementation of <see cref="IBusyService"/>. /// </summary> public class DefaultBusyService : IBusyService { /// <summary> /// The log. /// </summary> protected static readonly ILog Log = LogManager.GetLog(typeof(DefaultBusyService)); /// <summary> /// The Indicators lock. /// </summary> protected readonly object IndicatorLock = new object(); /// <summary> /// The currently active busy indicator, keyed by ViewModel. /// </summary> protected readonly Dictionary<object, BusyInfo> Indicators = new Dictionary<object, BusyInfo>(); /// <summary> /// The window manager. /// </summary> protected readonly IWindowManager WindowManager; readonly object defaultKey = new object(); /// <summary> /// Initializes a new instance of the <see cref="DefaultBusyService"/> class. /// </summary> /// <param name="windowManager">The window manager.</param> public DefaultBusyService(IWindowManager windowManager) { WindowManager = windowManager; } /// <summary> /// Marks a ViewModel as busy. /// </summary> /// <param name="sourceViewModel">The ViewModel to mark as busy.</param> /// <param name="busyViewModel">The busy content ViewModel.</param> public void MarkAsBusy(object sourceViewModel, object busyViewModel) { sourceViewModel = sourceViewModel ?? defaultKey; if(Indicators.ContainsKey(sourceViewModel)) { var info = Indicators[sourceViewModel]; info.BusyViewModel = busyViewModel; var indicator = TryFindBusyIndicator(sourceViewModel); if(info.BusyIndicator != indicator) { info.BusyIndicator = indicator; ToggleBusyIndicator(info, true); } UpdateIndicator(info); } else { var busyIndicator = TryFindBusyIndicator(sourceViewModel); if(busyIndicator == null) NoBusyIndicatorFound(sourceViewModel, busyViewModel); else BusyIndicatorFound(sourceViewModel, busyViewModel, busyIndicator); } } /// <summary> /// Marks a ViewModel as not busy. /// </summary> /// <param name="sourceViewModel">The ViewModel to mark as not busy.</param> public void MarkAsNotBusy(object sourceViewModel) { sourceViewModel = sourceViewModel ?? defaultKey; BusyInfo info; if(!Indicators.TryGetValue(sourceViewModel, out info)) return; lock(IndicatorLock) { info.Depth--; if(info.Depth == 0) { Indicators.Remove(sourceViewModel); ToggleBusyIndicator(info, false); } } } /// <summary> /// Called when the busy indicator is found. /// </summary> /// <param name="sourceViewModel">The source view model.</param> /// <param name="busyViewModel">The busy view model.</param> /// <param name="busyIndicator">The busy indicator.</param> protected virtual void BusyIndicatorFound(object sourceViewModel, object busyViewModel, UIElement busyIndicator) { var info = new BusyInfo { BusyIndicator = busyIndicator, BusyViewModel = busyViewModel }; Indicators[sourceViewModel] = info; ToggleBusyIndicator(info, true); UpdateIndicator(info); } /// <summary> /// Called when no busy indicator can be found. /// </summary> /// <param name="sourceViewModel">The source view model.</param> /// <param name="busyViewModel">The busy view model.</param> protected virtual void NoBusyIndicatorFound(object sourceViewModel, object busyViewModel) { var activator = busyViewModel as IActivate; if(activator == null) return; activator.Activated += (s, e) =>{ if(!e.WasInitialized) return; var info = new BusyInfo { BusyViewModel = busyViewModel }; Indicators[sourceViewModel] = info; UpdateIndicator(info); }; Log.Warn("No busy indicator was found in the UI hierarchy. Using modal dialog."); WindowManager.ShowDialog(busyViewModel, null); } /// <summary> /// Updates the indicator. /// </summary> /// <param name="info">The info.</param> protected virtual void UpdateIndicator(BusyInfo info) { lock(IndicatorLock) { info.Depth++; } if(info.BusyViewModel == null || info.BusyIndicator == null) return; var indicatorType = info.BusyIndicator.GetType(); var content = indicatorType.GetProperty("BusyContent"); if(content == null) { var contentProperty = indicatorType.GetAttributes<ContentPropertyAttribute>(true) .FirstOrDefault(); if(contentProperty == null) return; content = indicatorType.GetProperty(contentProperty.Name); } content.SetValue(info.BusyIndicator, info.BusyViewModel, null); } /// <summary> /// Toggles the busy indicator. /// </summary> /// <param name="info">The info.</param> /// <param name="isBusy">if set to <c>true</c> should be busy.</param> protected void ToggleBusyIndicator(BusyInfo info, bool isBusy) { if(info.BusyIndicator != null) { var busyProperty = info.BusyIndicator.GetType().GetProperty("IsBusy"); if(busyProperty != null) busyProperty.SetValue(info.BusyIndicator, isBusy, null); else info.BusyIndicator.Visibility = isBusy ? Visibility.Visible : Visibility.Collapsed; } else if(!isBusy) { var close = info.BusyViewModel.GetType().GetMethod("Close", Type.EmptyTypes); if(close != null) close.Invoke(info.BusyViewModel, null); } } /// <summary> /// Finds the busy indicator for the provided view. /// </summary> /// <param name="view">The view.</param> /// <returns>The busy indicator, or null if not found.</returns> protected UIElement FindBusyIndicatorCore(DependencyObject view) { UIElement busyIndicator = null; while(view != null && busyIndicator == null) { busyIndicator = view.FindName("busyIndicator") as UIElement; view = view.GetParent(); } return busyIndicator; } /// <summary> /// Gets the view. /// </summary> /// <param name="viewModel">The view model.</param> /// <returns></returns> protected virtual UIElement GetView(object viewModel) { var viewAware = viewModel as IViewAware; if(viewAware == null) return null; return viewAware.GetView(null) as UIElement; } UIElement TryFindBusyIndicator(object viewModel) { DependencyObject view = GetView(viewModel); if(view == null) { Log.Warn("Could not find view for {0}.", viewModel); return null; } view = (DependencyObject)View.GetFirstNonGeneratedView(view); return FindBusyIndicatorCore(view); } /// <summary> /// Stores information on currently active busy indicators. /// </summary> protected class BusyInfo { /// <summary> /// Gets or sets the busy indicator. /// </summary> /// <value>The busy indicator.</value> public UIElement BusyIndicator { get; set; } /// <summary> /// Gets or sets the busy view model. /// </summary> /// <value>The busy view model.</value> public object BusyViewModel { get; set; } /// <summary> /// Gets or sets the depth. /// </summary> /// <value>The depth.</value> public int Depth { get; set; } } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.IO; using System.Windows.Forms; using Autodesk; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Structure; using Autodesk.Revit.UI; namespace Revit.SDK.Samples.RotateFramingObjects.CS { /// <summary> /// Rotate the objects that were selected when the command was executed. /// and allow the user input the amount, in degrees that the objects should be rotated. /// the dialog contain option for the user to specify this value is absolute or relative. /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)] public class RotateFramingObjects : IExternalCommand { Autodesk.Revit.UI.UIApplication m_revit = null; // application of Revit double m_receiveRotationTextBox; // receive change of Angle bool m_isAbsoluteChecked; // true if moving absolute const string AngleDefinitionName = "Cross-Section Rotation"; /// <summary> /// receive change of Angle /// </summary> public double ReceiveRotationTextBox { get { return m_receiveRotationTextBox; } set { m_receiveRotationTextBox = value; } } /// <summary> /// is moving absolutely /// </summary> public bool IsAbsoluteChecked { get { return m_isAbsoluteChecked; } set { m_isAbsoluteChecked = value; } } /// <summary> /// Default constructor of RotateFramingObjects /// </summary> public RotateFramingObjects() { } /// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { Autodesk.Revit.UI.UIApplication revit = commandData.Application; m_revit = revit; RotateFramingObjectsForm displayForm = new RotateFramingObjectsForm(this); displayForm.StartPosition = FormStartPosition.CenterParent; ElementSet selection = revit.ActiveUIDocument.Selection.Elements; bool isSingle = true; //selection is single object bool isAllFamilyInstance = true; //all is not familyInstance // There must be beams, braces or columns selected if (selection.IsEmpty) { // nothing selected message = "Please select some beams, braces or columns."; return Autodesk.Revit.UI.Result.Failed; } else if (1 != selection.Size) { isSingle = false; try { if (DialogResult.OK != displayForm.ShowDialog()) { return Autodesk.Revit.UI.Result.Cancelled; } } catch (Exception) { return Autodesk.Revit.UI.Result.Failed; } // return Autodesk.Revit.UI.Result.Succeeded; // more than one object selected } // if the selected elements are familyInstances, try to get their existing rotation foreach (Autodesk.Revit.DB.Element e in selection) { FamilyInstance familyComponent = e as FamilyInstance; if (familyComponent != null) { if (StructuralType.Beam == familyComponent.StructuralType || StructuralType.Brace == familyComponent.StructuralType) { // selection is a beam or brace string returnValue = this.FindParameter(AngleDefinitionName, familyComponent); displayForm.rotationTextBox.Text = returnValue.ToString(); } else if (StructuralType.Column == familyComponent.StructuralType) { // selection is a column Location columnLocation = familyComponent.Location; LocationPoint pointLocation = columnLocation as LocationPoint; double temp = pointLocation.Rotation; string output = (Math.Round(temp * 180 / (Math.PI), 3)).ToString(); displayForm.rotationTextBox.Text = output; } else { // other familyInstance can not be rotated message = "It is not a beam, brace or column."; elements.Insert(familyComponent); return Autodesk.Revit.UI.Result.Failed; } } else { if (isSingle) { message = "It is not a FamilyInstance."; elements.Insert(e); return Autodesk.Revit.UI.Result.Failed; } // there is some objects is not familyInstance message = "They are not FamilyInstances"; elements.Insert(e); isAllFamilyInstance = false; } } if (isSingle) { try { if (DialogResult.OK != displayForm.ShowDialog()) { return Autodesk.Revit.UI.Result.Cancelled; } } catch (Exception) { return Autodesk.Revit.UI.Result.Failed; } } if (isAllFamilyInstance) { return Autodesk.Revit.UI.Result.Succeeded; } else { //output error information return Autodesk.Revit.UI.Result.Failed; } } /// <summary> /// The function set value to rotation of the beams and braces /// and rotate columns. /// </summary> public void RotateElement() { Transaction transaction = new Transaction(m_revit.ActiveUIDocument.Document, "RotateElement"); transaction.Start(); try { ElementSet selection = m_revit.ActiveUIDocument.Selection.Elements; foreach (Autodesk.Revit.DB.Element e in selection) { FamilyInstance familyComponent = e as FamilyInstance; if (familyComponent == null) { //is not a familyInstance continue; } // if be familyInstance,judge the types of familyInstance if (StructuralType.Beam == familyComponent.StructuralType || StructuralType.Brace == familyComponent.StructuralType) { // selection is a beam or Brace ParameterSetIterator paraIterator = familyComponent.Parameters.ForwardIterator(); paraIterator.Reset(); while (paraIterator.MoveNext()) { object para = paraIterator.Current; Parameter objectAttribute = para as Parameter; //set generic property named "Cross-Section Rotation" if (objectAttribute.Definition.Name.Equals(AngleDefinitionName)) { Double originDegree = objectAttribute.AsDouble(); double rotateDegree = m_receiveRotationTextBox * Math.PI / 180; if (!m_isAbsoluteChecked) { // absolute rotation rotateDegree += originDegree; } objectAttribute.Set(rotateDegree); // relative rotation } } } else if (StructuralType.Column == familyComponent.StructuralType) { // rotate a column Autodesk.Revit.DB.Location columnLocation = familyComponent.Location; // get the location object LocationPoint pointLocation = columnLocation as LocationPoint; Autodesk.Revit.DB.XYZ insertPoint = pointLocation.Point; // get the location point double temp = pointLocation.Rotation; //existing rotation Autodesk.Revit.DB.XYZ directionPoint = new Autodesk.Revit.DB.XYZ(0, 0, 1); // define the vector of axis Line rotateAxis = m_revit.Application.Create.NewLineUnbound(insertPoint, directionPoint); double rotateDegree = m_receiveRotationTextBox * Math.PI / 180; // rotate column by rotate method if (m_isAbsoluteChecked) { rotateDegree -= temp; } bool rotateResult = pointLocation.Rotate(rotateAxis, rotateDegree); if (rotateResult == false) { MessageBox.Show("Rotate Failed."); } } } transaction.Commit(); } catch (Exception ex) { MessageBox.Show("Rotate failed! " + ex.Message); transaction.RollBack(); } } /// <summary> /// get the parameter value according given parameter name /// </summary> public string FindParameter(string parameterName, FamilyInstance familyInstanceName) { ParameterSetIterator i = familyInstanceName.Parameters.ForwardIterator(); i.Reset(); string valueOfParameter = null; bool iMoreAttribute = i.MoveNext(); while (iMoreAttribute) { bool isFound = false; object o = i.Current; Parameter familyAttribute = o as Parameter; if (familyAttribute.Definition.Name == parameterName) { //find the parameter whose name is same to the given parameter name Autodesk.Revit.DB.StorageType st = familyAttribute.StorageType; switch (st) { //get the storage type case StorageType.Double: if (parameterName.Equals(AngleDefinitionName)) { //make conversion between degrees and radians Double temp = familyAttribute.AsDouble(); valueOfParameter = Math.Round(temp * 180 / (Math.PI), 3).ToString(); } else { valueOfParameter = familyAttribute.AsDouble().ToString(); } break; case StorageType.ElementId: //get Autodesk.Revit.DB.ElementId as string valueOfParameter = familyAttribute.AsElementId().IntegerValue.ToString(); break; case StorageType.Integer: //get Integer as string valueOfParameter = familyAttribute.AsInteger().ToString(); break; case StorageType.String: //get string valueOfParameter = familyAttribute.AsString(); break; case StorageType.None: valueOfParameter = familyAttribute.AsValueString(); break; default: break; } isFound = true; } if (isFound) { break; } iMoreAttribute = i.MoveNext(); } //return the value. return valueOfParameter; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- // Main code for the Datablock Editor plugin. $DATABLOCK_EDITOR_DEFAULT_FILENAME = "art/datablocks/managedDatablocks.cs"; //============================================================================================= // Initialization. //============================================================================================= //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::init( %this ) { if( !DatablockEditorTree.getItemCount() ) %this.populateTrees(); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::onWorldEditorStartup( %this ) { // Add ourselves to the window menu. %accel = EditorGui.addToEditorsMenu( "Datablock Editor", "", DatablockEditorPlugin ); // Add ourselves to the ToolsToolbar %tooltip = "Datablock Editor (" @ %accel @ ")"; EditorGui.addToToolsToolbar( "DatablockEditorPlugin", "DatablockEditorPalette", expandFilename("tools/worldEditor/images/toolbar/datablock-editor"), %tooltip ); //connect editor windows GuiWindowCtrl::Attach( DatablockEditorInspectorWindow, DatablockEditorTreeWindow); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::onActivated( %this ) { EditorGui-->WorldEditorToolbar.setVisible(false); EditorGui.bringToFront( DatablockEditorPlugin ); DatablockEditorTreeWindow.setVisible( true ); DatablockEditorInspectorWindow.setVisible( true ); DatablockEditorInspectorWindow.makeFirstResponder( true ); %this.map.push(); // Set the status bar here until all tool have been hooked up EditorGuiStatusBar.setInfo( "Datablock editor." ); %numSelected = %this.getNumSelectedDatablocks(); if( !%numSelected ) EditorGuiStatusBar.setSelection( "" ); else EditorGuiStatusBar.setSelection( %numSelected @ " datablocks selected" ); %this.init(); DatablockEditorPlugin.readSettings(); if( EWorldEditor.getSelectionSize() == 1 ) %this.onObjectSelected( EWorldEditor.getSelectedObject( 0 ) ); Parent::onActivated( %this ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::onDeactivated( %this ) { DatablockEditorPlugin.writeSettings(); DatablockEditorInspectorWindow.setVisible( false ); DatablockEditorTreeWindow.setVisible( false ); %this.map.pop(); Parent::onDeactivated(%this); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::onExitMission( %this ) { DatablockEditorTree.clear(); DatablockEditorInspector.inspect( "" ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::openDatablock( %this, %datablock ) { EditorGui.setEditor( DatablockEditorPlugin ); %this.selectDatablock( %datablock ); DatablockEditorTreeTabBook.selectedPage = 0; } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::setEditorFunction( %this ) { return true; } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::onObjectSelected( %this, %object ) { // Select datablock of object if this is a GameBase object. if( %object.isMemberOfClass( "GameBase" ) ) %this.selectDatablock( %object.getDatablock() ); else if( %object.isMemberOfClass( "SFXEmitter" ) && isObject( %object.track ) ) %this.selectDatablock( %object.track ); else if( %object.isMemberOfClass( "LightBase" ) && isObject( %object.animationType ) ) %this.selectDatablock( %object.animationType ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::populateTrees(%this) { // Populate datablock tree. if( %this.excludeClientOnlyDatablocks ) %set = DataBlockGroup; else %set = DataBlockSet; DatablockEditorTree.clear(); foreach( %datablock in %set ) { %unlistedFound = false; %id = %datablock.getId(); foreach( %obj in UnlistedDatablocks ) if( %obj.getId() == %id ) { %unlistedFound = true; break; } if( %unlistedFound ) continue; %this.addExistingItem( %datablock, true ); } DatablockEditorTree.sort( 0, true, false, false ); // Populate datablock type tree. %classList = enumerateConsoleClasses( "SimDatablock" ); DatablockEditorTypeTree.clear(); foreach$( %datablockClass in %classList ) { if( !%this.isExcludedDatablockType( %datablockClass ) && DatablockEditorTypeTree.findItemByName( %datablockClass ) == 0 ) DatablockEditorTypeTree.insertItem( 0, %datablockClass ); } DatablockEditorTypeTree.sort( 0, false, false, false ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::addExistingItem( %this, %datablock, %dontSort ) { %tree = DatablockEditorTree; // Look up class at root level. Create if needed. %class = %datablock.getClassName(); %parentID = %tree.findItemByName( %class ); if( %parentID == 0 ) %parentID = %tree.insertItem( 0, %class ); // If the datablock is already there, don't // do anything. if( %tree.findItemByValue( %datablock.getId() ) ) return; // It doesn't exist so add it. %name = %datablock.getName(); if( %this.PM.isDirty( %datablock ) ) %name = %name @ " *"; %id = DatablockEditorTree.insertItem( %parentID, %name, %datablock.getId() ); if( !%dontSort ) DatablockEditorTree.sort( %parentID, false, false, false ); return %id; } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::isExcludedDatablockType( %this, %className ) { switch$( %className ) { case "SimDatablock": return true; case "SFXTrack": // Abstract. return true; case "SFXFMODEvent": // Internally created. return true; case "SFXFMODEventGroup": // Internally created. return true; } return false; } //============================================================================================= // Settings. //============================================================================================= //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::initSettings( %this ) { EditorSettings.beginGroup("DatablockEditor", true); EditorSettings.setDefaultValue("libraryTab", "0"); EditorSettings.endGroup(); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::readSettings( %this ) { EditorSettings.beginGroup("DatablockEditor", true); DatablockEditorTreeTabBook.selectPage( EditorSettings.value( "libraryTab" ) ); %db = EditorSettings.value( "selectedDatablock" ); if( isObject( %db ) && %db.isMemberOfClass( "SimDatablock" ) ) %this.selectDatablock( %db ); EditorSettings.endGroup(); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::writeSettings( %this ) { EditorSettings.beginGroup( "DatablockEditor", true ); EditorSettings.setValue( "libraryTab", DatablockEditorTreeTabBook.getSelectedPage() ); if( %this.getNumSelectedDatablocks() > 0 ) EditorSettings.setValue( "selectedDatablock", %this.getSelectedDatablock().getName() ); EditorSettings.endGroup(); } //============================================================================================= // Persistence. //============================================================================================= //--------------------------------------------------------------------------------------------- /// Return true if there is any datablock with unsaved changes. function DatablockEditorPlugin::isDirty( %this ) { return %this.PM.hasDirty(); } //--------------------------------------------------------------------------------------------- /// Return true if any of the currently selected datablocks has unsaved changes. function DatablockEditorPlugin::selectedDatablockIsDirty( %this ) { %tree = DatablockEditorTree; %count = %tree.getSelectedItemsCount(); %selected = %tree.getSelectedItemList(); foreach$( %id in %selected ) { %db = %tree.getItemValue( %id ); if( %this.PM.isDirty( %db ) ) return true; } return false; } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::syncDirtyState( %this ) { %tree = DatablockEditorTree; %count = %tree.getSelectedItemsCount(); %selected = %tree.getSelectedItemList(); %haveDirty = false; foreach$( %id in %selected ) { %db = %tree.getItemValue( %id ); if( %this.PM.isDirty( %db ) ) { %this.flagDatablockAsDirty( %db, true ); %haveDirty = true; } else %this.flagInspectorAsDirty( %db, false ); } %this.flagInspectorAsDirty( %haveDirty ); } //--------------------------------------------------------------------------------------------- /// function DatablockEditorPlugin::flagInspectorAsDirty( %this, %dirty ) { if( %dirty ) DatablockEditorInspectorWindow.text = "Datablock *"; else DatablockEditorInspectorWindow.text = "Datablock"; } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::flagDatablockAsDirty(%this, %datablock, %dirty ) { %tree = DatablockEditorTree; %id = %tree.findItemByValue( %datablock.getId() ); if( %id == 0 ) return; // Tag the item caption and sync the persistence manager. if( %dirty ) { DatablockEditorTree.editItem( %id, %datablock.getName() @ " *", %datablock.getId() ); %this.PM.setDirty( %datablock ); } else { DatablockEditorTree.editItem( %id, %datablock.getName(), %datablock.getId() ); %this.PM.removeDirty( %datablock ); } // Sync the inspector dirty state. %this.flagInspectorAsDirty( %this.PM.hasDirty() ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::showSaveNewFileDialog(%this) { %currentFile = %this.getSelectedDatablock().getFilename(); getSaveFilename( "TorqueScript Files|*.cs|All Files|*.*", %this @ ".saveNewFileFinish", %currentFile, false ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::saveNewFileFinish( %this, %newFileName ) { // Clear the first responder to capture any inspector changes %ctrl = canvas.getFirstResponder(); if( isObject(%ctrl) ) %ctrl.clearFirstResponder(); %tree = DatablockEditorTree; %count = %tree.getSelectedItemsCount(); %selected = %tree.getSelectedItemList(); foreach$( %id in %selected ) { %db = %tree.getItemValue( %id ); %db = %this.getSelectedDatablock(); // Remove from current file. %oldFileName = %db.getFileName(); if( %oldFileName !$= "" ) %this.PM.removeObjectFromFile( %db, %oldFileName ); // Save to new file. %this.PM.setDirty( %db, %newFileName ); if( %this.PM.saveDirtyObject( %db ) ) { // Clear dirty state. %this.flagDatablockAsDirty( %db, false ); } } DatablockEditorInspectorWindow-->DatablockFile.setText( %newFileName ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::save( %this ) { // Clear the first responder to capture any inspector changes %ctrl = canvas.getFirstResponder(); if( isObject(%ctrl) ) %ctrl.clearFirstResponder(); %tree = DatablockEditorTree; %count = %tree.getSelectedItemsCount(); %selected = %tree.getSelectedItemList(); for( %i = 0; %i < %count; %i ++ ) { %id = getWord( %selected, %i ); %db = %tree.getItemValue( %id ); if( %this.PM.isDirty( %db ) ) { %this.PM.saveDirtyObject( %db ); %this.flagDatablockAsDirty( %db, false ); } } } //============================================================================================= // Selection. //============================================================================================= //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::getNumSelectedDatablocks( %this ) { return DatablockEditorTree.getSelectedItemsCount(); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::getSelectedDatablock( %this, %index ) { %tree = DatablockEditorTree; if( !%tree.getSelectedItemsCount() ) return 0; if( !%index ) %id = %tree.getSelectedItem(); else %id = getWord( %tree.getSelectedItemList(), %index ); return %tree.getItemValue( %id ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::resetSelectedDatablock( %this ) { DatablockEditorTree.clearSelection(); DatablockEditorInspector.inspect(0); DatablockEditorInspectorWindow-->DatablockFile.setText(""); EditorGuiStatusBar.setSelection( "" ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::selectDatablockCheck( %this, %datablock ) { if( %this.selectedDatablockIsDirty() ) %this.showSaveDialog( %datablock ); else %this.selectDatablock( %datablock ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::selectDatablock( %this, %datablock, %add, %dontSyncTree ) { if( %add ) DatablockEditorInspector.addInspect( %datablock ); else DatablockEditorInspector.inspect( %datablock ); if( !%dontSyncTree ) { %id = DatablockEditorTree.findItemByValue( %datablock.getId() ); if( !%add ) DatablockEditorTree.clearSelection(); DatablockEditorTree.selectItem( %id, true ); DatablockEditorTree.scrollVisible( %id ); } %this.syncDirtyState(); // Update the filename text field. %numSelected = %this.getNumSelectedDatablocks(); %fileNameField = DatablockEditorInspectorWindow-->DatablockFile; if( %numSelected == 1 ) { %fileName = %datablock.getFilename(); if( %fileName !$= "" ) %fileNameField.setText( %fileName ); else %fileNameField.setText( $DATABLOCK_EDITOR_DEFAULT_FILENAME ); } else { %fileNameField.setText( "" ); } EditorGuiStatusBar.setSelection( %this.getNumSelectedDatablocks() @ " Datablocks Selected" ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::unselectDatablock( %this, %datablock, %dontSyncTree ) { DatablockEditorInspector.removeInspect( %datablock ); if( !%dontSyncTree ) { %id = DatablockEditorTree.findItemByValue( %datablock.getId() ); DatablockEditorTree.selectItem( %id, false ); } %this.syncDirtyState(); // If we have exactly one selected datablock remaining, re-enable // the save-as button. %numSelected = %this.getNumSelectedDatablocks(); if( %numSelected == 1 ) { DatablockEditorInspectorWindow-->saveAsButton.setActive( true ); %fileNameField = DatablockEditorInspectorWindow-->DatablockFile; %fileNameField.setText( %this.getSelectedDatablock().getFilename() ); %fileNameField.setActive( true ); } EditorGuiStatusBar.setSelection( %this.getNumSelectedDatablocks() @ " Datablocks Selected" ); } //============================================================================================= // Creation and Deletion. //============================================================================================= //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::deleteDatablock( %this ) { %tree = DatablockEditorTree; // If we have more than single datablock selected, // turn our undos into a compound undo. %numSelected = %tree.getSelectedItemsCount(); if( %numSelected > 1 ) Editor.getUndoManager().pushCompound( "Delete Multiple Datablocks" ); for( %i = 0; %i < %numSelected; %i ++ ) { %id = %tree.getSelectedItem( %i ); %db = %tree.getItemValue( %id ); %fileName = %db.getFileName(); // Remove the datablock from the tree. DatablockEditorTree.removeItem( %id ); // Create undo. %action = %this.createUndo( ActionDeleteDatablock, "Delete Datablock" ); %action.db = %db; %action.dbName = %db.getName(); %action.fname = %fileName; %this.submitUndo( %action ); // Kill the datablock in the file. if( %fileName !$= "" ) %this.PM.removeObjectFromFile( %db ); UnlistedDatablocks.add( %db ); // Show some confirmation. if( %numSelected == 1 ) MessageBoxOk( "Datablock Deleted", "The datablock (" @ %db.getName() @ ") has been removed from " @ "it's file (" @ %db.getFilename() @ ") and upon restart will cease to exist" ); } // Close compound, if we were deleting multiple datablocks. if( %numSelected > 1 ) Editor.getUndoManager().popCompound(); // Show confirmation for multiple datablocks. if( %numSelected > 1 ) MessageBoxOk( "Datablocks Deleted", "The datablocks have been deleted and upon restart will cease to exist." ); // Clear selection. DatablockEditorPlugin.resetSelectedDatablock(); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::createDatablock(%this) { %class = DatablockEditorTypeTree.getItemText(DatablockEditorTypeTree.getSelectedItem()); if( %class !$= "" ) { // Need to prompt for a name. DatablockEditorCreatePrompt-->CreateDatablockName.setText("Name"); DatablockEditorCreatePrompt-->CreateDatablockName.selectAllText(); // Populate the copy source dropdown. %list = DatablockEditorCreatePrompt-->CopySourceDropdown; %list.clear(); %list.add( "", 0 ); %set = DataBlockSet; %count = %set.getCount(); for( %i = 0; %i < %count; %i ++ ) { %datablock = %set.getObject( %i ); %datablockClass = %datablock.getClassName(); if( !isMemberOfClass( %datablockClass, %class ) ) continue; %list.add( %datablock.getName(), %i + 1 ); } // Set up state of client-side checkbox. %clientSideCheckBox = DatablockEditorCreatePrompt-->ClientSideCheckBox; %canBeClientSide = DatablockEditorPlugin::canBeClientSideDatablock( %class ); %clientSideCheckBox.setStateOn( %canBeClientSide ); %clientSideCheckBox.setActive( %canBeClientSide ); // Show the dialog. canvas.pushDialog( DatablockEditorCreatePrompt, 0, true ); } } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::createPromptNameCheck(%this) { %name = DatablockEditorCreatePrompt-->CreateDatablockName.getText(); if( !Editor::validateObjectName( %name, true ) ) return; // Fetch the copy source and clear the list. %copySource = DatablockEditorCreatePrompt-->copySourceDropdown.getText(); DatablockEditorCreatePrompt-->copySourceDropdown.clear(); // Remove the dialog and create the datablock. canvas.popDialog( DatablockEditorCreatePrompt ); %this.createDatablockFinish( %name, %copySource ); } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::createDatablockFinish( %this, %name, %copySource ) { %class = DatablockEditorTypeTree.getItemText(DatablockEditorTypeTree.getSelectedItem()); if( %class !$= "" ) { %action = %this.createUndo( ActionCreateDatablock, "Create New Datablock" ); if( DatablockEditorCreatePrompt-->ClientSideCheckBox.isStateOn() ) %dbType = "singleton "; else %dbType = "datablock "; if( %copySource !$= "" ) %eval = %dbType @ %class @ "(" @ %name @ " : " @ %copySource @ ") { canSaveDynamicFields = \"1\"; };"; else %eval = %dbType @ %class @ "(" @ %name @ ") { canSaveDynamicFields = \"1\"; };"; %res = eval( %eval ); %action.db = %name.getId(); %action.dbName = %name; %action.fname = $DATABLOCK_EDITOR_DEFAULT_FILENAME; %this.submitUndo( %action ); %action.redo(); } } //--------------------------------------------------------------------------------------------- function DatablockEditorPlugin::canBeClientSideDatablock( %className ) { switch$( %className ) { case "SFXProfile" or "SFXPlayList" or "SFXAmbience" or "SFXEnvironment" or "SFXState" or "SFXDescription" or "SFXFMODProject": return true; default: return false; } } //============================================================================================= // Events. //============================================================================================= //--------------------------------------------------------------------------------------------- function DatablockEditorInspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue ) { // Same work to do as for the regular WorldEditor Inspector. Inspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue ); DatablockEditorPlugin.flagDatablockAsDirty( %object, true ); } //--------------------------------------------------------------------------------------------- function DatablockEditorInspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc ) { DatablockFieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc ); } //--------------------------------------------------------------------------------------------- function DatablockEditorInspector::onBeginCompoundEdit( %this ) { Editor.getUndoManager().pushCompound( "Multiple Field Edit" ); } //--------------------------------------------------------------------------------------------- function DatablockEditorInspector::onEndCompoundEdit( %this, %discard ) { Editor.getUndoManager().popCompound( %discard ); } //--------------------------------------------------------------------------------------------- function DatablockEditorInspector::onClear( %this ) { DatablockFieldInfoControl.setText( "" ); } //--------------------------------------------------------------------------------------------- function DatablockEditorTree::onDeleteSelection( %this ) { %this.undoDeleteList = ""; } //--------------------------------------------------------------------------------------------- function DatablockEditorTree::onDeleteObject( %this, %object ) { // Append it to our list. %this.undoDeleteList = %this.undoDeleteList TAB %object; // We're gonna delete this ourselves in the // completion callback. return true; } //--------------------------------------------------------------------------------------------- function DatablockEditorTree::onObjectDeleteCompleted( %this ) { //MEDeleteUndoAction::submit( %this.undoDeleteList ); // Let the world editor know to // clear its selection. //EWorldEditor.clearSelection(); //EWorldEditor.isDirty = true; } //--------------------------------------------------------------------------------------------- function DatablockEditorTree::onClearSelected(%this) { DatablockEditorInspector.inspect( 0 ); } //--------------------------------------------------------------------------------------------- function DatablockEditorTree::onAddSelection( %this, %id ) { %obj = %this.getItemValue( %id ); if( !isObject( %obj ) ) %this.selectItem( %id, false ); else DatablockEditorPlugin.selectDatablock( %obj, true, true ); } //--------------------------------------------------------------------------------------------- function DatablockEditorTree::onRemoveSelection( %this, %id ) { %obj = %this.getItemValue( %id ); if( isObject( %obj ) ) DatablockEditorPlugin.unselectDatablock( %obj, true ); } //--------------------------------------------------------------------------------------------- function DatablockEditorTree::onRightMouseUp( %this, %id, %mousePos ) { %datablock = %this.getItemValue( %id ); if( !isObject( %datablock ) ) return; if( !isObject( DatablockEditorTreePopup ) ) new PopupMenu( DatablockEditorTreePopup ) { superClass = "MenuBuilder"; isPopup = true; item[ 0 ] = "Delete" TAB "" TAB "DatablockEditorPlugin.selectDatablock( %this.datablockObject ); DatablockEditorPlugin.deleteDatablock( %this.datablockObject );"; item[ 1 ] = "Jump to Definition in Torsion" TAB "" TAB "EditorOpenDeclarationInTorsion( %this.datablockObject );"; datablockObject = ""; }; DatablockEditorTreePopup.datablockObject = %datablock; DatablockEditorTreePopup.showPopup( Canvas ); } //--------------------------------------------------------------------------------------------- function DatablockEditorTreeTabBook::onTabSelected(%this, %text, %id) { switch(%id) { case 0: DatablockEditorTreeWindow-->DeleteSelection.visible = true; DatablockEditorTreeWindow-->CreateSelection.visible = false; case 1: DatablockEditorTreeWindow-->DeleteSelection.visible = false; DatablockEditorTreeWindow-->CreateSelection.visible = true; } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NET_CF && !SILVERLIGHT namespace NLog.Targets.Wrappers { using System; using System.ComponentModel; using System.Web; using NLog.Common; using NLog.Internal; using NLog.Web; /// <summary> /// Buffers log events for the duration of ASP.NET request and sends them down /// to the wrapped target at the end of a request. /// </summary> /// <seealso href="http://nlog-project.org/wiki/AspNetBufferingWrapper_target">Documentation on NLog Wiki</seealso> /// <remarks> /// <p> /// Typically this target is used in cooperation with PostFilteringTargetWrapper /// to provide verbose logging for failing requests and normal or no logging for /// successful requests. We need to make the decision of the final filtering rule /// to apply after all logs for a page have been generated. /// </p> /// <p> /// To use this target, you need to add an entry in the httpModules section of /// web.config: /// </p> /// <code lang="XML"> /// <![CDATA[<?xml version="1.0" ?> /// <configuration> /// <system.web> /// <httpModules> /// <add name="NLog" type="NLog.Web.NLogHttpModule, NLog.Extended"/> /// </httpModules> /// </system.web> /// </configuration> /// ]]> /// </code> /// </remarks> /// <example> /// <p>To set up the ASP.NET Buffering target wrapper <a href="config.html">configuration file</a>, put /// the following in <c>web.nlog</c> file in your web application directory (this assumes /// that PostFilteringWrapper is used to provide the filtering and actual logs go to /// a file). /// </p> /// <code lang="XML" source="examples/targets/Configuration File/ASPNetBufferingWrapper/web.nlog" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To configure the target programmatically, put the following /// piece of code in your <c>Application_OnStart()</c> handler in Global.asax.cs /// or some other place that gets executed at the very beginning of your code: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/ASPNetBufferingWrapper/Global.asax.cs" /> /// <p> /// Fully working C# project can be found in the <c>Examples/Targets/Configuration API/ASPNetBufferingWrapper</c> /// directory along with usage instructions. /// </p> /// </example> [Target("AspNetBufferingWrapper", IsWrapper = true)] public class AspNetBufferingTargetWrapper : WrapperTargetBase { private readonly object dataSlot = new object(); private int growLimit; /// <summary> /// Initializes a new instance of the <see cref="AspNetBufferingTargetWrapper" /> class. /// </summary> public AspNetBufferingTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="AspNetBufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public AspNetBufferingTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 100) { } /// <summary> /// Initializes a new instance of the <see cref="AspNetBufferingTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="bufferSize">Size of the buffer.</param> public AspNetBufferingTargetWrapper(Target wrappedTarget, int bufferSize) { this.WrappedTarget = wrappedTarget; this.BufferSize = bufferSize; this.GrowBufferAsNeeded = true; } /// <summary> /// Gets or sets the number of log events to be buffered. /// </summary> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(100)] public int BufferSize { get; set; } /// <summary> /// Gets or sets a value indicating whether buffer should grow as needed. /// </summary> /// <value>A value of <c>true</c> if buffer should grow as needed; otherwise, <c>false</c>.</value> /// <remarks> /// Value of <c>true</c> causes the buffer to expand until <see cref="BufferGrowLimit"/> is hit, /// <c>false</c> causes the buffer to never expand and lose the earliest entries in case of overflow. /// </remarks> /// <docgen category='Buffering Options' order='100' /> [DefaultValue(false)] public bool GrowBufferAsNeeded { get; set; } /// <summary> /// Gets or sets the maximum number of log events that the buffer can keep. /// </summary> /// <docgen category='Buffering Options' order='100' /> public int BufferGrowLimit { get { return this.growLimit; } set { this.growLimit = value; this.GrowBufferAsNeeded = (value >= this.BufferSize) ? true : false; } } /// <summary> /// Initializes the target by hooking up the NLogHttpModule BeginRequest and EndRequest events. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); NLogHttpModule.BeginRequest += this.OnBeginRequest; NLogHttpModule.EndRequest += this.OnEndRequest; if (HttpContext.Current != null) { // we are in the context already, it's too late for OnBeginRequest to be called, so let's // just call it ourselves this.OnBeginRequest(null, null); } } /// <summary> /// Closes the target by flushing pending events in the buffer (if any). /// </summary> protected override void CloseTarget() { NLogHttpModule.BeginRequest -= this.OnBeginRequest; NLogHttpModule.EndRequest -= this.OnEndRequest; base.CloseTarget(); } /// <summary> /// Adds the specified log event to the buffer. /// </summary> /// <param name="logEvent">The log event.</param> protected override void Write(AsyncLogEventInfo logEvent) { LogEventInfoBuffer buffer = this.GetRequestBuffer(); if (buffer != null) { this.WrappedTarget.PrecalculateVolatileLayouts(logEvent.LogEvent); buffer.Append(logEvent); InternalLogger.Trace("Appending log event {0} to ASP.NET request buffer.", logEvent.LogEvent.SequenceID); } else { InternalLogger.Trace("ASP.NET request buffer does not exist. Passing to wrapped target."); this.WrappedTarget.WriteAsyncLogEvent(logEvent); } } private LogEventInfoBuffer GetRequestBuffer() { HttpContext context = HttpContext.Current; if (context == null) { return null; } return context.Items[this.dataSlot] as LogEventInfoBuffer; } private void OnBeginRequest(object sender, EventArgs args) { InternalLogger.Trace("Setting up ASP.NET request buffer."); HttpContext context = HttpContext.Current; context.Items[this.dataSlot] = new LogEventInfoBuffer(this.BufferSize, this.GrowBufferAsNeeded, this.BufferGrowLimit); } private void OnEndRequest(object sender, EventArgs args) { LogEventInfoBuffer buffer = this.GetRequestBuffer(); if (buffer != null) { InternalLogger.Trace("Sending buffered events to wrapped target: {0}.", this.WrappedTarget); AsyncLogEventInfo[] events= buffer.GetEventsAndClear(); this.WrappedTarget.WriteAsyncLogEvents(events); } } } } #endif
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.PerfTests.Bench.SBE.FIX { public class OrderCancelRequest { public const ushort TemplateId = (ushort)70; public const byte TemplateVersion = (byte)0; public const ushort BlockLength = (ushort)119; public const string SematicType = "F"; private readonly OrderCancelRequest _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public OrderCancelRequest() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = TemplateVersion; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(_limit); _limit = value; } } public const int AccountSchemaId = 1; public static string AccountMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte AccountNullValue = (byte)0; public const byte AccountMinValue = (byte)32; public const byte AccountMaxValue = (byte)126; public const int AccountLength = 12; public byte GetAccount(int index) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 0 + (index * 1)); } public void SetAccount(int index, byte value) { if (index < 0 || index >= 12) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 0 + (index * 1), value); } public const string AccountCharacterEncoding = "UTF-8"; public int GetAccount(byte[] dst, int dstOffset) { const int length = 12; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 0, dst, dstOffset, length); return length; } public void SetAccount(byte[] src, int srcOffset) { const int length = 12; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 0, src, srcOffset, length); } public const int ClOrdIDSchemaId = 11; public static string ClOrdIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte ClOrdIDNullValue = (byte)0; public const byte ClOrdIDMinValue = (byte)32; public const byte ClOrdIDMaxValue = (byte)126; public const int ClOrdIDLength = 20; public byte GetClOrdID(int index) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 12 + (index * 1)); } public void SetClOrdID(int index, byte value) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 12 + (index * 1), value); } public const string ClOrdIDCharacterEncoding = "UTF-8"; public int GetClOrdID(byte[] dst, int dstOffset) { const int length = 20; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 12, dst, dstOffset, length); return length; } public void SetClOrdID(byte[] src, int srcOffset) { const int length = 20; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 12, src, srcOffset, length); } public const int OrderIDSchemaId = 37; public static string OrderIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const long OrderIDNullValue = -9223372036854775808L; public const long OrderIDMinValue = -9223372036854775807L; public const long OrderIDMaxValue = 9223372036854775807L; public long OrderID { get { return _buffer.Int64GetLittleEndian(_offset + 32); } set { _buffer.Int64PutLittleEndian(_offset + 32, value); } } public const int OrigClOrdIDSchemaId = 41; public static string OrigClOrdIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte OrigClOrdIDNullValue = (byte)0; public const byte OrigClOrdIDMinValue = (byte)32; public const byte OrigClOrdIDMaxValue = (byte)126; public const int OrigClOrdIDLength = 20; public byte GetOrigClOrdID(int index) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 40 + (index * 1)); } public void SetOrigClOrdID(int index, byte value) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 40 + (index * 1), value); } public const string OrigClOrdIDCharacterEncoding = "UTF-8"; public int GetOrigClOrdID(byte[] dst, int dstOffset) { const int length = 20; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 40, dst, dstOffset, length); return length; } public void SetOrigClOrdID(byte[] src, int srcOffset) { const int length = 20; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 40, src, srcOffset, length); } public const int SideSchemaId = 54; public static string SideMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "char"; } return ""; } public Side Side { get { return (Side)_buffer.CharGet(_offset + 60); } set { _buffer.CharPut(_offset + 60, (byte)value); } } public const int SymbolSchemaId = 55; public static string SymbolMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SymbolNullValue = (byte)0; public const byte SymbolMinValue = (byte)32; public const byte SymbolMaxValue = (byte)126; public const int SymbolLength = 6; public byte GetSymbol(int index) { if (index < 0 || index >= 6) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 61 + (index * 1)); } public void SetSymbol(int index, byte value) { if (index < 0 || index >= 6) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 61 + (index * 1), value); } public const string SymbolCharacterEncoding = "UTF-8"; public int GetSymbol(byte[] dst, int dstOffset) { const int length = 6; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 61, dst, dstOffset, length); return length; } public void SetSymbol(byte[] src, int srcOffset) { const int length = 6; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 61, src, srcOffset, length); } public const int TransactTimeSchemaId = 60; public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "UTCTimestamp"; } return ""; } public const ulong TransactTimeNullValue = 0x8000000000000000UL; public const ulong TransactTimeMinValue = 0x0UL; public const ulong TransactTimeMaxValue = 0x7fffffffffffffffUL; public ulong TransactTime { get { return _buffer.Uint64GetLittleEndian(_offset + 67); } set { _buffer.Uint64PutLittleEndian(_offset + 67, value); } } public const int ManualOrderIndicatorSchemaId = 1028; public static string ManualOrderIndicatorMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public BooleanType ManualOrderIndicator { get { return (BooleanType)_buffer.Uint8Get(_offset + 75); } set { _buffer.Uint8Put(_offset + 75, (byte)value); } } public const int SecurityDescSchemaId = 107; public static string SecurityDescMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SecurityDescNullValue = (byte)0; public const byte SecurityDescMinValue = (byte)32; public const byte SecurityDescMaxValue = (byte)126; public const int SecurityDescLength = 20; public byte GetSecurityDesc(int index) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 76 + (index * 1)); } public void SetSecurityDesc(int index, byte value) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 76 + (index * 1), value); } public const string SecurityDescCharacterEncoding = "UTF-8"; public int GetSecurityDesc(byte[] dst, int dstOffset) { const int length = 20; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 76, dst, dstOffset, length); return length; } public void SetSecurityDesc(byte[] src, int srcOffset) { const int length = 20; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 76, src, srcOffset, length); } public const int SecurityTypeSchemaId = 167; public static string SecurityTypeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SecurityTypeNullValue = (byte)0; public const byte SecurityTypeMinValue = (byte)32; public const byte SecurityTypeMaxValue = (byte)126; public const int SecurityTypeLength = 3; public byte GetSecurityType(int index) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 96 + (index * 1)); } public void SetSecurityType(int index, byte value) { if (index < 0 || index >= 3) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 96 + (index * 1), value); } public const string SecurityTypeCharacterEncoding = "UTF-8"; public int GetSecurityType(byte[] dst, int dstOffset) { const int length = 3; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 96, dst, dstOffset, length); return length; } public void SetSecurityType(byte[] src, int srcOffset) { const int length = 3; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 96, src, srcOffset, length); } public const int CorrelationClOrdIDSchemaId = 9717; public static string CorrelationClOrdIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte CorrelationClOrdIDNullValue = (byte)0; public const byte CorrelationClOrdIDMinValue = (byte)32; public const byte CorrelationClOrdIDMaxValue = (byte)126; public const int CorrelationClOrdIDLength = 20; public byte GetCorrelationClOrdID(int index) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 99 + (index * 1)); } public void SetCorrelationClOrdID(int index, byte value) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 99 + (index * 1), value); } public const string CorrelationClOrdIDCharacterEncoding = "UTF-8"; public int GetCorrelationClOrdID(byte[] dst, int dstOffset) { const int length = 20; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 99, dst, dstOffset, length); return length; } public void SetCorrelationClOrdID(byte[] src, int srcOffset) { const int length = 20; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 99, src, srcOffset, length); } } }
using System; using System.Collections; using System.IO; using System.Text; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.TeleTrust; using Org.BouncyCastle.Asn1.Utilities; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Encodings; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Signers; using Org.BouncyCastle.Security; namespace Org.BouncyCastle.Crypto.Signers { public class RsaDigestSigner : ISigner { private readonly IAsymmetricBlockCipher rsaEngine = new Pkcs1Encoding(new RsaBlindedEngine()); private readonly AlgorithmIdentifier algId; private readonly IDigest digest; private bool forSigning; private static readonly Hashtable oidMap = new Hashtable(); /// <summary> /// Load oid table. /// </summary> static RsaDigestSigner() { oidMap["RIPEMD128"] = TeleTrusTObjectIdentifiers.RipeMD128; oidMap["RIPEMD160"] = TeleTrusTObjectIdentifiers.RipeMD160; oidMap["RIPEMD256"] = TeleTrusTObjectIdentifiers.RipeMD256; oidMap["SHA-1"] = X509ObjectIdentifiers.IdSha1; oidMap["SHA-224"] = NistObjectIdentifiers.IdSha224; oidMap["SHA-256"] = NistObjectIdentifiers.IdSha256; oidMap["SHA-384"] = NistObjectIdentifiers.IdSha384; oidMap["SHA-512"] = NistObjectIdentifiers.IdSha512; oidMap["MD2"] = PkcsObjectIdentifiers.MD2; oidMap["MD4"] = PkcsObjectIdentifiers.MD4; oidMap["MD5"] = PkcsObjectIdentifiers.MD5; } public RsaDigestSigner( IDigest digest) { this.digest = digest; algId = new AlgorithmIdentifier( (DerObjectIdentifier)oidMap[digest.AlgorithmName] , DerNull.Instance); } public string AlgorithmName { get { return digest.AlgorithmName + "withRSA"; } } /** * Initialise the signer for signing or verification. * * @param forSigning true if for signing, false otherwise * @param param necessary parameters. */ public void Init( bool forSigning, ICipherParameters parameters) { this.forSigning = forSigning; AsymmetricKeyParameter k; if (parameters is ParametersWithRandom) { k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters; } else { k = (AsymmetricKeyParameter)parameters; } if (forSigning && !k.IsPrivate) throw new InvalidKeyException("Signing requires private key."); if (!forSigning && k.IsPrivate) throw new InvalidKeyException("Verification requires public key."); Reset(); rsaEngine.Init(forSigning, parameters); } /** * update the internal digest with the byte b */ public void Update( byte input) { digest.Update(input); } /** * update the internal digest with the byte array in */ public void BlockUpdate( byte[] input, int inOff, int length) { digest.BlockUpdate(input, inOff, length); } /** * Generate a signature for the message we've been loaded with using * the key we were initialised with. */ public byte[] GenerateSignature() { if (!forSigning) throw new InvalidOperationException("RsaDigestSigner not initialised for signature generation."); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); byte[] data = DerEncode(hash); return rsaEngine.ProcessBlock(data, 0, data.Length); } /** * return true if the internal state represents the signature described * in the passed in array. */ public bool VerifySignature( byte[] signature) { if (forSigning) throw new InvalidOperationException("RsaDigestSigner not initialised for verification"); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); byte[] sig; byte[] expected; try { sig = rsaEngine.ProcessBlock(signature, 0, signature.Length); expected = DerEncode(hash); } catch (Exception) { return false; } if (sig.Length == expected.Length) { for (int i = 0; i < sig.Length; i++) { if (sig[i] != expected[i]) { return false; } } } else if (sig.Length == expected.Length - 2) // NULL left out { int sigOffset = sig.Length - hash.Length - 2; int expectedOffset = expected.Length - hash.Length - 2; expected[1] -= 2; // adjust lengths expected[3] -= 2; for (int i = 0; i < hash.Length; i++) { if (sig[sigOffset + i] != expected[expectedOffset + i]) // check hash { return false; } } for (int i = 0; i < sigOffset; i++) { if (sig[i] != expected[i]) // check header less NULL { return false; } } } else { return false; } return true; } public void Reset() { digest.Reset(); } private byte[] DerEncode( byte[] hash) { DigestInfo dInfo = new DigestInfo(algId, hash); return dInfo.GetDerEncoded(); } } }
using System; using System.Collections.Generic; using Sandbox.ModAPI.Ingame; using Sandbox.ModAPI.Interfaces; using Sandbox.Common.ObjectBuilders; using VRage; using VRageMath; class rev4a : Program { // Target power output to reach (in kW) // Default (Vanilla): 119 for large ship/station, 29 for small ship const int targetPowerOutput = 119; // Time to wait between two checks (in seconds) // Default: 2.0f const float loopDelay = 2.0f; // Time to wait if target power output has been reached (in seconds) // Default: 10.0f const float idleDelay = 10.0f; // Rotor speed (in RPM). Decreasing this value will increase accuracy. // Default: 0.1f const float rotorSpeed = 0.1f; // Solar panel to use as reference value for optimization const string referencePanelName = "Solar Panel (optimized)"; // Timer to use for looping const string timerName = "Loop Timer"; // Text that stands before the maximum power output amount in the detailed description of the solar panel // English: "Max Output: " const string lang_maxOutput = "Max Output: "; // Text that stands before the current power output amount in the detailed description of the solar panel // English: "Current Output: " const string lang_currentOutput = "Current Output: "; // Rotors to rotate for solar panel power output optimization readonly string[] rotorNames = new string[] { "Advanced Rotor" }; // ------------------------------------------------[ END OF CONFIGURATION ]------------------------------------------------ bool updatedRotor = false; bool testingDirection = false; bool setting = true; int currentIndex = 0; IMySolarPanel referencePanel; IMyTimerBlock timer; IMyMotorStator currentRotor; List<IMyTerminalBlock> rotors = new List<IMyTerminalBlock>(); void Main() { // get a list of all blocks in the grid terminal system List<IMyTerminalBlock> blocks = new List<IMyTerminalBlock>(); GridTerminalSystem.GetBlocks(blocks); // initialize the reference solar panel if it hasn't been initialized yet if (referencePanel == null) { // search all available blocks for one containing the reference panel name for (int i = 0; i < blocks.Count; i++) { if (blocks[i].CustomName.Contains(referencePanelName)) { referencePanel = blocks[i] as IMySolarPanel; if (referencePanel != null) break; } } if (referencePanel == null) throw new Exception(" Main(): failed to find solar panel with name '" + referencePanelName + "'"); } // initialize the timer if it hasn't been initialized yet if (timer == null) { // search all available blocks for one containing the timer name for (int i = 0; i < blocks.Count; i++) { if (blocks[i].CustomName.Contains(timerName)) { timer = blocks[i] as IMyTimerBlock; if (timer != null) break; } } if (timer == null) throw new Exception(" Main(): failed to find timer block with name '" + timerName + "'"); } // initialize the rotors list if no rotors have been registered yet if (rotors.Count <= 0) { for (int i = 0; i < rotorNames.Length; i++) { IMyTerminalBlock rotor = GridTerminalSystem.GetBlockWithName(rotorNames[i]); // only add rotors that actually exist and haven't been added yet if (rotor != null && !rotors.Contains(rotor)) { rotors.Add(rotor); rotor.SetValue("Velocity", rotorSpeed); ToggleOff(rotor); } } if (rotors.Count <= 0) throw new Exception(" Main(): failed to find any rotors with the specified names"); } // rotate the current rotor float currentPower; if (!MaxOutput(referencePanel, out currentPower)) throw new Exception(" Main(): failed to read current power output from DetailedInfo"); if (currentPower >= targetPowerOutput) { for (int i = 0; i < rotors.Count; i++) { ToggleOff(rotors[i]); } UpdateName(referencePanel); TriggerTimerIdle(); return; } if (currentRotor == null) { currentRotor = rotors[currentIndex] as IMyMotorStator; updatedRotor = true; } if (currentRotor == null) throw new Exception(" Main(): block '" + rotors[currentIndex].CustomName + "' is not a rotor but was registered as rotor to use"); if (updatedRotor) { if (!testingDirection) { // set the best rotation direction UpdateName(referencePanel); ToggleOn(currentRotor); testingDirection = true; TriggerTimer(); return; } ToggleOff(currentRotor); float oldPowerWDIHTCT; UpdateName(referencePanel, out oldPowerWDIHTCT, out currentPower); if (oldPowerWDIHTCT > currentPower) Reverse(currentRotor); updatedRotor = false; testingDirection = false; } // get the optimal rotation if (!setting) { ToggleOn(currentRotor); setting = true; UpdateName(referencePanel); TriggerTimer(); return; } float oldPower; UpdateName(referencePanel, out oldPower, out currentPower); if (oldPower > currentPower) { ToggleOff(currentRotor); currentRotor = null; currentIndex = (currentIndex + 1) % rotors.Count; } setting = false; TriggerTimer(); } void ToggleOn(IMyTerminalBlock block) { block.GetActionWithName("OnOff_On").Apply(block); } void ToggleOff(IMyTerminalBlock block) { block.GetActionWithName("OnOff_Off").Apply(block); } void Reverse(IMyMotorStator rotor) { rotor.GetActionWithName("Reverse").Apply(rotor); } void TriggerTimer() { timer.SetValue("TriggerDelay", loopDelay); timer.GetActionWithName("Start").Apply(timer); } void TriggerTimerIdle() { timer.SetValue("TriggerDelay", idleDelay); timer.GetActionWithName("Start").Apply(timer); } void UpdateName(IMySolarPanel solarPanel) { float __ignore; UpdateName(solarPanel, out __ignore); } void UpdateName(IMySolarPanel solarPanel, out float oldPower) { float __ignore; UpdateName(solarPanel, out oldPower, out __ignore); } void UpdateName(IMySolarPanel solarPanel, out float oldPower, out float currentPower) { oldPower = 0.0f; if (!MaxOutput(solarPanel, out currentPower)) throw new Exception(" UpdateName(IMySolarPanel, float): failed to read current power output from DetailedInfo"); if (solarPanel == null) throw new Exception(" UpdateName(IMySolarPanel, float): solarPanel is null"); string[] array = solarPanel.CustomName.Split('~'); if (array.Length > 1) { // old power has been set float.TryParse(array[array.Length - 1], out oldPower); // update current power output string newName = ""; for (int i = 0; i < array.Length - 1; i++) { newName += array[i]; } newName += "~" + currentPower; solarPanel.SetCustomName(newName); } else { // set current power output solarPanel.SetCustomName(solarPanel.CustomName + " ~" + currentPower); } } bool MaxOutput(IMySolarPanel solarPanel, out float power) { power = 0.0f; if (solarPanel == null) throw new Exception(" MaxOutput(IMySolarPanel, float): solarPanel is null"); int start = StartIndexMaxOutput(solarPanel); int end = StartIndexCurrentOutput(solarPanel) - lang_maxOutput.Length; string maxOutput = solarPanel.DetailedInfo.Substring(start, end - start); bool success = float.TryParse(System.Text.RegularExpressions.Regex.Replace(maxOutput, @"[^0-9.]", ""), out power); // power should be in kW if (success) { if (maxOutput.Contains(" W")) { // W -> kW: * 0.001 power *= 0.001f; } else if (maxOutput.Contains(" kW")) { // kW -> kW: * 1 power *= 1.0f; } else if (maxOutput.Contains(" MW")) { // MW -> kW: * 1,000 power *= 1000.0f; } else if (maxOutput.Contains(" GW")) { // GW -> kW: * 1,000,000 power *= 1000000.0f; } else throw new Exception(" MaxOutput(IMySolarPanel, float): maximum power output is too high (" + maxOutput + ")"); } return success; } // currently unused bool CurrentOutput(IMySolarPanel solarPanel, out float power) { power = 0.0f; if (solarPanel == null) throw new Exception(" CurrentOutput(IMySolarPanel, float): solarPanel is null"); int start = StartIndexCurrentOutput(solarPanel); int end = solarPanel.DetailedInfo.Length; string currentOutput = solarPanel.DetailedInfo.Substring(start, end - start); bool success = float.TryParse(System.Text.RegularExpressions.Regex.Replace(currentOutput, @"[^0-9.]", ""), out power); // power should be in kW if (success) { if (currentOutput.Contains(" W")) { // W -> kW: * 0.001 power *= 0.001f; } else if (currentOutput.Contains(" kW")) { // kW -> kW: * 1 power *= 1.0f; } else if (currentOutput.Contains(" MW")) { // MW -> kW: * 1,000 power *= 1000.0f; } else if (currentOutput.Contains(" GW")) { // GW -> kW: * 1,000,000 power *= 1000000.0f; } else throw new Exception(" CurrentOutput(IMySolarPanel, float): current power output is too high (" + currentOutput + ")"); } return success; } int StartIndexMaxOutput(IMySolarPanel solarPanel) { if (solarPanel == null) throw new Exception(" StartIndexMaxOutput(IMySolarPanel): solarPanel is null"); int ret = solarPanel.DetailedInfo.IndexOf(lang_maxOutput); if (ret < 0) throw new Exception(" StartIndexMaxOutput(IMySolarPanel): incompatible solar panel"); return ret + lang_maxOutput.Length; } int StartIndexCurrentOutput(IMySolarPanel solarPanel) { if (solarPanel == null) throw new Exception(" StartIndexCurrentOutput(IMySolarPanel): solarPanel is null"); int ret = solarPanel.DetailedInfo.IndexOf(lang_currentOutput); if (ret < 0 || ret <= StartIndexMaxOutput(solarPanel)) throw new Exception(" StartIndexCurrentOutput(IMySolarPanel): incompatible solar panel"); return ret + lang_currentOutput.Length; } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Egl { /// <summary> /// <para> /// [EGL] Egl.ChooseConfig: Must be followed by a nonnegative integer that indicates the desired alpha mask buffer size, in /// bits. The smallest alpha mask buffers of at least the specified size are preferred. The default value is zero. The alpha /// mask buffer is used only by OpenGL and OpenGL ES client APIs. /// </para> /// <para> /// [EGL] Egl.GetConfigAttrib: Returns the number of bits in the alpha mask buffer. /// </para> /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int ALPHA_MASK_SIZE = 0x303E; /// <summary> /// [EGL] Value of EGL_BUFFER_PRESERVED symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int BUFFER_PRESERVED = 0x3094; /// <summary> /// [EGL] Value of EGL_BUFFER_DESTROYED symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int BUFFER_DESTROYED = 0x3095; /// <summary> /// [EGL] Egl.QueryString: Returns a string describing which client rendering APIs are supported. The string contains a /// space-separate list of API names. The list must include at least one of OpenGL, OpenGL_ES, or OpenVG. These strings /// correspond respectively to values Egl.OPENGL_API, Egl.OPENGL_ES_API, and Egl.OPENVG_API of the Egl.BindAPI, api /// argument. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int CLIENT_APIS = 0x308D; /// <summary> /// [EGL] Value of EGL_COLORSPACE_sRGB symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int COLORSPACE_sRGB = 0x3089; /// <summary> /// [EGL] Value of EGL_COLORSPACE_LINEAR symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int COLORSPACE_LINEAR = 0x308A; /// <summary> /// <para> /// [EGL] Egl.ChooseConfig: Must be followed by one of Egl.RGB_BUFFER or Egl.LUMINANCE_BUFFER. Egl.RGB_BUFFER indicates an /// RGB color buffer; in this case, attributes Egl.RED_SIZE, Egl.GREEN_SIZE and Egl.BLUE_SIZE must be non-zero, and /// Egl.LUMINANCE_SIZE must be zero. Egl.LUMINANCE_BUFFER indicates a luminance color buffer. In this case Egl.RED_SIZE, /// Egl.GREEN_SIZE, Egl.BLUE_SIZE must be zero, and Egl.LUMINANCE_SIZE must be non-zero. For both RGB and luminance color /// buffers, Egl.ALPHA_SIZE may be zero or non-zero. /// </para> /// <para> /// [EGL] Egl.GetConfigAttrib: Returns the color buffer type. Possible types are Egl.RGB_BUFFER and Egl.LUMINANCE_BUFFER. /// </para> /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int COLOR_BUFFER_TYPE = 0x303F; /// <summary> /// [EGL] Egl.QueryContext: Returns the type of client API which the context supports (one of Egl.OPENGL_API, /// Egl.OPENGL_ES_API, or Egl.OPENVG_API). /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int CONTEXT_CLIENT_TYPE = 0x3097; /// <summary> /// [EGL] Value of EGL_DISPLAY_SCALING symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int DISPLAY_SCALING = 10000; /// <summary> /// [EGL] Egl.QuerySurface: Returns the horizontal dot pitch of the display on which a window surface is visible. The value /// returned is equal to the actual dot pitch, in pixels/meter, multiplied by the constant value Egl.DISPLAY_SCALING. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int HORIZONTAL_RESOLUTION = 0x3090; /// <summary> /// [EGL] Value of EGL_LUMINANCE_BUFFER symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int LUMINANCE_BUFFER = 0x308F; /// <summary> /// <para> /// [EGL] Egl.ChooseConfig: Must be followed by a nonnegative integer that indicates the desired size of the luminance /// component of the color buffer, in bits. If this value is zero, color buffers with the smallest luminance component size /// are preferred. Otherwise, color buffers with the largest luminance component of at least the specified size are /// preferred. The default value is zero. /// </para> /// <para> /// [EGL] Egl.GetConfigAttrib: Returns the number of bits of luminance stored in the luminance buffer. /// </para> /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int LUMINANCE_SIZE = 0x303D; /// <summary> /// [EGL] Value of EGL_OPENGL_ES_BIT symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] [Log(BitmaskName = "EGLRenderableTypeMask")] public const int OPENGL_ES_BIT = 0x0001; /// <summary> /// [EGL] Value of EGL_OPENVG_BIT symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] [Log(BitmaskName = "EGLRenderableTypeMask")] public const int OPENVG_BIT = 0x0002; /// <summary> /// [EGL] Value of EGL_OPENGL_ES_API symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int OPENGL_ES_API = 0x30A0; /// <summary> /// [EGL] Value of EGL_OPENVG_API symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int OPENVG_API = 0x30A1; /// <summary> /// [EGL] Value of EGL_OPENVG_IMAGE symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int OPENVG_IMAGE = 0x3096; /// <summary> /// [EGL] Egl.QuerySurface: Returns the aspect ratio of an individual pixel (the ratio of a pixel's width to its height). /// The value returned is equal to the actual aspect ratio multiplied by the constant value Egl.DISPLAY_SCALING. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int PIXEL_ASPECT_RATIO = 0x3092; /// <summary> /// <para> /// [EGL] Egl.ChooseConfig: Must be followed by a bitmask indicating which types of client API contexts the frame buffer /// configuration must support creating with Egl.CreateContext). Mask bits are the same as for attribute Egl.CONFORMANT. The /// default value is Egl.OPENGL_ES_BIT. /// </para> /// <para> /// [EGL] Egl.GetConfigAttrib: Returns a bitmask indicating the types of supported client API contexts. /// </para> /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int RENDERABLE_TYPE = 0x3040; /// <summary> /// <para> /// [EGL] Egl.CreateWindowSurface: Specifies which buffer should be used for client API rendering to the window. If its /// value is Egl.SINGLE_BUFFER, then client APIs should render directly into the visible window. If its value is /// Egl.BACK_BUFFER, then client APIs should render into the back buffer. The default value of Egl.RENDER_BUFFER is /// Egl.BACK_BUFFER. Client APIs may not be able to respect the requested rendering buffer. To determine the actual buffer /// being rendered to by a context, call Egl.QueryContext. /// </para> /// <para> /// [EGL] Egl.QueryContext: Returns the buffer which client API rendering via the context will use. The value returned /// depends on properties of both the context, and the surface to which the context is bound: If the context is bound to a /// pixmap surface, then Egl.SINGLE_BUFFER will be returned. If the context is bound to a pbuffer surface, then /// Egl.BACK_BUFFER will be returned. If the context is bound to a window surface, then either Egl.BACK_BUFFER or /// Egl.SINGLE_BUFFER may be returned. The value returned depends on both the buffer requested by the setting of the /// Egl.RENDER_BUFFER property of the surface (which may be queried by calling eglQuerySurface), and on the client API (not /// all client APIs support single-buffer rendering to window surfaces). If the context is not bound to a surface, such as /// an OpenGL ES context bound to a framebuffer object, then Egl.NONE will be returned. /// </para> /// <para> /// [EGL] Egl.QuerySurface: Returns the buffer which client API rendering is requested to use. For a window surface, this is /// the same attribute value specified when the surface was created. For a pbuffer surface, it is always Egl.BACK_BUFFER. /// For a pixmap surface, it is always Egl.SINGLE_BUFFER. To determine the actual buffer being rendered to by a context, /// call Egl.QueryContext. /// </para> /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int RENDER_BUFFER = 0x3086; /// <summary> /// [EGL] Value of EGL_RGB_BUFFER symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int RGB_BUFFER = 0x308E; /// <summary> /// [EGL] Value of EGL_SINGLE_BUFFER symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int SINGLE_BUFFER = 0x3085; /// <summary> /// <para> /// [EGL] Egl.QuerySurface: Returns the effect on the color buffer when posting a surface with Egl.SwapBuffers. Swap /// behavior may be either Egl.BUFFER_PRESERVED or Egl.BUFFER_DESTROYED, as described for Egl.SurfaceAttrib. /// </para> /// <para> /// [EGL] Egl.SurfaceAttrib: Specifies the effect on the color buffer of posting a surface with Egl.SwapBuffers. A value of /// Egl.BUFFER_PRESERVED indicates that color buffer contents are unaffected, while Egl.BUFFER_DESTROYED indicates that /// color buffer contents may be destroyed or changed by the operation. The initial value of Egl.SWAP_BEHAVIOR is chosen by /// the implementation. /// </para> /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int SWAP_BEHAVIOR = 0x3093; /// <summary> /// [EGL] Value of EGL_UNKNOWN symbol. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int UNKNOWN = -1; /// <summary> /// [EGL] Egl.QuerySurface: Returns the vertical dot pitch of the display on which a window surface is visible. The value /// returned is equal to the actual dot pitch, in pixels/meter, multiplied by the constant value Egl.DISPLAY_SCALING. /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public const int VERTICAL_RESOLUTION = 0x3091; /// <summary> /// [EGL] eglBindAPI: Set the current rendering API /// </summary> /// <param name="api"> /// Specifies the client API to bind, one of Egl.OPENGL_API, Egl.OPENGL_ES_API, or Egl.OPENVG_API. /// </param> [RequiredByFeature("EGL_VERSION_1_2")] public static bool BindAPI(uint api) { bool retValue; Debug.Assert(Delegates.peglBindAPI != null, "peglBindAPI not implemented"); retValue = Delegates.peglBindAPI(api); LogCommand("eglBindAPI", retValue, api ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglQueryAPI: Query the current rendering API /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public static uint QueryAPI() { uint retValue; Debug.Assert(Delegates.peglQueryAPI != null, "peglQueryAPI not implemented"); retValue = Delegates.peglQueryAPI(); LogCommand("eglQueryAPI", retValue ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglCreatePbufferFromClientBuffer: create a new EGL pixel buffer surface bound to an OpenVG image /// </summary> /// <param name="dpy"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="buftype"> /// Specifies the type of client API buffer to be bound. Must be Egl.OPENVG_IMAGE, corresponding to an OpenVG VGImage /// buffer. /// </param> /// <param name="buffer"> /// Specifies the OpenVG VGImage handle of the buffer to be bound. /// </param> /// <param name="config"> /// Specifies the EGL frame buffer configuration that defines the frame buffer resource available to the surface. /// </param> /// <param name="attrib_list"> /// Specifies pixel buffer surface attributes. May be Egl. or empty (first attribute is Egl.NONE). /// </param> [RequiredByFeature("EGL_VERSION_1_2")] public static IntPtr CreatePbufferFromClientBuffer(IntPtr dpy, uint buftype, IntPtr buffer, IntPtr config, int[] attrib_list) { IntPtr retValue; unsafe { fixed (int* p_attrib_list = attrib_list) { Debug.Assert(Delegates.peglCreatePbufferFromClientBuffer != null, "peglCreatePbufferFromClientBuffer not implemented"); retValue = Delegates.peglCreatePbufferFromClientBuffer(dpy, buftype, buffer, config, p_attrib_list); LogCommand("eglCreatePbufferFromClientBuffer", retValue, dpy, buftype, buffer, config, attrib_list ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglReleaseThread: Release EGL per-thread state /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public static bool ReleaseThread() { bool retValue; Debug.Assert(Delegates.peglReleaseThread != null, "peglReleaseThread not implemented"); retValue = Delegates.peglReleaseThread(); LogCommand("eglReleaseThread", retValue ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [EGL] eglWaitClient: Complete client API execution prior to subsequent native rendering calls /// </summary> [RequiredByFeature("EGL_VERSION_1_2")] public static bool WaitClient() { bool retValue; Debug.Assert(Delegates.peglWaitClient != null, "peglWaitClient not implemented"); retValue = Delegates.peglWaitClient(); LogCommand("eglWaitClient", retValue ); DebugCheckErrors(retValue); return (retValue); } internal static unsafe partial class Delegates { [RequiredByFeature("EGL_VERSION_1_2")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglBindAPI(uint api); [RequiredByFeature("EGL_VERSION_1_2")] internal static eglBindAPI peglBindAPI; [RequiredByFeature("EGL_VERSION_1_2")] [SuppressUnmanagedCodeSecurity] internal delegate uint eglQueryAPI(); [RequiredByFeature("EGL_VERSION_1_2")] internal static eglQueryAPI peglQueryAPI; [RequiredByFeature("EGL_VERSION_1_2")] [SuppressUnmanagedCodeSecurity] internal delegate IntPtr eglCreatePbufferFromClientBuffer(IntPtr dpy, uint buftype, IntPtr buffer, IntPtr config, int* attrib_list); [RequiredByFeature("EGL_VERSION_1_2")] internal static eglCreatePbufferFromClientBuffer peglCreatePbufferFromClientBuffer; [RequiredByFeature("EGL_VERSION_1_2")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglReleaseThread(); [RequiredByFeature("EGL_VERSION_1_2")] internal static eglReleaseThread peglReleaseThread; [RequiredByFeature("EGL_VERSION_1_2")] [SuppressUnmanagedCodeSecurity] internal delegate bool eglWaitClient(); [RequiredByFeature("EGL_VERSION_1_2")] internal static eglWaitClient peglWaitClient; } } }
using Android.Bluetooth; using Android.Content; using Java.Util; using System; using Java.Lang; using Java.Lang.Reflect; using TXCommunication; using Exception = System.Exception; using Object = System.Object; namespace FtApp.Droid.Native { /// <summary> /// This class implements the IRfcommAdapter interface. It is used to have a serial connection over bluetooth /// </summary> class BluetoothAdapter : IRfcommAdapter { private Context Context { get; } private static readonly UUID RfCommUuid = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); private BluetoothDevice _bluetoothDevice; private BluetoothSocket _bluetoothSocket; private readonly Android.Bluetooth.BluetoothAdapter _bluetoothAdapter; private BroadcastReceiver _bluetoothBroadcastRecevicer; public BluetoothAdapter(Context context) { Context = context; _bluetoothAdapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter; } public void OpenConnection(string address) { if (!_bluetoothAdapter.IsEnabled) { throw new InvalidOperationException("The bluetooth adapter is not enabled"); } if (!Android.Bluetooth.BluetoothAdapter.CheckBluetoothAddress(address)) { throw new InvalidOperationException("The given address is not valid"); } _bluetoothDevice = _bluetoothAdapter.GetRemoteDevice(address); try { // Create the socket using reflection Method m = _bluetoothDevice.Class.GetMethod("createRfcommSocket", Integer.Type); _bluetoothSocket = (BluetoothSocket) m.Invoke(_bluetoothDevice, 1); } catch (Exception) { try { // When the first method failed try to connect using the public method _bluetoothSocket = _bluetoothDevice?.CreateInsecureRfcommSocketToServiceRecord(RfCommUuid); } catch (Exception e) { } } _bluetoothSocket?.Connect(); } public void CloseConnection() { // Close the I/O streams _bluetoothSocket?.InputStream?.Close(); _bluetoothSocket?.OutputStream?.Close(); // Cose the socket connection _bluetoothSocket?.Close(); } public void Write(byte[] bytes) { if (_bluetoothSocket != null && _bluetoothSocket.IsConnected) { // Write the bytes to the socket _bluetoothSocket.OutputStream.Write(bytes, 0, bytes.Length); } } public byte[] Read(int count) { if (_bluetoothSocket != null && _bluetoothSocket.IsConnected) { // Read the arrived bytes byte[] bytes = new byte[count]; if (_bluetoothSocket != null && _bluetoothSocket.IsConnected) { _bluetoothSocket.InputStream.Read(bytes, 0, bytes.Length); } return bytes; } return new byte[count]; } public void CancelSearch() { // Cancel the bluetooth discovery if (_bluetoothAdapter != null && _bluetoothAdapter.IsDiscovering) { _bluetoothAdapter.CancelDiscovery(); } } public bool IsAvaliable(string address) { // Checks if a bluetooth adress is valid return Android.Bluetooth.BluetoothAdapter.CheckBluetoothAddress(address); } public void SearchAvailableDevices(SerialSearchStarted started, SerialSearchFound found, SerialSearchFinished finished) { // Search for bluetooth devices _bluetoothBroadcastRecevicer = new BluetoothBroadcastReceiver(started, found, finished); IntentFilter deviceFoundFilter = new IntentFilter(BluetoothDevice.ActionFound); Context.RegisterReceiver(_bluetoothBroadcastRecevicer, deviceFoundFilter); IntentFilter discoveryFinishedFilter = new IntentFilter(Android.Bluetooth.BluetoothAdapter.ActionDiscoveryFinished); Context.RegisterReceiver(_bluetoothBroadcastRecevicer, discoveryFinishedFilter); IntentFilter discoveryStartedFilter = new IntentFilter(Android.Bluetooth.BluetoothAdapter.ActionDiscoveryStarted); Context.RegisterReceiver(_bluetoothBroadcastRecevicer, discoveryStartedFilter); _bluetoothAdapter.StartDiscovery(); } public void Dispose() { if (_bluetoothSocket != null) { if (_bluetoothSocket.IsConnected) { _bluetoothSocket.InputStream.Close(); _bluetoothSocket.OutputStream.Close(); _bluetoothSocket.Close(); } _bluetoothSocket.Dispose(); } _bluetoothAdapter?.CancelDiscovery(); } private class BluetoothBroadcastReceiver : BroadcastReceiver { private readonly SerialSearchStarted _startedDelegate; private readonly SerialSearchFound _foundDelegate; private readonly SerialSearchFinished _finishedDelegate; public BluetoothBroadcastReceiver(SerialSearchStarted started, SerialSearchFound found, SerialSearchFinished finished) { _startedDelegate = started; _foundDelegate = found; _finishedDelegate = finished; } public override void OnReceive(Context context, Intent intent) { string action = intent.Action; switch (action) { case BluetoothDevice.ActionFound: BluetoothDevice device = ReadBluetoothDeviceFromIntent(intent); _foundDelegate(device.Address); break; case Android.Bluetooth.BluetoothAdapter.ActionDiscoveryStarted: _startedDelegate(); break; case Android.Bluetooth.BluetoothAdapter.ActionDiscoveryFinished: _finishedDelegate(); context.UnregisterReceiver(this); break; } } private BluetoothDevice ReadBluetoothDeviceFromIntent(Intent intent) { return intent.GetParcelableExtra(BluetoothDevice.ExtraDevice) as BluetoothDevice; } } } }
// Copyright (c) 2014 Thong Nguyen (tumtumtum@gmail.com) using System; using System.Collections.Specialized; using System.IO; using System.Text; using System.Collections.Generic; using Platform.Text; namespace Platform { /// <summary> /// Provides useful methods for dealing with string based URIs. /// </summary> public sealed class StringUriUtils { /// <summary> /// Array of standard <c>acceptable</c> seperator chars for use when normalizing a path. /// </summary> /// <remarks> /// This array holds the chars <c>'/'</c> and <c>'\'</c>. /// </remarks> public static readonly char[] AcceptableSeperatorChars = new char[] { '/', '\\' }; /// <summary> /// Returns the name part of a URL /// </summary> /// <param name="uri"></param> /// <returns></returns> public static string GetName(string uri) { return uri.SplitAroundCharFromRight(PredicateUtils.ObjectEqualsAny<char>('/', '\\')).Right; } public static Pair<string, string> GetSchemeAndPath(string uri) { var x = uri.IndexOf("://", StringComparison.Ordinal); if (x < 0) { return new Pair<string, string>("", uri); } else { return new Pair<string, string>(uri.Substring(0, x), uri.Substring(x + 1)); } } public static string GetPath(string uri) { int x = uri.IndexOf("://", StringComparison.Ordinal); if (x < 0) { return uri; } else { return uri.Substring(x + 3); } } public static string GetScheme(string uri) { int x = uri.IndexOf("://", StringComparison.Ordinal); if (x < 0) { return ""; } else { return uri.Substring(0, x); } } /// <summary> /// <see cref="NormalizePath(string, int, int)"/> /// </summary> /// <remarks> /// Calls <see cref="NormalizePath(string, int, int)"/> with the array /// <see cref="AcceptableSeperatorChars"/> which contains <c>'/'</c> and <c>'\'</c>. /// </remarks> public static string NormalizePath(string path) { return NormalizePath(path, 0, path.Length, AcceptableSeperatorChars, false); } public static string NormalizePath(string path, int startIndex, int count) { return NormalizePath(path, startIndex, count, AcceptableSeperatorChars, false); } private static bool CharArrayContains(char[] array, char c) { for (var i = 0; i < array.Length; i++) { if (array[i] == c) { return true; } } return false; } [ThreadStatic] private static int[] backtrackStack; /// <summary> /// Normalises a given path and returns the new normalised version. /// </summary> /// <remarks> /// <p> /// The normalization process consists of the following: /// /// Path elements consisting of '.' are removed. /// Path elements before path elements consisting of '..' are removed. /// The given chars are replaced with the standard URI seperator char '/'. /// </p> /// <p> /// Paths will always be returned without the trailing seperator char '/'. /// </p> /// </remarks> /// <param name="path"> /// The path to normalise. /// </param> /// <returns> /// A normalised version of the path. /// </returns> public static string NormalizePath(string path, int startIndex, int count, char[] seperatorChars, bool preserveEndingSeperator) { int x, y, z, xi; var startsWithSeperator = false; var endsWithSeperator = false; if (count == 0) { return ""; } xi = 0; x = startIndex; if (StringUriUtils.backtrackStack == null) { lock (typeof(StringUriUtils)) { if (StringUriUtils.backtrackStack == null) { StringUriUtils.backtrackStack = new int[100]; } } } var localBackTrackStack = StringUriUtils.backtrackStack; localBackTrackStack[xi] = startIndex; startsWithSeperator = CharArrayContains(seperatorChars, path[startIndex]); endsWithSeperator = CharArrayContains(seperatorChars, path[path.Length - 1]); if (startsWithSeperator) { if (count == 1) { return "/"; } else { x = startIndex + 1; localBackTrackStack[xi] = startIndex; } } xi++; var builder = new StringBuilder(path.Length); while (x < (count + startIndex)) { y = x; while (y < (count + startIndex)) { if (CharArrayContains(seperatorChars, path[y])) { break; } y++; } z = y - x; if (z == 0) { // Ignore '//'. } else if (z == 1 && path[x] == '.') { // Ignore '/./' } else if (z == 2 && path[x] == '.' && path[x + 1] == '.') { if (x < 2) { throw new ArgumentException("Root (/) has no parent.", path); } if (builder.Length == 0) { throw new InvalidOperationException("Impossible attempt to go above path root (/)."); } xi--; builder.Remove(StringUriUtils.backtrackStack[xi], builder.Length - StringUriUtils.backtrackStack[xi]); } else { localBackTrackStack[xi++] = builder.Length; if (x == 0) { if (startsWithSeperator) { builder.Append('/'); } } else { builder.Append('/'); } builder.Append(path, x, z); } x = y + 1; } if (builder.Length == 0) { if (startsWithSeperator) { return "/"; } else { return "."; } } if (endsWithSeperator && preserveEndingSeperator) { builder.Append("/"); } return builder.ToString(); } public static string Combine(string left, string right) { if (left.EndsWith("/")) { if (right.StartsWith("/")) { return left.Substring(0, left.Length - 1) + right; } else { return left + right; } } else { if (right.StartsWith("/")) { return left + right; } else { return left + "/" + right; } } } public static string Unescape(string s) { var builder = new StringBuilder(s.Length + 10); for (var i = 0; i < s.Length; ) { builder.Append(Uri.HexUnescape(s, ref i)); } return builder.ToString(); } public static string Escape(string s, Predicate<char> includeChar) { var writer = new StringWriter(); var reader = new StringReader(s); var charValue = reader.Read(); while (charValue != -1) { if (((charValue >= 48) && (charValue <= 57)) // 0-9 || ((charValue >= 65) && (charValue <= 90)) // A-Z || ((charValue >= 97) && (charValue <= 122))) // a-z { writer.Write((char)charValue); } else { writer.Write("%{0:x2}", charValue); } charValue = reader.Read(); } return writer.ToString(); } public static string UrlEncode(string instring) { return TextConversion.ToEscapedHexString(instring, TextConversion.IsStandardUrlEscapedChar); } public static string BuildQuery(NameValueCollection nameValueCollection) { return BuildQuery(Pair<string, string>.FromNameValueCollection(nameValueCollection), PredicateUtils<Pair<string, string>>.AlwaysTrue); } public static string BuildQuery(NameValueCollection nameValueCollection, Predicate<Pair<string, string>> acceptPair) { return BuildQuery(Pair<string, string>.FromNameValueCollection(nameValueCollection), acceptPair); } public static string BuildQuery(System.Collections.Generic.IEnumerable<KeyValuePair<string, string>> pairs) { return BuildQuery(pairs, PredicateUtils<Pair<string, string>>.AlwaysTrue); } public static string BuildQuery(System.Collections.Generic.IEnumerable<KeyValuePair<string, string>> pairs, Predicate<Pair<string, string>> acceptPair) { return BuildQuery(Pair<string, string>.FromKeyValuePairs(pairs), acceptPair); } public static string BuildQuery(System.Collections.Generic.IEnumerable<Pair<string, string>> pairs) { return BuildQuery(pairs, PredicateUtils<Pair<string, string>>.AlwaysTrue); } public static string BuildQuery(System.Collections.Generic.IEnumerable<Pair<string, string>> pairs, Predicate<Pair<string, string>> acceptPair) { var builder = new StringBuilder(); foreach (var pair in pairs) { if (acceptPair(pair)) { builder.Append(UrlEncode(pair.Key)); builder.Append('='); builder.Append(UrlEncode(pair.Value)); } } return builder.ToString(); } public static System.Collections.Generic.IEnumerable<Pair<string, string>> ParseQuery(string query) { if (query == "") { yield break; } var ss = query.Split('&'); for (var i = 0; i < ss.Length; i++) { int j; string key, value; j = ss[i].IndexOf('='); if (j < 0) { key = ss[i]; value=""; } else { key = ss[i].Substring(0, j); value = ss[i].Substring(j + 1); } yield return new Pair<string, string>(key, value); } } public static bool ContainsQuery(string uri) { return uri.LastIndexOf('?') >= 0; } public static string RemoveQuery(string uri) { return uri.Left(PredicateUtils.ObjectEquals<char>('?').Not()); } public static string AppendQueryPart(string uri, string key, string value) { if (uri.LastIndexOf('?') > 0) { uri += "&"; } else { uri += '?'; } uri += UrlEncode(key) + "=" + UrlEncode(value); return uri; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; // TODO: Move these tests to CoreFX once they can be run on CoreRT internal static class Runner { private const int Pass = 100; public static int Main() { Console.WriteLine(" WaitSubsystemTests.DoubleSetOnEventWithTimedOutWaiterShouldNotStayInWaitersList"); WaitSubsystemTests.DoubleSetOnEventWithTimedOutWaiterShouldNotStayInWaitersList(); Console.WriteLine(" WaitSubsystemTests.ManualResetEventTest"); WaitSubsystemTests.ManualResetEventTest(); Console.WriteLine(" WaitSubsystemTests.AutoResetEventTest"); WaitSubsystemTests.AutoResetEventTest(); Console.WriteLine(" WaitSubsystemTests.SemaphoreTest"); WaitSubsystemTests.SemaphoreTest(); Console.WriteLine(" WaitSubsystemTests.MutexTest"); WaitSubsystemTests.MutexTest(); Console.WriteLine(" WaitSubsystemTests.WaitDurationTest"); WaitSubsystemTests.WaitDurationTest(); // This test takes a long time to run in release and especially in debug builds. Enable for manual testing. //Console.WriteLine(" WaitSubsystemTests.MutexMaximumReacquireCountTest"); //WaitSubsystemTests.MutexMaximumReacquireCountTest(); Console.WriteLine(" TimersCreatedConcurrentlyOnDifferentThreadsAllFire"); TimerTests.TimersCreatedConcurrentlyOnDifferentThreadsAllFire(); Console.WriteLine(" ThreadPoolTests.RunProcessorCountItemsInParallel"); ThreadPoolTests.RunProcessorCountItemsInParallel(); Console.WriteLine(" ThreadPoolTests.RunMoreThanMaxJobsMakesOneJobWaitForStarvationDetection"); ThreadPoolTests.RunMoreThanMaxJobsMakesOneJobWaitForStarvationDetection(); Console.WriteLine(" ThreadPoolTests.ThreadPoolCanPickUpOneJobWhenThreadIsAvailable"); ThreadPoolTests.ThreadPoolCanPickUpOneJobWhenThreadIsAvailable(); Console.WriteLine(" ThreadPoolTests.ThreadPoolCanPickUpMultipleJobsWhenThreadsAreAvailable"); ThreadPoolTests.ThreadPoolCanPickUpMultipleJobsWhenThreadsAreAvailable(); Console.WriteLine(" ThreadPoolTests.ThreadPoolCanProcessManyWorkItemsInParallelWithoutDeadlocking"); ThreadPoolTests.ThreadPoolCanProcessManyWorkItemsInParallelWithoutDeadlocking(); // This test takes a long time to run (min 42 seconds sleeping). Enable for manual testing. // Console.WriteLine(" ThreadPoolTests.RunJobsAfterThreadTimeout"); // ThreadPoolTests.RunJobsAfterThreadTimeout(); Console.WriteLine(" ThreadPoolTests.WorkQueueDepletionTest"); ThreadPoolTests.WorkQueueDepletionTest(); Console.WriteLine(" ThreadPoolTests.WorkerThreadStateReset"); ThreadPoolTests.WorkerThreadStateReset(); // This test is not applicable (and will not pass) on Windows since it uses the Windows OS-provided thread pool. // Console.WriteLine(" ThreadPoolTests.SettingMinThreadsWillCreateThreadsUpToMinimum"); // ThreadPoolTests.SettingMinThreadsWillCreateThreadsUpToMinimum(); Console.WriteLine(" WaitThreadTests.SignalingRegisteredHandleCallsCalback"); WaitThreadTests.SignalingRegisteredHandleCallsCalback(); Console.WriteLine(" WaitThreadTests.TimingOutRegisteredHandleCallsCallback"); WaitThreadTests.TimingOutRegisteredHandleCallsCallback(); Console.WriteLine(" WaitThreadTests.UnregisteringBeforeSignalingDoesNotCallCallback"); WaitThreadTests.UnregisteringBeforeSignalingDoesNotCallCallback(); Console.WriteLine(" WaitThreadTests.RepeatingWaitFiresUntilUnregistered"); WaitThreadTests.RepeatingWaitFiresUntilUnregistered(); Console.WriteLine(" WaitThreadTests.UnregisterEventSignaledWhenUnregistered"); WaitThreadTests.UnregisterEventSignaledWhenUnregistered(); Console.WriteLine(" WaitThreadTests.CanRegisterMoreThan64Waits"); WaitThreadTests.CanRegisterMoreThan64Waits(); Console.WriteLine(" WaitThreadTests.StateIsPasssedThroughToCallback"); WaitThreadTests.StateIsPasssedThroughToCallback(); // This test takes a long time to run. Enable for manual testing. // Console.WriteLine(" WaitThreadTests.WaitWithLongerTimeoutThanWaitThreadCanStillTimeout"); // WaitThreadTests.WaitWithLongerTimeoutThanWaitThreadCanStillTimeout(); Console.WriteLine(" WaitThreadTests.UnregisterCallbackIsNotCalledAfterCallbackFinishesIfAnotherCallbackOnSameWaitRunning"); WaitThreadTests.UnregisterCallbackIsNotCalledAfterCallbackFinishesIfAnotherCallbackOnSameWaitRunning(); Console.WriteLine(" WaitThreadTests.CallingUnregisterOnAutomaticallyUnregisteredHandleReturnsTrue"); WaitThreadTests.CallingUnregisterOnAutomaticallyUnregisteredHandleReturnsTrue(); Console.WriteLine(" WaitThreadTests.EventSetAfterUnregisterNotObservedOnWaitThread"); WaitThreadTests.EventSetAfterUnregisterNotObservedOnWaitThread(); Console.WriteLine(" WaitThreadTests.BlockingUnregister"); WaitThreadTests.BlockingUnregister(); Console.WriteLine(" WaitThreadTests.CanDisposeEventAfterUnblockingUnregister"); WaitThreadTests.CanDisposeEventAfterUnblockingUnregister(); Console.WriteLine(" WaitThreadTests.UnregisterEventSignaledWhenUnregisteredEvenIfAutoUnregistered"); WaitThreadTests.UnregisterEventSignaledWhenUnregisteredEvenIfAutoUnregistered(); Console.WriteLine(" WaitThreadTests.BlockingUnregisterBlocksEvenIfCallbackExecuting"); WaitThreadTests.BlockingUnregisterBlocksEvenIfCallbackExecuting(); return Pass; } } internal static class WaitSubsystemTests { private const int AcceptableEarlyWaitTerminationDiffMilliseconds = -100; private const int AcceptableLateWaitTerminationDiffMilliseconds = 300; [Fact] public static void ManualResetEventTest() { // Constructor and dispose var e = new ManualResetEvent(false); Assert.False(e.WaitOne(0)); e.Dispose(); Assert.Throws<ObjectDisposedException>(() => e.Reset()); Assert.Throws<ObjectDisposedException>(() => e.Set()); Assert.Throws<ObjectDisposedException>(() => e.WaitOne(0)); e = new ManualResetEvent(true); Assert.True(e.WaitOne(0)); // Set and reset e = new ManualResetEvent(true); e.Reset(); Assert.False(e.WaitOne(0)); Assert.False(e.WaitOne(0)); e.Reset(); Assert.False(e.WaitOne(0)); e.Set(); Assert.True(e.WaitOne(0)); Assert.True(e.WaitOne(0)); e.Set(); Assert.True(e.WaitOne(0)); // Wait e.Set(); Assert.True(e.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.True(e.WaitOne()); e.Reset(); Assert.False(e.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds)); e = null; // Multi-wait with all indexes set var es = new ManualResetEvent[] { new ManualResetEvent(true), new ManualResetEvent(true), new ManualResetEvent(true), new ManualResetEvent(true) }; Assert.Equal(0, WaitHandle.WaitAny(es, 0)); Assert.Equal(0, WaitHandle.WaitAny(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.Equal(0, WaitHandle.WaitAny(es)); Assert.True(WaitHandle.WaitAll(es, 0)); Assert.True(WaitHandle.WaitAll(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.True(WaitHandle.WaitAll(es)); for (int i = 0; i < es.Length; ++i) { Assert.True(es[i].WaitOne(0)); } // Multi-wait with indexes 1 and 2 set es[0].Reset(); es[3].Reset(); Assert.Equal(1, WaitHandle.WaitAny(es, 0)); Assert.Equal(1, WaitHandle.WaitAny(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.False(WaitHandle.WaitAll(es, 0)); Assert.False(WaitHandle.WaitAll(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds)); for (int i = 0; i < es.Length; ++i) { Assert.Equal(i == 1 || i == 2, es[i].WaitOne(0)); } // Multi-wait with all indexes reset es[1].Reset(); es[2].Reset(); Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(es, 0)); Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds)); Assert.False(WaitHandle.WaitAll(es, 0)); Assert.False(WaitHandle.WaitAll(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds)); for (int i = 0; i < es.Length; ++i) { Assert.False(es[i].WaitOne(0)); } } [Fact] public static void AutoResetEventTest() { // Constructor and dispose var e = new AutoResetEvent(false); Assert.False(e.WaitOne(0)); e.Dispose(); Assert.Throws<ObjectDisposedException>(() => e.Reset()); Assert.Throws<ObjectDisposedException>(() => e.Set()); Assert.Throws<ObjectDisposedException>(() => e.WaitOne(0)); e = new AutoResetEvent(true); Assert.True(e.WaitOne(0)); // Set and reset e = new AutoResetEvent(true); e.Reset(); Assert.False(e.WaitOne(0)); Assert.False(e.WaitOne(0)); e.Reset(); Assert.False(e.WaitOne(0)); e.Set(); Assert.True(e.WaitOne(0)); Assert.False(e.WaitOne(0)); e.Set(); e.Set(); Assert.True(e.WaitOne(0)); // Wait e.Set(); Assert.True(e.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.False(e.WaitOne(0)); e.Set(); Assert.True(e.WaitOne()); Assert.False(e.WaitOne(0)); e.Reset(); Assert.False(e.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds)); e = null; // Multi-wait with all indexes set var es = new AutoResetEvent[] { new AutoResetEvent(true), new AutoResetEvent(true), new AutoResetEvent(true), new AutoResetEvent(true) }; Assert.Equal(0, WaitHandle.WaitAny(es, 0)); for (int i = 0; i < es.Length; ++i) { Assert.Equal(i > 0, es[i].WaitOne(0)); es[i].Set(); } Assert.Equal(0, WaitHandle.WaitAny(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); for (int i = 0; i < es.Length; ++i) { Assert.Equal(i > 0, es[i].WaitOne(0)); es[i].Set(); } Assert.Equal(0, WaitHandle.WaitAny(es)); for (int i = 0; i < es.Length; ++i) { Assert.Equal(i > 0, es[i].WaitOne(0)); es[i].Set(); } Assert.True(WaitHandle.WaitAll(es, 0)); for (int i = 0; i < es.Length; ++i) { Assert.False(es[i].WaitOne(0)); es[i].Set(); } Assert.True(WaitHandle.WaitAll(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); for (int i = 0; i < es.Length; ++i) { Assert.False(es[i].WaitOne(0)); es[i].Set(); } Assert.True(WaitHandle.WaitAll(es)); for (int i = 0; i < es.Length; ++i) { Assert.False(es[i].WaitOne(0)); } // Multi-wait with indexes 1 and 2 set es[1].Set(); es[2].Set(); Assert.Equal(1, WaitHandle.WaitAny(es, 0)); for (int i = 0; i < es.Length; ++i) { Assert.Equal(i == 2, es[i].WaitOne(0)); } es[1].Set(); es[2].Set(); Assert.Equal(1, WaitHandle.WaitAny(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); for (int i = 0; i < es.Length; ++i) { Assert.Equal(i == 2, es[i].WaitOne(0)); } es[1].Set(); es[2].Set(); Assert.False(WaitHandle.WaitAll(es, 0)); Assert.False(WaitHandle.WaitAll(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds)); for (int i = 0; i < es.Length; ++i) { Assert.Equal(i == 1 || i == 2, es[i].WaitOne(0)); } // Multi-wait with all indexes reset Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(es, 0)); Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds)); Assert.False(WaitHandle.WaitAll(es, 0)); Assert.False(WaitHandle.WaitAll(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds)); for (int i = 0; i < es.Length; ++i) { Assert.False(es[i].WaitOne(0)); } } [Fact] public static void SemaphoreTest() { // Constructor and dispose Assert.Throws<ArgumentOutOfRangeException>(() => new Semaphore(-1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Semaphore(0, 0)); Assert.Throws<ArgumentException>(() => new Semaphore(2, 1)); var s = new Semaphore(0, 1); Assert.False(s.WaitOne(0)); s.Dispose(); Assert.Throws<ObjectDisposedException>(() => s.Release()); Assert.Throws<ObjectDisposedException>(() => s.WaitOne(0)); s = new Semaphore(1, 1); Assert.True(s.WaitOne(0)); // Signal and unsignal Assert.Throws<ArgumentOutOfRangeException>(() => s.Release(0)); s = new Semaphore(1, 1); Assert.True(s.WaitOne(0)); Assert.False(s.WaitOne(0)); Assert.False(s.WaitOne(0)); Assert.Equal(0, s.Release()); Assert.True(s.WaitOne(0)); Assert.Throws<SemaphoreFullException>(() => s.Release(2)); Assert.Equal(0, s.Release()); Assert.Throws<SemaphoreFullException>(() => s.Release()); s = new Semaphore(1, 2); Assert.Throws<SemaphoreFullException>(() => s.Release(2)); Assert.Equal(1, s.Release(1)); Assert.True(s.WaitOne(0)); Assert.True(s.WaitOne(0)); Assert.Throws<SemaphoreFullException>(() => s.Release(3)); Assert.Equal(0, s.Release(2)); Assert.Throws<SemaphoreFullException>(() => s.Release()); // Wait s = new Semaphore(1, 2); Assert.True(s.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.False(s.WaitOne(0)); s.Release(); Assert.True(s.WaitOne()); Assert.False(s.WaitOne(0)); s.Release(2); Assert.True(s.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); s.Release(); Assert.True(s.WaitOne()); s = new Semaphore(0, 2); Assert.False(s.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds)); s = null; // Multi-wait with all indexes signaled var ss = new Semaphore[] { new Semaphore(1, 1), new Semaphore(1, 1), new Semaphore(1, 1), new Semaphore(1, 1) }; Assert.Equal(0, WaitHandle.WaitAny(ss, 0)); for (int i = 0; i < ss.Length; ++i) { Assert.Equal(i > 0, ss[i].WaitOne(0)); ss[i].Release(); } Assert.Equal(0, WaitHandle.WaitAny(ss, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); for (int i = 0; i < ss.Length; ++i) { Assert.Equal(i > 0, ss[i].WaitOne(0)); ss[i].Release(); } Assert.Equal(0, WaitHandle.WaitAny(ss)); for (int i = 0; i < ss.Length; ++i) { Assert.Equal(i > 0, ss[i].WaitOne(0)); ss[i].Release(); } Assert.True(WaitHandle.WaitAll(ss, 0)); for (int i = 0; i < ss.Length; ++i) { Assert.False(ss[i].WaitOne(0)); ss[i].Release(); } Assert.True(WaitHandle.WaitAll(ss, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); for (int i = 0; i < ss.Length; ++i) { Assert.False(ss[i].WaitOne(0)); ss[i].Release(); } Assert.True(WaitHandle.WaitAll(ss)); for (int i = 0; i < ss.Length; ++i) { Assert.False(ss[i].WaitOne(0)); } // Multi-wait with indexes 1 and 2 signaled ss[1].Release(); ss[2].Release(); Assert.Equal(1, WaitHandle.WaitAny(ss, 0)); for (int i = 0; i < ss.Length; ++i) { Assert.Equal(i == 2, ss[i].WaitOne(0)); } ss[1].Release(); ss[2].Release(); Assert.Equal(1, WaitHandle.WaitAny(ss, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); for (int i = 0; i < ss.Length; ++i) { Assert.Equal(i == 2, ss[i].WaitOne(0)); } ss[1].Release(); ss[2].Release(); Assert.False(WaitHandle.WaitAll(ss, 0)); Assert.False(WaitHandle.WaitAll(ss, ThreadTestHelpers.ExpectedTimeoutMilliseconds)); for (int i = 0; i < ss.Length; ++i) { Assert.Equal(i == 1 || i == 2, ss[i].WaitOne(0)); } // Multi-wait with all indexes unsignaled Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(ss, 0)); Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(ss, ThreadTestHelpers.ExpectedTimeoutMilliseconds)); Assert.False(WaitHandle.WaitAll(ss, 0)); Assert.False(WaitHandle.WaitAll(ss, ThreadTestHelpers.ExpectedTimeoutMilliseconds)); for (int i = 0; i < ss.Length; ++i) { Assert.False(ss[i].WaitOne(0)); } } // There is a race condition between a timed out WaitOne and a Set call not clearing the waiters list // in the wait subsystem (Unix only). More information can be found at // https://github.com/dotnet/corert/issues/3616 and https://github.com/dotnet/corert/pull/3782. [Fact] public static void DoubleSetOnEventWithTimedOutWaiterShouldNotStayInWaitersList() { AutoResetEvent threadStartedEvent = new AutoResetEvent(false); AutoResetEvent resetEvent = new AutoResetEvent(false); Thread thread = new Thread(() => { threadStartedEvent.Set(); Thread.Sleep(50); resetEvent.Set(); resetEvent.Set(); }); thread.IsBackground = true; thread.Start(); threadStartedEvent.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds); resetEvent.WaitOne(50); thread.Join(ThreadTestHelpers.UnexpectedTimeoutMilliseconds); } [Fact] public static void MutexTest() { // Constructor and dispose var m = new Mutex(); Assert.True(m.WaitOne(0)); m.ReleaseMutex(); m.Dispose(); Assert.Throws<ObjectDisposedException>(() => m.ReleaseMutex()); Assert.Throws<ObjectDisposedException>(() => m.WaitOne(0)); m = new Mutex(false); Assert.True(m.WaitOne(0)); m.ReleaseMutex(); m = new Mutex(true); Assert.True(m.WaitOne(0)); m.ReleaseMutex(); m.ReleaseMutex(); m = new Mutex(true); Assert.True(m.WaitOne(0)); m.Dispose(); Assert.Throws<ObjectDisposedException>(() => m.ReleaseMutex()); Assert.Throws<ObjectDisposedException>(() => m.WaitOne(0)); // Acquire and release m = new Mutex(); VerifyThrowsApplicationException(() => m.ReleaseMutex()); Assert.True(m.WaitOne(0)); m.ReleaseMutex(); VerifyThrowsApplicationException(() => m.ReleaseMutex()); Assert.True(m.WaitOne(0)); Assert.True(m.WaitOne(0)); Assert.True(m.WaitOne(0)); m.ReleaseMutex(); m.ReleaseMutex(); m.ReleaseMutex(); VerifyThrowsApplicationException(() => m.ReleaseMutex()); // Wait Assert.True(m.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.True(m.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); m.ReleaseMutex(); m.ReleaseMutex(); Assert.True(m.WaitOne()); Assert.True(m.WaitOne()); m.ReleaseMutex(); m.ReleaseMutex(); m = null; // Multi-wait with all indexes unlocked var ms = new Mutex[] { new Mutex(), new Mutex(), new Mutex(), new Mutex() }; Assert.Equal(0, WaitHandle.WaitAny(ms, 0)); ms[0].ReleaseMutex(); for (int i = 1; i < ms.Length; ++i) { VerifyThrowsApplicationException(() => ms[i].ReleaseMutex()); } Assert.Equal(0, WaitHandle.WaitAny(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); ms[0].ReleaseMutex(); for (int i = 1; i < ms.Length; ++i) { VerifyThrowsApplicationException(() => ms[i].ReleaseMutex()); } Assert.Equal(0, WaitHandle.WaitAny(ms)); ms[0].ReleaseMutex(); for (int i = 1; i < ms.Length; ++i) { VerifyThrowsApplicationException(() => ms[i].ReleaseMutex()); } Assert.True(WaitHandle.WaitAll(ms, 0)); for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); } Assert.True(WaitHandle.WaitAll(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); } Assert.True(WaitHandle.WaitAll(ms)); for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); } // Multi-wait with indexes 0 and 3 locked ms[0].WaitOne(0); ms[3].WaitOne(0); Assert.Equal(0, WaitHandle.WaitAny(ms, 0)); ms[0].ReleaseMutex(); VerifyThrowsApplicationException(() => ms[1].ReleaseMutex()); VerifyThrowsApplicationException(() => ms[2].ReleaseMutex()); Assert.Equal(0, WaitHandle.WaitAny(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); ms[0].ReleaseMutex(); VerifyThrowsApplicationException(() => ms[1].ReleaseMutex()); VerifyThrowsApplicationException(() => ms[2].ReleaseMutex()); Assert.Equal(0, WaitHandle.WaitAny(ms)); ms[0].ReleaseMutex(); VerifyThrowsApplicationException(() => ms[1].ReleaseMutex()); VerifyThrowsApplicationException(() => ms[2].ReleaseMutex()); Assert.True(WaitHandle.WaitAll(ms, 0)); for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); } Assert.True(WaitHandle.WaitAll(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); } Assert.True(WaitHandle.WaitAll(ms)); for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); } ms[0].ReleaseMutex(); VerifyThrowsApplicationException(() => ms[1].ReleaseMutex()); VerifyThrowsApplicationException(() => ms[2].ReleaseMutex()); ms[3].ReleaseMutex(); // Multi-wait with all indexes locked for (int i = 0; i < ms.Length; ++i) { Assert.True(ms[i].WaitOne(0)); } Assert.Equal(0, WaitHandle.WaitAny(ms, 0)); ms[0].ReleaseMutex(); Assert.Equal(0, WaitHandle.WaitAny(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); ms[0].ReleaseMutex(); Assert.Equal(0, WaitHandle.WaitAny(ms)); ms[0].ReleaseMutex(); Assert.True(WaitHandle.WaitAll(ms, 0)); for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); } Assert.True(WaitHandle.WaitAll(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); } Assert.True(WaitHandle.WaitAll(ms)); for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); } for (int i = 0; i < ms.Length; ++i) { ms[i].ReleaseMutex(); VerifyThrowsApplicationException(() => ms[i].ReleaseMutex()); } } private static void VerifyThrowsApplicationException(Action action) { // TODO: netstandard2.0 - After switching to ns2.0 contracts, use Assert.Throws<T> instead of this function // TODO: Enable this verification. There currently seem to be some reliability issues surrounding exceptions on Unix. //try //{ // action(); //} //catch (Exception ex) //{ // if (ex.HResult == unchecked((int)0x80131600)) // return; // Console.WriteLine( // "VerifyThrowsApplicationException: Assertion failure - Assert.Throws<ApplicationException>: got {1}", // ex.GetType()); // throw new AssertionFailureException(ex); //} //Console.WriteLine( // "VerifyThrowsApplicationException: Assertion failure - Assert.Throws<ApplicationException>: got no exception"); //throw new AssertionFailureException(); } [Fact] [OuterLoop] public static void WaitDurationTest() { VerifyWaitDuration( new ManualResetEvent(false), waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds, expectedWaitTerminationAfterMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds); VerifyWaitDuration( new ManualResetEvent(true), waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds, expectedWaitTerminationAfterMilliseconds: 0); VerifyWaitDuration( new AutoResetEvent(false), waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds, expectedWaitTerminationAfterMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds); VerifyWaitDuration( new AutoResetEvent(true), waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds, expectedWaitTerminationAfterMilliseconds: 0); VerifyWaitDuration( new Semaphore(0, 1), waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds, expectedWaitTerminationAfterMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds); VerifyWaitDuration( new Semaphore(1, 1), waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds, expectedWaitTerminationAfterMilliseconds: 0); VerifyWaitDuration( new Mutex(true), waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds, expectedWaitTerminationAfterMilliseconds: 0); VerifyWaitDuration( new Mutex(false), waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds, expectedWaitTerminationAfterMilliseconds: 0); } private static void VerifyWaitDuration( WaitHandle wh, int waitTimeoutMilliseconds, int expectedWaitTerminationAfterMilliseconds) { Assert.True(waitTimeoutMilliseconds > 0); Assert.True(expectedWaitTerminationAfterMilliseconds >= 0); var sw = new Stopwatch(); sw.Restart(); Assert.Equal(expectedWaitTerminationAfterMilliseconds == 0, wh.WaitOne(waitTimeoutMilliseconds)); sw.Stop(); int waitDurationDiffMilliseconds = (int)sw.ElapsedMilliseconds - expectedWaitTerminationAfterMilliseconds; Assert.True(waitDurationDiffMilliseconds >= AcceptableEarlyWaitTerminationDiffMilliseconds); Assert.True(waitDurationDiffMilliseconds <= AcceptableLateWaitTerminationDiffMilliseconds); } //[Fact] // This test takes a long time to run in release and especially in debug builds. Enable for manual testing. public static void MutexMaximumReacquireCountTest() { // Create a mutex with the maximum reacquire count var m = new Mutex(); int tenPercent = int.MaxValue / 10; int progressPercent = 0; Console.Write(" 0%"); for (int i = 0; i >= 0; ++i) { if (i >= (progressPercent + 1) * tenPercent) { ++progressPercent; if (progressPercent < 10) { Console.Write(" {0}%", progressPercent * 10); } } Assert.True(m.WaitOne(0)); } Assert.Throws<OverflowException>( () => { // Windows allows a slightly higher maximum reacquire count than this implementation Assert.True(m.WaitOne(0)); Assert.True(m.WaitOne(0)); }); Console.WriteLine(" 100%"); // Single wait fails Assert.Throws<OverflowException>(() => m.WaitOne(0)); Assert.Throws<OverflowException>(() => m.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.Throws<OverflowException>(() => m.WaitOne()); var e0 = new AutoResetEvent(false); var s0 = new Semaphore(0, 1); var e1 = new AutoResetEvent(false); var s1 = new Semaphore(0, 1); var h = new WaitHandle[] { e0, s0, m, e1, s1 }; Action<bool, bool, bool, bool> init = (signale0, signals0, signale1, signals1) => { if (signale0) e0.Set(); else e0.Reset(); s0.WaitOne(0); if (signals0) s0.Release(); if (signale1) e1.Set(); else e1.Reset(); s1.WaitOne(0); if (signals1) s1.Release(); }; Action<bool, bool, bool, bool> verify = (e0signaled, s0signaled, e1signaled, s1signaled) => { Assert.Equal(e0signaled, e0.WaitOne(0)); Assert.Equal(s0signaled, s0.WaitOne(0)); Assert.Throws<OverflowException>(() => m.WaitOne(0)); Assert.Equal(e1signaled, e1.WaitOne(0)); Assert.Equal(s1signaled, s1.WaitOne(0)); init(e0signaled, s0signaled, e1signaled, s1signaled); }; // WaitAny succeeds when a signaled object is before the mutex init(true, true, true, true); Assert.Equal(0, WaitHandle.WaitAny(h, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); verify(false, true, true, true); Assert.Equal(1, WaitHandle.WaitAny(h, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); verify(false, false, true, true); // WaitAny fails when all objects before the mutex are unsignaled init(false, false, true, true); Assert.Throws<OverflowException>(() => WaitHandle.WaitAny(h, 0)); verify(false, false, true, true); Assert.Throws<OverflowException>(() => WaitHandle.WaitAny(h, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); verify(false, false, true, true); Assert.Throws<OverflowException>(() => WaitHandle.WaitAny(h)); verify(false, false, true, true); // WaitAll fails and does not unsignal any signaled object init(true, true, true, true); Assert.Throws<OverflowException>(() => WaitHandle.WaitAll(h, 0)); verify(true, true, true, true); Assert.Throws<OverflowException>(() => WaitHandle.WaitAll(h, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); verify(true, true, true, true); Assert.Throws<OverflowException>(() => WaitHandle.WaitAll(h)); verify(true, true, true, true); m.Dispose(); } } internal static class TimerTests { [Fact] public static void TimersCreatedConcurrentlyOnDifferentThreadsAllFire() { int processorCount = Environment.ProcessorCount; int timerTickCount = 0; TimerCallback timerCallback = data => Interlocked.Increment(ref timerTickCount); var threadStarted = new AutoResetEvent(false); var createTimers = new ManualResetEvent(false); var timers = new Timer[processorCount]; Action<object> createTimerThreadStart = data => { int i = (int)data; var sw = new Stopwatch(); threadStarted.Set(); createTimers.WaitOne(); // Use the CPU a bit around creating the timer to try to have some of these threads run concurrently sw.Restart(); do { Thread.SpinWait(1000); } while (sw.ElapsedMilliseconds < 10); timers[i] = new Timer(timerCallback, null, 1, Timeout.Infinite); // Use the CPU a bit around creating the timer to try to have some of these threads run concurrently sw.Restart(); do { Thread.SpinWait(1000); } while (sw.ElapsedMilliseconds < 10); }; var waitsForThread = new Action[timers.Length]; for (int i = 0; i < timers.Length; ++i) { var t = ThreadTestHelpers.CreateGuardedThread(out waitsForThread[i], createTimerThreadStart); t.IsBackground = true; t.Start(i); threadStarted.CheckedWait(); } createTimers.Set(); ThreadTestHelpers.WaitForCondition(() => timerTickCount == timers.Length); foreach (var waitForThread in waitsForThread) { waitForThread(); } } } internal static class ThreadPoolTests { [Fact] public static void RunProcessorCountItemsInParallel() { int count = 0; AutoResetEvent e0 = new AutoResetEvent(false); for(int i = 0; i < Environment.ProcessorCount; ++i) { ThreadPool.QueueUserWorkItem( _ => { if(Interlocked.Increment(ref count) == Environment.ProcessorCount) { e0.Set(); } }); } e0.CheckedWait(); // Run the test again to make sure we can reuse the threads. count = 0; for(int i = 0; i < Environment.ProcessorCount; ++i) { ThreadPool.QueueUserWorkItem( _ => { if(Interlocked.Increment(ref count) == Environment.ProcessorCount) { e0.Set(); } }); } e0.CheckedWait(); } [Fact] public static void RunMoreThanMaxJobsMakesOneJobWaitForStarvationDetection() { ManualResetEvent e0 = new ManualResetEvent(false); AutoResetEvent jobsQueued = new AutoResetEvent(false); int count = 0; AutoResetEvent e1 = new AutoResetEvent(false); for(int i = 0; i < Environment.ProcessorCount; ++i) { ThreadPool.QueueUserWorkItem( _ => { if(Interlocked.Increment(ref count) == Environment.ProcessorCount) { jobsQueued.Set(); } e0.CheckedWait(); }); } jobsQueued.CheckedWait(); ThreadPool.QueueUserWorkItem( _ => e1.Set()); Thread.Sleep(500); // Sleep for the gate thread delay to wait for starvation e1.CheckedWait(); e0.Set(); } [Fact] public static void ThreadPoolCanPickUpOneJobWhenThreadIsAvailable() { ManualResetEvent e0 = new ManualResetEvent(false); AutoResetEvent jobsQueued = new AutoResetEvent(false); AutoResetEvent testJobCompleted = new AutoResetEvent(false); int count = 0; for(int i = 0; i < Environment.ProcessorCount - 1; ++i) { ThreadPool.QueueUserWorkItem( _ => { if(Interlocked.Increment(ref count) == Environment.ProcessorCount - 1) { jobsQueued.Set(); } e0.CheckedWait(); }); } jobsQueued.CheckedWait(); ThreadPool.QueueUserWorkItem( _ => testJobCompleted.Set()); testJobCompleted.CheckedWait(); e0.Set(); } [Fact] public static void ThreadPoolCanPickUpMultipleJobsWhenThreadsAreAvailable() { ManualResetEvent e0 = new ManualResetEvent(false); AutoResetEvent jobsQueued = new AutoResetEvent(false); AutoResetEvent testJobCompleted = new AutoResetEvent(false); int count = 0; for(int i = 0; i < Environment.ProcessorCount - 1; ++i) { ThreadPool.QueueUserWorkItem( _ => { if(Interlocked.Increment(ref count) == Environment.ProcessorCount - 1) { jobsQueued.Set(); } e0.CheckedWait(); }); } jobsQueued.CheckedWait(); int testJobsCount = 0; int maxCount = 5; void Job(object _) { if(Interlocked.Increment(ref testJobsCount) != maxCount) { ThreadPool.QueueUserWorkItem(Job); } else { testJobCompleted.Set(); } } ThreadPool.QueueUserWorkItem(Job); testJobCompleted.CheckedWait(); e0.Set(); } // See https://github.com/dotnet/corert/issues/6780 [Fact] public static void ThreadPoolCanProcessManyWorkItemsInParallelWithoutDeadlocking() { int iterationCount = 100_000; var done = new ManualResetEvent(false); WaitCallback wc = null; wc = data => { int n = Interlocked.Decrement(ref iterationCount); if (n == 0) { done.Set(); } else if (n > 0) { ThreadPool.QueueUserWorkItem(wc); } }; for (int i = 0, n = Environment.ProcessorCount; i < n; ++i) { ThreadPool.QueueUserWorkItem(wc); } done.WaitOne(); } private static WaitCallback CreateRecursiveJob(int jobCount, int targetJobCount, AutoResetEvent testJobCompleted) { return _ => { if (jobCount == targetJobCount) { testJobCompleted.Set(); } else { ThreadPool.QueueUserWorkItem(CreateRecursiveJob(jobCount + 1, targetJobCount, testJobCompleted)); } }; } [Fact] [OuterLoop] public static void RunJobsAfterThreadTimeout() { ManualResetEvent e0 = new ManualResetEvent(false); AutoResetEvent jobsQueued = new AutoResetEvent(false); AutoResetEvent testJobCompleted = new AutoResetEvent(false); int count = 0; for(int i = 0; i < Environment.ProcessorCount - 1; ++i) { ThreadPool.QueueUserWorkItem( _ => { if(Interlocked.Increment(ref count) == Environment.ProcessorCount - 1) { jobsQueued.Set(); } e0.CheckedWait(); }); } jobsQueued.CheckedWait(); ThreadPool.QueueUserWorkItem( _ => testJobCompleted.Set()); testJobCompleted.CheckedWait(); Console.Write("Sleeping to time out thread\n"); Thread.Sleep(21000); ThreadPool.QueueUserWorkItem( _ => testJobCompleted.Set()); testJobCompleted.CheckedWait(); e0.Set(); Console.Write("Sleeping to time out all threads\n"); Thread.Sleep(21000); ThreadPool.QueueUserWorkItem( _ => testJobCompleted.Set()); testJobCompleted.CheckedWait(); } [Fact] public static void WorkQueueDepletionTest() { ManualResetEvent e0 = new ManualResetEvent(false); int numLocalScheduled = 1; int numGlobalScheduled = 1; int numToSchedule = Environment.ProcessorCount * 64; int numCompleted = 0; object syncRoot = new object(); void ThreadLocalJob() { if(Interlocked.Increment(ref numLocalScheduled) <= numToSchedule) { Task.Factory.StartNew(ThreadLocalJob); } if(Interlocked.Increment(ref numLocalScheduled) <= numToSchedule) { Task.Factory.StartNew(ThreadLocalJob); } if (Interlocked.Increment(ref numCompleted) == numToSchedule * 2) { e0.Set(); } } void GlobalJob(object _) { if(Interlocked.Increment(ref numGlobalScheduled) <= numToSchedule) { ThreadPool.QueueUserWorkItem(GlobalJob); } if(Interlocked.Increment(ref numGlobalScheduled) <= numToSchedule) { ThreadPool.QueueUserWorkItem(GlobalJob); } if (Interlocked.Increment(ref numCompleted) == numToSchedule * 2) { e0.Set(); } } Task.Factory.StartNew(ThreadLocalJob); ThreadPool.QueueUserWorkItem(GlobalJob); e0.CheckedWait(); } [Fact] public static void WorkerThreadStateReset() { var cultureInfo = new CultureInfo("pt-BR"); var expectedCultureInfo = CultureInfo.CurrentCulture; var expectedUICultureInfo = CultureInfo.CurrentUICulture; int count = 0; AutoResetEvent e0 = new AutoResetEvent(false); for(int i = 0; i < Environment.ProcessorCount; ++i) { ThreadPool.QueueUserWorkItem( _ => { CultureInfo.CurrentCulture = cultureInfo; CultureInfo.CurrentUICulture = cultureInfo; Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; if(Interlocked.Increment(ref count) == Environment.ProcessorCount) { e0.Set(); } }); } e0.CheckedWait(); // Run the test again to make sure we can reuse the threads. count = 0; for(int i = 0; i < Environment.ProcessorCount; ++i) { ThreadPool.QueueUserWorkItem( _ => { Assert.Equal(expectedCultureInfo, CultureInfo.CurrentCulture); Assert.Equal(expectedUICultureInfo, CultureInfo.CurrentUICulture); Assert.Equal(ThreadPriority.Normal, Thread.CurrentThread.Priority); if(Interlocked.Increment(ref count) == Environment.ProcessorCount) { e0.Set(); } }); } e0.CheckedWait(); } [Fact] public static void SettingMinThreadsWillCreateThreadsUpToMinimum() { ThreadPool.GetMinThreads(out int minThreads, out int unusedMin); ThreadPool.GetMaxThreads(out int maxThreads, out int unusedMax); try { ManualResetEvent e0 = new ManualResetEvent(false); AutoResetEvent jobsQueued = new AutoResetEvent(false); int count = 0; ThreadPool.SetMaxThreads(minThreads, unusedMax); for(int i = 0; i < minThreads + 1; ++i) { ThreadPool.QueueUserWorkItem( _ => { if(Interlocked.Increment(ref count) == minThreads + 1) { jobsQueued.Set(); } e0.CheckedWait(); }); } Assert.False(jobsQueued.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds)); Assert.True(ThreadPool.SetMaxThreads(minThreads + 1, unusedMax)); Assert.True(ThreadPool.SetMinThreads(minThreads + 1, unusedMin)); jobsQueued.CheckedWait(); e0.Set(); } finally { ThreadPool.SetMinThreads(minThreads, unusedMin); ThreadPool.SetMaxThreads(maxThreads, unusedMax); } } } internal static class WaitThreadTests { private const int WaitThreadTimeoutTimeMs = 20000; [Fact] public static void SignalingRegisteredHandleCallsCalback() { var e0 = new AutoResetEvent(false); var e1 = new AutoResetEvent(false); ThreadPool.RegisterWaitForSingleObject(e0, (_, timedOut) => { if(!timedOut) { e1.Set(); } }, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true); e0.Set(); e1.CheckedWait(); } [Fact] public static void TimingOutRegisteredHandleCallsCallback() { var e0 = new AutoResetEvent(false); var e1 = new AutoResetEvent(false); ThreadPool.RegisterWaitForSingleObject(e0, (_, timedOut) => { if(timedOut) { e1.Set(); } }, null, ThreadTestHelpers.ExpectedTimeoutMilliseconds, true); e1.CheckedWait(); } [Fact] public static void UnregisteringBeforeSignalingDoesNotCallCallback() { var e0 = new AutoResetEvent(false); var e1 = new AutoResetEvent(false); var registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => { e1.Set(); }, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true); registeredWaitHandle.Unregister(null); Assert.False(e1.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds)); } [Fact] public static void RepeatingWaitFiresUntilUnregistered() { var e0 = new AutoResetEvent(false); var e1 = new AutoResetEvent(false); var registered = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => { e1.Set(); }, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, false); for (int i = 0; i < 4; ++i) { e0.Set(); e1.CheckedWait(); } registered.Unregister(null); e0.Set(); Assert.False(e1.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds)); } [Fact] public static void UnregisterEventSignaledWhenUnregistered() { var e0 = new AutoResetEvent(false); var e1 = new AutoResetEvent(false); var registered = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true); registered.Unregister(e1); e1.CheckedWait(); } [Fact] public static void CanRegisterMoreThan64Waits() { RegisteredWaitHandle[] handles = new RegisteredWaitHandle[65]; for(int i = 0; i < 65; ++i) { handles[i] = ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), (_, __) => {}, null, -1, true); } for(int i = 0; i < 65; ++i) { handles[i].Unregister(null); } } [Fact] public static void StateIsPasssedThroughToCallback() { object state = new object(); AutoResetEvent e0 = new AutoResetEvent(false); ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(true), (callbackState, _) => { if(state == callbackState) { e0.Set(); } }, state, 0, true); e0.CheckedWait(); } [Fact] [OuterLoop] public static void WaitWithLongerTimeoutThanWaitThreadCanStillTimeout() { AutoResetEvent e0 = new AutoResetEvent(false); ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), (_, __) => e0.Set(), null, WaitThreadTimeoutTimeMs + 1000, true); Thread.Sleep(WaitThreadTimeoutTimeMs); e0.CheckedWait(); } [Fact] public static void UnregisterCallbackIsNotCalledAfterCallbackFinishesIfAnotherCallbackOnSameWaitRunning() { AutoResetEvent e0 = new AutoResetEvent(false); AutoResetEvent e1 = new AutoResetEvent(false); AutoResetEvent e2 = new AutoResetEvent(false); RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => { e2.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds); }, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, false); e0.Set(); Thread.Sleep(50); e0.Set(); Thread.Sleep(50); handle.Unregister(e1); Assert.False(e1.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds)); e2.Set(); } [Fact] public static void CallingUnregisterOnAutomaticallyUnregisteredHandleReturnsTrue() { AutoResetEvent e0 = new AutoResetEvent(false); RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true); e0.Set(); Thread.Sleep(ThreadTestHelpers.ExpectedTimeoutMilliseconds); Assert.True(handle.Unregister(null)); } [Fact] public static void EventSetAfterUnregisterNotObservedOnWaitThread() { AutoResetEvent e0 = new AutoResetEvent(false); RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true); handle.Unregister(null); e0.Set(); e0.CheckedWait(); } [Fact] public static void BlockingUnregister() { RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true); handle.Unregister(new InvalidWaitHandle()); } [Fact] public static void CanDisposeEventAfterUnblockingUnregister() { using(var e0 = new AutoResetEvent(false)) { RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true); handle.Unregister(null); } } [Fact] public static void UnregisterEventSignaledWhenUnregisteredEvenIfAutoUnregistered() { var e0 = new AutoResetEvent(false); RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true); e0.Set(); Thread.Sleep(50); // Ensure the callback has happened var e1 = new AutoResetEvent(false); handle.Unregister(e1); e1.CheckedWait(); } [Fact] public static void BlockingUnregisterBlocksEvenIfCallbackExecuting() { bool callbackComplete = false; var e0 = new AutoResetEvent(false); RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => { Thread.Sleep(300); callbackComplete = true; }, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true); e0.Set(); Thread.Sleep(100); // Give the wait thread time to process removals. handle.Unregister(new InvalidWaitHandle()); Assert.True(callbackComplete); } } internal static class ThreadTestHelpers { public const int ExpectedTimeoutMilliseconds = 50; public const int ExpectedMeasurableTimeoutMilliseconds = 500; public const int UnexpectedTimeoutMilliseconds = 1000 * 30; // Wait longer for a thread to time out, so that an unexpected timeout in the thread is more likely to expire first and // provide a better stack trace for the failure public const int UnexpectedThreadTimeoutMilliseconds = UnexpectedTimeoutMilliseconds * 2; public static Thread CreateGuardedThread(out Action waitForThread, Action<object> start) { Action checkForThreadErrors; return CreateGuardedThread(out checkForThreadErrors, out waitForThread, start); } public static Thread CreateGuardedThread(out Action checkForThreadErrors, out Action waitForThread, Action<object> start) { Exception backgroundEx = null; var t = new Thread(parameter => { try { start(parameter); } catch (Exception ex) { backgroundEx = ex; Interlocked.MemoryBarrier(); } }); Action localCheckForThreadErrors = checkForThreadErrors = // cannot use ref or out parameters in lambda () => { Interlocked.MemoryBarrier(); if (backgroundEx != null) { throw new AggregateException(backgroundEx); } }; waitForThread = () => { Assert.True(t.Join(UnexpectedThreadTimeoutMilliseconds)); localCheckForThreadErrors(); }; return t; } public static void WaitForCondition(Func<bool> condition) { WaitForConditionWithCustomDelay(condition, () => Thread.Sleep(1)); } public static void WaitForConditionWithCustomDelay(Func<bool> condition, Action delay) { if (condition()) { return; } var startTime = Environment.TickCount; do { delay(); Assert.True(Environment.TickCount - startTime < UnexpectedTimeoutMilliseconds); } while (!condition()); } public static void CheckedWait(this WaitHandle wh) { Assert.True(wh.WaitOne(UnexpectedTimeoutMilliseconds)); } } internal sealed class InvalidWaitHandle : WaitHandle { } internal sealed class Stopwatch { private int _startTimeMs; private int _endTimeMs; private bool _isStopped; public void Restart() { _isStopped = false; _startTimeMs = Environment.TickCount; } public void Stop() { _endTimeMs = Environment.TickCount; _isStopped = true; } public long ElapsedMilliseconds => (_isStopped ? _endTimeMs : Environment.TickCount) - _startTimeMs; } internal static class Assert { public static void False(bool condition) { if (!condition) return; Console.WriteLine("Assertion failure - Assert.False"); throw new AssertionFailureException(); } public static void True(bool condition) { if (condition) return; Console.WriteLine("Assertion failure - Assert.True"); throw new AssertionFailureException(); } public static void Same<T>(T expected, T actual) where T : class { if (expected == actual) return; Console.WriteLine("Assertion failure - Assert.Same({0}, {1})", expected, actual); throw new AssertionFailureException(); } public static void Equal<T>(T expected, T actual) { if (EqualityComparer<T>.Default.Equals(expected, actual)) return; Console.WriteLine("Assertion failure - Assert.Equal({0}, {1})", expected, actual); throw new AssertionFailureException(); } public static void NotEqual<T>(T notExpected, T actual) { if (!EqualityComparer<T>.Default.Equals(notExpected, actual)) return; Console.WriteLine("Assertion failure - Assert.NotEqual({0}, {1})", notExpected, actual); throw new AssertionFailureException(); } public static void Throws<T>(Action action) where T : Exception { // TODO: Enable Assert.Throws<T> tests. There currently seem to be some reliability issues surrounding exceptions on Unix. //try //{ // action(); //} //catch (T ex) //{ // if (ex.GetType() == typeof(T)) // return; // Console.WriteLine("Assertion failure - Assert.Throws<{0}>: got {1}", typeof(T), ex.GetType()); // throw new AssertionFailureException(ex); //} //catch (Exception ex) //{ // Console.WriteLine("Assertion failure - Assert.Throws<{0}>: got {1}", typeof(T), ex.GetType()); // throw new AssertionFailureException(ex); //} //Console.WriteLine("Assertion failure - Assert.Throws<{0}>: got no exception", typeof(T)); //throw new AssertionFailureException(); } public static void Null(object value) { if (value == null) return; Console.WriteLine("Assertion failure - Assert.Null"); throw new AssertionFailureException(); } public static void NotNull(object value) { if (value != null) return; Console.WriteLine("Assertion failure - Assert.NotNull"); throw new AssertionFailureException(); } } internal class AssertionFailureException : Exception { public AssertionFailureException() { } public AssertionFailureException(string message) : base(message) { } public AssertionFailureException(Exception innerException) : base(null, innerException) { } } internal class FactAttribute : Attribute { } internal class OuterLoopAttribute : Attribute { }
using System; using System.Linq; using JetBrains.Application.changes; using JetBrains.Lifetimes; using JetBrains.ProjectModel; using JetBrains.ProjectModel.Tasks; using JetBrains.ReSharper.Plugins.Json.Psi; using JetBrains.ReSharper.Plugins.Json.Psi.Tree; using JetBrains.ReSharper.Plugins.Unity.AsmDef.Psi.Caches; using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Files; using JetBrains.ReSharper.Psi.Paths; using JetBrains.ReSharper.Psi.Transactions; using JetBrains.ReSharper.Psi.Util; using JetBrains.Util; using JetBrains.Util.dataStructures; using ProjectExtensions = JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel.ProjectExtensions; #nullable enable namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Psi.Modules { // Listen for a module reference being added or removed, and update the source module's .asmdef file, if possible. // * The source module is the module that is being added to or removed from. It will always be a project, and it // should have an asmdef file. All generated projects will have an asmdef file apart from the predefined // Assembly-CSharp* projects, which are at the root of the dependency tree. These predefined projects // automatically reference any asmdef project that has "autoReferenced" set to true. // * The target module is the module being added or removed. It will most likely/hopefully be an asmdef project, but // could also be a predefined project (which will be an incorrect add/remove) or a plain DLL, split into external, // plugin, system or engine DLLs. // * If we're adding/removing an asmdef project, update the "references" node in the source asmdef, or set // "autoReferenced" true if source is a predefined project (notification?) // * Adding/removing a predefined project is not supported // * If we're adding/removing an engine DLL (UnityEngine* or UnityEditor*), set "noEngineReferences" to true/false // * A plugin DLL is a DLL that lives inside Assets or a package. By default, they're automatically referenced. If // "overrideReferences" is true, the plugins need to be listed manually // * Adding/removing a system DLL (System* or Microsoft*) is not supported // * Any other DLL is external and is not supported // // * ReSharper will only add a valid module, so we won't get circular references // * If we have Player projects and use Alt+Enter to add a reference from a QF, the reference is only added to the // current project context. We could update the other context's project? [SolutionComponent] public class AsmDefModuleReferenceChangeListener : IChangeProvider { private readonly UnitySolutionTracker myUnitySolutionTracker; private readonly ChangeManager myChangeManager; private readonly AsmDefCache myAsmDefCache; private readonly MetaFileGuidCache myMetaFileGuidCache; private readonly IPsiServices myPsiServices; private readonly ILogger myLogger; public AsmDefModuleReferenceChangeListener(Lifetime lifetime, ISolution solution, UnitySolutionTracker unitySolutionTracker, ChangeManager changeManager, AsmDefCache asmDefCache, MetaFileGuidCache metaFileGuidCache, ISolutionLoadTasksScheduler solutionLoadTasksScheduler, IPsiServices psiServices, ILogger logger) { myUnitySolutionTracker = unitySolutionTracker; myChangeManager = changeManager; myAsmDefCache = asmDefCache; myMetaFileGuidCache = metaFileGuidCache; myPsiServices = psiServices; myLogger = logger; solutionLoadTasksScheduler.EnqueueTask(new SolutionLoadTask("RegisterAsmDefReferenceChangeListener", SolutionLoadTaskKinds.Done, () => { changeManager.RegisterChangeProvider(lifetime, this); changeManager.AddDependency(lifetime, this, solution); })); } public object? Execute(IChangeMap changeMap) { if (!myUnitySolutionTracker.IsUnityProject.Value) return null; var changes = changeMap.GetChanges<SolutionChange>().ToList(); if (changes.IsEmpty()) return null; var collector = new ReferenceChangeCollector(); foreach (var solutionChange in changes) solutionChange.Accept(collector); collector.RemoveProblematicChangeEvents(); // We can't make changes to the PSI while we're in a change notification if (!collector.AddedReferences.IsEmpty || !collector.RemovedReferences.IsEmpty) myChangeManager.ExecuteAfterChange(() => HandleReferenceChanges(collector)); return null; } private void HandleReferenceChanges(ReferenceChangeCollector collector) { // TODO: Handle multiple add/removes foreach (var addedReference in collector.AddedReferences) { // Note that an asmdef name will usually match the name of the project being added. The only exception // is for player projects. The returned addedAsmDefName here is the asmdef name/non-player project name var ownerProject = addedReference.OwnerModule; var addedReferenceName = addedReference.Name; var (_, ownerAsmDefLocation) = GetAsmDefLocationForProject(ownerProject.Name); var (addedAsmDefName, addedAsmDefLocation) = GetAsmDefLocationForProject(addedReferenceName); switch (addedReference) { case IProjectToProjectReference: OnAddedProjectReference(ownerProject, addedReferenceName, addedAsmDefName, ownerAsmDefLocation, addedAsmDefLocation); break; case IProjectToAssemblyReference: OnAddedAssemblyReference(ownerProject, addedReferenceName, ownerAsmDefLocation); break; default: var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); if (ownerProjectKind != ProjectKind.Custom) { // This is an unexpected reference modification (COM? SDK? Unresolved assembly?) to either // a predefined or asmdef project. This change will be lost when Unity next regenerates myLogger.Warn("Unsupported reference modification: {0}", addedReference); // TODO: Notify the user that a weird/unsupported reference modification has happened } break; } } foreach (var removedReference in collector.RemovedReferences) { var ownerProject = removedReference.OwnerModule; var removedReferenceName = removedReference.Name; var (_, ownerAsmDefLocation) = GetAsmDefLocationForProject(ownerProject.Name); var (removedAsmDefName, removedAsmDefLocation) = GetAsmDefLocationForProject(removedReferenceName); switch (removedReference) { case IProjectToProjectReference: OnRemovedProjectReference(ownerProject, removedReferenceName, removedAsmDefName, ownerAsmDefLocation, removedAsmDefLocation); break; case IProjectToAssemblyReference: OnRemovedAssemblyReference(ownerProject, removedReferenceName, ownerAsmDefLocation); break; default: var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); if (ownerProjectKind != ProjectKind.Custom) { // This is an unexpected reference modification (COM? SDK? Unresolved assembly?) to either // a predefined or asmdef project. This change will be lost when Unity next regenerates myLogger.Warn("Unsupported reference modification: {0}", removedReference); // TODO: Notify the user that a weird/unsupported reference modification has happened } break; } } } private void OnAddedProjectReference(IProject ownerProject, string addedProjectName, string addedAsmDefName, VirtualFileSystemPath ownerAsmDefLocation, VirtualFileSystemPath addedAsmDefLocation) { var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); var addedProjectKind = GetProjectKind(addedProjectName, addedAsmDefLocation); if (ownerProjectKind == ProjectKind.Custom) { // Unsupported scenario. The user is modifying a custom project. Do nothing - Unity won't regenerate the // project that's being modified, so there will be no data loss, so there's no need to notify the user. // Unity will regenerate teh solution, which will remove the custom project. If we want to notify the // user, it would be better to notify them when initially adding the custom project. myLogger.Info("{0} project {1} added as a reference to {2} project {3}. Ignoring change", addedProjectKind, addedProjectName, ownerProjectKind, ownerProject.Name); return; } if (addedProjectKind == ProjectKind.Custom) { // Unsupported scenario. The user is trying to modify a generated project by adding a reference to a // custom project. Changes will be lost the next time Unity regenerates the projects myLogger.Warn( "Unsupported reference modification. Added reference to unknown project will be lost when Unity regenerates projects"); // TODO: Notify user that modifying a generated project will lose changes return; } if (addedProjectKind == ProjectKind.Predefined) { // Weird scenario, shouldn't happen myLogger.Warn("Adding {0} project {1} as a reference to {2} project {3}?! Weird!", addedProjectKind, addedProjectName, ownerProjectKind, ownerProject.Name); return; } switch (ownerProjectKind, addedProjectKind) { case (ProjectKind.AsmDef, ProjectKind.AsmDef): AddAsmDefReference(ownerProject, ownerAsmDefLocation, addedAsmDefName, addedAsmDefLocation); break; case (ProjectKind.Predefined, ProjectKind.AsmDef): // Predefined projects reference all asmdef projects by default. An asmdef can opt out by setting // "autoReferenced" to false. myLogger.Info( "Adding asmdef reference to predefined project. Should already be referenced. Check 'autoReferenced' value in asmdef"); // TODO: Set "autoReferenced" to true break; } } private void AddAsmDefReference(IProject ownerProject, VirtualFileSystemPath ownerAsmDefLocation, string addedAsmDefName, VirtualFileSystemPath addedAsmDefLocation) { var sourceFile = ownerProject.GetPsiSourceFileInProject(ownerAsmDefLocation); if (sourceFile?.GetDominantPsiFile<JsonNewLanguage>() is not IJsonNewFile psiFile) return; var rootObject = psiFile.GetRootObject(); if (rootObject == null) return; var guid = myMetaFileGuidCache.GetAssetGuid(addedAsmDefLocation); if (guid == null) myLogger.Warn("Cannot find asset GUID for added asmdef {0}! Can only add as name", addedAsmDefLocation); var addedAsmDefGuid = guid == null ? null : AsmDefUtils.FormatGuidReference(guid.Value); var referencesProperty = rootObject.GetFirstPropertyValue<IJsonNewArray>("references"); var existingArrayElement = FindReferenceElement(referencesProperty, addedAsmDefName, addedAsmDefGuid, out var useGuids); if (existingArrayElement.Count != 0) { myLogger.Verbose("Reference {0} already exists in asmdef {1}", addedAsmDefName, ownerAsmDefLocation); return; } using (new PsiTransactionCookie(myPsiServices, DefaultAction.Commit, "AddAsmDefReference")) { var referenceText = useGuids && addedAsmDefGuid != null ? addedAsmDefGuid : addedAsmDefName; var elementFactory = JsonNewElementFactory.GetInstance(psiFile.GetPsiModule()); if (referencesProperty == null) { referencesProperty = (IJsonNewArray)elementFactory.CreateValue($"[ \"{referenceText}\" ]"); rootObject.AddMemberBefore("references", referencesProperty, null); } else { var reference = elementFactory.CreateStringLiteral(referenceText); referencesProperty.AddArrayElementBefore(reference, null); } } } private void OnAddedAssemblyReference(IProject ownerProject, string addedAssemblyName, VirtualFileSystemPath ownerAsmDefLocation) { var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); switch (ownerProjectKind) { case ProjectKind.Custom: // Don't care. The user has added a custom project, and has added a reference to it. The project // will be removed the next time Unity regenerates the solution, but they won't lose the changes to // the project. We don't notify about this action - it would be better to notify when the project is // initially added myLogger.Info("Adding assembly {0} to custom project {1}. Ignoring change", addedAssemblyName, ownerProject.Name); return; case ProjectKind.Predefined: // Unsupported scenario. Custom assemblies should live in Assets and requires regenerating the // project file myLogger.Warn( "Unsupported reference modification. Added assembly reference will be lost when Unity regenerates project files"); // TODO: Notify the user return; case ProjectKind.AsmDef: // AsmDef can only reference custom assemblies if that assembly is a plugin (i.e. it's an asset, // either in Assets or a package). By default, all asmdef projects will reference all plugin // assemblies. An asmdef can opt out by setting "overrideReferences" to true and listing each // plugin individually. // This is a complex scenario: // 1. Check addedAssembly is a plugin // 2. If not, notify user that this is not supported // 3. If true, check "overrideReferences" (if false, this is a weird scenario) // 4. If true, add assembly name to "precompiledReferences" // It might be easier to notify the user to edit assembly references using Unity // TODO: All of the above ^^ myLogger.Warn( "Unsupported reference modification. Added assembly reference will be lost when Unity regenerates project files"); break; } } private void OnRemovedProjectReference(IProject ownerProject, string removedProjectName, string removedAsmDefName, VirtualFileSystemPath ownerAsmDefLocation, VirtualFileSystemPath removedAsmDefLocation) { var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); var removedProjectKind = GetProjectKind(removedProjectName, removedAsmDefLocation); if (ownerProjectKind == ProjectKind.Custom) { // Unsupported scenario. The user is modifying a custom project. Do nothing - Unity won't regenerate the // project that's being modified, so there will be no data loss, so there's no need to notify the user. // Unity will regenerate teh solution, which will remove the custom project. If we want to notify the // user, it's best to notify them when initially adding the custom project. myLogger.Info("{0} project {1} removed as a reference from {2} project {3}. Ignoring change", removedProjectKind, removedProjectName, ownerProjectKind, ownerProject.Name); return; } if (removedProjectKind == ProjectKind.Custom) { // Unsupported scenario. The user is trying to modify a generated project by adding a reference to a // custom project. myLogger.Warn( "Unsupported reference modification. Added assembly reference will be lost when Unity regenerates project files"); // TODO: Notify user that modifying a generated project will lose changes return; } if (removedProjectKind == ProjectKind.Predefined) { // Weird scenario, shouldn't happen myLogger.Warn("Removing {0} project {1} reference from {2} project {3}?! Weird!", removedProjectKind, removedProjectName, ownerProjectKind, ownerProject.Name); return; } switch (ownerProjectKind, removedProjectKind) { case (ProjectKind.AsmDef, ProjectKind.AsmDef): RemoveAsmDefReference(ownerProject, ownerAsmDefLocation, removedAsmDefName, removedAsmDefLocation); break; case (ProjectKind.Predefined, ProjectKind.AsmDef): myLogger.Info( "Removing asmdef reference from predefined project. Check 'autoReferenced' value in asmdef"); // TODO: Should set "autoReferenced" to false in the removed asmdef project. Should this prompt? break; } } private void RemoveAsmDefReference(IProject ownerProject, VirtualFileSystemPath ownerAsmDefLocation, string removedAsmDefName, VirtualFileSystemPath removedAsmDefLocation) { var sourceFile = ownerProject.GetPsiSourceFileInProject(ownerAsmDefLocation); var psiFile = sourceFile?.GetDominantPsiFile<JsonNewLanguage>() as IJsonNewFile; var rootObject = psiFile?.GetRootObject(); if (rootObject == null) return; var guid = myMetaFileGuidCache.GetAssetGuid(removedAsmDefLocation); if (guid == null) myLogger.Warn("Cannot find asset for added asmdef {0}! Can only add as name", removedAsmDefLocation); var removedAsmDefGuid = guid == null ? null : AsmDefUtils.FormatGuidReference(guid.Value); // "references" might be missing if we've already removed all references and Unity isn't running to refresh // the project files var referencesProperty = rootObject.GetFirstPropertyValue<IJsonNewArray>("references"); if (referencesProperty == null) { myLogger.Verbose("Cannot find 'references' property. Nothing to remove"); return; } var existingArrayElement = FindReferenceElement(referencesProperty, removedAsmDefName, removedAsmDefGuid, out _); if (existingArrayElement.Count == 0) { myLogger.Verbose("Reference {0} already removed from asmdef {1}", removedAsmDefName, ownerAsmDefLocation); return; } using (new PsiTransactionCookie(myPsiServices, DefaultAction.Commit, "AddAsmDefReference")) { foreach (var existingLiteral in existingArrayElement) referencesProperty.RemoveArrayElement(existingLiteral); } } private void OnRemovedAssemblyReference(IProject ownerProject, string removedAssemblyName, VirtualFileSystemPath ownerAsmDefLocation) { var ownerProjectKind = GetProjectKind(ownerProject.Name, ownerAsmDefLocation); switch (ownerProjectKind) { case ProjectKind.Custom: // Don't care. The user has added a custom project, and has removed a reference from it. The project // will be removed the next time Unity regenerates the solution, but they won't lose the changes to // the project. We don't notify about this action - it would be better to notify when the project is // initially added myLogger.Info("Removing assembly {0} to custom project {1}. Ignoring change", removedAssemblyName, ownerProject.Name); return; case ProjectKind.Predefined: // Unsupported scenario. Custom assemblies should live in Assets and requires regenerating the // project file myLogger.Warn("Unsupported reference modification. Change will be lost when Unity regenerates project files"); // TODO: Notify the user return; case ProjectKind.AsmDef: // Like adding an assembly reference to an asmdef project, removing one is only supported if we're // removing an explicit plugin reference. // 1. Check removedAssembly is a plugin // 2. If not, notify user that this is not supported // 3. If true, check "overrideReferences" (if false, this is a weird scenario) // 4. If true, remove assembly name from "precompiledReferences" // It might be easier to notify the user to edit assembly references using Unity // TODO: All of the above ^^ myLogger.Warn( "Unsupported reference modification. Changes will be lost when Unity regenerates project files"); break; } } private static ProjectKind GetProjectKind(string projectName, VirtualFileSystemPath asmDefLocation) { if (asmDefLocation.IsNotEmpty) return ProjectKind.AsmDef; if (ProjectExtensions.IsOneOfPredefinedUnityProjects(projectName, true)) return ProjectKind.Predefined; return ProjectKind.Custom; } private static FrugalLocalList<IJsonNewValue> FindReferenceElement(IJsonNewArray? array, string asmDefName, string? asmDefGuid, out bool useGuids) { useGuids = false; var count = 0; var guidCount = 0; // The user might have added more than one, even though that's an error var results = new FrugalLocalList<IJsonNewValue>(); foreach (var literal in array.ValuesAsLiteral()) { // TODO: Helper function in JsonNewUtil that doesn't allocate? var text = literal.GetUnquotedText(); if (text.Equals(asmDefName, StringComparison.OrdinalIgnoreCase)) results.Add(literal); else if (asmDefGuid != null && text.Equals(asmDefGuid, StringComparison.OrdinalIgnoreCase)) results.Add(literal); count++; if (AsmDefUtils.IsGuidReference(text)) guidCount++; } // Prefer GUIDs, unless everything else is non-guid if (count == 0 || guidCount > 0) useGuids = true; return results; } private (string, VirtualFileSystemPath) GetAsmDefLocationForProject(string projectName) { // Assembly name and project name are the same for asmdef projects, unless it's a .Player project. We want // to return the actual name of the asmdef reference we'll be adding var location = myAsmDefCache.GetAsmDefLocationByAssemblyName(projectName); if (location.IsNotEmpty) return (projectName, location); projectName = ProjectExtensions.StripPlayerSuffix(projectName); return (projectName, myAsmDefCache.GetAsmDefLocationByAssemblyName(projectName)); } private class ReferenceChangeCollector : RecursiveProjectModelChangeDeltaVisitor { public FrugalLocalList<IProjectToModuleReference> AddedReferences; public FrugalLocalList<IProjectToModuleReference> RemovedReferences; public override void VisitProjectReferenceDelta(ProjectReferenceChange change) { if (change.IsClosingSolution || change.IsOpeningSolution) return; if (change.IsAdded) AddedReferences.Add(change.ProjectToModuleReference); else if (change.IsRemoved) RemovedReferences.Add(change.ProjectToModuleReference); } public void RemoveProblematicChangeEvents() { // We will be notified of reference changes when projects are reloaded after Unity regenerates the // project files. If we added a reference to a .Player project (the "Add reference" QF might arbitrarily // pick this) then Unity will regenerate the project files with the correct reference, and we'll see // both a removal of the .Player and an addition of the proper project. Since we always add the correct // asmdef reference even for .Player references, make sure we don't process this removal! // We could also post process this list to remove any notifications for .Player projects if there are // also notifications for non-player projects. var toRemove = new FrugalLocalList<IProjectToModuleReference>(); foreach (var removedReference in RemovedReferences) { if (ProjectExtensions.IsPlayerProjectName(removedReference.Name)) { var nonPlayerProjectName = ProjectExtensions.StripPlayerSuffix(removedReference.Name); foreach (var addedReference in AddedReferences) { if (addedReference.Name.Equals(nonPlayerProjectName, StringComparison.OrdinalIgnoreCase)) toRemove.Add(removedReference); } } } foreach (var reference in toRemove) RemovedReferences.Remove(reference); } } private enum ProjectKind { Predefined, AsmDef, Custom } } }
// 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.Immutable; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Reflection.Metadata.Ecma335 { internal class NamespaceCache { private readonly MetadataReader _metadataReader; private readonly object _namespaceTableAndListLock = new object(); private Dictionary<NamespaceDefinitionHandle, NamespaceData> _namespaceTable; private NamespaceData _rootNamespace; private ImmutableArray<NamespaceDefinitionHandle> _namespaceList; private uint _virtualNamespaceCounter; internal NamespaceCache(MetadataReader reader) { Debug.Assert(reader != null); _metadataReader = reader; } /// <summary> /// Returns whether the namespaceTable has been created. If it hasn't, calling a GetXXX method /// on this will probably have a very high amount of overhead. /// </summary> internal bool CacheIsRealized { get { return _namespaceTable != null; } } internal string GetFullName(NamespaceDefinitionHandle handle) { Debug.Assert(!handle.HasFullName); // we should not hit the cache in this case. NamespaceData data = GetNamespaceData(handle); return data.FullName; } internal NamespaceData GetRootNamespace() { EnsureNamespaceTableIsPopulated(); Debug.Assert(_rootNamespace != null); return _rootNamespace; } internal NamespaceData GetNamespaceData(NamespaceDefinitionHandle handle) { EnsureNamespaceTableIsPopulated(); NamespaceData result; if (!_namespaceTable.TryGetValue(handle, out result)) { Throw.InvalidHandle(); } return result; } /// <summary> /// This will return a StringHandle for the simple name of a namespace name at the given segment index. /// If no segment index is passed explicitly or the "segment" index is greater than or equal to the number /// of segments, then the last segment is used. "Segment" in this context refers to part of a namespace /// name between dots. /// /// Example: Given a NamespaceDefinitionHandle to "System.Collections.Generic.Test" called 'handle': /// /// reader.GetString(GetSimpleName(handle)) == "Test" /// reader.GetString(GetSimpleName(handle, 0)) == "System" /// reader.GetString(GetSimpleName(handle, 1)) == "Collections" /// reader.GetString(GetSimpleName(handle, 2)) == "Generic" /// reader.GetString(GetSimpleName(handle, 3)) == "Test" /// reader.GetString(GetSimpleName(handle, 1000)) == "Test" /// </summary> private StringHandle GetSimpleName(NamespaceDefinitionHandle fullNamespaceHandle, int segmentIndex = Int32.MaxValue) { StringHandle handleContainingSegment = fullNamespaceHandle.GetFullName(); Debug.Assert(!handleContainingSegment.IsVirtual); int lastFoundIndex = fullNamespaceHandle.GetHeapOffset() - 1; int currentSegment = 0; while (currentSegment < segmentIndex) { int currentIndex = _metadataReader.StringHeap.IndexOfRaw(lastFoundIndex + 1, '.'); if (currentIndex == -1) { break; } lastFoundIndex = currentIndex; ++currentSegment; } Debug.Assert(lastFoundIndex >= 0 || currentSegment == 0); // + 1 because lastFoundIndex will either "point" to a '.', or will be -1. Either way, // we want the next char. int resultIndex = lastFoundIndex + 1; return StringHandle.FromOffset(resultIndex).WithDotTermination(); } /// <summary> /// Two distinct namespace handles represent the same namespace if their full names are the same. This /// method merges builders corresponding to such namespace handles. /// </summary> private void PopulateNamespaceTable() { lock (_namespaceTableAndListLock) { if (_namespaceTable != null) { return; } var namespaceBuilderTable = new Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder>(); // Make sure to add entry for root namespace. The root namespace is special in that even // though it might not have types of its own it always has an equivalent representation // as a nil handle and we don't want to handle it below as dot-terminated virtual namespace. // We use NamespaceDefinitionHandle.FromIndexOfFullName(0) instead of default(NamespaceDefinitionHandle) so // that we never hand back a handle to the user that doesn't have a typeid as that prevents // round-trip conversion to Handle and back. (We may discover other handle aliases for the // root namespace (any nil/empty string will do), but we need this one to always be there. NamespaceDefinitionHandle rootNamespace = NamespaceDefinitionHandle.FromFullNameOffset(0); namespaceBuilderTable.Add( rootNamespace, new NamespaceDataBuilder( rootNamespace, rootNamespace.GetFullName(), String.Empty)); PopulateTableWithTypeDefinitions(namespaceBuilderTable); PopulateTableWithExportedTypes(namespaceBuilderTable); Dictionary<string, NamespaceDataBuilder> stringTable; MergeDuplicateNamespaces(namespaceBuilderTable, out stringTable); List<NamespaceDataBuilder> virtualNamespaces; ResolveParentChildRelationships(stringTable, out virtualNamespaces); var namespaceTable = new Dictionary<NamespaceDefinitionHandle, NamespaceData>(); foreach (var group in namespaceBuilderTable) { // Freeze() caches the result, so any many-to-one relationships // between keys and values will be preserved and efficiently handled. namespaceTable.Add(group.Key, group.Value.Freeze()); } if (virtualNamespaces != null) { foreach (var virtualNamespace in virtualNamespaces) { namespaceTable.Add(virtualNamespace.Handle, virtualNamespace.Freeze()); } } _namespaceTable = namespaceTable; _rootNamespace = namespaceTable[rootNamespace]; } } /// <summary> /// This will take 'table' and merge all of the NamespaceData instances that point to the same /// namespace. It has to create 'stringTable' as an intermediate dictionary, so it will hand it /// back to the caller should the caller want to use it. /// </summary> private void MergeDuplicateNamespaces(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table, out Dictionary<string, NamespaceDataBuilder> stringTable) { var namespaces = new Dictionary<string, NamespaceDataBuilder>(); List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>> remaps = null; foreach (var group in table) { NamespaceDataBuilder data = group.Value; NamespaceDataBuilder existingRecord; if (namespaces.TryGetValue(data.FullName, out existingRecord)) { // Children should not exist until the next step. Debug.Assert(data.Namespaces.Count == 0); data.MergeInto(existingRecord); if (remaps == null) { remaps = new List<KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>>(); } remaps.Add(new KeyValuePair<NamespaceDefinitionHandle, NamespaceDataBuilder>(group.Key, existingRecord)); } else { namespaces.Add(data.FullName, data); } } // Needs to be done outside of foreach (var group in table) to avoid modifying the dictionary while foreach'ing over it. if (remaps != null) { foreach (var tuple in remaps) { table[tuple.Key] = tuple.Value; } } stringTable = namespaces; } /// <summary> /// Creates a NamespaceDataBuilder instance that contains a synthesized NamespaceDefinitionHandle, /// as well as the name provided. /// </summary> private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceDefinitionHandle realChild) { Debug.Assert(realChild.HasFullName); int numberOfSegments = 0; foreach (char c in fullName) { if (c == '.') { numberOfSegments++; } } StringHandle simpleName = GetSimpleName(realChild, numberOfSegments); var namespaceHandle = NamespaceDefinitionHandle.FromVirtualIndex(++_virtualNamespaceCounter); return new NamespaceDataBuilder(namespaceHandle, simpleName, fullName); } /// <summary> /// Quick convenience method that handles linking together child + parent /// </summary> private void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent) { Debug.Assert(child != null && parent != null); Debug.Assert(!child.Handle.IsNil); child.Parent = parent.Handle; parent.Namespaces.Add(child.Handle); } /// <summary> /// Links a child to its parent namespace. If the parent namespace doesn't exist, this will create a /// virtual one. This will automatically link any virtual namespaces it creates up to its parents. /// </summary> private void LinkChildToParentNamespace(Dictionary<string, NamespaceDataBuilder> existingNamespaces, NamespaceDataBuilder realChild, ref List<NamespaceDataBuilder> virtualNamespaces) { Debug.Assert(realChild.Handle.HasFullName); string childName = realChild.FullName; var child = realChild; // The condition for this loop is very complex -- essentially, we keep going // until we: // A. Encounter the root namespace as 'child' // B. Find a preexisting namespace as 'parent' while (true) { int lastIndex = childName.LastIndexOf('.'); string parentName; if (lastIndex == -1) { if (childName.Length == 0) { return; } else { parentName = String.Empty; } } else { parentName = childName.Substring(0, lastIndex); } NamespaceDataBuilder parentData; if (existingNamespaces.TryGetValue(parentName, out parentData)) { LinkChildDataToParentData(child, parentData); return; } if (virtualNamespaces != null) { foreach (var data in virtualNamespaces) { if (data.FullName == parentName) { LinkChildDataToParentData(child, data); return; } } } else { virtualNamespaces = new List<NamespaceDataBuilder>(); } var virtualParent = SynthesizeNamespaceData(parentName, realChild.Handle); LinkChildDataToParentData(child, virtualParent); virtualNamespaces.Add(virtualParent); childName = virtualParent.FullName; child = virtualParent; } } /// <summary> /// This will link all parents/children in the given namespaces dictionary up to each other. /// /// In some cases, we need to synthesize namespaces that do not have any type definitions or forwarders /// of their own, but do have child namespaces. These are returned via the virtualNamespaces out /// parameter. /// </summary> private void ResolveParentChildRelationships(Dictionary<string, NamespaceDataBuilder> namespaces, out List<NamespaceDataBuilder> virtualNamespaces) { virtualNamespaces = null; foreach (var namespaceData in namespaces) { LinkChildToParentNamespace(namespaces, namespaceData.Value, ref virtualNamespaces); } } /// <summary> /// Loops through all type definitions in metadata, adding them to the given table /// </summary> private void PopulateTableWithTypeDefinitions(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table) { Debug.Assert(table != null); foreach (var typeHandle in _metadataReader.TypeDefinitions) { TypeDefinition type = _metadataReader.GetTypeDefinition(typeHandle); if (type.Attributes.IsNested()) { continue; } NamespaceDefinitionHandle namespaceHandle = _metadataReader.TypeDefTable.GetNamespaceDefinition(typeHandle); NamespaceDataBuilder builder; if (table.TryGetValue(namespaceHandle, out builder)) { builder.TypeDefinitions.Add(typeHandle); } else { StringHandle name = GetSimpleName(namespaceHandle); string fullName = _metadataReader.GetString(namespaceHandle); var newData = new NamespaceDataBuilder(namespaceHandle, name, fullName); newData.TypeDefinitions.Add(typeHandle); table.Add(namespaceHandle, newData); } } } /// <summary> /// Loops through all type forwarders in metadata, adding them to the given table /// </summary> private void PopulateTableWithExportedTypes(Dictionary<NamespaceDefinitionHandle, NamespaceDataBuilder> table) { Debug.Assert(table != null); foreach (var exportedTypeHandle in _metadataReader.ExportedTypes) { ExportedType exportedType = _metadataReader.GetExportedType(exportedTypeHandle); if (exportedType.Implementation.Kind == HandleKind.ExportedType) { continue; // skip nested exported types. } NamespaceDefinitionHandle namespaceHandle = exportedType.NamespaceDefinition; NamespaceDataBuilder builder; if (table.TryGetValue(namespaceHandle, out builder)) { builder.ExportedTypes.Add(exportedTypeHandle); } else { Debug.Assert(namespaceHandle.HasFullName); StringHandle simpleName = GetSimpleName(namespaceHandle); string fullName = _metadataReader.GetString(namespaceHandle); var newData = new NamespaceDataBuilder(namespaceHandle, simpleName, fullName); newData.ExportedTypes.Add(exportedTypeHandle); table.Add(namespaceHandle, newData); } } } /// <summary> /// Populates namespaceList with distinct namespaces. No ordering is guaranteed. /// </summary> private void PopulateNamespaceList() { lock (_namespaceTableAndListLock) { if (_namespaceList != null) { return; } Debug.Assert(_namespaceTable != null); var namespaceNameSet = new Dictionary<string, string>(); var namespaceListBuilder = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>(); foreach (var group in _namespaceTable) { var data = group.Value; if (!namespaceNameSet.ContainsKey(data.FullName)) { namespaceNameSet.Add(data.FullName, null); namespaceListBuilder.Add(group.Key); } } _namespaceList = namespaceListBuilder.ToImmutable(); } } /// <summary> /// If the namespace table doesn't exist, populates it! /// </summary> private void EnsureNamespaceTableIsPopulated() { // PERF: Branch will rarely be taken; do work in PopulateNamespaceList() so this can be inlined easily. if (_namespaceTable == null) { PopulateNamespaceTable(); } Debug.Assert(_namespaceTable != null); } /// <summary> /// If the namespace list doesn't exist, populates it! /// </summary> private void EnsureNamespaceListIsPopulated() { if (_namespaceList == null) { PopulateNamespaceList(); } Debug.Assert(_namespaceList != null); } /// <summary> /// An intermediate class used to build NamespaceData instances. This was created because we wanted to /// use ImmutableArrays in NamespaceData, but having ArrayBuilders and ImmutableArrays that served the /// same purpose in NamespaceData got ugly. With the current design of how we create our Namespace /// dictionary, this needs to be a class because we have a many-to-one mapping between NamespaceHandles /// and NamespaceData. So, the pointer semantics must be preserved. /// /// This class assumes that the builders will not be modified in any way after the first call to /// Freeze(). /// </summary> private class NamespaceDataBuilder { public readonly NamespaceDefinitionHandle Handle; public readonly StringHandle Name; public readonly string FullName; public NamespaceDefinitionHandle Parent; public ImmutableArray<NamespaceDefinitionHandle>.Builder Namespaces; public ImmutableArray<TypeDefinitionHandle>.Builder TypeDefinitions; public ImmutableArray<ExportedTypeHandle>.Builder ExportedTypes; private NamespaceData _frozen; public NamespaceDataBuilder(NamespaceDefinitionHandle handle, StringHandle name, string fullName) { Handle = handle; Name = name; FullName = fullName; Namespaces = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>(); TypeDefinitions = ImmutableArray.CreateBuilder<TypeDefinitionHandle>(); ExportedTypes = ImmutableArray.CreateBuilder<ExportedTypeHandle>(); } /// <summary> /// Returns a NamespaceData that represents this NamespaceDataBuilder instance. After calling /// this method, it is an error to use any methods or fields except Freeze() on the target /// NamespaceDataBuilder. /// </summary> public NamespaceData Freeze() { // It is not an error to call this function multiple times. We cache the result // because it's immutable. if (_frozen == null) { var namespaces = Namespaces.ToImmutable(); Namespaces = null; var typeDefinitions = TypeDefinitions.ToImmutable(); TypeDefinitions = null; var exportedTypes = ExportedTypes.ToImmutable(); ExportedTypes = null; _frozen = new NamespaceData(Name, FullName, Parent, namespaces, typeDefinitions, exportedTypes); } return _frozen; } public void MergeInto(NamespaceDataBuilder other) { Parent = default(NamespaceDefinitionHandle); other.Namespaces.AddRange(this.Namespaces); other.TypeDefinitions.AddRange(this.TypeDefinitions); other.ExportedTypes.AddRange(this.ExportedTypes); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json; using NUnit.Framework; using Verse.Schemas; namespace Verse.Bench { public class CompareNewtonsoft { [OneTimeSetUp] public void Setup() { #if DEBUG Assert.Fail("Library should be compiled in Release mode before benching"); #endif Trace.Listeners.Add(new TextWriterTraceListener("Verse.Bench.log")); Trace.AutoFlush = true; } [Test] public void DecodeFlatStructure() { const string source = "{" + "\"lorem\":0," + "\"ipsum\":65464658634633," + "\"sit\":1.1," + "\"amet\":\"Hello, World!\"," + "\"consectetur\":255," + "\"adipiscing\":64," + "\"elit\":\"z\"," + "\"sed\":53.25," + "\"pulvinar\":\"I sense a soul in search of answers\"," + "\"fermentum\":6553," + "\"hendrerit\":-32768" + "}"; var decoder = Linker.CreateDecoder(new JSONSchema<MyFlatStructure>()); CompareNewtonsoft.BenchDecode(decoder, source, 10000); } [Test] [TestCase(10, 10000)] [TestCase(1000, 100)] [TestCase(10000, 10)] [TestCase(100000, 1)] public void DecodeLargeArray(int length, int count) { var builder = new StringBuilder(); var random = new Random(); builder.Append("["); if (length > 0) { for (var i = 0;;) { builder.Append(random.Next().ToString(CultureInfo.InvariantCulture)); if (++i >= length) break; builder.Append(","); } } builder.Append("]"); var schema = new JSONSchema<long[]>(); schema.DecoderDescriptor.HasElements(() => 0, (ref long[] target, IEnumerable<long> elements) => target = elements.ToArray()).HasValue(); var decoder = schema.CreateDecoder(Array.Empty<long>); CompareNewtonsoft.BenchDecode(decoder, builder.ToString(), count); } [Test] public void DecodeNestedArray() { const string source = "{" + "\"children\":[{"+ "\"children\":[],\"value\":\"a\""+ "},{"+ "\"children\":[{\"children\":[],\"value\":\"b\"},{\"children\":[],\"value\":\"c\"}]," + "\"value\":\"d\""+ "},{"+ "\"children\":[],\"value\":\"e\""+ "}],"+ "\"value\":\"f\"" + "}"; var decoder = Linker.CreateDecoder(new JSONSchema<MyNestedArray>()); CompareNewtonsoft.BenchDecode(decoder, source, 10000); } [Test] public void EncodeFlatStructure() { var encoder = Linker.CreateEncoder(new JSONSchema<MyFlatStructure>()); var instance = new MyFlatStructure { adipiscing = 64, amet = "Hello, World!", consectetur = 255, elit = 'z', fermentum = 6553, hendrerit = -32768, ipsum = 65464658634633, lorem = 0, pulvinar = "I sense a soul in search of answers", sed = 53.25f, sit = 1.1 }; CompareNewtonsoft.BenchEncode(encoder, instance, 10000); } [Test] public void EncodeNestedArray() { var encoder = Linker.CreateEncoder(new JSONSchema<MyNestedArray>()); var instance = new MyNestedArray { children = new[] { new MyNestedArray { children = null, value = "a" }, new MyNestedArray { children = new[] { new MyNestedArray { children = null, value = "b" }, new MyNestedArray { children = null, value = "c" } }, value = "d" }, new MyNestedArray { children = new MyNestedArray[0], value = "e" } }, value = "f" }; CompareNewtonsoft.BenchEncode(encoder, instance, 10000); } private static void BenchDecode<T>(IDecoder<T> decoder, string source, int count) { var expected = JsonConvert.DeserializeObject<T>(source); var stream = new MemoryStream(Encoding.UTF8.GetBytes(source)); using (var decoderStream = decoder.Open(stream)) { Assert.That(decoderStream.TryDecode(out var candidate), Is.True); Assert.That(candidate, Is.EqualTo(expected)); } CompareNewtonsoft.Bench(new (string, Action)[] { ("Newtonsoft", () => { JsonConvert.DeserializeObject<T>(source); }), ("Verse", () => { stream.Seek(0, SeekOrigin.Begin); using (var decoderStream = decoder.Open(stream)) decoderStream.TryDecode(out _); }) }, count); } private static void BenchEncode<T>(IEncoder<T> encoder, T instance, int count) { var expected = JsonConvert.SerializeObject(instance); var stream = new MemoryStream(1024); using (var encoderStream = encoder.Open(stream)) encoderStream.Encode(instance); var candidate = Encoding.UTF8.GetString(stream.ToArray()); Assert.That(expected, Is.EqualTo(candidate)); CompareNewtonsoft.Bench(new (string, Action)[] { ("Newtonsoft", () => { JsonConvert.SerializeObject(instance); }), ("Verse", () => { stream.Seek(0, SeekOrigin.Begin); using (var encoderStream = encoder.Open(stream)) encoderStream.Encode(instance); }) }, count); } private static void Bench(IEnumerable<(string, Action)> variants, int repeat) { var timings = new List<(string, TimeSpan)>(); foreach (var (name, action) in variants) { action(); var timer = Stopwatch.StartNew(); for (var i = 0; i < repeat; ++i) action(); timings.Add((name, timer.Elapsed)); } Trace.WriteLine($"[{TestContext.CurrentContext.Test.FullName}]"); foreach (var (item1, timeSpan) in timings) Trace.WriteLine($" - {item1}: {timeSpan}"); } private struct MyFlatStructure : IEquatable<MyFlatStructure> { public int lorem; public long ipsum; public double sit; public string amet; public byte consectetur; public ushort adipiscing; public char elit; public float sed; public string pulvinar; public uint fermentum; public short hendrerit; public bool Equals(MyFlatStructure other) { return this.lorem == other.lorem && this.ipsum == other.ipsum && Math.Abs(this.sit - other.sit) < double.Epsilon && this.amet == other.amet && this.consectetur == other.consectetur && this.adipiscing == other.adipiscing && this.elit == other.elit && Math.Abs(this.sed - other.sed) < float.Epsilon && this.pulvinar == other.pulvinar && this.fermentum == other.fermentum && this.hendrerit == other.hendrerit; } } private class MyNestedArray : IEquatable<MyNestedArray> { public MyNestedArray[] children; public string value; public bool Equals(MyNestedArray other) { if (this.children.Length != other.children.Length) return false; for (var i = 0; i < this.children.Length; ++i) { if (!this.children[i].Equals(other.children[i])) return false; } return this.value == other.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.Diagnostics; using System.Threading; namespace System.Net.Sockets { // BaseOverlappedAsyncResult // // This class is used to track state for async Socket operations such as the BeginSend, BeginSendTo, // BeginReceive, BeginReceiveFrom, BeginSendFile, and BeginAccept calls. internal partial class BaseOverlappedAsyncResult : ContextAwareResult { private int _cleanupCount; private SafeNativeOverlapped _nativeOverlapped; // The WinNT Completion Port callback. private static unsafe readonly IOCompletionCallback s_ioCallback = new IOCompletionCallback(CompletionPortCallback); internal BaseOverlappedAsyncResult(Socket socket, Object asyncState, AsyncCallback asyncCallback) : base(socket, asyncState, asyncCallback) { _cleanupCount = 1; if (NetEventSource.IsEnabled) NetEventSource.Info(this, socket); } // SetUnmanagedStructures // // This needs to be called for overlapped IO to function properly. // // Fills in overlapped Structures used in an async overlapped Winsock call. // These calls are outside the runtime and are unmanaged code, so we need // to prepare specific structures and ints that lie in unmanaged memory // since the overlapped calls may complete asynchronously. internal void SetUnmanagedStructures(object objectsToPin) { Socket s = (Socket)AsyncObject; // Bind the Win32 Socket Handle to the ThreadPool Debug.Assert(s != null, "m_CurrentSocket is null"); Debug.Assert(s.SafeHandle != null, "m_CurrentSocket.SafeHandle is null"); if (s.SafeHandle.IsInvalid) { throw new ObjectDisposedException(s.GetType().FullName); } ThreadPoolBoundHandle boundHandle = s.GetOrAllocateThreadPoolBoundHandle(); unsafe { NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped(s_ioCallback, this, objectsToPin); _nativeOverlapped = new SafeNativeOverlapped(s.SafeHandle, overlapped); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"{boundHandle}::AllocateNativeOverlapped. return={_nativeOverlapped}"); } private static unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { #if DEBUG DebugThreadTracking.SetThreadSource(ThreadKinds.CompletionPort); using (DebugThreadTracking.SetThreadKind(ThreadKinds.System)) { #endif BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); if (asyncResult.InternalPeekCompleted) { NetEventSource.Fail(null, $"asyncResult.IsCompleted: {asyncResult}"); } if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"errorCode:{errorCode} numBytes:{numBytes} nativeOverlapped:{(IntPtr)nativeOverlapped}"); // Complete the IO and invoke the user's callback. SocketError socketError = (SocketError)errorCode; if (socketError != SocketError.Success && socketError != SocketError.OperationAborted) { // There are cases where passed errorCode does not reflect the details of the underlined socket error. // "So as of today, the key is the difference between WSAECONNRESET and ConnectionAborted, // .e.g remote party or network causing the connection reset or something on the local host (e.g. closesocket // or receiving data after shutdown (SD_RECV)). With Winsock/TCP stack rewrite in longhorn, there may // be other differences as well." Socket socket = asyncResult.AsyncObject as Socket; if (socket == null) { socketError = SocketError.NotSocket; } else if (socket.CleanedUp) { socketError = SocketError.OperationAborted; } else { try { // The async IO completed with a failure. // Here we need to call WSAGetOverlappedResult() just so GetLastSocketError() will return the correct error. SocketFlags ignore; bool success = Interop.Winsock.WSAGetOverlappedResult( socket.SafeHandle, nativeOverlapped, out numBytes, false, out ignore); if (!success) { socketError = SocketPal.GetLastSocketError(); } if (success) { NetEventSource.Fail(asyncResult, $"Unexpectedly succeeded. errorCode:{errorCode} numBytes:{numBytes}"); } } catch (ObjectDisposedException) { // CleanedUp check above does not always work since this code is subject to race conditions socketError = SocketError.OperationAborted; } } } // Set results and invoke callback asyncResult.CompletionCallback((int)numBytes, socketError); #if DEBUG } #endif } // Called either synchronously from SocketPal async routines or asynchronously via CompletionPortCallback above. private void CompletionCallback(int numBytes, SocketError socketError) { ErrorCode = (int)socketError; object result = PostCompletion(numBytes); ReleaseUnmanagedStructures(); // must come after PostCompletion, as overrides may use these resources InvokeCallback(result); } internal unsafe NativeOverlapped* DangerousOverlappedPointer => (NativeOverlapped*)_nativeOverlapped.DangerousGetHandle(); // Check the result of the overlapped operation. // Handle synchronous success by completing the asyncResult here. // Handle synchronous failure by cleaning up and returning a SocketError. internal SocketError ProcessOverlappedResult(bool success, int bytesTransferred) { if (success) { // Synchronous success. Socket socket = (Socket)AsyncObject; if (socket.SafeHandle.SkipCompletionPortOnSuccess) { // The socket handle is configured to skip completion on success, // so we can complete this asyncResult right now. CompletionCallback(bytesTransferred, SocketError.Success); return SocketError.Success; } // Socket handle is going to post a completion to the completion port (may have done so already). // Return pending and we will continue in the completion port callback. return SocketError.IOPending; } // Get the socket error (which may be IOPending) SocketError errorCode = SocketPal.GetLastSocketError(); if (errorCode == SocketError.IOPending) { // Operation is pending. // We will continue when the completion arrives (may have already at this point). return SocketError.IOPending; } // Synchronous failure. // Release overlapped and pinned structures. ReleaseUnmanagedStructures(); return errorCode; } internal void ReleaseUnmanagedStructures() { if (Interlocked.Decrement(ref _cleanupCount) == 0) { ForceReleaseUnmanagedStructures(); } } protected override void Cleanup() { base.Cleanup(); // If we get all the way to here and it's still not cleaned up... if (_cleanupCount > 0 && Interlocked.Exchange(ref _cleanupCount, 0) > 0) { ForceReleaseUnmanagedStructures(); } } // Utility cleanup routine. Frees the overlapped structure. // This should be overridden to free pinned and unmanaged memory in the subclass. // It needs to also be invoked from the subclass. protected virtual void ForceReleaseUnmanagedStructures() { // Free the unmanaged memory if allocated. if (NetEventSource.IsEnabled) NetEventSource.Enter(this); _nativeOverlapped.Dispose(); _nativeOverlapped = null; GC.SuppressFinalize(this); } } }
#region Using Directives using System; using System.Resources; using System.Drawing; using System.Globalization; #endregion namespace System.Workflow.ComponentModel.Design { #region Class DesignerResources (DR) internal static class DR { internal const string ResourceSet = "System.Workflow.ComponentModel.Design.DesignerResources"; private static ResourceManager resourceManager = new ResourceManager(ResourceSet, System.Reflection.Assembly.GetExecutingAssembly()); internal const string ViewPreviousActivity = "ViewPreviousActivity"; internal const string ViewNextActivity = "ViewNextActivity"; internal const string PreviewActivity = "PreviewActivity"; internal const string EditActivity = "EditActivity"; internal const string GenerateEventHandlers = "GenerateEventHandlers"; internal const string PromoteBindings = "PromoteBindings"; internal const string BindSelectedProperty = "BindSelectedProperty"; internal const string BindSelectedPropertyFormat = "BindSelectedPropertyFormat"; internal const string BindProperty = "BindProperty"; internal const string PackageFileInvalid = "PackageFileInvalid"; internal const string PackageFileInvalidChars = "PackageFileInvalidChars"; internal const string PackageFileDefault = "PackageFileDefault"; internal const string PackageInvalidValidatorType = "PackageInvalidValidatorType"; internal const string PackageFileExist = "PackageFileExist"; internal const string OpenfileDialogTitle = "OpenfileDialogTitle"; internal const string PackageAssemblyReferenceFilter = "PackageAssemblyReferenceFilter"; internal const string CreatePackageTitle = "CreatePackageTitle"; internal const string ActivitySetDefaultName = "ActivitySetDefaultName"; internal const string ActivitySetNoName = "ActivitySetNoName"; internal const string ActivitySetNoActivity = "ActivitySetNoActivity"; internal const string ModifyPackageTitle = "ModifyPackageTitle"; internal const string ViewPackageTitle = "ViewPackageTitle"; internal const string ErrorInitPackage = "ErrorInitPackage"; internal const string CheckAll = "CheckAll"; internal const string NoHelpAvailable = "NoHelpAvailable"; internal const string ActivitySetDefaultFileName = "ActivitySetDefaultFileName"; internal const string TypeInvalid = "TypeInvalid"; internal const string FilterDescription = "FilterDescription"; internal const string Zoom400Mode = "Zoom400Mode"; internal const string Zoom300Mode = "Zoom300Mode"; internal const string Zoom200Mode = "Zoom200Mode"; internal const string Zoom150Mode = "Zoom150Mode"; internal const string Zoom100Mode = "Zoom100Mode"; internal const string Zoom75Mode = "Zoom75Mode"; internal const string Zoom50Mode = "Zoom50Mode"; internal const string ZoomShowAll = "ZoomShowAll"; internal const string ActivityInsertError = "ActivityInsertError"; internal const string InvalidOperationBadClipboardFormat = "InvalidOperationBadClipboardFormat"; internal const string ArgumentExceptionDesignerVerbIdsRange = "ArgumentExceptionDesignerVerbIdsRange"; internal const string InvalidOperationStoreAlreadyClosed = "InvalidOperationStoreAlreadyClosed"; internal const string InvalidOperationDeserializationReturnedNonActivity = "InvalidOperationDeserializationReturnedNonActivity"; internal const string AccessibleAction = "AccessibleAction"; internal const string LeftScrollButtonAccessibleDescription = "LeftScrollButtonAccessibleDescription"; internal const string RightScrollButtonAccessibleDescription = "RightScrollButtonAccessibleDescription"; internal const string ActivityDesignerAccessibleDescription = "ActivityDesignerAccessibleDescription"; internal const string LeftScrollButtonAccessibleHelp = "LeftScrollButtonAccessibleHelp"; internal const string RightScrollButtonAccessibleHelp = "RightScrollButtonAccessibleHelp"; internal const string ActivityDesignerAccessibleHelp = "ActivityDesignerAccessibleHelp"; internal const string LeftScrollButtonName = "LeftScrollButtonName"; internal const string RightScrollButtonName = "RightScrollButtonName"; internal const string SelectActivityDesc = "SelectActivityDesc"; internal const string PreviewMode = "PreviewMode"; internal const string EditMode = "EditMode"; internal const string PreviewButtonAccessibleDescription = "PreviewButtonAccessibleDescription"; internal const string PreviewButtonAccessibleHelp = "PreviewButtonAccessibleHelp"; internal const string PreviewButtonName = "PreviewButtonName"; internal const string CancelDescriptionString = "CancelDescriptionString"; internal const string HeaderFooterStringNone = "HeaderFooterStringNone"; internal const string HeaderFooterStringCustom = "HeaderFooterStringCustom"; internal const string HeaderFooterFormat1 = "HeaderFooterFormat1"; internal const string HeaderFooterFormat2 = "HeaderFooterFormat2"; internal const string HeaderFooterFormat3 = "HeaderFooterFormat3"; internal const string HeaderFooterFormat4 = "HeaderFooterFormat4"; internal const string HeaderFooterFormat5 = "HeaderFooterFormat5"; internal const string HeaderFooterFormat6 = "HeaderFooterFormat6"; internal const string HeaderFooterFormat7 = "HeaderFooterFormat7"; internal const string HeaderFooterFormat8 = "HeaderFooterFormat8"; internal const string HeaderFooterFormat9 = "HeaderFooterFormat9"; internal const string EnteredMarginsAreNotValidErrorMessage = "EnteredMarginsAreNotValidErrorMessage"; internal const string ChildActivitiesNotConfigured = "ChildActivitiesNotConfigured"; internal const string ConnectorAccessibleDescription = "ConnectorAccessibleDescription"; internal const string ConnectorAccessibleHelp = "ConnectorAccessibleHelp"; internal const string ConnectorDesc = "ConnectorDesc"; internal const string WorkflowDesc = "WorkflowDesc"; internal const string AddBranch = "AddBranch"; internal const string DropActivitiesHere = "DropActivitiesHere"; internal const string DesignerNotInitialized = "DesignerNotInitialized"; internal const string MyFavoriteTheme = "MyFavoriteTheme"; internal const string AmbientThemeException = "AmbientThemeException"; internal const string ThemeTypesMismatch = "ThemeTypesMismatch"; internal const string DesignerThemeException = "DesignerThemeException"; internal const string CustomStyleNotSupported = "CustomStyleNotSupported"; internal const string EmptyFontFamilyNotSupported = "EmptyFontFamilyNotSupported"; internal const string FontFamilyNotSupported = "FontFamilyNotSupported"; internal const string ContentAlignmentNotSupported = "ContentAlignmentNotSupported"; internal const string ZoomLevelException2 = "ZoomLevelException2"; internal const string ShadowDepthException = "ShadowDepthException"; internal const string ThereIsNoPrinterInstalledErrorMessage = "ThereIsNoPrinterInstalledErrorMessage"; internal const string WorkflowViewAccessibleDescription = "WorkflowViewAccessibleDescription"; internal const string WorkflowViewAccessibleHelp = "WorkflowViewAccessibleHelp"; internal const string WorkflowViewAccessibleName = "WorkflowViewAccessibleName"; internal const string SelectedPrinterIsInvalidErrorMessage = "SelectedPrinterIsInvalidErrorMessage"; internal const string ObjectDoesNotSupportIPropertyValuesProvider = "ObjectDoesNotSupportIPropertyValuesProvider"; internal const string ThemeFileFilter = "ThemeFileFilter"; internal const string ThemeConfig = "ThemeConfig"; internal const string ThemeNameNotValid = "ThemeNameNotValid"; internal const string ThemePathNotValid = "ThemePathNotValid"; internal const string ThemeFileNotXml = "ThemeFileNotXml"; internal const string UpdateRelativePaths = "UpdateRelativePaths"; internal const string ThemeDescription = "ThemeDescription"; internal const string ThemeFileCreationError = "ThemeFileCreationError"; internal const string Preview = "Preview"; internal const string ArgumentExceptionSmartActionIdsRange = "ArgumentExceptionSmartActionIdsRange"; internal const string ActivitiesDesc = "ActivitiesDesc"; internal const string MoveLeftDesc = "MoveLeftDesc"; internal const string MoveRightDesc = "MoveRightDesc"; internal const string DropExceptionsHere = "DropExceptionsHere"; internal const string SpecifyTargetWorkflow = "SpecifyTargetWorkflow"; internal const string ServiceHelpText = "ServiceHelpText"; internal const string StartWorkFlow = "StartWorkFlow"; internal const string Complete = "Complete"; internal const string ServiceExceptions = "ServiceExceptions"; internal const string ServiceEvents = "ServiceEvents"; internal const string ServiceCompensation = "ServiceCompensation"; internal const string ScopeDesc = "ScopeDesc"; internal const string EventsDesc = "EventsDesc"; internal const string InvokeWebServiceDisplayName = "InvokeWebServiceDisplayName"; internal const string InvalidClassNameIdentifier = "InvalidClassNameIdentifier"; internal const string InvalidBaseTypeOfCompanion = "InvalidBaseTypeOfCompanion"; internal const string Error_InvalidActivity = "Error_InvalidActivity"; internal const string Error_MultiviewSequentialActivityDesigner = "Error_MultiviewSequentialActivityDesigner"; internal const string AddingBranch = "AddingBranch"; internal const string WorkflowPrintDocumentNotFound = "WorkflowPrintDocumentNotFound"; internal const string DefaultTheme = "DefaultTheme"; internal const string DefaultThemeDescription = "DefaultThemeDescription"; internal const string OSTheme = "OSTheme"; internal const string SystemThemeDescription = "SystemThemeDescription"; internal const string ActivitySetMessageBoxTitle = "ActivitySetMessageBoxTitle"; internal const string ViewExceptions = "ViewExceptions"; internal const string ViewEvents = "ViewEvents"; internal const string ViewCompensation = "ViewCompensation"; internal const string ViewCancelHandler = "ViewCancelHandler"; internal const string ViewActivity = "ViewActivity"; internal const string ThemeMessageBoxTitle = "ThemeMessageBoxTitle"; internal const string InfoTipTitle = "InfoTipTitle"; internal const string InfoTipId = "InfoTipId"; internal const string InfoTipDescription = "InfoTipDescription"; internal const string TypeBrowser_ProblemsLoadingAssembly = "TypeBrowser_ProblemsLoadingAssembly"; internal const string TypeBrowser_UnableToLoadOneOrMoreTypes = "TypeBrowser_UnableToLoadOneOrMoreTypes"; internal const string StartWorkflow = "StartWorkflow"; internal const string EndWorkflow = "EndWorkflow"; internal const string Error_FailedToDeserializeComponents = "Error_FailedToDeserializeComponents"; internal const string Error_Reason = "Error_Reason"; internal const string WorkflowDesignerTitle = "WorkflowDesignerTitle"; internal const string RuleName = "RuleName"; internal const string RuleExpression = "RuleExpression"; internal const string DeclarativeRules = "DeclarativeRules"; internal const string Error_ThemeAttributeMissing = "Error_ThemeAttributeMissing"; internal const string Error_ThemeTypeMissing = "Error_ThemeTypeMissing"; internal const string Error_ThemeTypesMismatch = "Error_ThemeTypesMismatch"; internal const string ZOrderUndoDescription = "ZOrderUndoDescription"; internal const string SendToBack = "SendToBack"; internal const string BringToFront = "BringToFront"; internal const string ResizeUndoDescription = "ResizeUndoDescription"; internal const string FitToScreenDescription = "FitToScreenDescription"; internal const string FitToWorkflowDescription = "FitToWorkflowDescription"; internal const string BMPImageFormat = "BMPImageFormat"; internal const string JPEGImageFormat = "JPEGImageFormat"; internal const string PNGImageFormat = "PNGImageFormat"; internal const string TIFFImageFormat = "TIFFImageFormat"; internal const string WMFImageFormat = "WMFImageFormat"; internal const string EXIFImageFormat = "EXIFImageFormat"; internal const string EMFImageFormat = "EMFImageFormat"; internal const string CustomEventType = "CustomEventType"; internal const string CustomPropertyType = "CustomPropertyType"; internal const string SaveWorkflowImageDialogTitle = "SaveWorkflowImageDialogTitle"; internal const string ImageFileFilter = "ImageFileFilter"; internal const string Rules = "Rules"; internal const string More = "More"; internal const string Empty = "Empty"; internal const string InvalidDockingStyle = "InvalidDockingStyle"; internal const string ButtonInformationMissing = "ButtonInformationMissing"; internal const string InvalidDesignerSpecified = "InvalidDesignerSpecified"; internal const string WorkflowViewNull = "WorkflowViewNull"; internal const string Error_AddConnector1 = "Error_AddConnector1"; internal const string Error_AddConnector2 = "Error_AddConnector2"; internal const string Error_AddConnector3 = "Error_AddConnector3"; internal const string Error_ConnectionPoint = "Error_ConnectionPoint"; internal const string Error_Connector1 = "Error_Connector1"; internal const string Error_Connector2 = "Error_Connector2"; internal const string Error_WorkflowNotLoaded = "Error_WorkflowNotLoaded"; internal const string Error_InvalidImageResource = "Error_InvalidImageResource"; internal const string ThemePropertyReadOnly = "ThemePropertyReadOnly"; internal const string Error_TabExistsWithSameId = "Error_TabExistsWithSameId"; internal const string Error_WorkflowLayoutNull = "Error_WorkflowLayoutNull"; internal const string BuildTargetWorkflow = "BuildTargetWorkflow"; //Bitmaps internal const string Activity = "Activity"; internal const string MoveLeft = "MoveLeft"; internal const string MoveLeftUp = "MoveLeftUp"; internal const string MoveRight = "MoveRight"; internal const string MoveRightUp = "MoveRightUp"; internal const string PreviewModeIcon = "PreviewModeIcon"; internal const string EditModeIcon = "EditModeIcon"; internal const string PreviewIndicator = "PreviewIndicator"; internal const string ReadOnly = "ReadOnly"; internal const string ConfigError = "ConfigError"; internal const string SmartTag = "SmartTag"; internal const string ArrowLeft = "ArrowLeft"; internal const string DropShapeShort = "DropShapeShort"; internal const string FitToWorkflow = "FitToWorkflow"; internal const string MoveAnchor = "MoveAnchor"; internal const string Activities = "Activities"; internal const string Compensation = "Compensation"; internal const string SequenceArrow = "SequenceArrow"; internal const string Exception = "Exception"; internal const string Event = "Event"; internal const string Start = "Start"; internal const string End = "End"; internal const string FitToScreen = "FitToScreen"; internal const string Bind = "Bind"; internal static string GetString(string resID, params object[] args) { return GetString(CultureInfo.CurrentUICulture, resID, args); } internal static string GetString(CultureInfo culture, string resID, params object[] args) { string str = DR.resourceManager.GetString(resID, culture); System.Diagnostics.Debug.Assert(str != null, string.Format(culture, "String resource {0} not found.", new object[] { resID })); if (args != null && args.Length > 0) str = string.Format(culture, str, args); return str; } internal static Image GetImage(string resID) { Image image = DR.resourceManager.GetObject(resID) as Image; //Please note that the default version of make transparent uses the color of pixel at left bottom of the image //as the transparent color to make the bitmap transparent. Hence we do not use it Bitmap bitmap = image as Bitmap; if (bitmap != null) bitmap.MakeTransparent(AmbientTheme.TransparentColor); return image; } } #endregion }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Text; using XSerializer.Encryption; namespace XSerializer { /// <summary> /// A representation of a JSON array. Provides an advanced dynamic API as well as a standard /// object API. /// </summary> public sealed class JsonArray : DynamicObject, IList<object> { private delegate bool TryFunc(out object result); private readonly ConcurrentDictionary<Type, TryFunc> _convertFuncs = new ConcurrentDictionary<Type, TryFunc>(); private readonly IJsonSerializeOperationInfo _info; private readonly List<object> _values = new List<object>(); private readonly List<object> _transformableValues = new List<object>(); private readonly List<Type> _transformedTypes = new List<Type>(); /// <summary> /// Initializes a new instance of the <see cref="JsonArray"/> class. /// </summary> public JsonArray() : this(null, null, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="JsonArray"/> class. /// </summary> /// <param name="dateTimeHandler">The object that determines how date time values are parsed.</param> /// <param name="encryptionMechanism">The object the performs encryption operations.</param> /// <param name="encryptKey">A key optionally used by the encryption mechanism during encryption operations.</param> /// <param name="serializationState">An object optionally used by the encryption mechanism to carry state across multiple encryption operations.</param> public JsonArray( IDateTimeHandler dateTimeHandler = null, IEncryptionMechanism encryptionMechanism = null, object encryptKey = null, SerializationState serializationState = null) : this(new JsonSerializeOperationInfo { DateTimeHandler = dateTimeHandler ?? DateTimeHandler.Default, EncryptionMechanism = encryptionMechanism, EncryptKey = encryptKey, SerializationState = serializationState }) { } internal JsonArray(IJsonSerializeOperationInfo info) { _info = info; } /// <summary> /// Adds an object to the end of the <see cref="JsonArray"/>. /// </summary> /// <param name="value">The object to be added to the end of the <see cref="JsonArray"/>.</param> public void Add(object value) { var jsonNumber = value as JsonNumber; if (jsonNumber != null) { _values.Add(jsonNumber.DoubleValue); _transformableValues.Add(jsonNumber); } else if (value is string) { _values.Add(value); _transformableValues.Add(value); } else { _values.Add(value); _transformableValues.Add(null); } } /// <summary> /// Determines whether the specified <see cref="object"/> is equal to the current <see cref="object"/>. /// </summary> /// <param name="obj">The <see cref="object"/> to compare with the current <see cref="object"/>.</param> /// <returns> /// true if the specified <see cref="object"/> is equal to the current <see cref="object"/>; otherwise, false. /// </returns> public override bool Equals(object obj) { var other = obj as JsonArray; if (other == null || _values.Count != other._values.Count) { return false; } for (int i = 0; i < _values.Count; i++) { if (!Equals(_values[i], other._values[i])) { return false; } } return true; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="object"/>. /// </returns> public override int GetHashCode() { unchecked { return _values.Aggregate( typeof(JsonArray).GetHashCode(), (current, item) => (current * 397) ^ (item != null ? item.GetHashCode() : 0)); } } /// <summary> /// Provides implementation for type conversion operations. /// </summary> /// <param name="binder">Provides information about the conversion operation.</param> /// <param name="result">The result of the type conversion operation.</param> /// <returns> /// true if the operation is successful; otherwise, false. /// </returns> public override bool TryConvert(ConvertBinder binder, out object result) { var convertFunc = _convertFuncs.GetOrAdd(binder.Type, GetConvertFunc); return convertFunc != null ? convertFunc(out result) : base.TryConvert(binder, out result); } /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> public object this[int index] { get { return _values[index]; } set { _values[index] = value; _transformableValues[index] = null; } } /// <summary> /// Gets the number of elements actually contained in the <see cref="JsonArray"/>. /// </summary> public int Count { get { return _values.Count; } } /// <summary> /// Removes all items from the <see cref="JsonArray"/>. /// </summary> public void Clear() { _values.Clear(); _transformableValues.Clear(); _transformedTypes.Clear(); } /// <summary> /// Determines whether the <see cref="JsonArray"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="JsonArray"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="JsonArray"/>; otherwise, false. /// </returns> public bool Contains(object item) { return _values.Contains(item); } /// <summary> /// Copies the elements of the <see cref="JsonArray"/> 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="JsonArray"/>. 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> public void CopyTo(object[] array, int arrayIndex) { _values.CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="JsonArray"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="JsonArray"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="JsonArray"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="JsonArray"/>. /// </returns> public bool Remove(object item) { var index = _values.IndexOf(item); if (index == -1) { return false; } _values.RemoveAt(index); _transformableValues.RemoveAt(index); return true; } /// <summary> /// Determines the index of a specific item in the <see cref="JsonArray"/>. /// </summary> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> /// <param name="item">The object to locate in the <see cref="JsonArray"/>.</param> public int IndexOf(object item) { return _values.IndexOf(item); } /// <summary> /// Inserts an item to the <see cref="JsonArray"/> 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="JsonArray"/>.</param> public void Insert(int index, object item) { _values.Insert(index, item); _transformableValues.Insert(index, null); } /// <summary> /// Removes the <see cref="JsonArray"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> public void RemoveAt(int index) { _values.RemoveAt(index); _transformableValues.RemoveAt(index); } /// <summary> /// Gets a value indicating whether the <see cref="JsonArray"/> is read-only. /// </summary> /// <returns> /// true if the <see cref="JsonArray"/> is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get { return false; } } /// <summary> /// Decrypts the item at the specified index, changing its value in place. /// </summary> /// <param name="index">The index of the value to decrypt.</param> /// <returns>This instance of <see cref="JsonArray"/>.</returns> public JsonArray Decrypt(int index) { if (_info.EncryptionMechanism != null) { var value = _transformableValues[index]; if (value is string) { var decryptedJson = _info.EncryptionMechanism.Decrypt( (string)value, _info.EncryptKey, _info.SerializationState); using (var stringReader = new StringReader(decryptedJson)) { using (var reader = new JsonReader(stringReader, _info)) { value = DynamicJsonSerializer.Get(false, JsonMappings.Empty).DeserializeObject(reader, _info); if (value == null || value is bool || value is JsonArray || value is JsonObject) { _values[index] = value; _transformableValues[index] = null; } else if (value is string) { _values[index] = value; _transformableValues[index] = value; } else { var jsonNumber = value as JsonNumber; if (jsonNumber != null) { _values[index] = jsonNumber.DoubleValue; _transformableValues[index] = jsonNumber; } else { throw new NotSupportedException("Unsupported value type: " + value.GetType()); } } } } } } return this; } /// <summary> /// Encrypts the item at the specified index, changing its value in place. /// </summary> /// <param name="index">The index of the value to encrypt.</param> /// <returns>This instance of <see cref="JsonArray"/>.</returns> public JsonArray Encrypt(int index) { if (_info.EncryptionMechanism != null) { var value = _values[index]; if (value != null) { var sb = new StringBuilder(); using (var stringwriter = new StringWriter(sb)) { using (var writer = new JsonWriter(stringwriter, _info)) { DynamicJsonSerializer.Get(false, JsonMappings.Empty).SerializeObject(writer, value, _info); } } value = _info.EncryptionMechanism.Encrypt(sb.ToString(), _info.EncryptKey, _info.SerializationState); _values[index] = value; } } return this; } /// <summary> /// Convert all of the items in this <see cref="JsonArray"/> to the type specified by /// the <typeparamref name="T"/> generic argument. /// </summary> /// <typeparam name="T">The type to convert items to.</typeparam> /// <returns>This instance of <see cref="JsonArray"/>.</returns> public JsonArray TransformItems<T>() { return TransformItems(typeof(T)); } /// <summary> /// Convert all of the items in this <see cref="JsonArray"/> to the type specified by /// the <paramref name="type"/> parameter. /// </summary> /// <param name="type">The type to convert items to.</param> /// <returns>This instance of <see cref="JsonArray"/>.</returns> public JsonArray TransformItems(Type type) { if (_transformedTypes.Contains(type)) { return this; } if (type.IsNullableType()) { var nullableOfType = type.GetGenericArguments()[0]; if (_transformedTypes.Contains(nullableOfType)) { return this; } _transformedTypes.Add(nullableOfType); } else { _transformedTypes.Add(type); } var transform = GetTransform(type); for (int i = 0; i < _values.Count; i++) { if (_transformableValues[i] != null) { _values[i] = transform(_values[i], _transformableValues[i]); } } return this; } private TryFunc GetConvertFunc(Type type) { if (type.IsInterface && type.IsGenericType) { var genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>) || genericTypeDefinition == typeof(IList<>)) { var collectionType = type.GetGenericArguments()[0]; if (collectionType == typeof(object)) { return ((out object r) => { r = _values; return true; }); } if (collectionType == typeof(JsonObject)) { return ((out object r) => { r = new ConversionList<JsonObject>(_values); return true; }); } if (collectionType == typeof(JsonArray)) { return ((out object r) => { r = new ConversionList<JsonArray>(_values); return true; }); } if (collectionType == typeof(bool)) { return ((out object r) => { r = new ConversionList<bool>(TransformItems<bool>()._values); return true; }); } if (collectionType == typeof(bool?)) { return ((out object r) => { r = new ConversionList<bool?>(TransformItems<bool?>()._values); return true; }); } if (collectionType == typeof(byte)) { return ((out object r) => { r = new ConversionList<byte>(TransformItems<byte>()._values); return true; }); } if (collectionType == typeof(byte?)) { return ((out object r) => { r = new ConversionList<byte?>(TransformItems<byte?>()._values); return true; }); } if (collectionType == typeof(sbyte)) { return ((out object r) => { r = new ConversionList<sbyte>(TransformItems<sbyte>()._values); return true; }); } if (collectionType == typeof(sbyte?)) { return ((out object r) => { r = new ConversionList<sbyte?>(TransformItems<sbyte?>()._values); return true; }); } if (collectionType == typeof(short)) { return ((out object r) => { r = new ConversionList<short>(TransformItems<short>()._values); return true; }); } if (collectionType == typeof(short?)) { return ((out object r) => { r = new ConversionList<short?>(TransformItems<short?>()._values); return true; }); } if (collectionType == typeof(ushort)) { return ((out object r) => { r = new ConversionList<ushort>(TransformItems<ushort>()._values); return true; }); } if (collectionType == typeof(ushort?)) { return ((out object r) => { r = new ConversionList<ushort?>(TransformItems<ushort?>()._values); return true; }); } if (collectionType == typeof(int)) { return ((out object r) => { r = new ConversionList<int>(TransformItems<int>()._values); return true; }); } if (collectionType == typeof(int?)) { return ((out object r) => { r = new ConversionList<int?>(TransformItems<int?>()._values); return true; }); } if (collectionType == typeof(uint)) { return ((out object r) => { r = new ConversionList<uint>(TransformItems<uint>()._values); return true; }); } if (collectionType == typeof(uint?)) { return ((out object r) => { r = new ConversionList<uint?>(TransformItems<uint?>()._values); return true; }); } if (collectionType == typeof(long)) { return ((out object r) => { r = new ConversionList<long>(TransformItems<long>()._values); return true; }); } if (collectionType == typeof(long?)) { return ((out object r) => { r = new ConversionList<long?>(TransformItems<long?>()._values); return true; }); } if (collectionType == typeof(ulong)) { return ((out object r) => { r = new ConversionList<ulong>(TransformItems<ulong>()._values); return true; }); } if (collectionType == typeof(ulong?)) { return ((out object r) => { r = new ConversionList<ulong?>(TransformItems<ulong?>()._values); return true; }); } if (collectionType == typeof(float)) { return ((out object r) => { r = new ConversionList<float>(TransformItems<float>()._values); return true; }); } if (collectionType == typeof(float?)) { return ((out object r) => { r = new ConversionList<float?>(TransformItems<float?>()._values); return true; }); } if (collectionType == typeof(double)) { return ((out object r) => { r = new ConversionList<double>(_values); return true; }); } if (collectionType == typeof(double?)) { return ((out object r) => { r = new ConversionList<double?>(_values); return true; }); } if (collectionType == typeof(decimal)) { return ((out object r) => { r = new ConversionList<decimal>(TransformItems<decimal>()._values); return true; }); } if (collectionType == typeof(decimal?)) { return ((out object r) => { r = new ConversionList<decimal?>(TransformItems<decimal?>()._values); return true; }); } if (collectionType == typeof(string)) { return ((out object r) => { r = new ConversionList<string>(_values); return true; }); } if (collectionType == typeof(DateTime)) { return ((out object r) => { r = new ConversionList<DateTime>(TransformItems<DateTime>()._values); return true; }); } if (collectionType == typeof(DateTime?)) { return ((out object r) => { r = new ConversionList<DateTime?>(TransformItems<DateTime?>()._values); return true; }); } if (collectionType == typeof(DateTimeOffset)) { return ((out object r) => { r = new ConversionList<DateTimeOffset>(TransformItems<DateTimeOffset>()._values); return true; }); } if (collectionType == typeof(DateTimeOffset?)) { return ((out object r) => { r = new ConversionList<DateTimeOffset?>(TransformItems<DateTimeOffset?>()._values); return true; }); } if (collectionType == typeof(Guid)) { return ((out object r) => { r = new ConversionList<Guid>(TransformItems<Guid>()._values); return true; }); } if (collectionType == typeof(Guid?)) { return ((out object r) => { r = new ConversionList<Guid?>(TransformItems<Guid?>()._values); return true; }); } } } return null; } private Func<object, object, object> GetTransform(Type type) { Func<object, object, object> transform = (currentItem, transformableValue) => currentItem; if (type == typeof(DateTime) || type == typeof(DateTime?)) { transform = TransformDateTime; } if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?)) { transform = TransformDateTimeOffset; } if (type == typeof(Guid) || type == typeof(Guid?)) { transform = TransformGuid; } if (type == typeof(byte) || type == typeof(byte?)) { transform = TransformByte; } if (type == typeof(sbyte) || type == typeof(sbyte?)) { transform = TransformSByte; } if (type == typeof(short) || type == typeof(short?)) { transform = TransformInt16; } if (type == typeof(ushort) || type == typeof(ushort?)) { transform = TransformUInt16; } if (type == typeof(int) || type == typeof(int?)) { transform = TransformInt32; } if (type == typeof(uint) || type == typeof(uint?)) { transform = TransformUInt32; } if (type == typeof(long) || type == typeof(long?)) { transform = TransformInt64; } if (type == typeof(ulong) || type == typeof(ulong?)) { transform = TransformUInt64; } if (type == typeof(float) || type == typeof(float?)) { transform = TransformSingle; } if (type == typeof(decimal) || type == typeof(decimal?)) { transform = TransformDecimal; } return transform; } private object TransformDateTime(object currentItem, object transformableValue) { if (transformableValue is JsonNumber) { return currentItem; } try { return _info.DateTimeHandler.ParseDateTime((string)transformableValue); } catch { return currentItem; } } private object TransformDateTimeOffset(object currentItem, object transformableValue) { if (transformableValue is JsonNumber) { return currentItem; } try { return _info.DateTimeHandler.ParseDateTimeOffset((string)transformableValue); } catch { return currentItem; } } private static object TransformGuid(object currentItem, object transformableValue) { if (transformableValue is JsonNumber) { return currentItem; } Guid value; return Guid.TryParse((string)transformableValue, out value) ? value : currentItem; } private static object TransformByte(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } byte value; return byte.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } private static object TransformSByte(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } sbyte value; return sbyte.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } private static object TransformInt16(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } short value; return short.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } private static object TransformUInt16(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } ushort value; return ushort.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } private static object TransformInt32(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } int value; return int.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } private static object TransformUInt32(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } uint value; return uint.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } private static object TransformInt64(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } long value; return long.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } private static object TransformUInt64(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } ulong value; return ulong.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } private static object TransformSingle(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } float value; return float.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } private static object TransformDecimal(object currentItem, object transformableValue) { if (transformableValue is string) { return currentItem; } decimal value; return decimal.TryParse(((JsonNumber)transformableValue).StringValue, out value) ? value : currentItem; } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="List{T}"/> of <see cref="object"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator List<object>(JsonArray jsonArray) { return jsonArray._values; } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an object array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator object[](JsonArray jsonArray) { return jsonArray._values.ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="JsonObject"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator JsonObject[](JsonArray jsonArray) { return jsonArray._values.Cast<JsonObject>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="JsonArray"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator JsonArray[](JsonArray jsonArray) { return jsonArray._values.Cast<JsonArray>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="string"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator string[](JsonArray jsonArray) { return jsonArray.TransformItems<string>()._values.Cast<string>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="DateTime"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator DateTime[](JsonArray jsonArray) { return jsonArray.TransformItems<DateTime>()._values.Cast<DateTime>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="DateTime"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator DateTime?[](JsonArray jsonArray) { return jsonArray.TransformItems<DateTime?>()._values.Cast<DateTime?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="DateTimeOffset"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator DateTimeOffset[](JsonArray jsonArray) { return jsonArray.TransformItems<DateTimeOffset>()._values.Cast<DateTimeOffset>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="DateTimeOffset"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator DateTimeOffset?[](JsonArray jsonArray) { return jsonArray.TransformItems<DateTimeOffset?>()._values.Cast<DateTimeOffset?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="Guid"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator Guid[](JsonArray jsonArray) { return jsonArray.TransformItems<Guid>()._values.Cast<Guid>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="Guid"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator Guid?[](JsonArray jsonArray) { return jsonArray.TransformItems<Guid?>()._values.Cast<Guid?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="bool"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator bool[](JsonArray jsonArray) { return jsonArray.TransformItems<bool>()._values.Cast<bool>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="bool"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator bool?[](JsonArray jsonArray) { return jsonArray.TransformItems<bool?>()._values.Cast<bool?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="byte"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator byte[](JsonArray jsonArray) { return jsonArray.TransformItems<byte>()._values.Cast<byte>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="byte"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator byte?[](JsonArray jsonArray) { return jsonArray.TransformItems<byte?>()._values.Cast<byte?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="sbyte"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> [CLSCompliantAttribute(false)] public static implicit operator sbyte[](JsonArray jsonArray) { return jsonArray.TransformItems<sbyte>()._values.Cast<sbyte>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="sbyte"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> [CLSCompliantAttribute(false)] public static implicit operator sbyte?[](JsonArray jsonArray) { return jsonArray.TransformItems<sbyte?>()._values.Cast<sbyte?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="short"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator short[](JsonArray jsonArray) { return jsonArray.TransformItems<short>()._values.Cast<short>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="short"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator short?[](JsonArray jsonArray) { return jsonArray.TransformItems<short?>()._values.Cast<short?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="ushort"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> [CLSCompliantAttribute(false)] public static implicit operator ushort[](JsonArray jsonArray) { return jsonArray.TransformItems<ushort>()._values.Cast<ushort>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="ushort"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> [CLSCompliantAttribute(false)] public static implicit operator ushort?[](JsonArray jsonArray) { return jsonArray.TransformItems<ushort?>()._values.Cast<ushort?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="int"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator int[](JsonArray jsonArray) { return jsonArray.TransformItems<int>()._values.Cast<int>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="int"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator int?[](JsonArray jsonArray) { return jsonArray.TransformItems<int?>()._values.Cast<int?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="uint"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> [CLSCompliantAttribute(false)] public static implicit operator uint[](JsonArray jsonArray) { return jsonArray.TransformItems<uint>()._values.Cast<uint>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="uint"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> [CLSCompliantAttribute(false)] public static implicit operator uint?[](JsonArray jsonArray) { return jsonArray.TransformItems<uint?>()._values.Cast<uint?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="long"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator long[](JsonArray jsonArray) { return jsonArray.TransformItems<long>()._values.Cast<long>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="long"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator long?[](JsonArray jsonArray) { return jsonArray.TransformItems<long?>()._values.Cast<long?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="ulong"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> [CLSCompliantAttribute(false)] public static implicit operator ulong[](JsonArray jsonArray) { return jsonArray.TransformItems<ulong>()._values.Cast<ulong>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="ulong"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> [CLSCompliantAttribute(false)] public static implicit operator ulong?[](JsonArray jsonArray) { return jsonArray.TransformItems<ulong?>()._values.Cast<ulong?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="float"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator float[](JsonArray jsonArray) { return jsonArray.TransformItems<float>()._values.Cast<float>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="float"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator float?[](JsonArray jsonArray) { return jsonArray.TransformItems<float?>()._values.Cast<float?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="double"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator double[](JsonArray jsonArray) { return jsonArray.TransformItems<double>()._values.Cast<double>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="double"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator double?[](JsonArray jsonArray) { return jsonArray.TransformItems<double?>()._values.Cast<double?>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to a <see cref="decimal"/> array. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator decimal[](JsonArray jsonArray) { return jsonArray.TransformItems<decimal>()._values.Cast<decimal>().ToArray(); } /// <summary> /// Defines an implicit conversion of a <see cref="JsonArray"/> object to an array of nullable <see cref="decimal"/>. /// </summary> /// <param name="jsonArray">The object to convert.</param> /// <returns>The converted object.</returns> public static implicit operator decimal?[](JsonArray jsonArray) { return jsonArray.TransformItems<decimal?>()._values.Cast<decimal?>().ToArray(); } /// <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 IEnumerator<object> GetEnumerator() { return _values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private class ConversionList<T> : IList<T> { private readonly List<T> _list = new List<T>(); private readonly List<object> _backingList; public ConversionList(List<object> backingList) { _backingList = backingList; foreach (var item in backingList) { _list.Add((T)item); } } public IEnumerator<T> GetEnumerator() { return _list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_list).GetEnumerator(); } public void Add(T item) { _list.Add(item); _backingList.Add(item); } public void Clear() { _list.Clear(); _backingList.Clear(); } public bool Contains(T item) { return _list.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public bool Remove(T item) { return _list.Remove(item) && _backingList.Remove(item); } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return false; } } public int IndexOf(T item) { return _list.IndexOf(item); } public void Insert(int index, T item) { _list.Insert(index, item); _backingList.Insert(index, item); } public void RemoveAt(int index) { _list.RemoveAt(index); _backingList.RemoveAt(index); } public T this[int index] { get { return _list[index]; } set { _list[index] = value; _backingList[index] = value; } } } } }
using System; using System.Web; using Fluid; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using OrchardCore.Admin; using OrchardCore.Data.Migration; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.Theming; using OrchardCore.Environment.Commands; using OrchardCore.Environment.Shell; using OrchardCore.Environment.Shell.Configuration; using OrchardCore.Environment.Shell.Scope; using OrchardCore.Liquid; using OrchardCore.Modules; using OrchardCore.Mvc.Core.Utilities; using OrchardCore.Navigation; using OrchardCore.Security; using OrchardCore.Security.Permissions; using OrchardCore.Settings; using OrchardCore.Setup.Events; using OrchardCore.Users.Commands; using OrchardCore.Users.Controllers; using OrchardCore.Users.Drivers; using OrchardCore.Users.Indexes; using OrchardCore.Users.Liquid; using OrchardCore.Users.Models; using OrchardCore.Users.Services; using OrchardCore.Users.ViewModels; using YesSql.Indexes; namespace OrchardCore.Users { public class Startup : StartupBase { private readonly AdminOptions _adminOptions; private readonly string _tenantName; public Startup(IOptions<AdminOptions> adminOptions, ShellSettings shellSettings) { _adminOptions = adminOptions.Value; _tenantName = shellSettings.Name; } public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { var userOptions = serviceProvider.GetRequiredService<IOptions<UserOptions>>().Value; var accountControllerName = typeof(AccountController).ControllerName(); routes.MapAreaControllerRoute( name: "Login", areaName: "OrchardCore.Users", pattern: userOptions.LoginPath, defaults: new { controller = accountControllerName, action = nameof(AccountController.Login) } ); routes.MapAreaControllerRoute( name: "ChangePassword", areaName: "OrchardCore.Users", pattern: userOptions.ChangePasswordUrl, defaults: new { controller = accountControllerName, action = nameof(AccountController.ChangePassword) } ); routes.MapAreaControllerRoute( name: "UsersLogOff", areaName: "OrchardCore.Users", pattern: userOptions.LogoffPath, defaults: new { controller = accountControllerName, action = nameof(AccountController.LogOff) } ); var adminControllerName = typeof(AdminController).ControllerName(); routes.MapAreaControllerRoute( name: "UsersIndex", areaName: "OrchardCore.Users", pattern: _adminOptions.AdminUrlPrefix + "/Users/Index", defaults: new { controller = adminControllerName, action = nameof(AdminController.Index) } ); routes.MapAreaControllerRoute( name: "UsersCreate", areaName: "OrchardCore.Users", pattern: _adminOptions.AdminUrlPrefix + "/Users/Create", defaults: new { controller = adminControllerName, action = nameof(AdminController.Create) } ); routes.MapAreaControllerRoute( name: "UsersDelete", areaName: "OrchardCore.Users", pattern: _adminOptions.AdminUrlPrefix + "/Users/Delete/{id}", defaults: new { controller = adminControllerName, action = nameof(AdminController.Delete) } ); routes.MapAreaControllerRoute( name: "UsersEdit", areaName: "OrchardCore.Users", pattern: _adminOptions.AdminUrlPrefix + "/Users/Edit/{id}", defaults: new { controller = adminControllerName, action = nameof(AdminController.Edit) } ); routes.MapAreaControllerRoute( name: "UsersEditPassword", areaName: "OrchardCore.Users", pattern: _adminOptions.AdminUrlPrefix + "/Users/EditPassword/{id}", defaults: new { controller = adminControllerName, action = nameof(AdminController.EditPassword) } ); builder.UseAuthorization(); } public override void ConfigureServices(IServiceCollection services) { services.Configure<UserOptions>(userOptions => { var configuration = ShellScope.Services.GetRequiredService<IShellConfiguration>(); configuration.GetSection("OrchardCore_Users").Bind(userOptions); }); services.AddSecurity(); // Add ILookupNormalizer as Singleton because it is needed by UserIndexProvider services.TryAddSingleton<ILookupNormalizer, UpperInvariantLookupNormalizer>(); // Adds the default token providers used to generate tokens for reset passwords, change email // and change telephone number operations, and for two factor authentication token generation. services.AddIdentity<IUser, IRole>().AddDefaultTokenProviders(); // Configure the authentication options to use the application cookie scheme as the default sign-out handler. // This is required for security modules like the OpenID module (that uses SignOutAsync()) to work correctly. services.AddAuthentication(options => options.DefaultSignOutScheme = IdentityConstants.ApplicationScheme); services.TryAddScoped<UserStore>(); services.TryAddScoped<IUserStore<IUser>>(sp => sp.GetRequiredService<UserStore>()); services.TryAddScoped<IUserRoleStore<IUser>>(sp => sp.GetRequiredService<UserStore>()); services.TryAddScoped<IUserPasswordStore<IUser>>(sp => sp.GetRequiredService<UserStore>()); services.TryAddScoped<IUserEmailStore<IUser>>(sp => sp.GetRequiredService<UserStore>()); services.TryAddScoped<IUserSecurityStampStore<IUser>>(sp => sp.GetRequiredService<UserStore>()); services.TryAddScoped<IUserLoginStore<IUser>>(sp => sp.GetRequiredService<UserStore>()); services.TryAddScoped<IUserClaimStore<IUser>>(sp => sp.GetRequiredService<UserStore>()); services.TryAddScoped<IUserAuthenticationTokenStore<IUser>>(sp => sp.GetRequiredService<UserStore>()); services.ConfigureApplicationCookie(options => { var userOptions = ShellScope.Services.GetRequiredService<IOptions<UserOptions>>(); options.Cookie.Name = "orchauth_" + HttpUtility.UrlEncode(_tenantName); // Don't set the cookie builder 'Path' so that it uses the 'IAuthenticationFeature' value // set by the pipeline and comming from the request 'PathBase' which already ends with the // tenant prefix but may also start by a path related e.g to a virtual folder. options.LoginPath = "/" + userOptions.Value.LoginPath; options.AccessDeniedPath = "/Error/403"; }); services.AddSingleton<IIndexProvider, UserIndexProvider>(); services.AddSingleton<IIndexProvider, UserByRoleNameIndexProvider>(); services.AddSingleton<IIndexProvider, UserByLoginInfoIndexProvider>(); services.AddSingleton<IIndexProvider, UserByClaimIndexProvider>(); services.AddScoped<IDataMigration, Migrations>(); services.AddScoped<IUserService, UserService>(); services.AddScoped<IUserClaimsPrincipalFactory<IUser>, DefaultUserClaimsPrincipalFactory>(); services.AddScoped<IMembershipService, MembershipService>(); services.AddScoped<ISetupEventHandler, SetupEventHandler>(); services.AddScoped<ICommandHandler, UserCommands>(); services.AddScoped<IRoleRemovedEventHandler, UserRoleRemovedEventHandler>(); services.AddScoped<IPermissionProvider, Permissions>(); services.AddScoped<INavigationProvider, AdminMenu>(); services.AddScoped<IDisplayDriver<ISite>, LoginSettingsDisplayDriver>(); services.AddScoped<ILiquidTemplateEventHandler, UserLiquidTemplateEventHandler>(); services.AddScoped<IDisplayManager<User>, DisplayManager<User>>(); services.AddScoped<IDisplayDriver<User>, UserDisplayDriver>(); services.AddScoped<IDisplayDriver<User>, UserButtonsDisplayDriver>(); services.AddScoped<IThemeSelector, UsersThemeSelector>(); } } [RequireFeatures("OrchardCore.Liquid")] public class LiquidStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { services.AddScoped<ILiquidTemplateEventHandler, UserLiquidTemplateEventHandler>(); services.AddLiquidFilter<HasPermissionFilter>("has_permission"); services.AddLiquidFilter<HasClaimFilter>("has_claim"); services.AddLiquidFilter<IsInRoleFilter>("is_in_role"); } } [Feature("OrchardCore.Users.ChangeEmail")] public class ChangeEmailStartup : StartupBase { private const string ChangeEmailPath = "ChangeEmail"; private const string ChangeEmailConfirmationPath = "ChangeEmailConfirmation"; static ChangeEmailStartup() { TemplateContext.GlobalMemberAccessStrategy.Register<ChangeEmailViewModel>(); } public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { routes.MapAreaControllerRoute( name: "ChangeEmail", areaName: "OrchardCore.Users", pattern: ChangeEmailPath, defaults: new { controller = "ChangeEmail", action = "Index" } ); routes.MapAreaControllerRoute( name: "ChangeEmailConfirmation", areaName: "OrchardCore.Users", pattern: ChangeEmailConfirmationPath, defaults: new { controller = "ChangeEmail", action = "ChangeEmailConfirmation" } ); } public override void ConfigureServices(IServiceCollection services) { services.AddScoped<INavigationProvider, ChangeEmailAdminMenu>(); services.AddScoped<IDisplayDriver<ISite>, ChangeEmailSettingsDisplayDriver>(); } } [Feature("OrchardCore.Users.Registration")] public class RegistrationStartup : StartupBase { private const string RegisterPath = "Register"; static RegistrationStartup() { TemplateContext.GlobalMemberAccessStrategy.Register<ConfirmEmailViewModel>(); } public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { routes.MapAreaControllerRoute( name: "Register", areaName: "OrchardCore.Users", pattern: RegisterPath, defaults: new { controller = "Registration", action = "Register" } ); } public override void ConfigureServices(IServiceCollection services) { services.AddScoped<INavigationProvider, RegistrationAdminMenu>(); services.AddScoped<IDisplayDriver<ISite>, RegistrationSettingsDisplayDriver>(); } } [Feature("OrchardCore.Users.ResetPassword")] public class ResetPasswordStartup : StartupBase { private const string ForgotPasswordPath = "ForgotPassword"; private const string ForgotPasswordConfirmationPath = "ForgotPasswordConfirmation"; private const string ResetPasswordPath = "ResetPassword"; private const string ResetPasswordConfirmationPath = "ResetPasswordConfirmation"; static ResetPasswordStartup() { TemplateContext.GlobalMemberAccessStrategy.Register<LostPasswordViewModel>(); } public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { routes.MapAreaControllerRoute( name: "ForgotPassword", areaName: "OrchardCore.Users", pattern: ForgotPasswordPath, defaults: new { controller = "ResetPassword", action = "ForgotPassword" } ); routes.MapAreaControllerRoute( name: "ForgotPasswordConfirmation", areaName: "OrchardCore.Users", pattern: ForgotPasswordConfirmationPath, defaults: new { controller = "ResetPassword", action = "ForgotPasswordConfirmation" } ); routes.MapAreaControllerRoute( name: "ResetPassword", areaName: "OrchardCore.Users", pattern: ResetPasswordPath, defaults: new { controller = "ResetPassword", action = "ResetPassword" } ); routes.MapAreaControllerRoute( name: "ResetPasswordConfirmation", areaName: "OrchardCore.Users", pattern: ResetPasswordConfirmationPath, defaults: new { controller = "ResetPassword", action = "ResetPasswordConfirmation" } ); } public override void ConfigureServices(IServiceCollection services) { services.AddScoped<INavigationProvider, ResetPasswordAdminMenu>(); services.AddScoped<IDisplayDriver<ISite>, ResetPasswordSettingsDisplayDriver>(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40) using System.Numerics; #endif using System.Text; namespace Newtonsoft.Json.Serialization { internal class TraceJsonWriter : JsonWriter { private readonly JsonWriter _innerWriter; private readonly JsonTextWriter _textWriter; private readonly StringWriter _sw; public TraceJsonWriter(JsonWriter innerWriter) { _innerWriter = innerWriter; _sw = new StringWriter(CultureInfo.InvariantCulture); _textWriter = new JsonTextWriter(_sw); _textWriter.Formatting = Formatting.Indented; _textWriter.Culture = innerWriter.Culture; _textWriter.DateFormatHandling = innerWriter.DateFormatHandling; _textWriter.DateFormatString = innerWriter.DateFormatString; _textWriter.DateTimeZoneHandling = innerWriter.DateTimeZoneHandling; _textWriter.FloatFormatHandling = innerWriter.FloatFormatHandling; } public string GetJson() { return _sw.ToString(); } public override void WriteValue(decimal value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(bool value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(byte value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(byte? value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(char value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(byte[] value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(DateTime value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } #if !NET20 public override void WriteValue(DateTimeOffset value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } #endif public override void WriteValue(double value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteUndefined() { _textWriter.WriteUndefined(); _innerWriter.WriteUndefined(); base.WriteUndefined(); } public override void WriteNull() { _textWriter.WriteNull(); _innerWriter.WriteNull(); base.WriteUndefined(); } public override void WriteValue(float value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(Guid value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(int value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(long value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(object value) { #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40) if (value is BigInteger) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); InternalWriteValue(JsonToken.Integer); } else #endif { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } } public override void WriteValue(sbyte value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(short value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(string value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(TimeSpan value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(uint value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(ulong value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(Uri value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(ushort value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteWhitespace(string ws) { _textWriter.WriteWhitespace(ws); _innerWriter.WriteWhitespace(ws); base.WriteWhitespace(ws); } //protected override void WriteValueDelimiter() //{ // _textWriter.WriteValueDelimiter(); // _innerWriter.WriteValueDelimiter(); // base.WriteValueDelimiter(); //} //protected override void WriteIndent() //{ // base.WriteIndent(); //} public override void WriteComment(string text) { _textWriter.WriteComment(text); _innerWriter.WriteComment(text); base.WriteComment(text); } //public override void WriteEnd() //{ // _textWriter.WriteEnd(); // _innerWriter.WriteEnd(); // base.WriteEnd(); //} //protected override void WriteEnd(JsonToken token) //{ // base.WriteEnd(token); //} public override void WriteStartArray() { _textWriter.WriteStartArray(); _innerWriter.WriteStartArray(); base.WriteStartArray(); } public override void WriteEndArray() { _textWriter.WriteEndArray(); _innerWriter.WriteEndArray(); base.WriteEndArray(); } public override void WriteStartConstructor(string name) { _textWriter.WriteStartConstructor(name); _innerWriter.WriteStartConstructor(name); base.WriteStartConstructor(name); } public override void WriteEndConstructor() { _textWriter.WriteEndConstructor(); _innerWriter.WriteEndConstructor(); base.WriteEndConstructor(); } public override void WritePropertyName(string name) { _textWriter.WritePropertyName(name); _innerWriter.WritePropertyName(name); base.WritePropertyName(name); } public override void WritePropertyName(string name, bool escape) { _textWriter.WritePropertyName(name, escape); _innerWriter.WritePropertyName(name, escape); // method with escape will error base.WritePropertyName(name); } public override void WriteStartObject() { _textWriter.WriteStartObject(); _innerWriter.WriteStartObject(); base.WriteStartObject(); } public override void WriteEndObject() { _textWriter.WriteEndObject(); _innerWriter.WriteEndObject(); base.WriteEndObject(); } public override void WriteRaw(string json) { _textWriter.WriteRaw(json); _innerWriter.WriteRaw(json); base.WriteRaw(json); } public override void WriteRawValue(string json) { _textWriter.WriteRawValue(json); _innerWriter.WriteRawValue(json); base.WriteRawValue(json); } //protected override void WriteIndentSpace() //{ // _textWriter.WriteIndentSpace(); // _innerWriter.WriteIndentSpace(); // base.WriteIndentSpace(); //} public override void Close() { _textWriter.Close(); _innerWriter.Close(); base.Close(); } public override void Flush() { _textWriter.Flush(); _innerWriter.Flush(); } } }
using System; using System.Web; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using gov.va.medora.mdo; using gov.va.medora.mdo.dao; using gov.va.medora.mdo.api; using gov.va.medora.mdws.dto; using gov.va.medora.mdo.dao.oracle; using gov.va.medora.mdo.dao.sql.cdw; namespace gov.va.medora.mdws { public class PatientLib { MySession mySession; public PatientLib(MySession mySession) { this.mySession = mySession; } // this function makes a call to cdwLookup - if results are returned, it replaces each PatientTO with an empty object so as not to return PII public PatientArray cdwLookupSlim(string password, string pid) { PatientArray result = cdwLookup(password, pid); if (result.fault != null) { return result; } else { for (int i = 0; i < result.patients.Length; i++) { result.patients[i] = new PatientTO(); } } return result; } // this function makes a call to cdwLookup - if results are returned, it replaces each PatientTO with an empty object so as not to return PII public PatientArray cdwLookupSlimWithAccount(string domain, string username, string password, string pid) { PatientArray result = cdwLookup(domain, username, password, pid); if (result.fault != null) { return result; } else { for (int i = 0; i < result.patients.Length; i++) { result.patients[i] = new PatientTO(); } } return result; } public PatientArray cdwLookup(string password, string pid) { return cdwLookup(mySession.MdwsConfiguration.CdwSqlConfig.RunasUser.Domain, mySession.MdwsConfiguration.CdwSqlConfig.RunasUser.UserName, mySession.MdwsConfiguration.CdwSqlConfig.RunasUser.Pwd, pid); } public PatientArray cdwLookup(string domain, string username, string password, string pid) { PatientArray result = new PatientArray(); if (String.IsNullOrEmpty(pid)) { result.fault = new FaultTO("Missing patient ID"); } if (result.fault != null) { return result; } try { using (CdwConnection cdwCxn = new CdwConnection( new DataSource() { ConnectionString = mySession.MdwsConfiguration.CdwSqlConfig.ConnectionString }, new User() { Domain = domain, UserName = username, Pwd = password })) { result = new PatientArray(new CdwPatientDao(cdwCxn).match(pid)); } } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public TaggedTextArray getCorrespondingIds(string sitecode, string patientId, string idType) { TaggedTextArray result = new TaggedTextArray(); if (mySession == null || mySession.ConnectionSet == null || mySession.ConnectionSet.BaseConnection == null || !mySession.ConnectionSet.HasBaseConnection || !mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("No connections", "Need to login?"); } else if (!String.IsNullOrEmpty(sitecode)) { result.fault = new FaultTO("Lookup by a specific sitecode is not currently supported - please leave this field empty and MDWS will query the base connection"); } else if (String.IsNullOrEmpty(patientId)) { result.fault = new FaultTO("Missing patient ID"); } else if (String.IsNullOrEmpty(idType)) { result.fault = new FaultTO("Missing ID type"); } else if (!String.Equals("DFN", idType, StringComparison.CurrentCultureIgnoreCase) && !String.Equals("ICN", idType, StringComparison.CurrentCultureIgnoreCase)) { result.fault = new FaultTO("Lookup by " + idType + " is not currently supported"); } if (result.fault != null) { return result; } if (String.IsNullOrEmpty(sitecode)) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { if (String.Equals("ICN", idType, StringComparison.CurrentCultureIgnoreCase)) { PatientApi patientApi = new PatientApi(); string localPid = patientApi.getLocalPid(mySession.ConnectionSet.BaseConnection, patientId); result = new TaggedTextArray(patientApi.getTreatingFacilityIds(mySession.ConnectionSet.BaseConnection, localPid)); } else if (String.Equals("DFN", idType, StringComparison.CurrentCultureIgnoreCase)) { PatientApi patientApi = new PatientApi(); result = new TaggedTextArray(patientApi.getTreatingFacilityIds(mySession.ConnectionSet.BaseConnection, patientId)); } } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public TaggedPatientArray match(string sitecode, string target) { TaggedPatientArray result = new TaggedPatientArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (sitecode == "") { result.fault = new FaultTO("Missing sitecode"); } if (result.fault != null) { return result; } return match(mySession.ConnectionSet.getConnection(sitecode), target); } internal TaggedPatientArray match(AbstractConnection cxn, string target) { TaggedPatientArray result = new TaggedPatientArray(); if (!cxn.IsConnected) { result = new TaggedPatientArray("Connection not open"); } else if (cxn.DataSource.Uid == "") { result = new TaggedPatientArray("No user authorized for lookup"); } else if (target == "") { result.fault = new FaultTO("Missing target"); } if (result.fault != null) { return result; } try { PatientApi patientApi = new PatientApi(); Patient[] matches = patientApi.match(cxn, target); result = new TaggedPatientArray(cxn.DataSource.SiteId.Id, matches); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } //internal TaggedPatientArrays matchLocal(Connection cxn, string target) //{ // TaggedPatientArrays result = new TaggedPatientArrays(); // TaggedPatientArray matches = match(cxn, target); // if (matches.fault != null) // { // result.fault = matches.fault; // } // else // { // result.count = 1; // result.arrays = new TaggedPatientArray[] { matches }; // } // return result; //} public TaggedPatientArrays match(string target) { TaggedPatientArrays result = new TaggedPatientArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (String.IsNullOrEmpty(target)) { result.fault = new FaultTO("Missing target"); } if (result.fault != null) { return result; } try { PatientApi api = new PatientApi(); IndexedHashtable t = api.match(mySession.ConnectionSet, target); return new TaggedPatientArrays(t); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedPatientArray matchByNameCityState(string name, string city, string stateAbbr) { return matchByNameCityState(mySession.ConnectionSet.BaseConnection, name, city, stateAbbr); } public TaggedPatientArray matchByNameCityState(string sitecode, string name, string city, string stateAbbr) { return matchByNameCityState(mySession.ConnectionSet.getConnection(sitecode), name, city, stateAbbr); } internal TaggedPatientArray matchByNameCityState(AbstractConnection cxn, string name, string city, string stateAbbr) { TaggedPatientArray result = new TaggedPatientArray(); if (name == "") { result.fault = new FaultTO("Missing name"); } else if (city == "") { result.fault = new FaultTO("Missing city"); } else if (stateAbbr == "") { result.fault = new FaultTO("Missing stateAbbr"); } else if (!State.isValidAbbr(stateAbbr)) { result.fault = new FaultTO("Invalid stateAbbr"); } if (result.fault != null) { return result; } try { PatientApi api = new PatientApi(); Patient[] matches = api.matchByNameCityState(cxn, name, city, stateAbbr); result = new TaggedPatientArray(cxn.DataSource.SiteId.Id, matches); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedPatientArrays matchByNameCityStateMS(string name, string city, string stateAbbr) { TaggedPatientArrays result = new TaggedPatientArrays(); string msg = MdwsUtils.isAuthorizedConnection(mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } if (name == "") { result.fault = new FaultTO("Missing name"); } else if (city == "") { result.fault = new FaultTO("Missing city"); } else if (stateAbbr == "") { result.fault = new FaultTO("Missing stateAbbr"); } else if (!State.isValidAbbr(stateAbbr)) { result.fault = new FaultTO("Invalid stateAbbr"); } if (result.fault != null) { return result; } try { PatientApi api = new PatientApi(); IndexedHashtable matches = api.matchByNameCityState(mySession.ConnectionSet, name, city, stateAbbr); result = new TaggedPatientArrays(matches); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedPatientArray getPatientsByWard(string wardId) { return getPatientsByWard(null,wardId); } public TaggedPatientArray getPatientsByWard(string sitecode, string wardId) { TaggedPatientArray result = new TaggedPatientArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (wardId == "") { result.fault = new FaultTO("Missing wardId"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); PatientApi patientApi = new PatientApi(); Patient[] matches = patientApi.getPatientsByWard(cxn, wardId); result = new TaggedPatientArray(sitecode, matches); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedPatientArray getPatientsByClinic(string clinicId) { return getPatientsByClinic(null, clinicId, "", ""); } public TaggedPatientArray getPatientsByClinic(string clinicId, string fromDate, string toDate) { return getPatientsByClinic("", clinicId, fromDate, toDate); } public TaggedPatientArray getPatientsByClinic(string sitecode, string clinicId, string fromDate, string toDate) { TaggedPatientArray result = new TaggedPatientArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (clinicId == "") { result.fault = new FaultTO("Missing clinicId"); } if (result.fault != null) { return result; } if (String.IsNullOrEmpty(fromDate)) { fromDate = "T"; } if (String.IsNullOrEmpty(toDate)) { toDate = "T"; } if (String.IsNullOrEmpty(sitecode)) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); PatientApi patientApi = new PatientApi(); Patient[] matches = patientApi.getPatientsByClinic(cxn, clinicId, fromDate, toDate); result = new TaggedPatientArray(sitecode, matches); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedPatientArray getPatientsBySpecialty(string specialtyId) { return getPatientsBySpecialty(null, specialtyId); } public TaggedPatientArray getPatientsBySpecialty(string sitecode, string specialtyId) { TaggedPatientArray result = new TaggedPatientArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (specialtyId == "") { result.fault = new FaultTO("Missing specialtyId"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); PatientApi patientApi = new PatientApi(); Patient[] matches = patientApi.getPatientsBySpecialty(cxn, specialtyId); result = new TaggedPatientArray(sitecode, matches); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedPatientArray getPatientsByTeam(string teamId) { return getPatientsByTeam(null, teamId); } public TaggedPatientArray getPatientsByTeam(string sitecode, string teamId) { TaggedPatientArray result = new TaggedPatientArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (teamId == "") { result.fault = new FaultTO("Missing teamId"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); PatientApi patientApi = new PatientApi(); Patient[] matches = patientApi.getPatientsByTeam(cxn, teamId); result = new TaggedPatientArray(sitecode, matches); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedPatientArray getPatientsByProvider(string duz) { return getPatientsByProvider(null, duz); } public TaggedPatientArray getPatientsByProvider(string sitecode, string duz) { TaggedPatientArray result = new TaggedPatientArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (duz == "") { result.fault = new FaultTO("Missing duz"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); PatientApi patientApi = new PatientApi(); Patient[] matches = patientApi.getPatientsByProvider(cxn, duz); result = new TaggedPatientArray(sitecode, matches); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public PatientTO select(string localPid) { return select(null, localPid); } public PatientTO select(string sitecode, string localPid) { PatientTO result = new PatientTO(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (String.IsNullOrEmpty(localPid)) { result.fault = new FaultTO("Missing local PID"); } if (result.fault != null) { return result; } if (String.IsNullOrEmpty(sitecode)) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); PatientApi api = new PatientApi(); Patient p = api.select(cxn, localPid); result = new PatientTO(p); mySession.Patient = p; mySession.ConnectionSet.getConnection(sitecode).Pid = result.localPid; if (p.Confidentiality.Key > 0) { if (p.Confidentiality.Key == 1) { // do nothing here - M code takes care of this per documentation } else if (p.Confidentiality.Key == 2) { api.issueConfidentialityBulletin(mySession.ConnectionSet); } else if (p.Confidentiality.Key > 2) { mySession.ConnectionSet.disconnectAll(); throw new ApplicationException(p.Confidentiality.Value); } } } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedOefOifArray getOefOif() { TaggedOefOifArray result = new TaggedOefOifArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, null); if (msg != "OK") { result.fault = new FaultTO(msg); } if (result.fault != null) { return result; } string sitecode = mySession.ConnectionSet.BaseSiteId; try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); PatientApi api = new PatientApi(); OEF_OIF[] rex = api.getOefOif(cxn); result = new TaggedOefOifArray(sitecode, rex); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } //public Patient findAtSite200(string ssn) //{ // MySession site200Session = new MySession(); // try // { // // Get a connection // Site site = (Site)mySession.SiteTable.Sites["200"]; // DataSource dataSource = site.getDataSourceByModality("HIS"); // ConnectionApi cxnApi = new ConnectionApi(dataSource); // site200Session.cxn = cxnApi.MdoConnection; // site200Session.cxn.connect(); // // Visit site 200 as DoD user // User dodUser = new User(); // dodUser.SSN = new SocSecNum("123456789"); // dodUser.Name = new PersonName("DEPARTMENT OF DEFENSE,USER"); // dodUser.LogonSiteUid = "31066"; // dodUser.LogonSiteId = new KeyValuePair<string, string>("200", "Site200"); // UserApi userApi = new UserApi(); // string duz = userApi.visit(site200Session.cxn, dodUser, MdwsConstants.CAPRI_CONTEXT, true); // // Do the lookup // PatientApi patApi = new PatientApi(); // Patient[] matches = patApi.match(site200Session.cxn, ssn); // // Process result // if (matches.Length == 0) // { // return null; // } // if (matches.Length > 1) // { // throw new Exception("Multiple matches to SSN"); // } // return patApi.select(site200Session.cxn, matches[0].LocalPid); // } // catch (Exception e) // { // throw e; // } // finally // { // // Disconnect // site200Session.cxn.disconnect(); // } //} //public Patient findAtVisn(string visnId, string ssn) //{ // MySession visnSession = new MySession(); // try // { // Site[] sites = MdwsUtils.parseSiteList(mySession.SiteTable, visnId); // ArrayList sources = new ArrayList(sites.Length); // for (int i = 0; i < sites.Length; i++) // { // for (int j = 0; j < sites[i].Sources.Length; j++) // { // if (sites[i].Sources[j].Protocol == "VISTA") // { // sources.Add(sites[i].Sources[j]); // } // } // } // ConnectionApi cxnApi = new ConnectionApi((DataSource[])sources.ToArray(typeof(DataSource))); // IndexedHashtable t = cxnApi.MultiSourceQuery.connect(); // visnSession.msq = cxnApi.MultiSourceQuery; // // Visit site 200 as DoD user // UserApi userApi = new UserApi(); // t = userApi.visit(visnSession.msq, mySession.user, MdwsConstants.CPRS_CONTEXT, true); // // Do the lookup // PatientApi patApi = new PatientApi(); // IndexedHashtable matches = patApi.match(visnSession.msq, ssn); // // Process result // for (int i = 0; i < matches.Count; i++) // { // Patient[] pa = (Patient[])matches.GetValue(i); // if (pa.Length == 0) // { // continue; // } // if (pa.Length > 1) // { // throw new Exception("Multiple matches from site " + (string)matches.GetKey(i)); // } // string sitecode = (string)matches.GetKey(i); // return patApi.select(visnSession.msq.getConnection(sitecode),pa[0].LocalPid); // } // return null; // } // catch (Exception e) // { // throw e; // } // finally // { // // Disconnect // visnSession.msq.disconnect(); // } //} //public Patient findAtVisns(string ssn) //{ // Patient result = null; // int visnIdx = 0; // do // { // Region r = (Region)mySession.SiteTable.Regions.GetByIndex(visnIdx++); // result = findAtVisn("v" + Convert.ToString(r.Id), ssn); // } // while (visnIdx < mySession.SiteTable.Regions.Count && result == null); // return result; //} //public Patient[] matchAtVisn(string visnId, string ssn) //{ // MySession visnSession = new MySession(); // try // { // Site[] sites = MdwsUtils.parseSiteList(mySession.SiteTable, visnId); // ArrayList sources = new ArrayList(sites.Length); // for (int i = 0; i < sites.Length; i++) // { // for (int j = 0; j < sites[i].Sources.Length; j++) // { // if (sites[i].Sources[j].Protocol == "VISTA") // { // sources.Add(sites[i].Sources[j]); // } // } // } // ConnectionApi cxnApi = new ConnectionApi((DataSource[])sources.ToArray(typeof(DataSource))); // IndexedHashtable t = cxnApi.MultiSourceQuery.connect(); // visnSession.msq = cxnApi.MultiSourceQuery; // // Visit site 200 as DoD user // UserApi userApi = new UserApi(); // t = userApi.visit(visnSession.msq, mySession.user, MdwsConstants.CPRS_CONTEXT, true); // // Do the lookup // PatientApi patApi = new PatientApi(); // IndexedHashtable matches = patApi.match(visnSession.msq, ssn); // // Process result // ArrayList lst = new ArrayList(); // for (int i = 0; i < matches.Count; i++) // { // Patient[] pa = (Patient[])matches.GetValue(i); // if (pa.Length == 0) // { // continue; // } // if (pa.Length > 1) // { // throw new Exception("Multiple matches from site " + (string)matches.GetKey(i)); // } // string sitecode = (string)matches.GetKey(i); // Patient p = patApi.select(visnSession.msq.getConnection(sitecode), pa[0].LocalPid); // p.LocalSiteId = sitecode; // lst.Add(p); // } // if (lst.Count == 0) // { // return null; // } // return (Patient[])lst.ToArray(typeof(Patient)); // } // catch (Exception e) // { // throw e; // } // finally // { // // Disconnect // visnSession.msq.disconnect(); // } //} //public Patient[] matchAtVisns(string ssn) //{ // ArrayList lst = new ArrayList(); // for (int visnIdx = 0; visnIdx < mySession.SiteTable.Regions.Count; visnIdx++) // { // Region r = (Region)mySession.SiteTable.Regions.GetByIndex(visnIdx); // if (r.Id > 23) // { // continue; // } // Patient[] p = matchAtVisn("v" + Convert.ToString(r.Id), ssn); // if (p != null) // { // for (int i = 0; i < p.Length; i++) // { // lst.Add(p[i]); // } // } // } // if (lst.Count == 0) // { // return null; // } // return (Patient[])lst.ToArray(typeof(Patient)); //} //public Patient findPatient(string ssn) //{ // Patient result = findAtSite200(ssn); // if (result != null) // { // return result; // } // return findAtVisns(ssn); //} //public IndexedHashtable matchAtSources(string ssn, int batchSize) //{ // IndexedHashtable result = new IndexedHashtable(); ; // int nSources = 0; // while (nSources < mySession.SiteTable.Sources.Count) // { // ArrayList srcLst = new ArrayList(batchSize); // int count = 0; // while (count < batchSize && nSources < mySession.SiteTable.Sources.Count) // { // DataSource src = (DataSource)mySession.SiteTable.Sources[nSources++]; // if (src.Protocol == "VISTA") // { // srcLst.Add(src); // count++; // } // } // if (srcLst.Count > 0) // { // ConnectionApi cxnApi = new ConnectionApi((DataSource[])srcLst.ToArray(typeof(DataSource))); // IndexedHashtable t = cxnApi.MultiSourceQuery.connect(); // // Visit site 200 as DoD user // UserApi userApi = new UserApi(); // t = userApi.visit(cxnApi.MultiSourceQuery, mySession.user, MdwsConstants.CPRS_CONTEXT, true); // // Do the lookup // PatientApi patApi = new PatientApi(); // IndexedHashtable matches = patApi.match(cxnApi.MultiSourceQuery, ssn); // mySession.msq = cxnApi.MultiSourceQuery; // // Process result // for (int i = 0; i < matches.Count; i++) // { // if (matches.GetValue(i).GetType().Name.EndsWith("Exception")) // { // //TBD: need to return exception here // continue; // } // Patient[] pa = (Patient[])matches.GetValue(i); // if (pa.Length == 0) // { // continue; // } // if (pa.Length > 1) // { // throw new Exception("Multiple matches from site " + (string)matches.GetKey(i)); // } // string sitecode = (string)matches.GetKey(i); // Patient p = patApi.select(cxnApi.MultiSourceQuery.getConnection(sitecode), pa[0].LocalPid); // p.LocalSiteId = sitecode; // result.Add(sitecode,p); // } // mySession.msq.disconnect(); // } // } // if (result.Count == 0) // { // return null; // } // return result; //} public PatientArray findPatient(string ssn) { return mpiLookup(ssn, "", "", "", "", "", ""); } //public PatientLocationTO locatePatient(string sitecode, string dfn) //{ // PatientLocationTO result = new PatientLocationTO(); // //string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); // //if (msg != "OK") // //{ // // result.fault = new FaultTO(msg); // //} // if (sitecode == "") // { // result.fault = new FaultTO("Missing sitecode"); // } // else if (dfn == "") // { // result.fault = new FaultTO("Missing DFN"); // } // if (result.fault != null) // { // return result; // } // try // { // // get Vista // Site site = mySession.SiteTable.getSite(sitecode); // if (site == null) // { // result.fault = new FaultTO("Invalide sitecode"); // return result; // } // DataSource vista = site.getDataSourceByModality("HIS"); // // connect to site // ConnectionApi cxnApi = new ConnectionApi(vista); // cxnApi.connect(); // // visit site // UserApi userApi = new UserApi(); // string duz = userApi.visit(cxnApi.MdoConnection, mySession.user, MdwsConstants.CPRS_CONTEXT, true); // // get all sites // PatientApi patientApi = new PatientApi(); // mySession.Patient = patientApi.select(cxnApi.MdoConnection, dfn); // if (mySession.Patient.DeceasedDate != "") // { // result.deceasedDate = mySession.Patient.DeceasedDate; // return result; // } // IndexedHashtable selectedPatients = null; // // catch here if this is the only site // if (mySession.Patient.MpiPid == "") // { // selectedPatients = new IndexedHashtable(1); // selectedPatients.Add(mySession.Patient.LocalPid, mySession.Patient); // cxnApi.MultiSourceQuery = new MultiSourceQuery(new DataSource[] { vista }); // } // else // { // // close cxn // cxnApi.disconnect(); // // visit all sites // ArrayList lst = new ArrayList(mySession.Patient.SiteIDs.Length); // for (int i = 0; i < mySession.Patient.SiteIDs.Length; i++) // { // site = mySession.SiteTable.getSite(mySession.Patient.SiteIDs[i].Id); // if (site == null) // { // continue; // } // DataSource ds = site.getDataSourceByModality("HIS"); // if (ds.Protocol == "VISTA") // { // lst.Add(ds); // } // } // DataSource[] sources = (DataSource[])lst.ToArray(typeof(DataSource)); // cxnApi = new ConnectionApi(sources); // cxnApi.MultiSourceQuery.connect(); // mySession.msq = cxnApi.MultiSourceQuery; // IndexedHashtable t = userApi.visit(mySession.msq, mySession.user, MdwsConstants.CPRS_CONTEXT, true); // // set DFNs // t = patientApi.setLocalPids(mySession.msq, mySession.Patient.MpiPid); // // select patient // selectedPatients = patientApi.select(mySession.msq); // for (int i = 0; i < selectedPatients.Count; i++) // { // Patient p = (Patient)selectedPatients.GetValue(i); // if (p.DeceasedDate != "") // { // result.deceasedDate = p.DeceasedDate; // return result; // } // } // } // // get appointments // EncounterApi encounterApi = new EncounterApi(); // IndexedHashtable appts = encounterApi.getFutureAppointments(mySession.msq); // // get contacts // IndexedHashtable contacts = patientApi.getPatientAssociates(mySession.msq); // // close cxns // cxnApi.MultiSourceQuery.disconnect(); // // check for current inpatient // for (int i = 0; i < selectedPatients.Count; i++) // { // Patient p = (Patient)selectedPatients.GetValue(i); // if (p.IsInpatient) // { // result.medicalCenter = new SiteTO(); // result.medicalCenter.sitecode = (string)selectedPatients.GetKey(i); // result.medicalCenter.name = mySession.SiteTable.getSite(result.medicalCenter.sitecode).Name; // result.inpatientLocation = new HospitalLocationTO(p.Location); // } // } // // set appointments // result.futureAppointments = new TaggedAppointmentArrays(appts); // // and contacts // result.contacts = processContacts(contacts); // return result; // } // catch (Exception e) // { // result.fault = new FaultTO(e.Message); // } // return result; //} internal PatientAssociateArray processContacts(IndexedHashtable t) { ArrayList lst = new ArrayList(); for (int siteIdx = 0; siteIdx < t.Count; siteIdx++) { PatientAssociate[] pas = (PatientAssociate[])t.GetValue(siteIdx); for (int i = 0; i < pas.Length; i++) { lst.Add(pas[i]); } } return new PatientAssociateArray(lst); } /// <summary> /// Lookup a patient in the Medora Patient Index. This can be a stateless call (i.e. not currently required to login) /// </summary> /// <param name="SSN">Patient SSN (required)</param> /// <param name="lastName">Patient Last Name (optional)</param> /// <param name="firstName">Patient First Name (optional)</param> /// <param name="middleName">Patient Middle Name (optional)</param> /// <param name="nameSuffix">Patient Name Suffix (optional)</param> /// <param name="DOB">Patient Date Of Birth (optional)</param> /// <param name="gender">Patient Gender (not currently used for matching)</param> /// <returns>PatientArray of matches</returns> public PatientArray mpiLookup( string SSN, string lastName, string firstName, string middleName, string nameSuffix, string DOB, string gender) { PatientArray result = new PatientArray(); if (String.IsNullOrEmpty(SSN)) { result.fault = new FaultTO("Missing SSN"); } else if (!SocSecNum.isValid(SSN)) { result.fault = new FaultTO("Invalid SSN"); } // hard coded the cxn string since our MPI database should really be a service for everyone //else if (mySession == null || mySession.MdwsConfiguration == null || mySession.MdwsConfiguration.SqlConfiguration == null || // String.IsNullOrEmpty(mySession.MdwsConfiguration.SqlConfiguration.ConnectionString)) //{ // result.fault = new FaultTO("Your MDWS configuration does not contain a valid SQL connection string"); //} if (result.fault != null) { return result; } Patient patient = new Patient(); patient.SSN = new SocSecNum(SSN); if (!String.IsNullOrEmpty(lastName) && !String.IsNullOrEmpty(firstName)) { patient.Name = new PersonName(); patient.Name.Lastname = lastName; patient.Name.Firstname = firstName; if(!String.IsNullOrEmpty(middleName)) { patient.Name.Firstname = firstName + " " + middleName; } patient.Name.Suffix = nameSuffix; } if(!String.IsNullOrEmpty(DOB)) { patient.DOB = DOB; } // SQL query doesn't care about gender so just ignore it for now //patient.Gender = gender; try { PatientApi api = new PatientApi(); Patient[] matches = null; Site site = mySession.SiteTable.getSite("500"); matches = api.mpiMatch(site.Sources[0], SSN); //if (patient.Name != null && !String.IsNullOrEmpty(patient.Name.LastNameFirst)) // match all patient info if present //{ // matches = api.mpiLookup(patient); //} //else // otherwise just match on SSN //{ // matches = api.mpiLookup(SSN); //} result = new PatientArray(matches); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public PatientArray mpiMatchSSN(string ssn) { PatientArray result = new PatientArray(); if (!SocSecNum.isValid(ssn)) { result.fault = new FaultTO("Invalid SSN"); } if (result.fault != null) { return result; } try { PatientApi api = new PatientApi(); Site site = mySession.SiteTable.getSite("500"); Patient[] p = api.mpiMatch(site.Sources[0], ssn); addHomeData(p); result = new PatientArray(p); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } internal void addHomeData(Patient[] patients) { for (int i = 0; i < patients.Length; i++) { addHomeData(patients[i]); } } //internal void addHomeData(Patient[] patients) //{ // for (int i = 0; i < patients.Length; i++) // { // Site site = mySession.SiteTable.getSite(patients[i].CmorSiteId); // DataSource src = site.getDataSourceByModality("HIS"); // ConnectionApi cxnApi = new ConnectionApi(src); // cxnApi.connect(); // UserApi userApi = new UserApi(); // string duz = userApi.visit(cxnApi.MdoConnection, mySession.user, MdwsConstants.CPRS_CONTEXT, true); // PatientApi patientApi = new PatientApi(); // patients[i].LocalPid = patientApi.getLocalPid(cxnApi.MdoConnection, patients[i].MpiPid); // patientApi.addHomeDate(cxnApi.MdoConnection, patients[i]); // cxnApi.disconnect(); // } //} internal void addHomeData(Patient patient) { if (patient == null) { return; } try { Site site = mySession.SiteTable.getSite(patient.CmorSiteId); DataSource src = site.getDataSourceByModality("HIS"); MySession newMySession = new MySession(mySession.FacadeName); AccountLib accountLib = new AccountLib(newMySession); UserTO visitUser = accountLib.visitAndAuthorize("Good players are always lucky", patient.CmorSiteId, mySession.ConnectionSet.BaseConnection.DataSource.SiteId.Id, mySession.User.Name.LastNameFirst, mySession.User.Uid, mySession.User.SSN.toString(), "OR CPRS GUI CHART"); PatientApi patientApi = new PatientApi(); patient.LocalPid = patientApi.getLocalPid(newMySession.ConnectionSet.BaseConnection, patient.MpiPid); patientApi.addHomeDate(newMySession.ConnectionSet.BaseConnection, patient); newMySession.ConnectionSet.BaseConnection.disconnect(); } catch (Exception) { // just pass back patient unchanged } } internal Patient getHomeData(Patient patient) { PatientApi api = new PatientApi(); api.addHomeDate(mySession.ConnectionSet.BaseConnection, patient); return patient; } public TaggedPatientAssociateArray getPatientAssociates(string dfn) { return getPatientAssociates(mySession.ConnectionSet.BaseConnection, dfn); } public TaggedPatientAssociateArray getPatientAssociates(string sitecode, string dfn) { return getPatientAssociates(mySession.ConnectionSet.getConnection(sitecode), dfn); } internal TaggedPatientAssociateArray getPatientAssociates(AbstractConnection cxn, string dfn) { TaggedPatientAssociateArray result = new TaggedPatientAssociateArray(); if (dfn == "") { result.fault = new FaultTO("Missing dfn"); } if (result.fault != null) { return result; } try { PatientApi patientApi = new PatientApi(); PatientAssociate[] pas = patientApi.getPatientAssociates(cxn, dfn); result = new TaggedPatientAssociateArray(cxn.DataSource.SiteId.Id, pas); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedPatientAssociateArrays getPatientAssociatesMS() { TaggedPatientAssociateArrays result = new TaggedPatientAssociateArrays(); if (result.fault != null) { return result; } try { PatientApi api = new PatientApi(); IndexedHashtable t = api.getPatientAssociates(mySession.ConnectionSet); return new TaggedPatientAssociateArrays(t); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedTextArray getConfidentiality() { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { PatientApi api = new PatientApi(); result = new TaggedTextArray(api.getConfidentiality(mySession.ConnectionSet)); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray issueConfidentialityBulletin() { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { PatientApi api = new PatientApi(); result = new TaggedTextArray(api.issueConfidentialityBulletin(mySession.ConnectionSet)); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TextTO getLocalPid(string mpiPid) { return getLocalPid(null, mpiPid); } public TextTO getLocalPid(string sitecode, string mpiPid) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (mpiPid == "") { result.fault = new FaultTO("Missing mpiPid"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); PatientApi api = new PatientApi(); string localPid = api.getLocalPid(cxn, mpiPid); result = new TextTO(localPid); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } /// <summary> /// Make a patient inquiry call (address, contact numbers, NOK, etc. information) /// </summary> /// <returns>TextTO with selected patient inquiry text</returns> public TextTO patientInquiry() { TextTO result = new TextTO(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (String.IsNullOrEmpty(mySession.ConnectionSet.getConnection(mySession.ConnectionSet.BaseSiteId).Pid)) { result.fault = new FaultTO("Need to select patient"); } if (result.fault != null) { return result; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(mySession.ConnectionSet.BaseSiteId); string selectedPatient = cxn.Pid; PatientApi api = new PatientApi(); string resultText = api.patientInquiry(cxn, selectedPatient); result = new TextTO(resultText); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } //public PatientArray pcsMatch(string ssn) //{ // PatientArray result = new PatientArray(); // if (mySession == null || mySession.cxnMgr == null || mySession.cxnMgr.LoginConnection == null || !mySession.cxnMgr.isAuthorized) // { // result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); // } // if (result.fault != null) // { // return result; // } // try // { // PatientApi api = new PatientApi(); // result = new PatientArray(api.pcsMatch(ssn)); // } // catch (Exception e) // { // result.fault = new FaultTO(e); // } // return result; //} public PatientTO getDemographics() { PatientTO result = new PatientTO(); string msg = MdwsUtils.isAuthorizedConnection(mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (String.IsNullOrEmpty(mySession.ConnectionSet.BaseConnection.Pid) || mySession.Patient == null) { result.fault = new FaultTO("Need to select patient"); } if (result.fault != null) { return result; } try { result = new PatientTO(getHomeData(mySession.Patient)); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } /// <summary> /// Given a national identifier find the patient's sites /// </summary> /// <param name="mpiPid"></param> /// <returns></returns> public TaggedTextArray getPatientSitesByMpiPid(string mpiPid) { TaggedTextArray result = new TaggedTextArray(); if (String.IsNullOrEmpty(mpiPid)) { result.fault = new FaultTO("Missing mpiPid"); } if (result.fault != null) { return result; } // Temporary visit to site 200 for initial lookup AccountLib acctLib = new AccountLib(mySession); result = acctLib.visitDoD(null); if (result.fault != null) { return result; } TextTO localPid = getLocalPid(mpiPid); if (localPid.fault != null) { result.fault = localPid.fault; return result; } if (String.IsNullOrEmpty(localPid.text)) { result.fault = new FaultTO("Empty DFN returned from VistA"); return result; } PatientApi patientApi = new PatientApi(); StringDictionary siteIds = patientApi.getRemoteSiteIds(mySession.ConnectionSet.BaseConnection, localPid.text); mySession.ConnectionSet.disconnectAll(); result = new TaggedTextArray(siteIds); // Fake a logged in user... //mySession.user = new User(); //mySession.user.LogonSiteId = new KeyValuePair<string, string>("506", "Ann Arbor, MI"); //mySession.user.LogonSiteUid = ""; //mySession.user.Name = new PersonName(""); //string[] sitelists = new string[] //{ // "V11,V2,V4", // "V5,V6,V7", // "V8,V9,V10", // "V12,V15", // "V16,V17,V18", // //"V19,V20,612,662,570,459,640,654", // exclude Manila from V21 // "V3,V22,V23,V11" //}; //ConnectionLib cxnLib = new ConnectionLib(mySession); //try //{ // for (int siteIdx = 0; siteIdx < sitelists.Length; siteIdx++) // { // TaggedTextArray sites = cxnLib.visitSites("", sitelists[siteIdx], MdwsConstants.CPRS_CONTEXT); // if (sites.fault != null) // { // result.fault = sites.fault; // return result; // } // PatientApi patientApi = new PatientApi(); // MultiSourceQuery msq = new MultiSourceQuery(mySession.cxnMgr.Connections); // IndexedHashtable t = patientApi.getLocalPids(msq, mpiPid); // for (int i = 0; i < t.Count; i++) // { // if ((string)t.GetValue(i) != "") // { // Connection c = mySession.cxnMgr.getConnection((string)t.GetKey(i)); // StringDictionary siteIds = patientApi.getRemoteSiteIds(c, (string)t.GetValue(i)); // return new TaggedTextArray(siteIds); // } // } // } //} //catch (Exception ex) //{ // result.fault = new FaultTO(ex); //} //finally //{ // if (mySession.cxnMgr != null) // { // mySession.cxnMgr.disconnect(); // } //} return result; } public PatientArray nptLookup( string SSN, string lastName, string firstName, string middleName, string nameSuffix, string DOB, string gender) { PatientArray result = new PatientArray(); if (String.IsNullOrEmpty(SSN)) { result.fault = new FaultTO("Must supply SSN"); } else if (!SocSecNum.isValid(SSN)) { result.fault = new FaultTO("Invalid SSN"); } if (result.fault != null) { return result; } try { PatientApi api = new PatientApi(); Patient[] patients = api.nptMatch(SSN); result = new PatientArray(patients); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public TaggedText getPcpForPatient(string pid) { TaggedText result = new TaggedText(); string msg = MdwsUtils.isAuthorizedConnection(mySession); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (String.IsNullOrEmpty(pid)) { result.fault = new FaultTO("Empty PID"); } if (result.fault != null) { return result; } try { KeyValuePair<string, string> kvp = Patient.getPcpForPatient(mySession.ConnectionSet.BaseConnection, pid); result = new TaggedText(kvp); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public TaggedText getMOSReport(string appPwd, string EDIPI) { TaggedText result = new TaggedText(); if (String.IsNullOrEmpty(appPwd)) { result.fault = new FaultTO("Missing appPwd"); } // TBD - should we check this? must set to correct MHV password //else if (!String.Equals(appPwd, "MHV APP PWD")) //{ // result.fault = new FaultTO("Invalid appPwd"); //} else if (String.IsNullOrEmpty(EDIPI)) { result.fault = new FaultTO("Missing EDIPI"); } if (result.fault != null) { return result; } try { AbstractConnection cxn = new MdoOracleConnection(new DataSource() { ConnectionString = mySession.MdwsConfiguration.MosConnectionString }); PatientApi api = new PatientApi(); Patient p = new Patient() { EDIPI = EDIPI }; TextReport rpt = api.getMOSReport(cxn, p); result.text = rpt.Text; result.tag = "VADIR"; } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace Gate.Utils { // #if NET40 internal static class Net40Extensions { public static Task WriteAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancel = default(CancellationToken)) { cancel.ThrowIfCancellationRequested(); var tcs = new TaskCompletionSource<object>(); var sr = stream.BeginWrite(buffer, offset, count, ar => { if (ar.CompletedSynchronously) { return; } try { stream.EndWrite(ar); tcs.SetResult(null); } catch (Exception ex) { // Assume errors were caused by cancelation. if (cancel.IsCancellationRequested) { tcs.TrySetCanceled(); } tcs.SetException(ex); } }, null); if (sr.CompletedSynchronously) { try { stream.EndWrite(sr); tcs.SetResult(null); } catch (Exception ex) { // Assume errors were caused by cancelation. if (cancel.IsCancellationRequested) { tcs.TrySetCanceled(); } tcs.SetException(ex); } } return tcs.Task; } public static Task FlushAsync(this Stream stream) { stream.Flush(); return TaskHelpers.Completed(); } // Copy the source stream to the destination. The source is always disposed at the end, regardless of success or failure. // It is the consumers responsiblity to dispose of the destination. public static Task CopyToAsync(this Stream source, Stream destination, CancellationToken cancel = default(CancellationToken)) { return CopyToAsync(source, destination, null, cancel); } public static Task CopyToAsync(this Stream source, Stream destination, int? bytesRemaining, CancellationToken cancel = default(CancellationToken)) { if (source == null) { throw new ArgumentNullException("source"); } if (destination == null) { throw new ArgumentNullException("destination"); } int bufferSize = 64 * 1024; if (bytesRemaining.HasValue) { bufferSize = Math.Min(bytesRemaining.Value, bufferSize); } CopyOperation copy = new CopyOperation() { source = source, destination = destination, bytesRemaining = bytesRemaining, buffer = new byte[bufferSize], cancel = cancel, complete = new TaskCompletionSource<object>() }; return copy.Start(); } private class CopyOperation { internal Stream source; internal Stream destination; internal byte[] buffer; internal int? bytesRemaining; internal CancellationToken cancel; internal TaskCompletionSource<object> complete; internal Task Start() { ReadNextSegment(); return complete.Task; } private void Complete() { complete.TrySetResult(null); source.Dispose(); } private void Fail(Exception ex) { complete.TrySetException(ex); source.Dispose(); } private void ReadNextSegment() { // The natural end of the range. if (bytesRemaining.HasValue && bytesRemaining.Value <= 0) { Complete(); return; } try { cancel.ThrowIfCancellationRequested(); int readLength = buffer.Length; if (bytesRemaining.HasValue) { readLength = Math.Min(bytesRemaining.Value, readLength); } IAsyncResult async = source.BeginRead(buffer, 0, readLength, ReadCallback, null); if (async.CompletedSynchronously) { int read = source.EndRead(async); WriteToOutputStream(read); } } catch (Exception ex) { Fail(ex); } } private void ReadCallback(IAsyncResult async) { if (async.CompletedSynchronously) { return; } try { cancel.ThrowIfCancellationRequested(); int read = source.EndRead(async); WriteToOutputStream(read); } catch (Exception ex) { Fail(ex); } } private void WriteToOutputStream(int count) { if (bytesRemaining.HasValue) { bytesRemaining -= count; } // End of the source stream. if (count == 0) { Complete(); return; } try { cancel.ThrowIfCancellationRequested(); IAsyncResult async = destination.BeginWrite(buffer, 0, count, WriteCallback, null); if (async.CompletedSynchronously) { destination.EndWrite(async); ReadNextSegment(); } } catch (Exception ex) { Fail(ex); } } private void WriteCallback(IAsyncResult async) { if (async.CompletedSynchronously) { return; } try { cancel.ThrowIfCancellationRequested(); destination.EndWrite(async); ReadNextSegment(); } catch (Exception ex) { Fail(ex); } } } } // #endif }
using UnityEngine; using System.Collections; using System.Collections.Generic; [AddComponentMenu("2D Toolkit/Camera/tk2dCamera")] [ExecuteInEditMode] /// <summary> /// Maintains a screen resolution camera. /// Whole number increments seen through this camera represent one pixel. /// For example, setting an object to 300, 300 will position it at exactly that pixel position. /// </summary> public class tk2dCamera : MonoBehaviour { static int CURRENT_VERSION = 1; public int version = 0; [SerializeField] private tk2dCameraSettings cameraSettings = new tk2dCameraSettings(); /// <summary> /// The unity camera settings. /// Use this instead of camera.XXX to change parameters. /// </summary> public tk2dCameraSettings CameraSettings { get { return cameraSettings; } } /// <summary> /// Resolution overrides, if necessary. See <see cref="tk2dCameraResolutionOverride"/> /// </summary> public tk2dCameraResolutionOverride[] resolutionOverride = new tk2dCameraResolutionOverride[1] { tk2dCameraResolutionOverride.DefaultOverride }; /// <summary> /// The currently used override /// </summary> public tk2dCameraResolutionOverride CurrentResolutionOverride { get { tk2dCamera settings = SettingsRoot; Camera cam = ScreenCamera; float pixelWidth = cam.pixelWidth; float pixelHeight = cam.pixelHeight; #if UNITY_EDITOR if (settings.useGameWindowResolutionInEditor) { pixelWidth = settings.gameWindowResolution.x; pixelHeight = settings.gameWindowResolution.y; } else if (settings.forceResolutionInEditor) { pixelWidth = settings.forceResolution.x; pixelHeight = settings.forceResolution.y; } #endif tk2dCameraResolutionOverride currentResolutionOverride = null; if ((currentResolutionOverride == null || (currentResolutionOverride != null && (currentResolutionOverride.width != pixelWidth || currentResolutionOverride.height != pixelHeight)) )) { currentResolutionOverride = null; // find one if it matches the current resolution if (settings.resolutionOverride != null) { foreach (var ovr in settings.resolutionOverride) { if (ovr.Match((int)pixelWidth, (int)pixelHeight)) { currentResolutionOverride = ovr; break; } } } } return currentResolutionOverride; } } /// <summary> /// A tk2dCamera to inherit configuration from. /// All resolution and override settings will be pulled from the root inherited camera. /// This allows you to create a tk2dCamera prefab in your project or a master camera /// in the scene and guarantee that multiple instances of tk2dCameras referencing this /// will use exactly the same paramaters. /// </summary> public tk2dCamera InheritConfig { get { return inheritSettings; } set { if (inheritSettings != value) { inheritSettings = value; _settingsRoot = null; } } } [SerializeField] private tk2dCamera inheritSettings = null; /// <summary> /// Native resolution width of the camera. Override this in the inspector. /// Don't change this at runtime unless you understand the implications. /// </summary> public int nativeResolutionWidth = 960; /// <summary> /// Native resolution height of the camera. Override this in the inspector. /// Don't change this at runtime unless you understand the implications. /// </summary> public int nativeResolutionHeight = 640; [SerializeField] private Camera _unityCamera; private Camera UnityCamera { get { if (_unityCamera == null) { _unityCamera = GetComponent<Camera>(); if (_unityCamera == null) { Debug.LogError("A unity camera must be attached to the tk2dCamera script"); } } return _unityCamera; } } static tk2dCamera inst; /// <summary> /// Global instance, used by sprite and textmesh class to quickly find the tk2dCamera instance. /// </summary> public static tk2dCamera Instance { get { return inst; } } // Global instance of active tk2dCameras, used to quickly find cameras matching a particular layer. private static List<tk2dCamera> allCameras = new List<tk2dCamera>(); /// <summary> /// Returns the first camera in the list that can "see" this layer, or null if none can be found /// </summary> public static tk2dCamera CameraForLayer( int layer ) { int layerMask = 1 << layer; int cameraCount = allCameras.Count; for (int i = 0; i < cameraCount; ++i) { tk2dCamera cam = allCameras[i]; if ((cam.UnityCamera.cullingMask & layerMask) == layerMask) { return cam; } } return null; } /// <summary> /// Returns screen extents - top, bottom, left and right will be the extent of the physical screen /// Regardless of resolution or override /// </summary> public Rect ScreenExtents { get { return _screenExtents; } } /// <summary> /// Returns screen extents - top, bottom, left and right will be the extent of the native screen /// before it gets scaled and processed by overrides /// </summary> public Rect NativeScreenExtents { get { return _nativeScreenExtents; } } /// <summary> /// Enable/disable viewport clipping. /// ScreenCamera must be valid for it to be actually enabled when rendering. /// </summary> public bool viewportClippingEnabled = false; /// <summary> /// Viewport clipping region. /// </summary> public Vector4 viewportRegion = new Vector4(0, 0, 100, 100); /// <summary> /// Target resolution /// The target resolution currently being used. /// If displaying on a 960x640 display, this will be the number returned here, regardless of scale, etc. /// If the editor resolution is forced, the returned value will be the forced resolution. /// </summary> public Vector2 TargetResolution { get { return _targetResolution; } } Vector2 _targetResolution = Vector2.zero; /// <summary> /// Native resolution /// The native resolution of this camera. /// This is the native resolution of the camera before any scaling is performed. /// The resolution the game is set up to run at initially. /// </summary> public Vector2 NativeResolution { get { return new Vector2(nativeResolutionWidth, nativeResolutionHeight); } } // Some obselete functions, use ScreenExtents instead [System.Obsolete] public Vector2 ScreenOffset { get { return new Vector2(ScreenExtents.xMin - NativeScreenExtents.xMin, ScreenExtents.yMin - NativeScreenExtents.yMin); } } [System.Obsolete] public Vector2 resolution { get { return new Vector2( ScreenExtents.xMax, ScreenExtents.yMax ); } } [System.Obsolete] public Vector2 ScreenResolution { get { return new Vector2( ScreenExtents.xMax, ScreenExtents.yMax ); } } [System.Obsolete] public Vector2 ScaledResolution { get { return new Vector2( ScreenExtents.width, ScreenExtents.height ); } } /// <summary> /// Zooms the current display /// A zoom factor of 2 will zoom in 2x, i.e. the object on screen will be twice as large /// Anchors will still be anchored, but will be scaled with the zoomScale. /// It is recommended to use a second camera for HUDs if necessary to avoid this behaviour. /// </summary> public float ZoomFactor { get { return zoomFactor; } set { zoomFactor = Mathf.Max(0.01f, value); } } /// <summary> /// Obselete - use <see cref="ZoomFactor"/> instead. /// </summary> [System.Obsolete] public float zoomScale { get { return 1.0f / Mathf.Max(0.001f, zoomFactor); } set { ZoomFactor = 1.0f / Mathf.Max(0.001f, value); } } [SerializeField] float zoomFactor = 1.0f; [HideInInspector] /// <summary> /// Forces the resolution in the editor. This option is only used when tk2dCamera can't detect the game window resolution. /// </summary> public bool forceResolutionInEditor = false; [HideInInspector] /// <summary> /// The resolution to force the game window to when <see cref="forceResolutionInEditor"/> is enabled. /// </summary> public Vector2 forceResolution = new Vector2(960, 640); #if UNITY_EDITOR // When true, overrides the "forceResolutionInEditor" flag above bool useGameWindowResolutionInEditor = false; // Usred when useGameWindowResolutionInEditor == true Vector2 gameWindowResolution = new Vector2(960, 640); #endif /// <summary> /// The camera that sees the screen - i.e. if viewport clipping is enabled, its the camera that sees the entire screen /// </summary> public Camera ScreenCamera { get { bool viewportClippingEnabled = this.viewportClippingEnabled && this.inheritSettings != null && this.inheritSettings.UnityCamera.rect == unitRect; return viewportClippingEnabled ? this.inheritSettings.UnityCamera : UnityCamera; } } // Use this for initialization void Awake () { Upgrade(); if (allCameras.IndexOf(this) == -1) { allCameras.Add(this); } tk2dCamera settings = SettingsRoot; tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings; if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { UnityCamera.transparencySortMode = inheritedCameraSettings.transparencySortMode; } } void OnEnable() { if (UnityCamera != null) { UpdateCameraMatrix(); } else { this.GetComponent<Camera>().enabled = false; } if (!viewportClippingEnabled) // the main camera can't display rect inst = this; if (allCameras.IndexOf(this) == -1) { allCameras.Add(this); } } void OnDestroy() { int idx = allCameras.IndexOf(this); if (idx != -1) { allCameras.RemoveAt( idx ); } } void OnPreCull() { // Commit all pending changes - this more or less guarantees // everything is committed before drawing this camera. tk2dUpdateManager.FlushQueues(); UpdateCameraMatrix(); } #if UNITY_EDITOR void LateUpdate() { if (!Application.isPlaying) { UpdateCameraMatrix(); } } #endif Rect _screenExtents; Rect _nativeScreenExtents; Rect unitRect = new Rect(0, 0, 1, 1); // Gives you the size of one pixel in world units at the native resolution // For perspective cameras, it is dependent on the distance to the camera. public float GetSizeAtDistance(float distance) { tk2dCameraSettings cameraSettings = SettingsRoot.CameraSettings; switch (cameraSettings.projection) { case tk2dCameraSettings.ProjectionType.Orthographic: if (cameraSettings.orthographicType == tk2dCameraSettings.OrthographicType.PixelsPerMeter) { return 1.0f / cameraSettings.orthographicPixelsPerMeter; } else { return 2.0f * cameraSettings.orthographicSize / SettingsRoot.nativeResolutionHeight; } case tk2dCameraSettings.ProjectionType.Perspective: return Mathf.Tan(CameraSettings.fieldOfView * Mathf.Deg2Rad * 0.5f) * distance * 2.0f / SettingsRoot.nativeResolutionHeight; } return 1; } // This returns the tk2dCamera object which has the settings stored on it // Trace back to the source, however far up the hierarchy that may be // You can't change this at runtime tk2dCamera _settingsRoot; public tk2dCamera SettingsRoot { get { if (_settingsRoot == null) { _settingsRoot = (inheritSettings == null || inheritSettings == this) ? this : inheritSettings.SettingsRoot; } return _settingsRoot; } } #if UNITY_EDITOR public static tk2dCamera Editor__Inst { get { if (inst != null) { return inst; } return GameObject.FindObjectOfType(typeof(tk2dCamera)) as tk2dCamera; } } #endif #if UNITY_EDITOR static bool Editor__getGameViewSizeError = false; public static bool Editor__gameViewReflectionError = false; // Try and get game view size // Will return true if it is able to work this out // If width / height == 0, it means the user has selected an aspect ratio "Resolution" public static bool Editor__GetGameViewSize(out float width, out float height, out float aspect) { try { Editor__gameViewReflectionError = false; System.Type gameViewType = System.Type.GetType("UnityEditor.GameView,UnityEditor"); System.Reflection.MethodInfo GetMainGameView = gameViewType.GetMethod("GetMainGameView", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); object mainGameViewInst = GetMainGameView.Invoke(null, null); if (mainGameViewInst == null) { width = height = aspect = 0; return false; } System.Reflection.FieldInfo s_viewModeResolutions = gameViewType.GetField("s_viewModeResolutions", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); if (s_viewModeResolutions == null) { System.Reflection.PropertyInfo currentGameViewSize = gameViewType.GetProperty("currentGameViewSize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); object gameViewSize = currentGameViewSize.GetValue(mainGameViewInst, null); System.Type gameViewSizeType = gameViewSize.GetType(); int gvWidth = (int)gameViewSizeType.GetProperty("width").GetValue(gameViewSize, null); int gvHeight = (int)gameViewSizeType.GetProperty("height").GetValue(gameViewSize, null); int gvSizeType = (int)gameViewSizeType.GetProperty("sizeType").GetValue(gameViewSize, null); if (gvWidth == 0 || gvHeight == 0) { width = height = aspect = 0; return false; } else if (gvSizeType == 0) { width = height = 0; aspect = (float)gvWidth / (float)gvHeight; return true; } else { width = gvWidth; height = gvHeight; aspect = (float)gvWidth / (float)gvHeight; return true; } } else { Vector2[] viewModeResolutions = (Vector2[])s_viewModeResolutions.GetValue(null); float[] viewModeAspects = (float[])gameViewType.GetField("s_viewModeAspects", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(null); string[] viewModeStrings = (string[])gameViewType.GetField("s_viewModeAspectStrings", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(null); if (mainGameViewInst != null && viewModeStrings != null && viewModeResolutions != null && viewModeAspects != null) { int aspectRatio = (int)gameViewType.GetField("m_AspectRatio", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(mainGameViewInst); string thisViewModeString = viewModeStrings[aspectRatio]; if (thisViewModeString.Contains("Standalone")) { width = UnityEditor.PlayerSettings.defaultScreenWidth; height = UnityEditor.PlayerSettings.defaultScreenHeight; aspect = width / height; } else if (thisViewModeString.Contains("Web")) { width = UnityEditor.PlayerSettings.defaultWebScreenWidth; height = UnityEditor.PlayerSettings.defaultWebScreenHeight; aspect = width / height; } else { width = viewModeResolutions[ aspectRatio ].x; height = viewModeResolutions[ aspectRatio ].y; aspect = viewModeAspects[ aspectRatio ]; // this is an error state if (width == 0 && height == 0 && aspect == 0) { return false; } } return true; } } } catch (System.Exception e) { if (Editor__getGameViewSizeError == false) { Debug.LogError("tk2dCamera.GetGameViewSize - has a Unity update broken this?\nThis is not a fatal error, but a warning that you've probably not got the latest 2D Toolkit update.\n\n" + e.ToString()); Editor__getGameViewSizeError = true; } Editor__gameViewReflectionError = true; } width = height = aspect = 0; return false; } #endif public Matrix4x4 OrthoOffCenter(Vector2 scale, float left, float right, float bottom, float top, float near, float far) { // Additional half texel offset // Takes care of texture unit offset, if necessary. float x = (2.0f) / (right - left) * scale.x; float y = (2.0f) / (top - bottom) * scale.y; float z = -2.0f / (far - near); float a = -(right + left) / (right - left); float b = -(bottom + top) / (top - bottom); float c = -(far + near) / (far - near); Matrix4x4 m = new Matrix4x4(); m[0,0] = x; m[0,1] = 0; m[0,2] = 0; m[0,3] = a; m[1,0] = 0; m[1,1] = y; m[1,2] = 0; m[1,3] = b; m[2,0] = 0; m[2,1] = 0; m[2,2] = z; m[2,3] = c; m[3,0] = 0; m[3,1] = 0; m[3,2] = 0; m[3,3] = 1; return m; } Vector2 GetScaleForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float width, float height) { Vector2 scale = Vector2.one; float s = 1.0f; if (currentOverride == null) { return scale; } switch (currentOverride.autoScaleMode) { case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfect: s = 1; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight: s = height / settings.nativeResolutionHeight; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth: s = width / settings.nativeResolutionWidth; scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible: case tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo: float nativeAspect = (float)settings.nativeResolutionWidth / settings.nativeResolutionHeight; float currentAspect = width / height; if (currentAspect < nativeAspect) s = width / settings.nativeResolutionWidth; else s = height / settings.nativeResolutionHeight; if (currentOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo) { if (s > 1.0f) s = Mathf.Floor(s); // round number else s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two } scale.Set(s, s); break; case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit: scale.Set(width / settings.nativeResolutionWidth, height / settings.nativeResolutionHeight); break; case tk2dCameraResolutionOverride.AutoScaleMode.Fill: s = Mathf.Max(width / settings.nativeResolutionWidth,height / settings.nativeResolutionHeight); scale.Set(s, s); break; default: case tk2dCameraResolutionOverride.AutoScaleMode.None: s = currentOverride.scale; scale.Set(s, s); break; } return scale; } Vector2 GetOffsetForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, Vector2 scale, float width, float height) { Vector2 offset = Vector2.zero; if (currentOverride == null) { return offset; } switch (currentOverride.fitMode) { case tk2dCameraResolutionOverride.FitMode.Center: if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.BottomLeft) { offset = new Vector2(Mathf.Round((settings.nativeResolutionWidth * scale.x - width ) / 2.0f), Mathf.Round((settings.nativeResolutionHeight * scale.y - height) / 2.0f)); } break; default: case tk2dCameraResolutionOverride.FitMode.Constant: offset = -currentOverride.offsetPixels; break; } return offset; } #if UNITY_EDITOR private Matrix4x4 Editor__GetPerspectiveMatrix() { float aspect = (float)nativeResolutionWidth / (float)nativeResolutionHeight; return Matrix4x4.Perspective(SettingsRoot.CameraSettings.fieldOfView, aspect, UnityCamera.nearClipPlane, UnityCamera.farClipPlane); } public Matrix4x4 Editor__GetNativeProjectionMatrix( ) { tk2dCamera settings = SettingsRoot; if (settings.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { return Editor__GetPerspectiveMatrix(); } Rect rect1 = new Rect(0, 0, 1, 1); Rect rect2 = new Rect(0, 0, 1, 1); return GetProjectionMatrixForOverride( settings, null, nativeResolutionWidth, nativeResolutionHeight, false, out rect1, out rect2 ); } public Matrix4x4 Editor__GetFinalProjectionMatrix( ) { tk2dCamera settings = SettingsRoot; if (settings.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { return Editor__GetPerspectiveMatrix(); } Vector2 resolution = GetScreenPixelDimensions(settings); Rect rect1 = new Rect(0, 0, 1, 1); Rect rect2 = new Rect(0, 0, 1, 1); return GetProjectionMatrixForOverride( settings, settings.CurrentResolutionOverride, resolution.x, resolution.y, false, out rect1, out rect2 ); } #endif Matrix4x4 GetProjectionMatrixForOverride( tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float pixelWidth, float pixelHeight, bool halfTexelOffset, out Rect screenExtents, out Rect unscaledScreenExtents ) { Vector2 scale = GetScaleForOverride( settings, currentOverride, pixelWidth, pixelHeight ); Vector2 offset = GetOffsetForOverride( settings, currentOverride, scale, pixelWidth, pixelHeight); float left = offset.x, bottom = offset.y; float right = pixelWidth + offset.x, top = pixelHeight + offset.y; Vector2 nativeResolutionOffset = Vector2.zero; bool usingLegacyViewportClipping = false; // Correct for viewport clipping rendering // Coordinates in subrect are "native" pixels, but origin is from the extrema of screen if (this.viewportClippingEnabled && this.InheritConfig != null) { float vw = (right - left) / scale.x; float vh = (top - bottom) / scale.y; Vector4 sr = new Vector4((int)this.viewportRegion.x, (int)this.viewportRegion.y, (int)this.viewportRegion.z, (int)this.viewportRegion.w); usingLegacyViewportClipping = true; float viewportLeft = -offset.x / pixelWidth + sr.x / vw; float viewportBottom = -offset.y / pixelHeight + sr.y / vh; float viewportWidth = sr.z / vw; float viewportHeight = sr.w / vh; if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { viewportLeft += (pixelWidth - settings.nativeResolutionWidth * scale.x) / pixelWidth / 2.0f; viewportBottom += (pixelHeight - settings.nativeResolutionHeight * scale.y) / pixelHeight / 2.0f; } Rect r = new Rect( viewportLeft, viewportBottom, viewportWidth, viewportHeight ); if (UnityCamera.rect.x != viewportLeft || UnityCamera.rect.y != viewportBottom || UnityCamera.rect.width != viewportWidth || UnityCamera.rect.height != viewportHeight) { UnityCamera.rect = r; } float maxWidth = Mathf.Min( 1.0f - r.x, r.width ); float maxHeight = Mathf.Min( 1.0f - r.y, r.height ); float rectOffsetX = sr.x * scale.x - offset.x; float rectOffsetY = sr.y * scale.y - offset.y; if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { rectOffsetX -= settings.nativeResolutionWidth * 0.5f * scale.x; rectOffsetY -= settings.nativeResolutionHeight * 0.5f * scale.y; } if (r.x < 0.0f) { rectOffsetX += -r.x * pixelWidth; maxWidth = (r.x + r.width); } if (r.y < 0.0f) { rectOffsetY += -r.y * pixelHeight; maxHeight = (r.y + r.height); } left += rectOffsetX; bottom += rectOffsetY; right = pixelWidth * maxWidth + offset.x + rectOffsetX; top = pixelHeight * maxHeight + offset.y + rectOffsetY; } else { if (UnityCamera.rect != CameraSettings.rect) { UnityCamera.rect = CameraSettings.rect; } // By default the camera is orthographic, bottom left, 1 pixel per meter if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) { float w = (right - left) * 0.5f; left -= w; right -= w; float h = (top - bottom) * 0.5f; top -= h; bottom -= h; nativeResolutionOffset.Set(-nativeResolutionWidth / 2.0f, -nativeResolutionHeight / 2.0f); } } float zoomScale = 1.0f / ZoomFactor; // Only need the half texel offset on PC/D3D, when not running in d3d11 mode bool needHalfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.WindowsEditor); float halfTexel = (halfTexelOffset && needHalfTexelOffset && SystemInfo.graphicsShaderLevel < 40) ? 0.5f : 0.0f; float orthoSize = settings.cameraSettings.orthographicSize; switch (settings.cameraSettings.orthographicType) { case tk2dCameraSettings.OrthographicType.OrthographicSize: orthoSize = 2.0f * settings.cameraSettings.orthographicSize / settings.nativeResolutionHeight; break; case tk2dCameraSettings.OrthographicType.PixelsPerMeter: orthoSize = 1.0f / settings.cameraSettings.orthographicPixelsPerMeter; break; } // Fixup for clipping if (!usingLegacyViewportClipping) { float clipWidth = Mathf.Min(UnityCamera.rect.width, 1.0f - UnityCamera.rect.x); float clipHeight = Mathf.Min(UnityCamera.rect.height, 1.0f - UnityCamera.rect.y); if (clipWidth > 0 && clipHeight > 0) { scale.x /= clipWidth; scale.y /= clipHeight; } } float s = orthoSize * zoomScale; screenExtents = new Rect(left * s / scale.x, bottom * s / scale.y, (right - left) * s / scale.x, (top - bottom) * s / scale.y); unscaledScreenExtents = new Rect(nativeResolutionOffset.x * s, nativeResolutionOffset.y * s, nativeResolutionWidth * s, nativeResolutionHeight * s); // Near and far clip planes are tweakable per camera, so we pull from current camera instance regardless of inherited values return OrthoOffCenter(scale, orthoSize * (left + halfTexel) * zoomScale, orthoSize * (right + halfTexel) * zoomScale, orthoSize * (bottom - halfTexel) * zoomScale, orthoSize * (top - halfTexel) * zoomScale, UnityCamera.nearClipPlane, UnityCamera.farClipPlane); } Vector2 GetScreenPixelDimensions(tk2dCamera settings) { Vector2 dimensions = new Vector2(ScreenCamera.pixelWidth, ScreenCamera.pixelHeight); #if UNITY_EDITOR // This bit here allocates memory, but only runs in the editor float gameViewPixelWidth = 0, gameViewPixelHeight = 0; float gameViewAspect = 0; settings.useGameWindowResolutionInEditor = false; if (Editor__GetGameViewSize( out gameViewPixelWidth, out gameViewPixelHeight, out gameViewAspect)) { if (gameViewPixelWidth != 0 && gameViewPixelHeight != 0) { if (!settings.useGameWindowResolutionInEditor || settings.gameWindowResolution.x != gameViewPixelWidth || settings.gameWindowResolution.y != gameViewPixelHeight) { settings.useGameWindowResolutionInEditor = true; settings.gameWindowResolution.x = gameViewPixelWidth; settings.gameWindowResolution.y = gameViewPixelHeight; } dimensions.x = settings.gameWindowResolution.x; dimensions.y = settings.gameWindowResolution.y; } } if (!settings.useGameWindowResolutionInEditor && settings.forceResolutionInEditor) { dimensions.x = settings.forceResolution.x; dimensions.y = settings.forceResolution.y; } #endif return dimensions; } private void Upgrade() { if (version != CURRENT_VERSION) { if (version == 0) { // Backwards compatibility cameraSettings.orthographicPixelsPerMeter = 1; cameraSettings.orthographicType = tk2dCameraSettings.OrthographicType.PixelsPerMeter; cameraSettings.orthographicOrigin = tk2dCameraSettings.OrthographicOrigin.BottomLeft; cameraSettings.projection = tk2dCameraSettings.ProjectionType.Orthographic; foreach (tk2dCameraResolutionOverride ovr in resolutionOverride) { ovr.Upgrade( version ); } // Mirror camera settings Camera unityCamera = GetComponent<Camera>(); if (unityCamera != null) { cameraSettings.rect = unityCamera.rect; if (!unityCamera.orthographic) { cameraSettings.projection = tk2dCameraSettings.ProjectionType.Perspective; cameraSettings.fieldOfView = unityCamera.fieldOfView * ZoomFactor; } unityCamera.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy; } } Debug.Log("tk2dCamera '" + this.name + "' - Upgraded from version " + version.ToString()); version = CURRENT_VERSION; } } /// <summary> /// Updates the camera matrix to ensure 1:1 pixel mapping /// Or however the override is set up. /// </summary> public void UpdateCameraMatrix() { Upgrade(); if (!this.viewportClippingEnabled) inst = this; Camera unityCamera = UnityCamera; tk2dCamera settings = SettingsRoot; tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings; if (unityCamera.rect != cameraSettings.rect) unityCamera.rect = cameraSettings.rect; // Projection type is inherited from base camera _targetResolution = GetScreenPixelDimensions(settings); if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) { if (unityCamera.orthographic == true) unityCamera.orthographic = false; float fov = Mathf.Min(179.9f, inheritedCameraSettings.fieldOfView / Mathf.Max(0.001f, ZoomFactor)); if (unityCamera.fieldOfView != fov) unityCamera.fieldOfView = fov; _screenExtents.Set( -unityCamera.aspect, -1, unityCamera.aspect * 2, 2 ); _nativeScreenExtents = _screenExtents; unityCamera.ResetProjectionMatrix(); } else { if (unityCamera.orthographic == false) unityCamera.orthographic = true; // Find an override if necessary Matrix4x4 m = GetProjectionMatrixForOverride( settings, settings.CurrentResolutionOverride, _targetResolution.x, _targetResolution.y, true, out _screenExtents, out _nativeScreenExtents ); #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_1) // Windows phone? if (Application.platform == RuntimePlatform.WP8Player && (Screen.orientation == ScreenOrientation.LandscapeLeft || Screen.orientation == ScreenOrientation.LandscapeRight)) { float angle = (Screen.orientation == ScreenOrientation.LandscapeRight) ? 90.0f : -90.0f; Matrix4x4 m2 = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one); m = m2 * m; } #endif if (unityCamera.projectionMatrix != m) { unityCamera.projectionMatrix = m; } } } }
using System; using System.Collections.Generic; using System.Reflection; using UnityEngine; namespace Stratus { public static partial class Extensions { /// <summary> /// Returns a container of all the children of this GameObject. /// </summary> /// <param name="gameObj"></param> /// <returns>A container of all the children of this GameObject.</returns> public static List<GameObject> Children(this GameObject gameObj) { List<GameObject> children = new List<GameObject>(); ListChildren(gameObj, children); return children; } /// <summary> /// Returns the parent GameObject of this GameObject. /// </summary> /// <param name="gameObj"></param> /// <returns>A reference to the GameObject parent of this GameObject.</returns> public static GameObject Parent(this GameObject gameObj) { return gameObj.transform.parent.gameObject; } /// <summary> /// Adds a component to this GameObject, through copying an existing one. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="gameObj"></param> /// <param name="componentToCopy">The component to copy.</param> /// <returns>A reference to the newly added component.</returns> public static T AddComponent<T>(this GameObject gameObj, T componentToCopy) where T : Component { return gameObj.AddComponent<T>().CopyFrom(componentToCopy); } /// <summary> /// Checks whether this GameObject has the specified component. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="gameObj"></param> /// <returns>True if the component was present, false otherwise.</returns> public static bool HasComponent<T>(this GameObject gameObj) where T : Component { if (gameObj.GetComponent<T>()) { return true; } return false; } /// <summary> /// Finds the child of this GameObject with a given name /// </summary> /// <param name="gameObj"></param> /// <param name="name"></param> /// <returns></returns> public static GameObject FindChild(this GameObject gameObj, string name) { return FindChildBFS(gameObj.transform, name).gameObject; } /// <summary> /// Gets or if not present, adds the specified component to the GameObject. /// </summary> public static T GetOrAddComponent<T>(this GameObject go) where T : Component { T component = go.GetComponent<T>(); if (component == null) { component = go.gameObject.AddComponent<T>(); } return component; } /// <summary> /// Gets or if not present, adds the specified component to the GameObject. /// </summary> public static Component GetOrAddComponent(this GameObject go, Type type) { Component component = go.GetComponent(type); if (component == null) { component = go.gameObject.AddComponent(type); } return component; } public static bool RemoveComponent<T>(this GameObject gameObject) where T : Component { T component = gameObject.GetComponent<T>(); if (component != null) { if (Application.isPlaying) { UnityEngine.Object.Destroy(component); } else if (Application.isEditor) { UnityEngine.Object.DestroyImmediate(component); } return true; } return false; } public static bool RemoveComponent(this GameObject gameObject, System.Type type) { Component component = gameObject.GetComponent(type); if (component != null) { if (Application.isPlaying) { UnityEngine.Object.Destroy(component); } else if (Application.isEditor) { UnityEngine.Object.DestroyImmediate(component); } return true; } return false; } public static void RemoveComponents(this GameObject gameObject, params Type[] types) { foreach (Type type in types) { gameObject.RemoveComponent(type); } } /// <summary> /// Duplicates the given component on this GameObject /// </summary> /// <param name="gameObject"></param> /// <param name="component"></param> /// <returns></returns> public static Component DuplicateComponent(this GameObject gameObject, Component component, bool copy = false) { Type type = component.GetType(); Component newComponent = gameObject.AddComponent(type); if (copy) { newComponent.CopyFrom(component); } return newComponent; } /// <summary> /// Duplicates the given component onto this GameObject. All its values will be copied over into the copy. /// </summary> /// <param name="gameObject"></param> /// <param name="component"></param> /// <returns></returns> public static T DuplicateComponent<T>(this GameObject gameObject, T component) where T : Component { T newComponent = gameObject.AddComponent<T>(); newComponent.CopyFrom(component); return newComponent; } ///// <summary> ///// Returns true if the GameObject has been properly destroyed by the engine ///// </summary> ///// <param name="go"></param> //public static bool IsDestroyed(this GameObject go) //{ // return go == null && !ReferenceEquals(go, null); //} /// <summary> /// Finds and invokes the method with the given name among all components /// attached to this GameObject /// </summary> /// <param name="go"></param> /// <param name="methodName"></param> /// <returns></returns> public static void FindAndInvokeMethod(this GameObject go, string methodName) { MonoBehaviour[] components = go.GetComponents<MonoBehaviour>(); MethodInfo mInfo = components.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); if (mInfo != null) { mInfo.Invoke(components, null); } } private static void ListChildren(GameObject obj, List<GameObject> children) { foreach (Transform child in obj.transform) { children.Add(child.gameObject); ListChildren(child.gameObject, children); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using hw.Helper; using JetBrains.Annotations; namespace hw.DebugFormatter { /// <summary> Summary description for Tracer. </summary> public static class Tracer { static readonly Writer _writer = new Writer(); public static readonly Dumper Dumper = new Dumper(); [UsedImplicitly] public static bool IsBreakDisabled; [UsedImplicitly] public const string VisualStudioLineFormat = "{fileName}({lineNr},{colNr},{lineNrEnd},{colNrEnd}): {tagText}: "; /// <summary> /// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE /// </summary> /// <param name="sf"> the stack frame where the location is stored </param> /// <param name="tag"> </param> /// <returns> the "FileName(LineNr,ColNr): tag: " string </returns> public static string FilePosn(this StackFrame sf, FilePositionTag tag) { if(sf.GetFileLineNumber() == 0) return "<nofile> " + tag; return FilePosn ( sf.GetFileName(), sf.GetFileLineNumber() - 1, sf.GetFileColumnNumber(), tag ); } /// <summary> /// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE /// </summary> /// <param name="fileName"> asis </param> /// <param name="lineNr"> asis </param> /// <param name="colNr"> asis </param> /// <param name="tag"> asis </param> /// <returns> the "fileName(lineNr,colNr): tag: " string </returns> public static string FilePosn ( string fileName, int lineNr, int colNr, FilePositionTag tag ) => FilePosn(fileName, lineNr, colNr, lineNr, colNr, tag); /// <summary> /// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE /// </summary> /// <param name="fileName"> asis </param> /// <param name="lineNr"> asis </param> /// <param name="colNr"> asis </param> /// <param name="colNrEnd"></param> /// <param name="tag"> asis </param> /// <param name="lineNrEnd"></param> /// <returns> the "fileName(lineNr,colNr): tag: " string </returns> public static string FilePosn ( string fileName, int lineNr, int colNr, int lineNrEnd, int colNrEnd, FilePositionTag tag) { var tagText = tag.ToString(); return FilePosn(fileName, lineNr, colNr, lineNrEnd, colNrEnd, tagText); } /// <summary> /// creates the file(line,col) string to be used with "Edit.GotoNextLocation" command of IDE /// </summary> /// <param name="fileName"> asis </param> /// <param name="lineNr"> asis </param> /// <param name="colNr"> asis </param> /// <param name="colNrEnd"></param> /// <param name="tagText"> asis </param> /// <param name="lineNrEnd"></param> /// <returns> the "fileName(lineNr,colNr): tag: " string </returns> public static string FilePosn ( string fileName, int lineNr, int colNr, int lineNrEnd, int colNrEnd, string tagText) => VisualStudioLineFormat .Replace("{fileName}", fileName) .Replace("{lineNr}", (lineNr + 1).ToString()) .Replace("{colNr}", colNr.ToString()) .Replace("{lineNrEnd}", (lineNrEnd + 1).ToString()) .Replace("{colNrEnd}", colNrEnd.ToString()) .Replace("{tagText}", tagText); /// <summary> /// creates a string to inspect a method /// </summary> /// <param name="m"> the method </param> /// <param name="showParam"> controls if parameter list is appended </param> /// <returns> string to inspect a method </returns> public static string DumpMethod(this MethodBase m, bool showParam) { var result = m.DeclaringType.PrettyName() + "."; result += m.Name; if(!showParam) return result; if(m.IsGenericMethod) { result += "<"; result += m.GetGenericArguments().Select(t => t.PrettyName()).Stringify(", "); result += ">"; } result += "("; for(int i = 0, n = m.GetParameters().Length; i < n; i++) { if(i != 0) result += ", "; var p = m.GetParameters()[i]; result += p.ParameterType.PrettyName(); result += " "; result += p.Name; } result += ")"; return result; } /// <summary> /// creates a string to inspect the method call contained in current call stack /// </summary> /// <param name="stackFrameDepth"> the index of stack frame </param> /// <param name="tag"> </param> /// <param name="showParam"> controls if parameter list is appended </param> /// <returns> string to inspect the method call </returns> public static string MethodHeader ( FilePositionTag tag = FilePositionTag.Debug, bool showParam = false, int stackFrameDepth = 0) { var sf = new StackTrace(true).GetFrame(stackFrameDepth + 1); return FilePosn(sf, tag) + DumpMethod(sf.GetMethod(), showParam); } public static string CallingMethodName(int stackFrameDepth = 0) { var sf = new StackTrace(true).GetFrame(stackFrameDepth + 1); return DumpMethod(sf.GetMethod(), false); } [UsedImplicitly] public static string StackTrace(FilePositionTag tag, int stackFrameDepth = 0) { var stackTrace = new StackTrace(true); var result = ""; for(var i = stackFrameDepth + 1; i < stackTrace.FrameCount; i++) { var stackFrame = stackTrace.GetFrame(i); var filePosn = FilePosn(stackFrame, tag) + DumpMethod(stackFrame.GetMethod(), false); result += "\n" + filePosn; } return result; } /// <summary> /// write a line to debug output /// </summary> /// <param name="s"> the text </param> public static void Line(string s) => _writer.ThreadSafeWrite(s, true); /// <summary> /// write a line to debug output /// </summary> /// <param name="s"> the text </param> public static void LinePart(string s) => _writer.ThreadSafeWrite(s, false); /// <summary> /// write a line to debug output, flagged with FileName(LineNr,ColNr): Method (without parameter list) /// </summary> /// <param name="s"> the text </param> /// <param name="flagText"> </param> /// <param name="showParam"></param> /// <param name="stackFrameDepth"> The stack frame depth. </param> public static void FlaggedLine ( string s, FilePositionTag flagText = FilePositionTag.Debug, bool showParam = false, int stackFrameDepth = 0) { var methodHeader = MethodHeader ( flagText, stackFrameDepth: stackFrameDepth + 1, showParam: showParam); Line(methodHeader + " " + s); } /// <summary> /// generic dump function by use of reflection /// </summary> /// <param name="x"> the object to dump </param> /// <returns> </returns> public static string Dump(object x) => Dumper.Dump(x); /// <summary> /// generic dump function by use of reflection /// </summary> /// <param name="x"> the object to dump </param> /// <returns> </returns> public static string DumpData(object x) { if(x == null) return ""; return Dumper.DumpData(x); } /// <summary> /// creates a string to inspect the method call contained in stack. Runtime parameters are dumped too. /// </summary> /// <param name="parameter"> parameter objects list for the frame </param> public static void DumpStaticMethodWithData(params object[] parameter) { var result = DumpMethodWithData("", null, parameter, 1); Line(result); } internal static string DumpMethodWithData (string text, object thisObject, object[] parameter, int stackFrameDepth = 0) { var sf = new StackTrace(true).GetFrame(stackFrameDepth + 1); return FilePosn(sf, FilePositionTag.Debug) + DumpMethod(sf.GetMethod(), true) + text + DumpMethodWithData(sf.GetMethod(), thisObject, parameter).Indent(); } /// <summary> /// Dumps the data. /// </summary> /// <param name="text"> The text. </param> /// <param name="data"> The data, as name/value pair. </param> /// <param name="stackFrameDepth"> The stack stackFrameDepth. </param> /// <returns> </returns> public static string DumpData(string text, object[] data, int stackFrameDepth = 0) { var sf = new StackTrace(true).GetFrame(stackFrameDepth + 1); return FilePosn(sf, FilePositionTag.Debug) + DumpMethod(sf.GetMethod(), true) + text + DumpMethodWithData(null, data).Indent(); } static string DumpMethodWithData(MethodBase m, object o, object[] p) { var result = "\n"; result += "this="; result += Dump(o); result += "\n"; result += DumpMethodWithData(m.GetParameters(), p); return result; } static string DumpMethodWithData(ParameterInfo[] infos, object[] p) { var result = ""; var n = 0; if(infos != null) n = infos.Length; for(var i = 0; i < n; i++) { if(i > 0) result += "\n"; Assert(infos != null); Assert(infos[i] != null); result += infos[i].Name; result += "="; result += Dump(p[i]); } for(var i = n; i < p.Length; i += 2) { result += "\n"; result += (string) p[i]; result += "="; result += Dump(p[i + 1]); } return result; } /// <summary> /// Function used for condition al break /// </summary> /// <param name="cond"> The cond. </param> /// <param name="getText"> The data. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> /// <returns> </returns> [DebuggerHidden] public static void ConditionalBreak (string cond, Func<string> getText = null, int stackFrameDepth = 0) { var result = "Conditional break: " + cond + "\nData: " + (getText == null ? "" : getText()); FlaggedLine(result, stackFrameDepth: stackFrameDepth + 1); TraceBreak(); } /// <summary> /// Check boolean expression /// </summary> /// <param name="b"> /// if set to <c>true</c> [b]. /// </param> /// <param name="getText"> The text. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> [DebuggerHidden] public static void ConditionalBreak (bool b, Func<string> getText = null, int stackFrameDepth = 0) { if(b) ConditionalBreak("", getText, stackFrameDepth + 1); } /// <summary> /// Throws the assertion failed. /// </summary> /// <param name="cond"> The cond. </param> /// <param name="getText"> The data. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> /// created 15.10.2006 18:04 [DebuggerHidden] public static void ThrowAssertionFailed (string cond, Func<string> getText = null, int stackFrameDepth = 0) { var result = AssertionFailed(cond, getText, stackFrameDepth + 1); throw new AssertionFailedException(result); } /// <summary> /// Function used in assertions /// </summary> /// <param name="cond"> The cond. </param> /// <param name="getText"> The data. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> /// <returns> </returns> [DebuggerHidden] public static string AssertionFailed (string cond, Func<string> getText = null, int stackFrameDepth = 0) { var result = "Assertion Failed: " + cond + "\nData: " + (getText == null ? "" : getText()); FlaggedLine(result, stackFrameDepth: stackFrameDepth + 1); AssertionBreak(result); return result; } /// <summary> /// Check boolean expression /// </summary> /// <param name="b"> /// if set to <c>true</c> [b]. /// </param> /// <param name="getText"> The text. </param> /// <param name="stackFrameDepth"> The stack frame depth. </param> [DebuggerHidden] [ContractAnnotation("b: false => halt")] public static void Assert(bool b, Func<string> getText = null, int stackFrameDepth = 0) { if(b) return; AssertionFailed("", getText, stackFrameDepth + 1); } [DebuggerHidden] [ContractAnnotation("b: false => halt")] public static void Assert(bool b, string s) { Assert(b, () => s, 1); } sealed class AssertionFailedException : Exception { public AssertionFailedException(string result) : base(result) {} } sealed class BreakException : Exception {} [DebuggerHidden] static void AssertionBreak(string result) { if(!Debugger.IsAttached || IsBreakDisabled) throw new AssertionFailedException(result); Debugger.Break(); } [UsedImplicitly] [DebuggerHidden] public static void TraceBreak() { if(!Debugger.IsAttached) return; if(IsBreakDisabled) throw new BreakException(); Debugger.Break(); } public static int CurrentFrameCount(int stackFrameDepth) => new StackTrace(true).FrameCount - stackFrameDepth; [DebuggerHidden] public static void LaunchDebugger() => Debugger.Launch(); public static void IndentStart() => _writer.IndentStart(); public static void IndentEnd() => _writer.IndentEnd(); } public enum FilePositionTag { Debug, Output, Query, Test, Profiler } interface IDumpExceptAttribute { bool IsException(object target); } public abstract class DumpAttributeBase : Attribute {} }
// --------------------------------------------------------------------------- // <copyright file="Transaction.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- // --------------------------------------------------------------------- // <summary> // </summary> // --------------------------------------------------------------------- namespace Microsoft.Database.Isam { using System; /// <summary> /// A IsamTransaction object represents a single save point of a transaction /// that is begun on a Session object. This object is not required to /// begin, commit, or abort a transaction as this can be done directly /// on the Session object. However, this object is very useful for making /// convenient code constructs involving transactions with the "using" /// keyword in C# like this: /// <code> /// using( IsamTransaction t = new IsamTransaction( session ) ) /// { /// /* do some work */ /// /// /* save the work */ /// t.Commit(); /// } /// </code> /// </summary> public class IsamTransaction : IDisposable { /// <summary> /// The session /// </summary> private readonly IsamSession isamSession; /// <summary> /// The transaction level /// </summary> private readonly long transactionLevel; /// <summary> /// The transaction level identifier /// </summary> private readonly long transactionLevelID; /// <summary> /// The cleanup /// </summary> private bool cleanup = false; /// <summary> /// The disposed /// </summary> private bool disposed = false; /// <summary> /// Initializes a new instance of the <see cref="IsamTransaction"/> class. /// Begin a transaction on the given session. /// </summary> /// <param name="isamSession"> /// The session we will use for the transaction. /// </param> /// <remarks> /// If this transaction is not committed before this object is disposed /// then the transaction will automatically be aborted. /// </remarks> public IsamTransaction(IsamSession isamSession) { lock (isamSession) { this.isamSession = isamSession; this.isamSession.BeginTransaction(); this.transactionLevel = isamSession.TransactionLevel; this.transactionLevelID = isamSession.TransactionLevelID(isamSession.TransactionLevel); this.cleanup = true; } } /// <summary> /// Initializes a new instance of the <see cref="IsamTransaction"/> class. /// Joins the current transaction on the given session. If the session /// is not currently in a transaction then a new transaction will be /// begun. /// </summary> /// <param name="isamSession"> /// The session we will use for the transaction. /// </param> /// <param name="join"> /// If true, the current transaction on the session will be joined. If false or if there is no current transaction then a new transaction will be begun. /// </param> /// <remarks> /// If an existing transaction is joined, then committing or aborting /// this transaction will have no effect on the joined transaction. If /// a new transaction was begun then these actions will work normally. /// <para> /// If this transaction is not committed before this object is disposed /// then the transaction will automatically be aborted. /// </para> /// </remarks> public IsamTransaction(IsamSession isamSession, bool join) { lock (isamSession) { this.isamSession = isamSession; if (!join || isamSession.TransactionLevel == 0) { this.isamSession.BeginTransaction(); this.transactionLevel = isamSession.TransactionLevel; this.transactionLevelID = isamSession.TransactionLevelID(isamSession.TransactionLevel); this.cleanup = true; } } } /// <summary> /// Finalizes an instance of the IsamTransaction class /// </summary> ~IsamTransaction() { this.Dispose(false); } /// <summary> /// Gets the save point (level) for this transaction. /// </summary> public long TransactionLevel { get { this.CheckDisposed(); return this.transactionLevel; } } /// <summary> /// Gets or sets a value indicating whether [disposed]. /// </summary> /// <value> /// <c>true</c> if [disposed]; otherwise, <c>false</c>. /// </value> internal bool Disposed { get { return this.disposed || this.isamSession.Disposed || (this.cleanup && this.isamSession.TransactionLevelID(this.transactionLevel) != this.transactionLevelID); } set { this.disposed = value; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { lock (this) { this.Dispose(true); } GC.SuppressFinalize(this); } /// <summary> /// Commits the save point (level) represented by this transaction on /// this session. All changes made to the database for this save point /// (level) will be kept. /// </summary> /// <remarks> /// Changes made to the database will become permanent if and only if /// those changes are committed to save point (level) zero. /// <para> /// A commit to save point (level) zero is guaranteed to be persisted /// to the database upon completion of this method. /// </para> /// <para> /// The transaction object will be disposed as a side effect of this /// call. /// </para> /// </remarks> public void Commit() { this.Commit(true); } /// <summary> /// Commits the save point (level) represented by this transaction on /// this session. All changes made to the database for this save point /// (level) will be kept. /// </summary> /// <param name="durableCommit">When true, a commit to save point (level) zero is guaranteed to be persisted to the database upon completion of this method.</param> /// <remarks> /// Changes made to the database will become permanent if and only if /// those changes are committed to save point (level) zero. /// <para> /// A commit to save point (level) zero is guaranteed to be persisted /// to the database upon completion of this method only if /// durableCommit is true. If durableCommit is false then the changes /// will only be persisted to the database if their transaction log /// entries happen to be written to disk before a crash or if the /// database is shut down cleanly. /// </para> /// <para> /// The transaction object will be disposed as a side effect of this /// call. /// </para> /// </remarks> public void Commit(bool durableCommit) { lock (this.isamSession) { this.CheckDisposed(); if (this.cleanup) { this.isamSession.CommitTransaction(durableCommit); this.cleanup = false; } this.Dispose(); } } /// <summary> /// Aborts the save point (level) represented by this transaction on /// this session. All changes made to the database for this save point /// (level) will be discarded. /// </summary> /// <remarks> /// The transaction object will be disposed as a side effect of this /// call. /// </remarks> public void Rollback() { lock (this.isamSession) { this.CheckDisposed(); this.Dispose(); } } /// <summary> /// Aborts the save point (level) represented by this transaction on /// this session. All changes made to the database for this save point /// (level) will be discarded. /// </summary> /// <remarks> /// The transaction object will be disposed as a side effect of this /// call. /// <para> /// IsamTransaction.Abort is an alias for <see cref="IsamTransaction.Rollback"/>. /// </para> /// </remarks> public void Abort() { this.Rollback(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { this.Dispose(); } /// <summary> /// Checks whether this object is disposed. /// </summary> /// <exception cref="System.ObjectDisposedException">If the object has already been disposed.</exception> internal void CheckDisposed() { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { lock (this.isamSession) { if (!this.Disposed) { if (this.cleanup) { this.isamSession.RollbackTransaction(); this.cleanup = false; } this.Disposed = true; } } } } }
#region Foreign-License /* Copyright (c) 1997 Cornell University. Copyright (c) 1997 Sun Microsystems, Inc. Copyright (c) 2012 Sky Morey See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES. This file is adapted from the JDK 1.0 QSortAlgorithm.java demo program. Original copyright notice is preserveed below. @(#)QSortAlgorithm.java 1.3 29 Feb 1996 James Gosling Copyright (c) 1994-1996 Sun Microsystems, Inc. All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and without fee is hereby granted. Please refer to the file http://www.javasoft.com/copy_trademarks.html for further important copyright and trademark information and to http://www.javasoft.com/licensing.html for further important licensing information for the Java (tm) Technology. SUN MAKES NO REPRESENTATIONS OR WARRANTIES. ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SUN SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. */ #endregion using System.Text; namespace Tcl.Lang { /// <summary> Sorts an array of TclObjects.</summary> sealed class QSort { internal const int ASCII = 0; internal const int INTEGER = 1; internal const int REAL = 2; internal const int COMMAND = 3; internal const int DICTIONARY = 4; // Data used during sort. private int sortMode; private int sortIndex; private bool sortIncreasing; private string sortCommand; private Interp sortInterp; /// <summary> This is a generic version of C.A.R Hoare's Quick Sort /// algorithm. This will handle arrays that are already /// sorted, and arrays with duplicate keys.<BR> /// /// If you think of a one dimensional array as going from /// the lowest index on the left to the highest index on the right /// then the parameters to this function are lowest index or /// left and highest index or right. The first time you call /// this function it will be with the parameters 0, a.length - 1. /// /// </summary> /// <param name="a"> an integer array /// </param> /// <param name="lo0"> left boundary of array partition /// </param> /// <param name="hi0"> right boundary of array partition /// </param> private void quickSort(TclObject[] a, int lo0, int hi0) { int lo = lo0; int hi = hi0; TclObject mid; if (hi0 > lo0) { // Arbitrarily establishing partition element as the midpoint of // the array. mid = a[(lo0 + hi0) / 2]; // loop through the array until indices cross while (lo <= hi) { // find the first element that is greater than or equal to // the partition element starting from the left Index. while ((lo < hi0) && (compare(a[lo], mid) < 0)) { ++lo; } // find an element that is smaller than or equal to // the partition element starting from the right Index. while ((hi > lo0) && (compare(a[hi], mid) > 0)) { --hi; } // if the indexes have not crossed, swap if (lo <= hi) { swap(a, lo, hi); ++lo; --hi; } } // If the right index has not reached the left side of array // must now sort the left partition. if (lo0 < hi) { quickSort(a, lo0, hi); } // If the left index has not reached the right side of array // must now sort the right partition. if (lo < hi0) { quickSort(a, lo, hi0); } } } /// <summary> Swaps two items in the array. /// /// </summary> /// <param name="a">the array. /// </param> /// <param name="i">index of first item. /// </param> /// <param name="j">index of first item. /// </param> private static void swap(TclObject[] a, int i, int j) { TclObject T; T = a[i]; a[i] = a[j]; a[j] = T; } /// <summary> Starts the quick sort with the given parameters. /// /// </summary> /// <param name="interp">if cmd is specified, it is evaluated inside this /// interp. /// </param> /// <param name="a">the array of TclObject's to sort. /// </param> /// <param name="mode">the sortng mode. /// </param> /// <param name="increasing">true if the sorted array should be in increasing /// order. /// </param> /// <param name="cmd">the command to use for comparing items. It is used only /// if sortMode is COMMAND. /// </param> /// <param name="unique">true if the result should contain no duplicates. /// </param> /// <returns> the length of the sorted array. This length may be different /// from the length if array a due to the unique option. /// </returns> /// <exception cref=""> TclException if an error occurs during sorting. /// </exception> internal int sort(Interp interp, TclObject[] a, int mode, int index, bool increasing, string cmd, bool unique) { sortInterp = interp; sortMode = mode; sortIndex = index; sortIncreasing = increasing; sortCommand = cmd; quickSort(a, 0, a.Length - 1); if (!unique) { return a.Length; } int uniqueIx = 1; for (int ix = 1; ix < a.Length; ix++) { if (compare(a[ix], a[uniqueIx - 1]) == 0) { a[ix].Release(); } else { if (ix != uniqueIx) { a[uniqueIx] = a[ix]; a[uniqueIx].Preserve(); } uniqueIx++; } } return uniqueIx; } /// <summary> Compares the order of two items in the array. /// /// </summary> /// <param name="obj1">first item. /// </param> /// <param name="obj2">second item. /// </param> /// <returns> 0 if they are equal, 1 if obj1 > obj2, -1 otherwise. /// /// </returns> /// <exception cref=""> TclException if an error occurs during sorting. /// </exception> private int compare(TclObject obj1, TclObject obj2) { int index; int code = 0; if (sortIndex != -1) { // The "-index" option was specified. Treat each object as a // list, extract the requested element from each list, and // compare the elements, not the lists. The special index "end" // is signaled here with a negative index (other than -1). TclObject obj; if (sortIndex < -1) { index = TclList.getLength(sortInterp, obj1) - 1; } else { index = sortIndex; } obj = TclList.index(sortInterp, obj1, index); if (obj == null) { throw new TclException(sortInterp, "element " + index + " missing from sublist \"" + obj1 + "\""); } obj1 = obj; if (sortIndex < -1) { index = TclList.getLength(sortInterp, obj2) - 1; } else { index = sortIndex; } obj = TclList.index(sortInterp, obj2, index); if (obj == null) { throw new TclException(sortInterp, "element " + index + " missing from sublist \"" + obj2 + "\""); } obj2 = obj; } switch (sortMode) { case ASCII: // ATK C# CompareTo use option // similar to -dictionary but a > A code = System.Globalization.CultureInfo.InvariantCulture.CompareInfo.Compare(obj1.ToString(), obj2.ToString(), System.Globalization.CompareOptions.Ordinal); // code = obj1.ToString().CompareTo(obj2.ToString()); break; case DICTIONARY: code = doDictionary(obj1.ToString(), obj2.ToString()); break; case INTEGER: try { int int1 = TclInteger.Get(sortInterp, obj1); int int2 = TclInteger.Get(sortInterp, obj2); if (int1 > int2) { code = 1; } else if (int2 > int1) { code = -1; } } catch (TclException e1) { sortInterp.AddErrorInfo("\n (converting list element from string to integer)"); throw e1; } break; case REAL: try { double f1 = TclDouble.Get(sortInterp, obj1); double f2 = TclDouble.Get(sortInterp, obj2); if (f1 > f2) { code = 1; } else if (f2 > f1) { code = -1; } } catch (TclException e2) { sortInterp.AddErrorInfo("\n (converting list element from string to real)"); throw e2; } break; case COMMAND: StringBuilder sbuf = new StringBuilder(sortCommand); Util.appendElement(sortInterp, sbuf, obj1.ToString()); Util.appendElement(sortInterp, sbuf, obj2.ToString()); try { sortInterp.Eval(sbuf.ToString(), 0); } catch (TclException e3) { sortInterp.AddErrorInfo("\n (user-defined comparison command)"); throw e3; } try { code = TclInteger.Get(sortInterp, sortInterp.GetResult()); } catch (TclException e) { sortInterp.ResetResult(); TclException e4 = new TclException(sortInterp, "comparison command returned non-numeric result"); throw e4; } break; default: throw new TclRuntimeError("Unknown sortMode " + sortMode); } if (sortIncreasing) { return code; } else { return -code; } } /// <summary> Compares the order of two strings in "dictionary" order. /// /// </summary> /// <param name="str1">first item. /// </param> /// <param name="str2">second item. /// </param> /// <returns> 0 if they are equal, 1 if obj1 > obj2, -1 otherwise. /// </returns> private int doDictionary(string str1, string str2) { int diff = 0, zeros; int secondaryDiff = 0; bool cont = true; int i1 = 0, i2 = 0; int len1 = str1.Length; int len2 = str2.Length; while (cont) { if (i1 >= len1 || i2 >= len2) { break; } if (System.Char.IsDigit(str2[i2]) && System.Char.IsDigit(str1[i1])) { // There are decimal numbers embedded in the two // strings. Compare them as numbers, rather than // strings. If one number has more leading zeros than // the other, the number with more leading zeros sorts // later, but only as a secondary choice. zeros = 0; while ((i2 < (len2 - 1)) && (str2[i2] == '0')) { i2++; zeros--; } while ((i1 < (len1 - 1)) && (str1[i1] == '0')) { i1++; zeros++; } if (secondaryDiff == 0) { secondaryDiff = zeros; } // The code below compares the numbers in the two // strings without ever converting them to integers. It // does this by first comparing the lengths of the // numbers and then comparing the digit values. diff = 0; while (true) { if (i1 >= len1 || i2 >= len2) { cont = false; break; } if (diff == 0) { diff = str1[i1] - str2[i2]; } i1++; i2++; if (i1 >= len1 || i2 >= len2) { cont = false; break; } if (!System.Char.IsDigit(str2[i2])) { if (System.Char.IsDigit(str1[i1])) { return 1; } else { if (diff != 0) { return diff; } break; } } else if (!System.Char.IsDigit(str1[i1])) { return -1; } } continue; } diff = str1[i1] - str2[i2]; if (diff != 0) { if (System.Char.IsUpper(str1[i1]) && System.Char.IsLower(str2[i2])) { diff = System.Char.ToLower(str1[i1]) - str2[i2]; if (diff != 0) { return diff; } else if (secondaryDiff == 0) { secondaryDiff = -1; } } else if (System.Char.IsUpper(str2[i2]) && System.Char.IsLower(str1[i1])) { diff = str1[i1] - System.Char.ToLower(str2[i2]); if (diff != 0) { return diff; } else if (secondaryDiff == 0) { secondaryDiff = 1; } } else { return diff; } } i1++; i2++; } if (i1 >= len1 && i2 < len2) { if (!System.Char.IsDigit(str2[i2])) { return 1; } else { return -1; } } else if (i2 >= len2 && i1 < len1) { if (!System.Char.IsDigit(str1[i1])) { return -1; } else { return 1; } } if (diff == 0) { diff = secondaryDiff; } return diff; } } }
// 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.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.DotNet.RemoteExecutor; using Xunit; using System.Tests; namespace System.ComponentModel.Tests { public abstract class TypeConverterTestBase { public abstract TypeConverter Converter { get; } public virtual IEnumerable<ConvertTest> ConvertToTestData() => Enumerable.Empty<ConvertTest>(); public virtual IEnumerable<ConvertTest> ConvertFromTestData() => Enumerable.Empty<ConvertTest>(); public virtual bool PropertiesSupported => false; public virtual bool StandardValuesSupported => false; public virtual bool StandardValuesExclusive => false; public virtual bool CanConvertFromNull => false; public virtual bool CanConvertToString => true; [Fact] public void ConvertTo_DestinationType_Success() { Assert.All(ConvertToTestData(), convertTest => { // We need to duplicate this test code as RemoteInvoke can't // create "this" as the declaring type is an abstract class. if (convertTest.RemoteInvokeCulture == null) { Assert.Equal(convertTest.CanConvert, Converter.CanConvertTo(convertTest.Context, convertTest.DestinationType)); if (convertTest.CanConvert) { object actual = Converter.ConvertTo(convertTest.Context, convertTest.Culture, convertTest.Source, convertTest.DestinationType); AssertEqualInstanceDescriptor(convertTest.Expected, actual); } else { Assert.Throws<NotSupportedException>(() => Converter.ConvertTo(convertTest.Context, convertTest.Culture, convertTest.Source, convertTest.DestinationType)); } } else { using (new ThreadCultureChange(convertTest.RemoteInvokeCulture)) { Assert.Equal(convertTest.CanConvert, this.Converter.CanConvertTo(convertTest.Context, convertTest.DestinationType)); if (convertTest.CanConvert) { object actual = this.Converter.ConvertTo(convertTest.Context, convertTest.Culture, convertTest.Source, convertTest.DestinationType); Assert.Equal(convertTest.Expected, actual); } else { Assert.Throws<NotSupportedException>(() => this.Converter.ConvertTo(convertTest.Context, convertTest.Culture, convertTest.Source, convertTest.DestinationType)); } } } }); } [Fact] public void ConvertTo_String_ReturnsExpected() { Assert.Equal(CanConvertToString ? nameof(CustomToString) : string.Empty, Converter.ConvertTo(new CustomToString(), typeof(string))); } [Fact] public void ConvertTo_NullDestinationType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("destinationType", () => Converter.ConvertTo(null, null)); AssertExtensions.Throws<ArgumentNullException>("destinationType", () => Converter.ConvertTo(TypeConverterTests.s_context, null, "", null)); } [Fact] public void CanConvertTo_StringDestinationType_ReturnsTrue() { Assert.True(Converter.CanConvertTo(typeof(string))); } [Fact] public void CanConvertTo_NullDestinationType_ReturnsFalse() { Assert.False(Converter.CanConvertTo(null)); } [Fact] public void ConvertFrom_DestinationType_Success() { Assert.All(ConvertFromTestData(), convertTest => { // We need to duplicate this test code as RemoteInvoke can't // create "this" as the declaring type is an abstract class. if (convertTest.RemoteInvokeCulture == null) { if (convertTest.Source != null) { Assert.Equal(convertTest.CanConvert, Converter.CanConvertFrom(convertTest.Context, convertTest.Source.GetType())); } if (convertTest.NetCoreExceptionType == null) { object actual = Converter.ConvertFrom(convertTest.Context, convertTest.Culture, convertTest.Source); Assert.Equal(convertTest.Expected, actual); } else { AssertExtensions.Throws(convertTest.NetCoreExceptionType, convertTest.NetFrameworkExceptionType, () => Converter.ConvertFrom(convertTest.Context, convertTest.Culture, convertTest.Source)); } } else { using (new ThreadCultureChange(convertTest.RemoteInvokeCulture)) { if (convertTest.Source != null) { Assert.Equal(convertTest.CanConvert, this.Converter.CanConvertFrom(convertTest.Context, convertTest.Source.GetType())); } if (convertTest.NetCoreExceptionType == null) { object actual = this.Converter.ConvertFrom(convertTest.Context, convertTest.Culture, convertTest.Source); Assert.Equal(convertTest.Expected, actual); } else { AssertExtensions.Throws(convertTest.NetCoreExceptionType, convertTest.NetFrameworkExceptionType, () => this.Converter.ConvertFrom(convertTest.Context, convertTest.Culture, convertTest.Source)); } } } }); } [Fact] public void ConvertFrom_NullValue_ThrowsNotSupportedException() { if (!CanConvertFromNull) { Assert.Throws<NotSupportedException>(() => Converter.ConvertFrom(null)); } } [Fact] public void CanConvertFrom_InstanceDescriptorSourceType_ReturnsTrue() { Assert.True(Converter.CanConvertFrom(typeof(InstanceDescriptor))); } [Fact] public void CanConvertFrom_NullSourceType_ReturnsFalse() { Assert.False(Converter.CanConvertFrom(null)); } [Fact] public void GetPropertiesSupported_Invoke_ReturnsExpected() { TypeConverter converter = Converter; Assert.Equal(PropertiesSupported, converter.GetPropertiesSupported()); } [Fact] public void GetStandardValuesSupported_Invoke_ReturnsExpected() { TypeConverter converter = Converter; Assert.Equal(StandardValuesSupported, converter.GetStandardValuesSupported()); } [Fact] public void GetStandardValuesExclusive_Invoke_ReturnsExpected() { TypeConverter converter = Converter; Assert.Equal(StandardValuesExclusive, converter.GetStandardValuesExclusive()); } private static void AssertEqualInstanceDescriptor(object expected, object actual) { if (expected is InstanceDescriptor expectedDescriptor && actual is InstanceDescriptor actualDescriptor) { Assert.Equal(expectedDescriptor.MemberInfo, actualDescriptor.MemberInfo); Assert.Equal(expectedDescriptor.Arguments, actualDescriptor.Arguments); Assert.Equal(expectedDescriptor.IsComplete, actualDescriptor.IsComplete); } else { Assert.Equal(expected, actual); } } [Serializable] public class ConvertTest : ISerializable { public object Source { get; set; } public Type DestinationType { get; set; } public object Expected { get; set; } public CultureInfo Culture { get; set; } public Type NetCoreExceptionType { get; set; } public Type NetFrameworkExceptionType { get; set; } public ITypeDescriptorContext Context { get; set; } = TypeConverterTests.s_context; public CultureInfo RemoteInvokeCulture { get; set; } public bool CanConvert { get; set; } public override string ToString() => // for debugging / xunit test output $"Source='{Source}', Type='{DestinationType}', Culture='{Culture?.Name ?? "(null)"}', RemoteCulture='{RemoteInvokeCulture?.Name ?? "(null)"}'"; public static ConvertTest Valid(object source, object expected, CultureInfo culture = null) { return new ConvertTest { Source = source, DestinationType = expected?.GetType(), Expected = expected, Culture = culture, CanConvert = true, }; } public static ConvertTest Throws<TException>(object source, CultureInfo culture = null) where TException : Exception { return Throws<TException, TException>(source, culture); } public static ConvertTest Throws<TNetCoreException, TNetFrameworkException>(object source, CultureInfo culture = null) where TNetCoreException : Exception where TNetFrameworkException : Exception { return new ConvertTest { Source = source, Culture = culture, NetCoreExceptionType = typeof(TNetCoreException), NetFrameworkExceptionType = typeof(TNetFrameworkException), CanConvert = true }; } public static ConvertTest CantConvertTo(object source, Type destinationType = null, CultureInfo culture = null) { return new ConvertTest { Source = source, DestinationType = destinationType, Culture = culture, NetCoreExceptionType = typeof(NotSupportedException), NetFrameworkExceptionType = typeof(NotSupportedException), CanConvert = false }; } public static ConvertTest CantConvertFrom(object source, CultureInfo culture = null) { return new ConvertTest { Source = source, Culture = culture, NetCoreExceptionType = typeof(NotSupportedException), NetFrameworkExceptionType = typeof(NotSupportedException), CanConvert = false }; } public ConvertTest WithContext(ITypeDescriptorContext context) { Context = context; return this; } public ConvertTest WithRemoteInvokeCulture(CultureInfo culture) { RemoteInvokeCulture = culture; return this; } public ConvertTest WithInvariantRemoteInvokeCulture() => WithRemoteInvokeCulture(CultureInfo.InvariantCulture); public ConvertTest() { } protected ConvertTest(SerializationInfo info, StreamingContext context) { string sourceType = (string)info.GetValue("SourceType", typeof(string)); if (sourceType != null) { Source = info.GetValue(nameof(Source), Type.GetType(sourceType)); } string destinationType = (string)info.GetValue(nameof(DestinationType), typeof(string)); if (destinationType != null) { DestinationType = Type.GetType(destinationType); } string culture = (string)info.GetValue(nameof(Culture), typeof(string)); if (culture != null) { Culture = culture == string.Empty ? CultureInfo.InvariantCulture : new CultureInfo(culture); } string contextType = (string)info.GetValue("ContextType", typeof(string)); if (contextType != null) { Context = (ITypeDescriptorContext)info.GetValue(nameof(Context), Type.GetType(contextType)); } string expectedType = (string)info.GetValue("ExpectedType", typeof(string)); if (expectedType != null) { Expected = info.GetValue(nameof(Expected), Type.GetType(expectedType)); } string netCoreExceptionType = (string)info.GetValue(nameof(NetCoreExceptionType), typeof(string)); if (netCoreExceptionType != null) { NetCoreExceptionType = Type.GetType(netCoreExceptionType); } string netFrameworkExceptionType = (string)info.GetValue(nameof(NetFrameworkExceptionType), typeof(string)); if (netFrameworkExceptionType != null) { NetFrameworkExceptionType = Type.GetType(netFrameworkExceptionType); } string remoteInvokeCulture = (string)info.GetValue(nameof(RemoteInvokeCulture), typeof(string)); if (remoteInvokeCulture != null) { RemoteInvokeCulture = culture == string.Empty ? CultureInfo.InvariantCulture : new CultureInfo(remoteInvokeCulture); } CanConvert = (bool)info.GetValue(nameof(CanConvert), typeof(bool)); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(Source), Source); info.AddValue("SourceType", Source?.GetType()?.AssemblyQualifiedName); info.AddValue(nameof(DestinationType), DestinationType?.AssemblyQualifiedName); info.AddValue(nameof(Culture), Culture?.Name); info.AddValue(nameof(Context), Context); info.AddValue("ContextType", Context?.GetType()?.AssemblyQualifiedName); info.AddValue(nameof(Expected), Expected); info.AddValue("ExpectedType", Expected?.GetType()?.AssemblyQualifiedName); info.AddValue(nameof(NetCoreExceptionType), NetCoreExceptionType?.AssemblyQualifiedName); info.AddValue(nameof(NetFrameworkExceptionType), NetFrameworkExceptionType?.AssemblyQualifiedName); info.AddValue(nameof(RemoteInvokeCulture), RemoteInvokeCulture?.Name); info.AddValue(nameof(CanConvert), CanConvert); } public static ConvertTest FromSerializedString(string s) { byte[] bytes = Convert.FromBase64String(s); using (var stream = new MemoryStream(bytes, 0, bytes.Length)) { stream.Write(bytes, 0, bytes.Length); stream.Position = 0; return (ConvertTest)new BinaryFormatter().Deserialize(stream); } } public string GetSerializedString() { using (var stream = new MemoryStream()) { new BinaryFormatter().Serialize(stream, this); return Convert.ToBase64String(stream.ToArray()); } } } private class CustomToString { public override string ToString() => nameof(CustomToString); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using FileHelpers.Helpers; using FileHelpers.Streams; namespace FileHelpers { /// <summary> /// This class allow you to convert the records of a file to a different record format. /// </summary> /// <typeparam name="TSource">The source record type.</typeparam> /// <typeparam name="TDestination">The destination record type.</typeparam> [DebuggerDisplay( "FileTransformanEngine for types: {SourceType.Name} --> {DestinationType.Name}. Source Encoding: {SourceEncoding.EncodingName}. Destination Encoding: {DestinationEncoding.EncodingName}" )] public sealed class FileTransformEngine<TSource, TDestination> where TSource : class, ITransformable<TDestination> where TDestination : class { #region " Constructor " /// <summary>Create a new FileTransformEngine.</summary> public FileTransformEngine() {} #endregion #region " Private Fields " // [DebuggerBrowsable(DebuggerBrowsableState.Never)] // private static object[] mEmptyArray = new object[] {}; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private Encoding mSourceEncoding = Encoding.GetEncoding(0); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private Encoding mDestinationEncoding = Encoding.GetEncoding(0); private ErrorMode mErrorMode; /// <summary>Indicates the behavior of the engine when an error is found.</summary> public ErrorMode ErrorMode { get { return mErrorMode; } set { mErrorMode = value; mSourceErrorManager = new ErrorManager(value); mDestinationErrorManager = new ErrorManager(value); } } private ErrorManager mSourceErrorManager = new ErrorManager(); /// <summary> /// Allow access the <see cref="ErrorManager"/> of the engine used to /// read the source file, is null before any file is transformed /// </summary> public ErrorManager SourceErrorManager { get { return mSourceErrorManager; } } private ErrorManager mDestinationErrorManager = new ErrorManager(); /// <summary> /// Allow access the <see cref="ErrorManager"/> of the engine used to /// write the destination file, is null before any file is transformed /// </summary> public ErrorManager DestinationErrorManager { get { return mDestinationErrorManager; } } #endregion #region " TransformFile " /// <summary> /// Transform the contents of the sourceFile and write them to the /// destFile.(use only if you need the array of the transformed /// records, TransformFileFast is faster) /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destFile">The destination file.</param> /// <returns>The transformed records.</returns> public TDestination[] TransformFile(string sourceFile, string destFile) { ExHelper.CheckNullParam(sourceFile, "sourceFile"); ExHelper.CheckNullParam(destFile, "destFile"); ExHelper.CheckDifferentsParams(sourceFile, "sourceFile", destFile, "destFile"); return CoreTransformFile(sourceFile, destFile); } /// <summary> /// Transform the contents of the sourceFile and write them to the /// destFile. (faster and uses less memory, best choice for big /// files) /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destFile">The destination file.</param> /// <returns>The number of transformed records.</returns> public int TransformFileFast(string sourceFile, string destFile) { ExHelper.CheckNullParam(sourceFile, "sourceFile"); ExHelper.CheckNullParam(destFile, "destFile"); ExHelper.CheckDifferentsParams(sourceFile, "sourceFile", destFile, "destFile"); return CoreTransformAsync( new InternalStreamReader(sourceFile, SourceEncoding, true, EngineBase.DefaultReadBufferSize*5), new StreamWriter(destFile, false, DestinationEncoding, EngineBase.DefaultWriteBufferSize*5)); } /// <summary> /// Transform the contents of the sourceFile and write them to the /// destFile. (faster and uses less memory, best choice for big /// files) /// </summary> /// <param name="sourceStream">The source stream.</param> /// <param name="destFile">The destination file.</param> /// <returns>The number of transformed records.</returns> public int TransformFileFast(TextReader sourceStream, string destFile) { ExHelper.CheckNullParam(sourceStream, "sourceStream"); ExHelper.CheckNullParam(destFile, "destFile"); return CoreTransformAsync(sourceStream, new StreamWriter(destFile, false, DestinationEncoding, EngineBase.DefaultWriteBufferSize*5)); } /// <summary> /// Transform the contents of the sourceFile and write them to the /// destFile. (faster and uses less memory, best choice for big /// files) /// </summary> /// <param name="sourceStream">The source stream.</param> /// <param name="destStream">The destination stream.</param> /// <returns>The number of transformed records.</returns> public int TransformFileFast(TextReader sourceStream, StreamWriter destStream) { ExHelper.CheckNullParam(sourceStream, "sourceStream"); ExHelper.CheckNullParam(destStream, "destStream"); return CoreTransformAsync(sourceStream, destStream); } /// <summary> /// Transform the contents of the sourceFile and write them to the /// destFile. (faster and uses less memory, best choice for big /// files) /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destStream">The destination stream.</param> /// <returns>The number of transformed records.</returns> public int TransformFileFast(string sourceFile, StreamWriter destStream) { ExHelper.CheckNullParam(sourceFile, "sourceFile"); ExHelper.CheckNullParam(destStream, "destStream"); return CoreTransformAsync( new InternalStreamReader(sourceFile, SourceEncoding, true, EngineBase.DefaultReadBufferSize*5), destStream); } #endregion // public string TransformString(string sourceData) // { // if (mConvert1to2 == null) // throw new BadUsageException("You must define a method in the class " + SourceType.Name + " with the attribute [TransfortToRecord(typeof(" + DestinationType.Name + "))] that return an object of type " + DestinationType.Name); // // return CoreTransformAsync(sourceFile, destFile, mSourceType, mDestinationType, mConvert1to2); // } /// <summary> /// Transforms an array of records from the source type to the destination type /// </summary> /// <param name="sourceRecords">An array of the source records.</param> /// <returns>The transformed records.</returns> public TDestination[] TransformRecords(TSource[] sourceRecords) { return CoreTransformRecords(sourceRecords); //return CoreTransformAsync(sourceFile, destFile, mSourceType, mDestinationType, mConvert1to2); } /// <summary> /// Transform a file that contains source records to an array of the destination type /// </summary> /// <param name="sourceFile">A file containing the source records.</param> /// <returns>The transformed records.</returns> public TDestination[] ReadAndTransformRecords(string sourceFile) { var engine = new FileHelperAsyncEngine<TSource>(mSourceEncoding) { ErrorMode = ErrorMode }; mSourceErrorManager = engine.ErrorManager; mDestinationErrorManager = new ErrorManager(ErrorMode); var res = new List<TDestination>(); engine.BeginReadFile(sourceFile); foreach (var record in engine) res.Add(record.TransformTo()); engine.Close(); return res.ToArray(); } #region " Transform Internal Methods " private TDestination[] CoreTransform(InternalStreamReader sourceFile, StreamWriter destFile) { var sourceEngine = new FileHelperEngine<TSource>(mSourceEncoding); var destEngine = new FileHelperEngine<TDestination>(mDestinationEncoding); sourceEngine.ErrorMode = ErrorMode; destEngine.ErrorManager.ErrorMode = ErrorMode; mSourceErrorManager = sourceEngine.ErrorManager; mDestinationErrorManager = destEngine.ErrorManager; TSource[] source = sourceEngine.ReadStream(sourceFile); TDestination[] transformed = CoreTransformRecords(source); destEngine.WriteStream(destFile, transformed); return transformed; } private TDestination[] CoreTransformRecords(TSource[] sourceRecords) { var res = new List<TDestination>(sourceRecords.Length); for (int i = 0; i < sourceRecords.Length; i++) res.Add(sourceRecords[i].TransformTo()); return res.ToArray(); } private TDestination[] CoreTransformFile(string sourceFile, string destFile) { TDestination[] tempRes; using ( var fs = new InternalStreamReader(sourceFile, mSourceEncoding, true, EngineBase.DefaultReadBufferSize*10) ) { using ( var ds = new StreamWriter(destFile, false, mDestinationEncoding, EngineBase.DefaultWriteBufferSize*10)) { tempRes = CoreTransform(fs, ds); ds.Close(); } fs.Close(); } return tempRes; } private int CoreTransformAsync(TextReader sourceFile, StreamWriter destFile) { var sourceEngine = new FileHelperAsyncEngine<TSource>(); var destEngine = new FileHelperAsyncEngine<TDestination>(); sourceEngine.ErrorMode = ErrorMode; destEngine.ErrorMode = ErrorMode; mSourceErrorManager = sourceEngine.ErrorManager; mDestinationErrorManager = destEngine.ErrorManager; sourceEngine.Encoding = mSourceEncoding; destEngine.Encoding = mDestinationEncoding; sourceEngine.BeginReadStream(sourceFile); destEngine.BeginWriteStream(destFile); foreach (var record in sourceEngine) destEngine.WriteNext(record.TransformTo()); sourceEngine.Close(); destEngine.Close(); return sourceEngine.TotalRecords; } #endregion #region " Properties " /// <summary>The source record Type.</summary> public Type SourceType { get { return typeof (TSource); } } /// <summary>The destination record Type.</summary> public Type DestinationType { get { return typeof (TDestination); } } /// <summary>The Encoding of the Source File.</summary> public Encoding SourceEncoding { get { return mSourceEncoding; } set { mSourceEncoding = value; } } /// <summary>The Encoding of the Destination File.</summary> public Encoding DestinationEncoding { get { return mDestinationEncoding; } set { mDestinationEncoding = value; } } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using OpenLiveWriter.BlogClient; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.Localization; namespace OpenLiveWriter.PostEditor.Configuration.Wizard { /// <summary> /// Summary description for WeblogConfigurationWizardPanelAuthentication. /// </summary> internal class WeblogConfigurationWizardPanelSharePointAuthentication : WeblogConfigurationWizardPanel, IAccountBasicInfoProvider { private System.Windows.Forms.Label labelPassword; private System.Windows.Forms.TextBox textBoxPassword; private System.Windows.Forms.TextBox textBoxUsername; private System.Windows.Forms.Label labelUsername; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.CheckBox cbUseSystemLogin; private System.Windows.Forms.CheckBox checkBoxSavePassword; IAccountBasicInfoProvider _basicInfoProvider; public WeblogConfigurationWizardPanelSharePointAuthentication() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); labelHeader.Text = Res.Get(StringId.CWSharePointTitle2); labelUsername.Text = Res.Get(StringId.UsernameLabel); labelPassword.Text = Res.Get(StringId.PasswordLabel); cbUseSystemLogin.Text = Res.Get(StringId.CWSharePointUseSystemLogin); checkBoxSavePassword.Text = Res.Get(StringId.RememberPassword); textBoxPassword.PasswordChar = Res.PasswordChar; cbUseSystemLogin.Checked = true; } public WeblogConfigurationWizardPanelSharePointAuthentication(IAccountBasicInfoProvider basicInfoProvider) : this() { _basicInfoProvider = basicInfoProvider; } public override void NaturalizeLayout() { if (!DesignMode) { MaximizeWidth(labelUsername); MaximizeWidth(labelPassword); MaximizeWidth(checkBoxSavePassword); MaximizeWidth(cbUseSystemLogin); LayoutHelper.NaturalizeHeight(labelUsername, labelPassword, checkBoxSavePassword, cbUseSystemLogin); LayoutHelper.DistributeVertically(10, false, cbUseSystemLogin, labelUsername); LayoutHelper.DistributeVertically(3, false, labelUsername, textBoxUsername); LayoutHelper.DistributeVertically(10, false, textBoxUsername, labelPassword); LayoutHelper.DistributeVertically(3, false, labelPassword, textBoxPassword, checkBoxSavePassword); } } public override ConfigPanelId? PanelId { get { return ConfigPanelId.SharePointAuth; } } /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.labelPassword = new System.Windows.Forms.Label(); this.textBoxPassword = new System.Windows.Forms.TextBox(); this.textBoxUsername = new System.Windows.Forms.TextBox(); this.labelUsername = new System.Windows.Forms.Label(); this.cbUseSystemLogin = new System.Windows.Forms.CheckBox(); this.checkBoxSavePassword = new System.Windows.Forms.CheckBox(); this.panelMain.SuspendLayout(); this.SuspendLayout(); // // panelMain // this.panelMain.Controls.Add(this.labelUsername); this.panelMain.Controls.Add(this.textBoxUsername); this.panelMain.Controls.Add(this.labelPassword); this.panelMain.Controls.Add(this.textBoxPassword); this.panelMain.Controls.Add(this.cbUseSystemLogin); this.panelMain.Controls.Add(this.checkBoxSavePassword); // // labelPassword // this.labelPassword.Location = new System.Drawing.Point(20, 0); this.labelPassword.FlatStyle = FlatStyle.System; this.labelPassword.Name = "labelPassword"; this.labelPassword.Size = new System.Drawing.Size(168, 13); this.labelPassword.TabIndex = 3; this.labelPassword.Text = "&Password:"; // // textBoxPassword // this.textBoxPassword.Location = new System.Drawing.Point(20, 16); this.textBoxPassword.Name = "textBoxPassword"; this.textBoxPassword.PasswordChar = '*'; this.textBoxPassword.Size = new System.Drawing.Size(168, 20); this.textBoxPassword.TabIndex = 4; this.textBoxPassword.Text = ""; // // textBoxUsername // this.textBoxUsername.Location = new System.Drawing.Point(20, 16); this.textBoxUsername.Name = "textBoxUsername"; this.textBoxUsername.Size = new System.Drawing.Size(168, 20); this.textBoxUsername.TabIndex = 2; this.textBoxUsername.Text = ""; // // labelUsername // this.labelUsername.Location = new System.Drawing.Point(20, 0); this.labelUsername.FlatStyle = FlatStyle.System; this.labelUsername.Name = "labelUsername"; this.labelUsername.Size = new System.Drawing.Size(168, 13); this.labelUsername.TabIndex = 1; this.labelUsername.Text = "&Username:"; // // cbUseSystemLogin // this.cbUseSystemLogin.FlatStyle = System.Windows.Forms.FlatStyle.System; this.cbUseSystemLogin.Location = new System.Drawing.Point(20, 0); this.cbUseSystemLogin.Name = "cbUseSystemLogin"; this.cbUseSystemLogin.Size = new System.Drawing.Size(360, 24); this.cbUseSystemLogin.TabIndex = 0; this.cbUseSystemLogin.Text = "Use my &Windows username and password"; this.cbUseSystemLogin.CheckedChanged += new System.EventHandler(this.cbUseSystemLogin_CheckedChanged); // // checkBoxSavePassword // this.checkBoxSavePassword.FlatStyle = System.Windows.Forms.FlatStyle.System; this.checkBoxSavePassword.Location = new System.Drawing.Point(20, 40); this.checkBoxSavePassword.Name = "checkBoxSavePassword"; this.checkBoxSavePassword.Size = new System.Drawing.Size(176, 26); this.checkBoxSavePassword.TabIndex = 5; this.checkBoxSavePassword.Text = "&Remember my password"; this.checkBoxSavePassword.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // WeblogConfigurationWizardPanelSharePointAuthentication // this.Name = "WeblogConfigurationWizardPanelSharePointAuthentication"; this.panelMain.ResumeLayout(false); this.ResumeLayout(false); } #endregion /*public string Username { get{ return textBoxUsername.Text.Trim(); } set{ textBoxUsername.Text = value; } } public string Password { get{ return textBoxPassword.Text.Trim(); } set{ textBoxPassword.Text = value; } }*/ public override bool ValidatePanel() { if (!cbUseSystemLogin.Checked) { if (textBoxUsername.Text.Trim() == String.Empty) { ShowValidationError(textBoxUsername, MessageId.UsernameAndPasswordRequired); return false; } if (textBoxPassword.Text.Trim() == String.Empty) { ShowValidationError(textBoxPassword, MessageId.UsernameAndPasswordRequired); return false; } } return true; } public bool IsDirty(TemporaryBlogSettings settings) { return _basicInfoProvider.IsDirty(settings) || Credentials.Username != settings.Credentials.Username; } private void cbUseSystemLogin_CheckedChanged(object sender, System.EventArgs e) { if (cbUseSystemLogin.Checked) { textBoxUsername.Text = ""; textBoxPassword.Text = ""; } textBoxUsername.Enabled = textBoxPassword.Enabled = checkBoxSavePassword.Enabled = !cbUseSystemLogin.Checked; } public IBlogProviderAccountWizardDescription ProviderAccountWizard { set { } } public string AccountId { set { _basicInfoProvider.AccountId = value; } } public string HomepageUrl { get { return _basicInfoProvider.HomepageUrl; } set { _basicInfoProvider.HomepageUrl = value; } } public bool SavePassword { get { return checkBoxSavePassword.Checked; } set { checkBoxSavePassword.Checked = value; } } public bool ForceManualConfiguration { get { return false; } set { } } public IBlogCredentials Credentials { get { TemporaryBlogCredentials credentials = new TemporaryBlogCredentials(); credentials.Username = textBoxUsername.Text.Trim(); credentials.Password = textBoxPassword.Text.Trim(); return credentials; } set { textBoxUsername.Text = value.Username; textBoxPassword.Text = value.Password; cbUseSystemLogin.Checked = textBoxUsername.Text == String.Empty && textBoxPassword.Text == String.Empty; } } public BlogInfo BlogAccount { get { return _basicInfoProvider.BlogAccount; } } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.MapKit; using MonoTouch.CoreLocation; using MonoTouch.ObjCRuntime; //using System.Runtime.InteropServices; namespace LMT81 { public partial class MapController : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code public MapController (IntPtr handle) : base(handle) { Initialize (); } [Export("initWithCoder:")] public MapController (NSCoder coder) : base(coder) { Initialize (); } public MapController () : base("MapController", null) { Initialize (); } void Initialize () { } #endregion MapDelegate _md; public override void ViewDidLoad () { base.ViewDidLoad (); _md = new MapDelegate (); map.Delegate = _md; map.AddAnnotation (new RestaurantAnnotation[] { new RestaurantAnnotation ("Mike's Pizza", "Gourmet Pizza Kitchen", new CLLocationCoordinate2D (41.86337816, -72.56874647), RestaurantKind.Pizza), new RestaurantAnnotation ("Barb's Seafod", "Best Seafood in New England", new CLLocationCoordinate2D (41.96337816, -72.96874647), RestaurantKind.Seafood), new RestaurantAnnotation ("John's Pizza", "Deep Dish Style", new CLLocationCoordinate2D (41.45537816, -72.76874647), RestaurantKind.Pizza)}); AddOverlays (); map.MapType = MKMapType.Hybrid; } public void AddOverlays () { // sample coordinates CLLocationCoordinate2D c1 = new CLLocationCoordinate2D (41.86337816, -72.56874647); CLLocationCoordinate2D c2 = new CLLocationCoordinate2D (41.96337816, -72.96874647); CLLocationCoordinate2D c3 = new CLLocationCoordinate2D (41.45537816, -72.76874647); CLLocationCoordinate2D c4 = new CLLocationCoordinate2D (42.34994, -71.09292); // circle MKCircle circle = MKCircle.Circle (c1, 10000.0); // 10000 meter radius map.AddOverlay (circle); // polygon MKPolygon polygon = MKPolygon.FromCoordinates(new CLLocationCoordinate2D[]{c1,c2,c3}); map.AddOverlay(polygon); // triangle MKPolyline polyline = MKPolyline.FromCoordinates(new CLLocationCoordinate2D[]{c1,c2,c3}); map.AddOverlay(polyline); CustomOverlay co = new CustomOverlay(c4); map.AddOverlay(co); } class MapDelegate : MKMapViewDelegate { static string annotationId = "restaurauntAnnotation"; public override void DidSelectAnnotationView (MKMapView mapView, MKAnnotationView view) { MKUserLocation userLocationAnnotation = view.Annotation as MKUserLocation; if (userLocationAnnotation != null) { CLLocationCoordinate2D coord = userLocationAnnotation.Location.Coordinate; MKCoordinateRegion region = MKCoordinateRegion.FromDistance (coord, 500, 500); mapView.CenterCoordinate = coord; mapView.Region = region; userLocationAnnotation.Title = "I am here"; } } public override MKAnnotationView GetViewForAnnotation (MKMapView mapView, NSObject annotation) { if (annotation is MKUserLocation) return null; // stock pin annotation view // MKPinAnnotationView annotationView = mapView.DequeueReusableAnnotation (annotationId) as MKPinAnnotationView; // if (annotationView == null) // annotationView = new MKPinAnnotationView (annotation, annotationId); // // annotationView.PinColor = MKPinAnnotationColor.Purple; // annotationView.CanShowCallout = true; // annotationView.Draggable = true; // annotationView.RightCalloutAccessoryView = UIButton.FromType (UIButtonType.DetailDisclosure); // annotation view with custom image set var restaurantAnnotation = annotation as RestaurantAnnotation; MKAnnotationView annotationView = mapView.DequeueReusableAnnotation (annotationId); if (annotationView == null) annotationView = new MKAnnotationView (annotation, annotationId); switch (restaurantAnnotation.Kind) { case RestaurantKind.Pizza: annotationView.Image = UIImage.FromFile ("images/Pizza.png"); break; case RestaurantKind.Seafood: annotationView.Image = UIImage.FromFile ("images/Seafood.png"); break; } annotationView.CanShowCallout = true; annotationView.RightCalloutAccessoryView = UIButton.FromType (UIButtonType.DetailDisclosure); return annotationView; } public override MKOverlayView GetViewForOverlay (MKMapView mapView, NSObject overlay) { MKOverlayView overlayView = null; if(overlay is MKPolygon){ MKPolygon polygon = overlay as MKPolygon; var polygonView = new MKPolygonView(polygon); polygonView.FillColor = UIColor.Purple; polygonView.Alpha = 0.7f; overlayView = polygonView; } else if(overlay is MKCircle){ MKCircle circle = overlay as MKCircle; var circleView = new MKCircleView (circle); circleView.FillColor = UIColor.Green; overlayView = circleView; } else if(overlay is MKPolyline){ MKPolyline polyline = overlay as MKPolyline; var polylineView = new MKPolylineView (polyline); polylineView.StrokeColor = UIColor.Black; overlayView = polylineView; } else if(overlay is CustomOverlay) { CustomOverlay co = overlay as CustomOverlay; var v = new CustomOverlayView(co); overlayView = v; } return overlayView; } public override void DidAddAnnotationViews (MKMapView mapView, MKAnnotationView[] views) { Console.WriteLine ("TODO: add region code to zoom in here..."); } public override void CalloutAccessoryControlTapped (MKMapView mapView, MKAnnotationView view, UIControl control) { var annotation = view.Annotation as RestaurantAnnotation; if (annotation != null) { string message = String.Format ("{0} tapped", annotation.Title); UIAlertView alert = new UIAlertView ("Annotation Tapped", message, null, "OK"); alert.Show (); } } public override void ChangedDragState (MKMapView mapView, MKAnnotationView annotationView, MKAnnotationViewDragState newState, MKAnnotationViewDragState oldState) { Console.WriteLine ("drag state changed"); } } } }
// 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. using System.Linq.Expressions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Reflection; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime.Binding { using Ast = Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; internal partial class MetaPythonType : MetaPythonObject, IPythonInvokable { #region IPythonInvokable Members public DynamicMetaObject/*!*/ Invoke(PythonInvokeBinder/*!*/ pythonInvoke, Expression/*!*/ codeContext, DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args) { DynamicMetaObject translated = BuiltinFunction.TranslateArguments(pythonInvoke, codeContext, target, args, false, Value.Name); if (translated != null) { return translated; } return InvokeWorker(pythonInvoke, args, codeContext); } #endregion #region MetaObject Overrides public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) { foreach (PythonType pt in Value.ResolutionOrder) { if (pt.IsSystemType) { return action.FallbackInvokeMember(this, args); } else if (pt.TryResolveSlot(DefaultContext.DefaultCLS, action.Name, out _)) { break; } } return BindingHelpers.GenericInvokeMember(action, null, this, args); } public override DynamicMetaObject/*!*/ BindInvoke(InvokeBinder/*!*/ call, params DynamicMetaObject/*!*/[]/*!*/ args) { return InvokeWorker(call, args, PythonContext.GetCodeContext(call)); } #endregion #region Invoke Implementation private DynamicMetaObject/*!*/ InvokeWorker(DynamicMetaObjectBinder/*!*/ call, DynamicMetaObject/*!*/[]/*!*/ args, Expression/*!*/ codeContext) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Type Invoke " + Value.UnderlyingSystemType.FullName + args.Length); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "Type Invoke"); if (this.NeedsDeferral()) { return call.Defer(ArrayUtils.Insert(this, args)); } for (int i = 0; i < args.Length; i++) { if (args[i].NeedsDeferral()) { return call.Defer(ArrayUtils.Insert(this, args)); } } DynamicMetaObject res; if (IsStandardDotNetType(call)) { res = MakeStandardDotNetTypeCall(call, codeContext, args); } else { res = MakePythonTypeCall(call, codeContext, args); } return BindingHelpers.AddPythonBoxing(res); } /// <summary> /// Creating a standard .NET type is easy - we just call it's constructor with the provided /// arguments. /// </summary> private DynamicMetaObject/*!*/ MakeStandardDotNetTypeCall(DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext, DynamicMetaObject/*!*/[]/*!*/ args) { CallSignature signature = BindingHelpers.GetCallSignature(call); PythonContext state = PythonContext.GetPythonContext(call); MethodBase[] ctors = PythonTypeOps.GetConstructors(Value.UnderlyingSystemType, state.Binder.PrivateBinding); if (ctors.Length > 0) { return state.Binder.CallMethod( new PythonOverloadResolver( state.Binder, args, signature, codeContext ), ctors, Restrictions.Merge(BindingRestrictions.GetInstanceRestriction(Expression, Value)) ); } else { string msg; if (Value.UnderlyingSystemType.IsAbstract) { msg = String.Format("Cannot create instances of {0} because it is abstract", Value.Name); }else{ msg = String.Format("Cannot create instances of {0} because it has no public constructors", Value.Name); } return new DynamicMetaObject( call.Throw( Ast.New( typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(msg) ) ), Restrictions.Merge(BindingRestrictions.GetInstanceRestriction(Expression, Value)) ); } } /// <summary> /// Creating a Python type involves calling __new__ and __init__. We resolve them /// and generate calls to either the builtin funcions directly or embed sites which /// call the slots at runtime. /// </summary> private DynamicMetaObject/*!*/ MakePythonTypeCall(DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext, DynamicMetaObject/*!*/[]/*!*/ args) { ValidationInfo valInfo = MakeVersionCheck(); DynamicMetaObject self = new RestrictedMetaObject( AstUtils.Convert(Expression, LimitType), BindingRestrictionsHelpers.GetRuntimeTypeRestriction(Expression, LimitType), Value ); CallSignature sig = BindingHelpers.GetCallSignature(call); ArgumentValues ai = new ArgumentValues(sig, self, args); NewAdapter newAdapter; InitAdapter initAdapter; if (TooManyArgsForDefaultNew(call, args)) { return MakeIncorrectArgumentsForCallError(call, ai, valInfo); } else if (Value.UnderlyingSystemType.IsGenericTypeDefinition) { return MakeGenericTypeDefinitionError(call, ai, valInfo); } else if (Value.HasAbstractMethods(PythonContext.GetPythonContext(call).SharedContext)) { return MakeAbstractInstantiationError(call, ai, valInfo); } DynamicMetaObject translated = BuiltinFunction.TranslateArguments(call, codeContext, self, args, false, Value.Name); if (translated != null) { return translated; } GetAdapters(ai, call, codeContext, out newAdapter, out initAdapter); PythonContext state = PythonContext.GetPythonContext(call); // get the expression for calling __new__ DynamicMetaObject createExpr = newAdapter.GetExpression(state.Binder); if (createExpr.Expression.Type == typeof(void)) { return BindingHelpers.AddDynamicTestAndDefer( call, createExpr, args, valInfo ); } Expression res; BindingRestrictions additionalRestrictions; if (!Value.IsSystemType && (!(newAdapter is DefaultNewAdapter) || HasFinalizer(call))) { // we need to dynamically check the return value to see if it's a subtype of // the type that we are calling. If it is then we need to call __init__/__del__ // for the actual returned type. res = DynamicExpression.Dynamic( Value.GetLateBoundInitBinder(sig), typeof(object), ArrayUtils.Insert( codeContext, Expression.Convert(createExpr.Expression, typeof(object)), DynamicUtils.GetExpressions(args) ) ); additionalRestrictions = createExpr.Restrictions; } else { // just call the __init__ method, built-in types currently have // no wacky return values which don't return the derived type. // then get the statement for calling __init__ ParameterExpression allocatedInst = Ast.Variable(createExpr.GetLimitType(), "newInst"); Expression tmpRead = allocatedInst; DynamicMetaObject initCall = initAdapter.MakeInitCall( state.Binder, new RestrictedMetaObject( AstUtils.Convert(allocatedInst, Value.UnderlyingSystemType), createExpr.Restrictions ) ); List<Expression> body = new List<Expression>(); Debug.Assert(!HasFinalizer(call)); // add the call to init if we need to if (initCall.Expression != tmpRead) { // init can fail but if __new__ returns a different type // no exception is raised. DynamicMetaObject initStmt = initCall; if (body.Count == 0) { body.Add( Ast.Assign(allocatedInst, createExpr.Expression) ); } if (!Value.UnderlyingSystemType.IsAssignableFrom(createExpr.Expression.Type)) { // return type of object, we need to check the return type before calling __init__. body.Add( AstUtils.IfThen( Ast.TypeIs(allocatedInst, Value.UnderlyingSystemType), initStmt.Expression ) ); } else { // just call the __init__ method, no type check necessary (TODO: need null check?) body.Add(initStmt.Expression); } } // and build the target from everything we have if (body.Count == 0) { res = createExpr.Expression; } else { body.Add(allocatedInst); res = Ast.Block(body); } res = Ast.Block(new ParameterExpression[] { allocatedInst }, res); additionalRestrictions = initCall.Restrictions; } return BindingHelpers.AddDynamicTestAndDefer( call, new DynamicMetaObject( res, self.Restrictions.Merge(additionalRestrictions) ), ArrayUtils.Insert(this, args), valInfo ); } #endregion #region Adapter support private void GetAdapters(ArgumentValues/*!*/ ai, DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext, out NewAdapter/*!*/ newAdapter, out InitAdapter/*!*/ initAdapter) { PythonTypeSlot newInst, init; Value.TryResolveSlot(PythonContext.GetPythonContext(call).SharedContext, "__new__", out newInst); Value.TryResolveSlot(PythonContext.GetPythonContext(call).SharedContext, "__init__", out init); // these are never null because we always resolve to __new__ or __init__ somewhere. Assert.NotNull(newInst, init); newAdapter = GetNewAdapter(ai, newInst, call, codeContext); initAdapter = GetInitAdapter(ai, init, call, codeContext); } private InitAdapter/*!*/ GetInitAdapter(ArgumentValues/*!*/ ai, PythonTypeSlot/*!*/ init, DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext) { PythonContext state = PythonContext.GetPythonContext(call); if ((init == InstanceOps.Init && !HasFinalizer(call)) || (Value == TypeCache.PythonType && ai.Arguments.Length == 2)) { return new DefaultInitAdapter(ai, state, codeContext); } else if (init is BuiltinMethodDescriptor) { return new BuiltinInitAdapter(ai, ((BuiltinMethodDescriptor)init).Template, state, codeContext); } else if (init is BuiltinFunction) { return new BuiltinInitAdapter(ai, (BuiltinFunction)init, state, codeContext); } else { return new SlotInitAdapter(init, ai, state, codeContext); } } private NewAdapter/*!*/ GetNewAdapter(ArgumentValues/*!*/ ai, PythonTypeSlot/*!*/ newInst, DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext) { PythonContext state = PythonContext.GetPythonContext(call); if (newInst == InstanceOps.New) { return new DefaultNewAdapter(ai, Value, state, codeContext); } else if (newInst is ConstructorFunction) { return new ConstructorNewAdapter(ai, Value, state, codeContext); } else if (newInst is BuiltinFunction) { return new BuiltinNewAdapter(ai, Value, ((BuiltinFunction)newInst), state, codeContext); } return new NewAdapter(ai, state, codeContext); } private class CallAdapter { private readonly ArgumentValues/*!*/ _argInfo; private readonly PythonContext/*!*/ _state; private readonly Expression/*!*/ _context; public CallAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) { _argInfo = ai; _state = state; _context = codeContext; } protected PythonContext PythonContext { get { return _state; } } protected Expression CodeContext { get { return _context; } } protected ArgumentValues/*!*/ Arguments { get { return _argInfo; } } } private class ArgumentValues { public readonly DynamicMetaObject/*!*/ Self; public readonly DynamicMetaObject/*!*/[]/*!*/ Arguments; public readonly CallSignature Signature; public ArgumentValues(CallSignature signature, DynamicMetaObject/*!*/ self, DynamicMetaObject/*!*/[]/*!*/ args) { Self = self; Signature = signature; Arguments = args; } } #endregion #region __new__ adapters private class NewAdapter : CallAdapter { public NewAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { } public virtual DynamicMetaObject/*!*/ GetExpression(PythonBinder/*!*/ binder) { return MakeDefaultNew( binder, Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.PythonTypeGetMember)), CodeContext, AstUtils.Convert(Arguments.Self.Expression, typeof(PythonType)), AstUtils.Constant(null), AstUtils.Constant("__new__") ) ); } protected DynamicMetaObject/*!*/ MakeDefaultNew(DefaultBinder/*!*/ binder, Expression/*!*/ function) { // calling theType.__new__(theType, args) List<Expression> args = new List<Expression>(); args.Add(CodeContext); args.Add(function); AppendNewArgs(args); return new DynamicMetaObject( DynamicExpression.Dynamic( PythonContext.Invoke( GetDynamicNewSignature() ), typeof(object), args.ToArray() ), Arguments.Self.Restrictions ); } private void AppendNewArgs(List<Expression> args) { // theType args.Add(Arguments.Self.Expression); // args foreach (DynamicMetaObject mo in Arguments.Arguments) { args.Add(mo.Expression); } } protected CallSignature GetDynamicNewSignature() { return Arguments.Signature.InsertArgument(Argument.Simple); } } private class DefaultNewAdapter : NewAdapter { private readonly PythonType/*!*/ _creating; public DefaultNewAdapter(ArgumentValues/*!*/ ai, PythonType/*!*/ creating, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _creating = creating; } public override DynamicMetaObject/*!*/ GetExpression(PythonBinder/*!*/ binder) { PythonOverloadResolver resolver; if (_creating.IsSystemType || _creating.HasSystemCtor) { resolver = new PythonOverloadResolver(binder, DynamicMetaObject.EmptyMetaObjects, new CallSignature(0), CodeContext); } else { resolver = new PythonOverloadResolver(binder, new[] { Arguments.Self }, new CallSignature(1), CodeContext); } return binder.CallMethod(resolver, _creating.UnderlyingSystemType.GetConstructors(), BindingRestrictions.Empty, _creating.Name); } } private class ConstructorNewAdapter : NewAdapter { private readonly PythonType/*!*/ _creating; public ConstructorNewAdapter(ArgumentValues/*!*/ ai, PythonType/*!*/ creating, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _creating = creating; } public override DynamicMetaObject/*!*/ GetExpression(PythonBinder/*!*/ binder) { PythonOverloadResolver resolve; if (_creating.IsSystemType || _creating.HasSystemCtor) { resolve = new PythonOverloadResolver( binder, Arguments.Arguments, Arguments.Signature, CodeContext ); } else { resolve = new PythonOverloadResolver( binder, ArrayUtils.Insert(Arguments.Self, Arguments.Arguments), GetDynamicNewSignature(), CodeContext ); } return binder.CallMethod( resolve, _creating.UnderlyingSystemType.GetConstructors(), Arguments.Self.Restrictions, _creating.Name ); } } private class BuiltinNewAdapter : NewAdapter { private readonly PythonType/*!*/ _creating; private readonly BuiltinFunction/*!*/ _ctor; public BuiltinNewAdapter(ArgumentValues/*!*/ ai, PythonType/*!*/ creating, BuiltinFunction/*!*/ ctor, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _creating = creating; _ctor = ctor; } public override DynamicMetaObject/*!*/ GetExpression(PythonBinder/*!*/ binder) { return binder.CallMethod( new PythonOverloadResolver( binder, ArrayUtils.Insert(Arguments.Self, Arguments.Arguments), Arguments.Signature.InsertArgument(new Argument(ArgumentType.Simple)), CodeContext ), _ctor.Targets, _creating.Name ); } } #endregion #region __init__ adapters private abstract class InitAdapter : CallAdapter { protected InitAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { } public abstract DynamicMetaObject/*!*/ MakeInitCall(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr); protected DynamicMetaObject/*!*/ MakeDefaultInit(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr, Expression/*!*/ init) { List<Expression> args = new List<Expression>(); args.Add(CodeContext); args.Add(Expression.Convert(createExpr.Expression, typeof(object))); foreach (DynamicMetaObject mo in Arguments.Arguments) { args.Add(mo.Expression); } return new DynamicMetaObject( DynamicExpression.Dynamic( ((PythonType)Arguments.Self.Value).GetLateBoundInitBinder(Arguments.Signature), typeof(object), args.ToArray() ), Arguments.Self.Restrictions.Merge(createExpr.Restrictions) ); } } private class SlotInitAdapter : InitAdapter { private readonly PythonTypeSlot/*!*/ _slot; public SlotInitAdapter(PythonTypeSlot/*!*/ slot, ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _slot = slot; } public override DynamicMetaObject/*!*/ MakeInitCall(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr) { Expression init = Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.GetInitSlotMember)), CodeContext, Ast.Convert(Arguments.Self.Expression, typeof(PythonType)), Ast.Convert(AstUtils.WeakConstant(_slot), typeof(PythonTypeSlot)), AstUtils.Convert(createExpr.Expression, typeof(object)) ); return MakeDefaultInit(binder, createExpr, init); } } private class DefaultInitAdapter : InitAdapter { public DefaultInitAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { } public override DynamicMetaObject/*!*/ MakeInitCall(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr) { // default init, we can just return the value from __new__ return createExpr; } } private class BuiltinInitAdapter : InitAdapter { private readonly BuiltinFunction/*!*/ _method; public BuiltinInitAdapter(ArgumentValues/*!*/ ai, BuiltinFunction/*!*/ method, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _method = method; } public override DynamicMetaObject/*!*/ MakeInitCall(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr) { if (_method == InstanceOps.Init.Template) { // we have a default __init__, don't call it. return createExpr; } return binder.CallMethod( new PythonOverloadResolver( binder, createExpr, Arguments.Arguments, Arguments.Signature, CodeContext ), _method.Targets, Arguments.Self.Restrictions ); } } #endregion #region Helpers private DynamicMetaObject/*!*/ MakeIncorrectArgumentsForCallError(DynamicMetaObjectBinder/*!*/ call, ArgumentValues/*!*/ ai, ValidationInfo/*!*/ valInfo) { string message; if (Value.IsSystemType) { if (Value.UnderlyingSystemType.GetConstructors().Length == 0) { // this is a type we can't create ANY instances of, give the user a half-way decent error message message = "cannot create instances of " + Value.Name; } else { message = InstanceOps.ObjectNewNoParameters; } } else { message = InstanceOps.ObjectNewNoParameters; } return BindingHelpers.AddDynamicTestAndDefer( call, new DynamicMetaObject( call.Throw( Ast.New( typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(message) ) ), GetErrorRestrictions(ai) ), ai.Arguments, valInfo ); } private DynamicMetaObject/*!*/ MakeGenericTypeDefinitionError(DynamicMetaObjectBinder/*!*/ call, ArgumentValues/*!*/ ai, ValidationInfo/*!*/ valInfo) { Debug.Assert(Value.IsSystemType); string message = "cannot create instances of " + Value.Name + " because it is a generic type definition"; return BindingHelpers.AddDynamicTestAndDefer( call, new DynamicMetaObject( call.Throw( Ast.New( typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(message) ), typeof(object) ), GetErrorRestrictions(ai) ), ai.Arguments, valInfo ); } private DynamicMetaObject/*!*/ MakeAbstractInstantiationError(DynamicMetaObjectBinder/*!*/ call, ArgumentValues/*!*/ ai, ValidationInfo/*!*/ valInfo) { CodeContext context = PythonContext.GetPythonContext(call).SharedContext; string message = Value.GetAbstractErrorMessage(context); Debug.Assert(message != null); return BindingHelpers.AddDynamicTestAndDefer( call, new DynamicMetaObject( Ast.Throw( Ast.New( typeof(ArgumentTypeException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(message) ), typeof(object) ), GetErrorRestrictions(ai) ), ai.Arguments, valInfo ); } private BindingRestrictions/*!*/ GetErrorRestrictions(ArgumentValues/*!*/ ai) { BindingRestrictions res = Restrict(this.GetRuntimeType()).Restrictions; res = res.Merge(GetInstanceRestriction(ai)); foreach (DynamicMetaObject mo in ai.Arguments) { if (mo.HasValue) { res = res.Merge(mo.Restrict(mo.GetRuntimeType()).Restrictions); } } return res; } private static BindingRestrictions GetInstanceRestriction(ArgumentValues ai) { return BindingRestrictions.GetInstanceRestriction(ai.Self.Expression, ai.Self.Value); } private bool HasFinalizer(DynamicMetaObjectBinder/*!*/ action) { // only user types have finalizers... if (Value.IsSystemType) return false; bool hasDel = Value.TryResolveSlot(PythonContext.GetPythonContext(action).SharedContext, "__del__", out _); return hasDel; } private bool HasDefaultNew(DynamicMetaObjectBinder/*!*/ action) { PythonTypeSlot newInst; Value.TryResolveSlot(PythonContext.GetPythonContext(action).SharedContext, "__new__", out newInst); return newInst == InstanceOps.New; } private bool HasDefaultInit(DynamicMetaObjectBinder/*!*/ action) { PythonTypeSlot init; Value.TryResolveSlot(PythonContext.GetPythonContext(action).SharedContext, "__init__", out init); return init == InstanceOps.Init; } private bool HasDefaultNewAndInit(DynamicMetaObjectBinder/*!*/ action) { return HasDefaultNew(action) && HasDefaultInit(action); } /// <summary> /// Checks if we have a default new and init - in this case if we have any /// arguments we don't allow the call. /// </summary> private bool TooManyArgsForDefaultNew(DynamicMetaObjectBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) { if (args.Length > 0 && HasDefaultNewAndInit(action)) { Argument[] infos = BindingHelpers.GetCallSignature(action).GetArgumentInfos(); for (int i = 0; i < infos.Length; i++) { Argument curArg = infos[i]; switch(curArg.Kind) { case ArgumentType.List: // Deferral? if (((IList<object>)args[i].Value).Count > 0) { return true; } break; case ArgumentType.Dictionary: // Deferral? if (PythonOps.Length(args[i].Value) > 0) { return true; } break; default: return true; } } } return false; } /// <summary> /// Creates a test which tests the specific version of the type. /// </summary> private ValidationInfo/*!*/ MakeVersionCheck() { int version = Value.Version; return new ValidationInfo( Ast.Equal( Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.GetTypeVersion)), Ast.Convert(Expression, typeof(PythonType)) ), AstUtils.Constant(version) ) ); } private bool IsStandardDotNetType(DynamicMetaObjectBinder/*!*/ action) { PythonContext bState = PythonContext.GetPythonContext(action); return Value.IsSystemType && !Value.IsPythonType && !bState.Binder.HasExtensionTypes(Value.UnderlyingSystemType) && !typeof(Delegate).IsAssignableFrom(Value.UnderlyingSystemType) && !Value.UnderlyingSystemType.IsArray; } #endregion } }
/* * IDictionaryConverter.cs * * Copyright ?2007 Michael Schwarz (http://www.ajaxpro.info). * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, 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. */ /* * MS 05-12-21 added Deserialize for Hashtables * JavaScript object will now include the type for key and value * MS 06-04-25 removed unnecessarily used cast * MS 06-05-16 added Generic.IDictionary support * (initial version with new client-side script) * MS 06-05-23 using local variables instead of "new Type()" for get De-/SerializableTypes * MS 06-06-09 removed addNamespace use * MS 06-06-14 changed access to keys and values * MS 06-09-26 improved performance using StringBuilder * MS 07-04-24 added renderJsonCompliant serialization * * */ using System; using System.Reflection; using System.Text; using System.Collections; using System.Collections.Specialized; namespace AjaxPro { /// <summary> /// Provides methods to serialize and deserialize an object that implements IDictionary. /// </summary> public class IDictionaryConverter : IJavaScriptConverter { private string clientType = "Ajax.Web.Dictionary"; /// <summary> /// Initializes a new instance of the <see cref="IDictionaryConverter"/> class. /// </summary> public IDictionaryConverter() : base() { m_AllowInheritance = true; #if(NET20) m_serializableTypes = new Type[] { typeof(IDictionary), typeof(System.Collections.Generic.IDictionary<,>) }; m_deserializableTypes = m_serializableTypes; #else m_serializableTypes = new Type[] { typeof(IDictionary), typeof(NameValueCollection) }; m_deserializableTypes = new Type[] { typeof(IDictionary), typeof(NameValueCollection) }; #endif } /// <summary> /// Render the JavaScript code for prototypes or any other JavaScript method needed from this converter /// on the client-side. /// </summary> /// <returns>Returns JavaScript code.</returns> public override string GetClientScript() { if (AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant")) return ""; return JavaScriptUtil.GetClientNamespaceRepresentation(clientType) + @" " + clientType + @" = function(type,items) { this.__type = type; this.keys = []; this.values = []; if(items != null && !isNaN(items.length)) { for(var i=0; i<items.length; i++) this.add(items[i][0], items[i][1]); } }; Object.extend(" + clientType + @".prototype, { add: function(k, v) { this.keys.push(k); this.values.push(v); return this.values.length -1; }, containsKey: function(key) { for(var i=0; i<this.keys.length; i++) { if(this.keys[i] == key) return true; } return false; }, getKeys: function() { return this.keys; }, getValue: function(key) { for(var i=0; i<this.keys.length && i<this.values.length; i++) { if(this.keys[i] == key){ return this.values[i]; } } return null; }, setValue: function(k, v) { for(var i=0; i<this.keys.length && i<this.values.length; i++) { if(this.keys[i] == k){ this.values[i] = v; } return i; } return this.add(k, v); }, toJSON: function() { return AjaxPro.toJSON({__type:this.__type,keys:this.keys,values:this.values}); } }, true); "; } /// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { JavaScriptObject ht = o as JavaScriptObject; if (ht == null) throw new NotSupportedException(); if (!ht.Contains("keys") || !ht.Contains("values")) throw new NotSupportedException(); IDictionary d = (IDictionary)Activator.CreateInstance(t); ParameterInfo[] p = t.GetMethod("Add").GetParameters(); Type kT = p[0].ParameterType; Type vT = p[1].ParameterType; object key; object value; JavaScriptArray keys = ht["keys"] as JavaScriptArray; JavaScriptArray values = ht["values"] as JavaScriptArray; for (int i = 0; i < keys.Count && i < values.Count; i++) { key = JavaScriptDeserializer.Deserialize(keys[i], kT); value = JavaScriptDeserializer.Deserialize(values[i], vT); d.Add(key, value); } return d; } /// <summary> /// Converts a .NET object into a JSON string. /// </summary> /// <param name="o">The object to convert.</param> /// <returns>Returns a JSON string.</returns> public override string Serialize(object o) { StringBuilder sb = new StringBuilder(); Serialize(o, sb); return sb.ToString(); } /// <summary> /// Serializes the specified o. /// </summary> /// <param name="o">The o.</param> /// <param name="sb">The sb.</param> public override void Serialize(object o, StringBuilder sb) { IDictionary dic = o as IDictionary; if(dic == null) throw new NotSupportedException(); IDictionaryEnumerator enumerable = dic.GetEnumerator(); enumerable.Reset(); bool b = true; bool readFirst = enumerable.MoveNext(); // read the first item Type t = o.GetType(); if (!AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant")) { sb.Append("new "); sb.Append(clientType); sb.Append("("); sb.Append(JavaScriptSerializer.Serialize(t.FullName)); sb.Append(","); } sb.Append("["); if (readFirst) { do { if (b) { b = false; } else { sb.Append(","); } sb.Append('['); sb.Append(JavaScriptSerializer.Serialize(enumerable.Key)); sb.Append(','); sb.Append(JavaScriptSerializer.Serialize(enumerable.Value)); sb.Append(']'); } while (enumerable.MoveNext()); } sb.Append("]"); if (!AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant")) sb.Append(")"); } /// <summary> /// Tries the serialize value. /// </summary> /// <param name="o">The o.</param> /// <param name="t">The t.</param> /// <param name="sb">The sb.</param> /// <returns></returns> public override bool TrySerializeValue(object o, Type t, StringBuilder sb) { #if(NET20) if (IsInterfaceImplemented(o, typeof(IDictionary))) { this.Serialize(o, sb); return true; } #endif return base.TrySerializeValue(o, t, sb); } #if(NET20) /// <summary> /// Determines whether [is interface implemented] [the specified obj]. /// </summary> /// <param name="obj">The obj.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns> /// <c>true</c> if [is interface implemented] [the specified obj]; otherwise, <c>false</c>. /// </returns> internal static bool IsInterfaceImplemented(object obj, Type interfaceType) { if (obj == null) throw new ArgumentNullException("obj"); return obj.GetType().FindInterfaces( new TypeFilter( delegate(Type type, object filter) { return (type.Name == ((Type)filter).Name) && (type.Namespace == ((Type)filter).Namespace); }), interfaceType ).Length == 1; } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace System.Net { [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public enum CookieVariant { Unknown, Plain, Rfc2109, Rfc2965, Default = Rfc2109 } // Cookie class // // Adheres to RFC 2965 // // Currently, only represents client-side cookies. The cookie classes know // how to parse a set-cookie format string, but not a cookie format string // (e.g. "Cookie: $Version=1; name=value; $Path=/foo; $Secure") [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class Cookie { // NOTE: these two constants must change together. internal const int MaxSupportedVersion = 1; internal const string MaxSupportedVersionString = "1"; internal const string SeparatorLiteral = "; "; internal const string EqualsLiteral = "="; internal const string QuotesLiteral = "\""; internal const string SpecialAttributeLiteral = "$"; internal static readonly char[] PortSplitDelimiters = new char[] { ' ', ',', '\"' }; // Space (' ') should be reserved as well per RFCs, but major web browsers support it and some web sites use it - so we support it too internal static readonly char[] ReservedToName = new char[] { '\t', '\r', '\n', '=', ';', ',' }; internal static readonly char[] ReservedToValue = new char[] { ';', ',' }; private string m_comment = string.Empty; // Do not rename (binary serialization) private Uri m_commentUri = null; // Do not rename (binary serialization) private CookieVariant m_cookieVariant = CookieVariant.Plain; // Do not rename (binary serialization) private bool m_discard = false; // Do not rename (binary serialization) private string m_domain = string.Empty; // Do not rename (binary serialization) private bool m_domain_implicit = true; // Do not rename (binary serialization) private DateTime m_expires = DateTime.MinValue; // Do not rename (binary serialization) private string m_name = string.Empty; // Do not rename (binary serialization) private string m_path = string.Empty; // Do not rename (binary serialization) private bool m_path_implicit = true; // Do not rename (binary serialization) private string m_port = string.Empty; // Do not rename (binary serialization) private bool m_port_implicit = true; // Do not rename (binary serialization) private int[] m_port_list = null; // Do not rename (binary serialization) private bool m_secure = false; // Do not rename (binary serialization) [System.Runtime.Serialization.OptionalField] private bool m_httpOnly = false; // Do not rename (binary serialization) private DateTime m_timeStamp = DateTime.Now; // Do not rename (binary serialization) private string m_value = string.Empty; // Do not rename (binary serialization) private int m_version = 0; // Do not rename (binary serialization) private string m_domainKey = string.Empty; // Do not rename (binary serialization) /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif bool IsQuotedVersion = false; /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif bool IsQuotedDomain = false; #if DEBUG static Cookie() { Debug.Assert(MaxSupportedVersion.ToString(NumberFormatInfo.InvariantInfo).Equals(MaxSupportedVersionString, StringComparison.Ordinal)); } #endif public Cookie() { } public Cookie(string name, string value) { Name = name; Value = value; } public Cookie(string name, string value, string path) : this(name, value) { Path = path; } public Cookie(string name, string value, string path, string domain) : this(name, value, path) { Domain = domain; } public string Comment { get { return m_comment; } set { m_comment = value ?? string.Empty; } } public Uri CommentUri { get { return m_commentUri; } set { m_commentUri = value; } } public bool HttpOnly { get { return m_httpOnly; } set { m_httpOnly = value; } } public bool Discard { get { return m_discard; } set { m_discard = value; } } public string Domain { get { return m_domain; } set { m_domain = value ?? string.Empty; m_domain_implicit = false; m_domainKey = string.Empty; // _domainKey will be set when adding this cookie to a container. } } internal bool DomainImplicit { get { return m_domain_implicit; } set { m_domain_implicit = value; } } public bool Expired { get { return (m_expires != DateTime.MinValue) && (m_expires.ToLocalTime() <= DateTime.Now); } set { if (value == true) { m_expires = DateTime.Now; } } } public DateTime Expires { get { return m_expires; } set { m_expires = value; } } public string Name { get { return m_name; } set { if (string.IsNullOrEmpty(value) || !InternalSetName(value)) { throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", value == null ? "<null>" : value)); } } } /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif bool InternalSetName(string value) { if (string.IsNullOrEmpty(value) || value[0] == '$' || value.IndexOfAny(ReservedToName) != -1 || value[0] == ' ' || value[value.Length - 1] == ' ') { m_name = string.Empty; return false; } m_name = value; return true; } public string Path { get { return m_path; } set { m_path = value ?? string.Empty; m_path_implicit = false; } } internal bool Plain { get { return Variant == CookieVariant.Plain; } } /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif Cookie Clone() { Cookie clonedCookie = new Cookie(m_name, m_value); // Copy over all the properties from the original cookie if (!m_port_implicit) { clonedCookie.Port = m_port; } if (!m_path_implicit) { clonedCookie.Path = m_path; } clonedCookie.Domain = m_domain; // If the domain in the original cookie was implicit, we should preserve that property clonedCookie.DomainImplicit = m_domain_implicit; clonedCookie.m_timeStamp = m_timeStamp; clonedCookie.Comment = m_comment; clonedCookie.CommentUri = m_commentUri; clonedCookie.HttpOnly = m_httpOnly; clonedCookie.Discard = m_discard; clonedCookie.Expires = m_expires; clonedCookie.Version = m_version; clonedCookie.Secure = m_secure; // The variant is set when we set properties like port/version. So, // we should copy over the variant from the original cookie after // we set all other properties clonedCookie.m_cookieVariant = m_cookieVariant; return clonedCookie; } private static bool IsDomainEqualToHost(string domain, string host) { // +1 in the host length is to account for the leading dot in domain return (host.Length + 1 == domain.Length) && (string.Compare(host, 0, domain, 1, host.Length, StringComparison.OrdinalIgnoreCase) == 0); } // According to spec we must assume default values for attributes but still // keep in mind that we must not include them into the requests. // We also check the validity of all attributes based on the version and variant (read RFC) // // To work properly this function must be called after cookie construction with // default (response) URI AND setDefault == true // // Afterwards, the function can be called many times with other URIs and // setDefault == false to check whether this cookie matches given uri internal bool VerifySetDefaults(CookieVariant variant, Uri uri, bool isLocalDomain, string localDomain, bool setDefault, bool shouldThrow) { string host = uri.Host; int port = uri.Port; string path = uri.AbsolutePath; bool valid = true; if (setDefault) { // Set Variant. If version is zero => reset cookie to Version0 style if (Version == 0) { variant = CookieVariant.Plain; } else if (Version == 1 && variant == CookieVariant.Unknown) { // Since we don't expose Variant to an app, set it to Default variant = CookieVariant.Default; } m_cookieVariant = variant; } // Check the name if (string.IsNullOrEmpty(m_name) || m_name[0] == '$' || m_name.IndexOfAny(ReservedToName) != -1 || m_name[0] == ' ' || m_name[m_name.Length - 1] == ' ') { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", m_name == null ? "<null>" : m_name)); } return false; } // Check the value if (m_value == null || (!(m_value.Length > 2 && m_value[0] == '\"' && m_value[m_value.Length - 1] == '\"') && m_value.IndexOfAny(ReservedToValue) != -1)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, "Value", m_value == null ? "<null>" : m_value)); } return false; } // Check Comment syntax if (Comment != null && !(Comment.Length > 2 && Comment[0] == '\"' && Comment[Comment.Length - 1] == '\"') && (Comment.IndexOfAny(ReservedToValue) != -1)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.CommentAttributeName, Comment)); } return false; } // Check Path syntax if (Path != null && !(Path.Length > 2 && Path[0] == '\"' && Path[Path.Length - 1] == '\"') && (Path.IndexOfAny(ReservedToValue) != -1)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PathAttributeName, Path)); } return false; } // Check/set domain // // If domain is implicit => assume a) uri is valid, b) just set domain to uri hostname. if (setDefault && m_domain_implicit == true) { m_domain = host; } else { if (!m_domain_implicit) { // Forwarding note: If Uri.Host is of IP address form then the only supported case // is for IMPLICIT domain property of a cookie. // The code below (explicit cookie.Domain value) will try to parse Uri.Host IP string // as a fqdn and reject the cookie. // Aliasing since we might need the KeyValue (but not the original one). string domain = m_domain; // Syntax check for Domain charset plus empty string. if (!DomainCharsTest(domain)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, domain == null ? "<null>" : domain)); } return false; } // Domain must start with '.' if set explicitly. if (domain[0] != '.') { if (!(variant == CookieVariant.Rfc2965 || variant == CookieVariant.Plain)) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, m_domain)); } return false; } domain = '.' + domain; } int host_dot = host.IndexOf('.'); // First quick check is for pushing a cookie into the local domain. if (isLocalDomain && string.Equals(localDomain, domain, StringComparison.OrdinalIgnoreCase)) { valid = true; } else if (domain.IndexOf('.', 1, domain.Length - 2) == -1) { // A single label domain is valid only if the domain is exactly the same as the host specified in the URI. if (!IsDomainEqualToHost(domain, host)) { valid = false; } } else if (variant == CookieVariant.Plain) { // We distinguish between Version0 cookie and other versions on domain issue. // According to Version0 spec a domain must be just a substring of the hostname. if (!IsDomainEqualToHost(domain, host)) { if (host.Length <= domain.Length || (string.Compare(host, host.Length - domain.Length, domain, 0, domain.Length, StringComparison.OrdinalIgnoreCase) != 0)) { valid = false; } } } else if (host_dot == -1 || domain.Length != host.Length - host_dot || (string.Compare(host, host_dot, domain, 0, domain.Length, StringComparison.OrdinalIgnoreCase) != 0)) { // Starting from the first dot, the host must match the domain. // // For null hosts, the host must match the domain exactly. if (!IsDomainEqualToHost(domain, host)) { valid = false; } } if (valid) { m_domainKey = domain.ToLowerInvariant(); } } else { // For implicitly set domain AND at the set_default == false time // we simply need to match uri.Host against m_domain. if (!string.Equals(host, m_domain, StringComparison.OrdinalIgnoreCase)) { valid = false; } } if (!valid) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, m_domain)); } return false; } } // Check/Set Path if (setDefault && m_path_implicit == true) { // This code assumes that the URI path is always valid and contains at least one '/'. switch (m_cookieVariant) { case CookieVariant.Plain: m_path = path; break; case CookieVariant.Rfc2109: m_path = path.Substring(0, path.LastIndexOf('/')); // May be empty break; case CookieVariant.Rfc2965: default: // NOTE: this code is not resilient against future versions with different 'Path' semantics. m_path = path.Substring(0, path.LastIndexOf('/') + 1); break; } } else { // Check current path (implicit/explicit) against given URI. if (!path.StartsWith(CookieParser.CheckQuoted(m_path))) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PathAttributeName, m_path)); } return false; } } // Set the default port if Port attribute was present but had no value. if (setDefault && (m_port_implicit == false && m_port.Length == 0)) { m_port_list = new int[1] { port }; } if (m_port_implicit == false) { // Port must match against the one from the uri. valid = false; foreach (int p in m_port_list) { if (p == port) { valid = true; break; } } if (!valid) { if (shouldThrow) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, m_port)); } return false; } } return true; } // Very primitive test to make sure that the name does not have illegal characters // as per RFC 952 (relaxed on first char could be a digit and string can have '_'). private static bool DomainCharsTest(string name) { if (name == null || name.Length == 0) { return false; } for (int i = 0; i < name.Length; ++i) { char ch = name[i]; if (!((ch >= '0' && ch <= '9') || (ch == '.' || ch == '-') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '_'))) { return false; } } return true; } public string Port { get { return m_port; } set { m_port_implicit = false; if (string.IsNullOrEmpty(value)) { // "Port" is present but has no value. m_port = string.Empty; } else { // Parse port list if (value[0] != '\"' || value[value.Length - 1] != '\"') { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value)); } string[] ports = value.Split(PortSplitDelimiters); List<int> portList = new List<int>(); int port; for (int i = 0; i < ports.Length; ++i) { // Skip spaces if (ports[i] != string.Empty) { if (!int.TryParse(ports[i], out port)) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value)); } // valid values for port 0 - 0xFFFF if ((port < 0) || (port > 0xFFFF)) { throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value)); } portList.Add(port); } } m_port_list = portList.ToArray(); m_port = value; m_version = MaxSupportedVersion; m_cookieVariant = CookieVariant.Rfc2965; } } } internal int[] PortList { get { // PortList will be null if Port Attribute was omitted in the response. return m_port_list; } } public bool Secure { get { return m_secure; } set { m_secure = value; } } public DateTime TimeStamp { get { return m_timeStamp; } } public string Value { get { return m_value; } set { m_value = value ?? string.Empty; } } /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif CookieVariant Variant { get { return m_cookieVariant; } set { // Only set by HttpListenerRequest::Cookies_get() if (value != CookieVariant.Rfc2965) { NetEventSource.Fail(this, $"value != Rfc2965:{value}"); } m_cookieVariant = value; } } // _domainKey member is set internally in VerifySetDefaults(). // If it is not set then verification function was not called; // this should never happen. internal string DomainKey { get { return m_domain_implicit ? Domain : m_domainKey; } } public int Version { get { return m_version; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } m_version = value; if (value > 0 && m_cookieVariant < CookieVariant.Rfc2109) { m_cookieVariant = CookieVariant.Rfc2109; } } } public override bool Equals(object comparand) { Cookie other = comparand as Cookie; return other != null && string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(Value, other.Value, StringComparison.Ordinal) && string.Equals(Path, other.Path, StringComparison.Ordinal) && string.Equals(Domain, other.Domain, StringComparison.OrdinalIgnoreCase) && (Version == other.Version); } public override int GetHashCode() { return (Name + "=" + Value + ";" + Path + "; " + Domain + "; " + Version).GetHashCode(); } public override string ToString() { StringBuilder sb = StringBuilderCache.Acquire(); ToString(sb); return StringBuilderCache.GetStringAndRelease(sb); } internal void ToString(StringBuilder sb) { int beforeLength = sb.Length; // Add the Cookie version if necessary. if (Version != 0) { sb.Append(SpecialAttributeLiteral + CookieFields.VersionAttributeName + EqualsLiteral); // const strings if (IsQuotedVersion) sb.Append('"'); sb.Append(m_version.ToString(NumberFormatInfo.InvariantInfo)); if (IsQuotedVersion) sb.Append('"'); sb.Append(SeparatorLiteral); } // Add the Cookie Name=Value pair. sb.Append(Name).Append(EqualsLiteral).Append(Value); if (!Plain) { // Add the Path if necessary. if (!m_path_implicit && m_path.Length > 0) { sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.PathAttributeName + EqualsLiteral); // const strings sb.Append(m_path); } // Add the Domain if necessary. if (!m_domain_implicit && m_domain.Length > 0) { sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.DomainAttributeName + EqualsLiteral); // const strings if (IsQuotedDomain) sb.Append('"'); sb.Append(m_domain); if (IsQuotedDomain) sb.Append('"'); } } // Add the Port if necessary. if (!m_port_implicit) { sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.PortAttributeName); // const strings if (m_port.Length > 0) { sb.Append(EqualsLiteral); sb.Append(m_port); } } // Check to see whether the only thing we added was "=", and if so, // remove it so that we leave the StringBuilder unchanged in contents. int afterLength = sb.Length; if (afterLength == (1 + beforeLength) && sb[beforeLength] == '=') { sb.Length = beforeLength; } } /* TODO: #13607 VSO 449560 Reflecting on internal method won't work on AOT without rd.xml and DisableReflection block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive public, this is a temporary workaround till that happens. */ #if uap public #else internal #endif string ToServerString() { string result = Name + EqualsLiteral + Value; if (m_comment != null && m_comment.Length > 0) { result += SeparatorLiteral + CookieFields.CommentAttributeName + EqualsLiteral + m_comment; } if (m_commentUri != null) { result += SeparatorLiteral + CookieFields.CommentUrlAttributeName + EqualsLiteral + QuotesLiteral + m_commentUri.ToString() + QuotesLiteral; } if (m_discard) { result += SeparatorLiteral + CookieFields.DiscardAttributeName; } if (!m_domain_implicit && m_domain != null && m_domain.Length > 0) { result += SeparatorLiteral + CookieFields.DomainAttributeName + EqualsLiteral + m_domain; } if (Expires != DateTime.MinValue) { int seconds = (int)(Expires.ToLocalTime() - DateTime.Now).TotalSeconds; if (seconds < 0) { // This means that the cookie has already expired. Set Max-Age to 0 // so that the client will discard the cookie immediately. seconds = 0; } result += SeparatorLiteral + CookieFields.MaxAgeAttributeName + EqualsLiteral + seconds.ToString(NumberFormatInfo.InvariantInfo); } if (!m_path_implicit && m_path != null && m_path.Length > 0) { result += SeparatorLiteral + CookieFields.PathAttributeName + EqualsLiteral + m_path; } if (!Plain && !m_port_implicit && m_port != null && m_port.Length > 0) { // QuotesLiteral are included in _port. result += SeparatorLiteral + CookieFields.PortAttributeName + EqualsLiteral + m_port; } if (m_version > 0) { result += SeparatorLiteral + CookieFields.VersionAttributeName + EqualsLiteral + m_version.ToString(NumberFormatInfo.InvariantInfo); } return result == EqualsLiteral ? null : result; } } }
using System; using System.Threading; namespace Shielded { /// <summary> /// Makes your data thread safe. Works with structs, or simple value types, /// and the language does the necessary cloning. If T is a class, then only /// the reference itself is protected. /// </summary> public class Shielded<T> : IShielded { private class ValueKeeper { public long Version; public T Value; public ValueKeeper Older; } private ValueKeeper _current; // once negotiated, kept until commit or rollback private volatile WriteStamp _writerStamp; private readonly TransactionalStorage<ValueKeeper> _locals = new TransactionalStorage<ValueKeeper>(); private readonly object _owner; /// <summary> /// Constructs a new Shielded container, containing default value of type T. /// </summary> /// <param name="owner">If this is given, then in WhenCommitting subscriptions /// this shielded will report its owner instead of itself.</param> public Shielded(object owner = null) { _current = new ValueKeeper(); _owner = owner ?? this; } /// <summary> /// Constructs a new Shielded container, containing the given initial value. /// </summary> /// <param name="initial">Initial value to contain.</param> /// <param name="owner">If this is given, then in WhenCommitting subscriptions /// this shielded will report its owner instead of itself.</param> public Shielded(T initial, object owner = null) { _current = new ValueKeeper(); _current.Value = initial; _owner = owner ?? this; } /// <summary> /// Enlists the field in the current transaction and, if this is the first /// access, checks the write lock. Will wait (using StampLocker) if the write /// stamp &lt;= <see cref="Shield.ReadStamp"/>, until write lock is released. /// Since write stamps are increasing, this is likely to happen only at the /// beginning of transactions. /// </summary> private void CheckLockAndEnlist(bool write) { // if already enlisted, no need to check lock. if (!Shield.Enlist(this, _locals.HasValue, write)) return; var ws = _writerStamp; if (ws != null && ws.Locked && ws.Version <= Shield.ReadStamp) ws.Wait(); } private ValueKeeper CurrentTransactionOldValue() { var point = _current; while (point.Version > Shield.ReadStamp) point = point.Older; return point; } /// <summary> /// Gets the value that this Shielded contained at transaction opening. During /// a transaction, this is constant. See also <see cref="Shield.ReadOldState"/>. /// </summary> public T GetOldValue() { CheckLockAndEnlist(false); return CurrentTransactionOldValue().Value; } private ValueKeeper PrepareForWriting(bool prepareOld) { CheckLockAndEnlist(true); if (!Shield.CommitCheckDone && _current.Version > Shield.ReadStamp) throw new TransException("Write collision."); if (_locals.HasValue) return _locals.Value; var v = new ValueKeeper(); if (prepareOld) v.Value = CurrentTransactionOldValue().Value; _locals.Value = v; return v; } /// <summary> /// Reads or writes into the content of the field. Reading can be /// done out of transaction, but writes must be inside. /// </summary> public T Value { get { if (!Shield.IsInTransaction) return _current.Value; CheckLockAndEnlist(false); if (!_locals.HasValue || Shield.ReadingOldState) return CurrentTransactionOldValue().Value; else if (!Shield.CommitCheckDone && _current.Version > Shield.ReadStamp) throw new TransException("Writable read collision."); return _locals.Value.Value; } set { PrepareForWriting(false).Value = value; RaiseChanged(); } } /// <summary> /// Delegate type used for modifications, i.e. read and write operations. /// It has the advantage of working directly on the internal, thread-local /// storage copy, to which it gets a reference. This is more efficient if /// the type T is a big value-type. /// </summary> public delegate void ModificationDelegate(ref T value); /// <summary> /// Modifies the content of the field, i.e. read and write operation. /// It has the advantage of working directly on the internal, thread-local /// storage copy, to which it gets a reference. This is more efficient if /// the type T is a big value-type. /// </summary> public void Modify(ModificationDelegate d) { d(ref PrepareForWriting(true).Value); RaiseChanged(); } /// <summary> /// The action is performed just before commit, and reads the latest /// data. If it conflicts, only it is retried. If it succeeds, /// we (try to) commit with the same write stamp along with it. /// But, if you access this Shielded, it gets executed directly in this transaction. /// The Changed event is raised only when the commute is enlisted, and not /// when (and every time, given possible repetitions..) it executes. /// </summary> public void Commute(ModificationDelegate perform) { Shield.EnlistStrictCommute( () => perform(ref PrepareForWriting(true).Value), this); RaiseChanged(); } /// <summary> /// For use by the ProxyGen, since the users of it know only about the base type used /// to generate the proxy. The struct used internally is not exposed, and so users /// of proxy classes could not write a ModificationDelegate which works on an argument /// whose type is that hidden struct. /// </summary> public void Commute(Action perform) { Shield.EnlistStrictCommute(perform, this); RaiseChanged(); } /// <summary> /// Event raised after any change, and directly in the transaction that changed it. /// Subscriptions are transactional. In case of a commute, event is raised immediately /// after the commute is enlisted, and your handler can easily cause commutes to /// degenerate. /// </summary> public ShieldedEvent<EventArgs> Changed { get { var ev = _changed; if (ev == null) { var newObj = new ShieldedEvent<EventArgs>(); ev = Interlocked.CompareExchange(ref _changed, newObj, null) ?? newObj; } return ev; } } private ShieldedEvent<EventArgs> _changed; private void RaiseChanged() { var ev = _changed; if (ev != null) ev.Raise(this, EventArgs.Empty); } /// <summary> /// Returns the current <see cref="Value"/>. /// </summary> public static implicit operator T(Shielded<T> obj) { return obj.Value; } bool IShielded.HasChanges { get { return _locals.HasValue; } } object IShielded.Owner { get { return _owner; } } bool IShielded.CanCommit(WriteStamp writeStamp) { var res = _writerStamp == null && _current.Version <= Shield.ReadStamp; if (res && _locals.HasValue) _writerStamp = writeStamp; return res; } void IShielded.Commit() { if (!_locals.HasValue) return; var newCurrent = _locals.Value; newCurrent.Older = _current; newCurrent.Version = _writerStamp.Version.Value; _current = newCurrent; _writerStamp = null; _locals.Release(); } void IShielded.Rollback() { if (!_locals.HasValue) return; var ws = _writerStamp; if (ws != null && ws.Locker == Shield.Context) _writerStamp = null; _locals.Release(); } void IShielded.TrimCopies(long smallestOpenTransactionId) { // NB the "smallest transaction" and others can freely read while // we're doing this. var point = _current; while (point.Version > smallestOpenTransactionId) point = point.Older; // point is the last accessible - his Older is not needed. point.Older = null; } } }
// 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 gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>ConversionCustomVariable</c> resource.</summary> public sealed partial class ConversionCustomVariableName : gax::IResourceName, sys::IEquatable<ConversionCustomVariableName> { /// <summary>The possible contents of <see cref="ConversionCustomVariableName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c>. /// </summary> CustomerConversionCustomVariable = 1, } private static gax::PathTemplate s_customerConversionCustomVariable = new gax::PathTemplate("customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}"); /// <summary> /// Creates a <see cref="ConversionCustomVariableName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ConversionCustomVariableName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ConversionCustomVariableName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ConversionCustomVariableName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ConversionCustomVariableName"/> with the pattern /// <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversionCustomVariableId"> /// The <c>ConversionCustomVariable</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// A new instance of <see cref="ConversionCustomVariableName"/> constructed from the provided ids. /// </returns> public static ConversionCustomVariableName FromCustomerConversionCustomVariable(string customerId, string conversionCustomVariableId) => new ConversionCustomVariableName(ResourceNameType.CustomerConversionCustomVariable, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionCustomVariableId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionCustomVariableId, nameof(conversionCustomVariableId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConversionCustomVariableName"/> with /// pattern <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversionCustomVariableId"> /// The <c>ConversionCustomVariable</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ConversionCustomVariableName"/> with pattern /// <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c>. /// </returns> public static string Format(string customerId, string conversionCustomVariableId) => FormatCustomerConversionCustomVariable(customerId, conversionCustomVariableId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConversionCustomVariableName"/> with /// pattern <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversionCustomVariableId"> /// The <c>ConversionCustomVariable</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ConversionCustomVariableName"/> with pattern /// <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c>. /// </returns> public static string FormatCustomerConversionCustomVariable(string customerId, string conversionCustomVariableId) => s_customerConversionCustomVariable.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversionCustomVariableId, nameof(conversionCustomVariableId))); /// <summary> /// Parses the given resource name string into a new <see cref="ConversionCustomVariableName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="conversionCustomVariableName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="ConversionCustomVariableName"/> if successful.</returns> public static ConversionCustomVariableName Parse(string conversionCustomVariableName) => Parse(conversionCustomVariableName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ConversionCustomVariableName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="conversionCustomVariableName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ConversionCustomVariableName"/> if successful.</returns> public static ConversionCustomVariableName Parse(string conversionCustomVariableName, bool allowUnparsed) => TryParse(conversionCustomVariableName, allowUnparsed, out ConversionCustomVariableName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ConversionCustomVariableName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="conversionCustomVariableName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ConversionCustomVariableName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string conversionCustomVariableName, out ConversionCustomVariableName result) => TryParse(conversionCustomVariableName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ConversionCustomVariableName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="conversionCustomVariableName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ConversionCustomVariableName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string conversionCustomVariableName, bool allowUnparsed, out ConversionCustomVariableName result) { gax::GaxPreconditions.CheckNotNull(conversionCustomVariableName, nameof(conversionCustomVariableName)); gax::TemplatedResourceName resourceName; if (s_customerConversionCustomVariable.TryParseName(conversionCustomVariableName, out resourceName)) { result = FromCustomerConversionCustomVariable(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(conversionCustomVariableName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ConversionCustomVariableName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversionCustomVariableId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; ConversionCustomVariableId = conversionCustomVariableId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="ConversionCustomVariableName"/> class from the component parts of /// pattern <c>customers/{customer_id}/conversionCustomVariables/{conversion_custom_variable_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversionCustomVariableId"> /// The <c>ConversionCustomVariable</c> ID. Must not be <c>null</c> or empty. /// </param> public ConversionCustomVariableName(string customerId, string conversionCustomVariableId) : this(ResourceNameType.CustomerConversionCustomVariable, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionCustomVariableId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionCustomVariableId, nameof(conversionCustomVariableId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>ConversionCustomVariable</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string ConversionCustomVariableId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerConversionCustomVariable: return s_customerConversionCustomVariable.Expand(CustomerId, ConversionCustomVariableId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ConversionCustomVariableName); /// <inheritdoc/> public bool Equals(ConversionCustomVariableName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ConversionCustomVariableName a, ConversionCustomVariableName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ConversionCustomVariableName a, ConversionCustomVariableName b) => !(a == b); } public partial class ConversionCustomVariable { /// <summary> /// <see cref="gagvr::ConversionCustomVariableName"/>-typed view over the <see cref="ResourceName"/> resource /// name property. /// </summary> internal ConversionCustomVariableName ResourceNameAsConversionCustomVariableName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::ConversionCustomVariableName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::ConversionCustomVariableName"/>-typed view over the <see cref="Name"/> resource name /// property. /// </summary> internal ConversionCustomVariableName ConversionCustomVariableName { get => string.IsNullOrEmpty(Name) ? null : gagvr::ConversionCustomVariableName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="CustomerName"/>-typed view over the <see cref="OwnerCustomer"/> resource name property. /// </summary> internal CustomerName OwnerCustomerAsCustomerName { get => string.IsNullOrEmpty(OwnerCustomer) ? null : CustomerName.Parse(OwnerCustomer, allowUnparsed: true); set => OwnerCustomer = value?.ToString() ?? ""; } } }
/* Copyright (c) 2006- DEVSENSE Copyright (c) 2004-2006 Tomas Matousek, Vaclav Novak, and Martin Maly. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Diagnostics; using System.Reflection.Emit; using PHP.Core.AST; using PHP.Core.Emit; using PHP.Core.Parsers; using PHP.Core.Reflection; namespace PHP.Core.Compiler.AST { partial class NodeCompilers { [NodeCompiler(typeof(IndirectVarUse))] sealed class IndirectVarUseCompiler : SimpleVarUseCompiler<IndirectVarUse>, IVariableSwitchEmitter { #region Analysis public override Evaluation Analyze(IndirectVarUse node, Analyzer analyzer, ExInfoFromParent info) { access = info.Access; base.Analyze(node, analyzer, info); if (node.IsMemberOf == null) { if (!(access == AccessType.Read || access == AccessType.Write || access == AccessType.ReadAndWrite || access == AccessType.None)) { analyzer.CurrentVarTable.SetAllRef(); } analyzer.AddCurrentRoutineProperty(RoutineProperties.IndirectLocalAccess); } node.varNameEx = node.VarNameEx.Analyze(analyzer, ExInfoFromParent.DefaultExInfo).Literalize(); return new Evaluation(node); } #endregion #region Emission public override PhpTypeCode Emit(IndirectVarUse node, CodeGenerator codeGenerator) { Statistics.AST.AddNode("IndirectVarUse"); PhpTypeCode result = PhpTypeCode.Invalid; switch (codeGenerator.SelectAccess(access)) { // This case occurs everytime we want to get current variable value // All we do is push the value onto the IL stack case AccessType.Read: // Push value onto a IL stack result = EmitNodeRead(node, codeGenerator); break; // This case occurs when the varible is written ($a = $b, then $a has Write mark) // We only prepare the stack for storing, the work will be done later, // by EmitAssign() case AccessType.Write: result = EmitNodeWrite(node, codeGenerator); break; case AccessType.None: EmitNodeRead(node, codeGenerator); codeGenerator.IL.Emit(OpCodes.Pop); result = PhpTypeCode.Void; break; case AccessType.ReadRef: // if the selector is set to the ReadRef, the chain is emitted as if it was written // (chained nodes are marked as ReadAndWrite): if (codeGenerator.AccessSelector == AccessType.ReadRef) codeGenerator.AccessSelector = AccessType.Write; result = EmitNodeReadRef(node, codeGenerator); Debug.Assert(result == PhpTypeCode.PhpReference); break; case AccessType.ReadUnknown: result = EmitNodeReadUnknown(node, codeGenerator); break; case AccessType.WriteRef: EmitNodeWriteRef(node, codeGenerator); result = PhpTypeCode.PhpReference; break; default: result = PhpTypeCode.Invalid; Debug.Fail(null); break; } return result; } private PhpTypeCode EmitNodeRead(IndirectVarUse node, CodeGenerator codeGenerator) { if (codeGenerator.ChainBuilder.IsMember) { // 1,4,5,6,9 if (node.IsMemberOf != null) { // 1: ...->$a->... codeGenerator.ChainBuilder.Lengthen(); // for hop over -> node.IsMemberOf.Emit(codeGenerator); return codeGenerator.ChainBuilder.EmitGetProperty(node); } if (codeGenerator.ChainBuilder.IsArrayItem && !codeGenerator.ChainBuilder.IsLastMember) { // 6: $b->${"a"}[3] return codeGenerator.ChainBuilder.EmitGetProperty(node); } // 4: ${"a"}[][] // 5: $$a->b->c->... // 9: $$a->b return EmitLoad(node, codeGenerator); } // 2,3,7,8 if (node.IsMemberOf != null) { // 2: $b->$a // 8: b[]->$a codeGenerator.ChainBuilder.Create(); codeGenerator.ChainBuilder.Begin(); //codeGenerator.ChainBuilder.Lengthen(); // for hop over -> //PhpTypeCode result = node.IsMemberOf.Emit(codeGenerator); //codeGenerator.ChainBuilder.EmitGetProperty(this); var result = codeGenerator.CallSitesBuilder.EmitGetProperty( codeGenerator, false, node.IsMemberOf, null, null, null, null, node.VarNameEx, codeGenerator.ChainBuilder.QuietRead); codeGenerator.ChainBuilder.End(); return result; } // 3: ${"a"}[3] // 7: $$a return EmitLoad(node, codeGenerator); } private PhpTypeCode EmitNodeReadRef(IndirectVarUse node, CodeGenerator codeGenerator) { // Cases 1, 4, 5, 6, 9 never reached Debug.Assert(codeGenerator.ChainBuilder.IsMember == false); // Case 3 never reached Debug.Assert(codeGenerator.ChainBuilder.IsArrayItem == false); // 2, 7, 8 if (node.IsMemberOf != null) { // 2: $b->a // 8: b[]->a codeGenerator.ChainBuilder.Create(); codeGenerator.ChainBuilder.Begin(); if (node.IsMemberOf is FunctionCall) codeGenerator.ChainBuilder.LoadAddressOfFunctionReturnValue = true; PhpTypeCode result = EmitReadField(node, codeGenerator, true); codeGenerator.ChainBuilder.EndRef(); Debug.Assert(result == PhpTypeCode.PhpReference); } else { // 7: $a //codeGenerator.EmitVariableLoadRef(this); EmitLoadRef(node, codeGenerator); } return PhpTypeCode.PhpReference; } private PhpTypeCode EmitNodeReadUnknown(IndirectVarUse node, CodeGenerator codeGenerator) { if (codeGenerator.ChainBuilder.IsMember) { // 1,4,5,6,9 if (node.IsMemberOf != null) { // 1: ...->$a->... codeGenerator.ChainBuilder.Lengthen(); // for hop over -> PhpTypeCode res = node.IsMemberOf.Emit(codeGenerator); if (res != PhpTypeCode.PhpRuntimeChain) { codeGenerator.EmitBoxing(res); codeGenerator.ChainBuilder.EmitCreateRTChain(); } codeGenerator.ChainBuilder.EmitRTChainAddField(node); return PhpTypeCode.PhpRuntimeChain; } if (codeGenerator.ChainBuilder.IsArrayItem && !codeGenerator.ChainBuilder.IsLastMember) { // 6: $b->${"a"}[3] codeGenerator.ChainBuilder.EmitRTChainAddField(node); return PhpTypeCode.PhpRuntimeChain; } // 4: ${"a"}[][] // 5: $$a->b->c->... // 9: $$a->b this.EmitLoadRef(node, codeGenerator); codeGenerator.ChainBuilder.EmitCreateRTChain(); return PhpTypeCode.PhpRuntimeChain; } // 2,3,7,8 if (node.IsMemberOf != null) { // 2: $b->$a // 8: b[]->$a codeGenerator.ChainBuilder.Create(); codeGenerator.ChainBuilder.Begin(); codeGenerator.ChainBuilder.Lengthen(); // for hop over -> PhpTypeCode res = node.IsMemberOf.Emit(codeGenerator); if (res != PhpTypeCode.PhpRuntimeChain) { codeGenerator.EmitBoxing(res); codeGenerator.ChainBuilder.EmitCreateRTChain(); } codeGenerator.ChainBuilder.EmitRTChainAddField(node); codeGenerator.ChainBuilder.End(); return PhpTypeCode.PhpRuntimeChain; } // 3: ${"a"}[3] // 7: $$a this.EmitLoadRef(node, codeGenerator); return PhpTypeCode.PhpReference; } private PhpTypeCode EmitNodeWrite(IndirectVarUse node, CodeGenerator codeGenerator) { ChainBuilder chain = codeGenerator.ChainBuilder; if (chain.IsMember) { // 1,4,5,6,9 if (node.IsMemberOf != null) { // 1: ...->$a->... chain.Lengthen(); chain.EmitEnsureProperty(node.IsMemberOf, node, false); return PhpTypeCode.DObject; } if (chain.IsArrayItem) { // 4,6 if (chain.IsLastMember) { // 4: ${"a"}[][] chain.EmitEnsureVariableIsArray(node); return PhpTypeCode.PhpArray; } else { // 6: $b->${"a"}[3] ChainBuilder.ObjectFieldLazyEmitInfo object_info = chain.GetObjectForLazyEmit(); // Lengthen for hop over -> chain.EmitEnsureProperty(object_info.ObjectForLazyEmit, node, true); chain.ReleaseObjectForLazyEmit(object_info); chain.IsArrayItem = true; chain.IsLastMember = false; return PhpTypeCode.PhpArray; } } if (chain.Exists) { // 5: $$a->b->c->... chain.EmitEnsureVariableIsObject(node); return PhpTypeCode.DObject; } else { // 9: $$a->b this.EmitLoadAddress(node, codeGenerator); return PhpTypeCode.ObjectAddress; } } // 2,3,7,8 if (node.IsMemberOf != null) { // 2: $b->a // 8: b[]->a chain.Create(); chain.Begin(); assignmentCallback = EmitWriteField(node, codeGenerator, false); // Note: more work is done in EmitAssign return PhpTypeCode.Unknown; } // 3,7 if (codeGenerator.ChainBuilder.IsArrayItem) { // 3: ${"a"}[3] this.EmitLoadAddress(node, codeGenerator); return PhpTypeCode.ObjectAddress; } // 7: $a //codeGenerator.EmitVariableStorePrepare(this); this.EmitStorePrepare(node, codeGenerator); return PhpTypeCode.Unknown; } private void EmitNodeWriteAssign(IndirectVarUse node, CodeGenerator codeGenerator) { ChainBuilder chain = codeGenerator.ChainBuilder; // Note that for cases 1,3,4,5,6,9 EmitAssign is never called!!! // 2,7,8 if (chain.IsMember) { // 2,8 if (chain.Exists) { // 8: b[]->$a chain.EmitSetObjectField(); } else { // 2: $b->a Debug.Assert(node.IsMemberOf is SimpleVarUse || node.IsMemberOf is FunctionCall); if (node.IsMemberOf is FunctionCall) codeGenerator.ChainBuilder.LoadAddressOfFunctionReturnValue = true; assignmentCallback(codeGenerator, PhpTypeCode.Object); SimpleVarUse svu = node.IsMemberOf as SimpleVarUse; if (svu != null) SimpleVarUseHelper.EmitLoadAddress_StoreBack(svu, codeGenerator); // else do nothing } chain.End(); } else { // 7: $a //codeGenerator.EmitVariableStoreAssign(this); this.EmitStoreAssign(node, codeGenerator); } } private void EmitNodeWriteRef(IndirectVarUse node, CodeGenerator codeGenerator) { // Cases 1, 4, 5, 6, 9 never reached Debug.Assert(codeGenerator.ChainBuilder.IsMember == false); // Case 3 never reached Debug.Assert(codeGenerator.ChainBuilder.IsArrayItem == false); // 2,7,8 if (node.IsMemberOf != null) { // 2: $b->a // 8: b[]->a codeGenerator.ChainBuilder.Create(); codeGenerator.ChainBuilder.Begin(); assignmentCallback = EmitWriteField(node, codeGenerator, true); // Note: more work is done in EmitAssign return; } // 7: $a //codeGenerator.EmitVariableStoreRefPrepare(this); this.EmitStoreRefPrepare(node, codeGenerator); } private void EmitNodeWriteRefAssign(IndirectVarUse node, CodeGenerator codeGenerator) { // Note that for cases 1,3,4,5,6,9 EmitAssign is never called!!! // 2,7,8 if (codeGenerator.ChainBuilder.IsMember) { // 2,8 if (codeGenerator.ChainBuilder.Exists) { // 8: b[]->a // TODO: <MARTIN> May be this call will change to SetObjectFieldRef codeGenerator.ChainBuilder.EmitSetObjectField(); } else { // 2: $b->$a Debug.Assert(node.IsMemberOf is SimpleVarUse || node.IsMemberOf is FunctionCall); if (node.IsMemberOf is FunctionCall) codeGenerator.ChainBuilder.LoadAddressOfFunctionReturnValue = true; assignmentCallback(codeGenerator, PhpTypeCode.Object); SimpleVarUse svu = node.IsMemberOf as SimpleVarUse; if (svu != null) SimpleVarUseHelper.EmitLoadAddress_StoreBack(svu, codeGenerator); } codeGenerator.ChainBuilder.End(); } else { // 7: $a //codeGenerator.EmitVariableStoreRefAssign(this); this.EmitStoreRefAssign(node, codeGenerator); } } internal override PhpTypeCode EmitAssign(IndirectVarUse node, CodeGenerator codeGenerator) { PhpTypeCode result; switch (access) { case AccessType.None: // Do nothing result = PhpTypeCode.Void; break; case AccessType.Read: // Do nothing result = PhpTypeCode.Object; break; case AccessType.Write: case AccessType.WriteAndReadRef: case AccessType.WriteAndReadUnknown: case AccessType.ReadAndWrite: case AccessType.ReadAndWriteAndReadRef: case AccessType.ReadAndWriteAndReadUnknown: EmitNodeWriteAssign(node, codeGenerator); result = PhpTypeCode.Void; break; case AccessType.ReadRef: // Do nothing result = PhpTypeCode.PhpReference; break; case AccessType.WriteRef: EmitNodeWriteRefAssign(node, codeGenerator); result = PhpTypeCode.PhpReference; break; default: Debug.Fail(null); result = PhpTypeCode.Invalid; break; } return result; } internal override void EmitUnset(IndirectVarUse node, CodeGenerator codeGenerator) { //Template: "unset($$x)" $$x = null; //Template: "unset(x)" x = null Debug.Assert(access == AccessType.Read); // Cases 1, 4, 5, 6, 9 never reached Debug.Assert(codeGenerator.ChainBuilder.IsMember == false); // Case 3 never reached Debug.Assert(codeGenerator.ChainBuilder.IsArrayItem == false); codeGenerator.ChainBuilder.QuietRead = true; // 2, 7, 8 if (node.IsMemberOf != null) { // 2: $b->$a // 8: b[]->$a codeGenerator.ChainBuilder.Create(); codeGenerator.ChainBuilder.Begin(); EmitUnsetField(node, codeGenerator); codeGenerator.ChainBuilder.End(); return; } // 7: $a // Unset this variable //codeGenerator.EmitVariableUnset(this); ILEmitter il = codeGenerator.IL; if (codeGenerator.OptimizedLocals) { EmitSwitch(node, codeGenerator, new SwitchMethod(UnsetLocal)); } else { // CALL Operators.UnsetVariable(<script context>, <local variable table>, <variable name>); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); EmitName(node, codeGenerator); il.Emit(OpCodes.Call, Methods.Operators.UnsetVariable); } } /// <summary> /// Emits IL instructions that unset an instance field. /// </summary> /// <remarks> /// Nothing is expected on the evaluation stack. Nothing is left on the evaluation stack. /// </remarks> private void EmitUnsetField(IndirectVarUse node, CodeGenerator codeGenerator) { // call UnsetProperty operator codeGenerator.ChainBuilder.Lengthen(); // for hop over -> node.IsMemberOf.Emit(codeGenerator); EmitName(node, codeGenerator); codeGenerator.EmitLoadClassContext(); codeGenerator.IL.EmitCall(OpCodes.Call, Methods.Operators.UnsetProperty, null); } internal override PhpTypeCode EmitIsset(IndirectVarUse node, CodeGenerator codeGenerator, bool empty) { //TODO: // Template: "isset(x)" x != null // isset doesn't distinguish between the NULL and uninitialized variable // a reference is dereferenced, i.e. isset tells us whether the referenced variable is set Debug.Assert(access == AccessType.Read); // Cases 1, 4, 5, 6, 9 never reached Debug.Assert(codeGenerator.ChainBuilder.IsMember == false); // Case 3 never reached Debug.Assert(codeGenerator.ChainBuilder.IsArrayItem == false); // 2,7,8 if (node.IsMemberOf != null) { // 2: $b->$a // 8: b[]->$a codeGenerator.ChainBuilder.Create(); codeGenerator.ChainBuilder.Begin(); codeGenerator.ChainBuilder.Lengthen(); // for hop over -> codeGenerator.ChainBuilder.QuietRead = true; EmitReadField(node, codeGenerator, false); codeGenerator.ChainBuilder.End(); return PhpTypeCode.Object; } else { // 7: $a // Check wheteher this variable is set codeGenerator.ChainBuilder.QuietRead = true; this.EmitLoad(node, codeGenerator); return PhpTypeCode.Object; } } /// <summary> /// Emits load of the name to the stack. /// </summary> internal override void EmitName(IndirectVarUse node, CodeGenerator codeGenerator) { codeGenerator.ChainBuilder.Create(); codeGenerator.EmitConversion(node.VarNameEx, PhpTypeCode.String); codeGenerator.ChainBuilder.End(); } /// <summary> /// Emits IL instructions that load the variable onto the evaluation stack. /// </summary> /// <param name="node">Instance.</param> /// <param name="codeGenerator"></param> /// <remarks><B>$this</B> cannot be accessed indirectly.</remarks> internal override PhpTypeCode EmitLoad(IndirectVarUse node, CodeGenerator codeGenerator) { ILEmitter il = codeGenerator.IL; if (codeGenerator.OptimizedLocals) { // Switch over all local variables and dereference those being of type PhpReference EmitSwitch(node, codeGenerator, new SwitchMethod(LoadLocal)); } else { // LOAD Operators.GetVariable[Unchecked](<script context>, <local variables table>, <variable name>); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); EmitName(node, codeGenerator); if (codeGenerator.ChainBuilder.QuietRead) il.Emit(OpCodes.Call, Methods.Operators.GetVariableUnchecked); else il.Emit(OpCodes.Call, Methods.Operators.GetVariable); } return PhpTypeCode.Object; } internal override void EmitLoadAddress(IndirectVarUse node, CodeGenerator codeGenerator) { ILEmitter il = codeGenerator.IL; if (codeGenerator.OptimizedLocals) { // Template: for IndirectVarUse // ***** emit "switch" to make sure whether a variable is PhpReference or not // Inside the switch do the same work as in DirectVarUse case. // For IndirectVarUse emit switch over all variables. Load address of specified variable. EmitSwitch(node, codeGenerator, new SwitchMethod(LoadLocalAddress)); } else { // Template: // object Operators.GetVariableUnchecked(IDictionary table, string name) //returns variable value this.LoadTabledVariableAddress(node, codeGenerator); } } internal override void EmitLoadAddress_StoreBack(IndirectVarUse node, CodeGenerator codeGenerator) { EmitLoadAddress_StoreBack(node, codeGenerator, false); } internal override void EmitLoadAddress_StoreBack(IndirectVarUse node, CodeGenerator codeGenerator, bool duplicate_value) { ILEmitter il = codeGenerator.IL; if (codeGenerator.OptimizedLocals) { // Take no action return; } this.StoreTabledVariableBack(node, codeGenerator, duplicate_value); } internal override void EmitLoadRef(IndirectVarUse node, CodeGenerator codeGenerator) { ILEmitter il = codeGenerator.IL; if (codeGenerator.OptimizedLocals) { // For IndirectVarUse emit switch over all variables. EmitSwitch(node, codeGenerator, new SwitchMethod(LoadLocalRef)); } else { // Template: // PhpReference Operators.GetVariableRef(IDictionary table, string name) //returns variable value; variable is of type PhpReference codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); EmitName(node, codeGenerator); il.Emit(OpCodes.Call, Methods.Operators.GetVariableRef); } } internal override void EmitStorePrepare(IndirectVarUse node, CodeGenerator codeGenerator) { ILEmitter il = codeGenerator.IL; if (codeGenerator.OptimizedLocals) { // Switch over all variables // /*historical reason, not needed now*/EmitSwitch(codeGenerator, new SwitchMethod(StoreLocalPrepare)); } else { // Template: // void Operators.SetVariable(table, "x", PhpVariable.Copy(Operators.getValue(table, "x"), CopyReason.Assigned)); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); EmitName(node, codeGenerator); // now load value the call Operators.SetVariable in EmitVariableStoreAssignFromTable } } internal override void EmitStoreAssign(IndirectVarUse node, CodeGenerator codeGenerator) { ILEmitter il = codeGenerator.IL; if (codeGenerator.OptimizedLocals) { // For IndirectVarUse emit switch over all variables EmitSwitch(node, codeGenerator, new SwitchMethod(StoreLocalAssign)); } else { // Template: // void Operators.SetVariable(table, "x", PhpVariable.Copy(Operators.getValue(table, "x"), CopyReason.Assigned)); il.Emit(OpCodes.Call, Methods.Operators.SetVariable); } } internal override void EmitStoreRefPrepare(IndirectVarUse node, CodeGenerator codeGenerator) { ILEmitter il = codeGenerator.IL; if (codeGenerator.OptimizedLocals) { // Switch over all variables // /*copypaste bug*/EmitSwitch(codeGenerator, new SwitchMethod(StoreLocalPrepare)); } else { // Template: // void Operators.SetVariable(table, "x", PhpVariable.Copy(Operators.getValue(table, "x"), CopyReason.Assigned)); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); EmitName(node, codeGenerator); // now load value the call Operators.SetVariable in EmitVariableStoreAssignFromTable } } internal override void EmitStoreRefAssign(IndirectVarUse node, CodeGenerator codeGenerator) { ILEmitter il = codeGenerator.IL; if (codeGenerator.OptimizedLocals) { // For IndirectVarUse emit switch over all variables EmitSwitch(node, codeGenerator, new SwitchMethod(StoreLocalRefAssign)); } else { // Operators.SetVariable( <FROM EmitStoreRefPrepare> ) il.Emit(OpCodes.Call, Methods.Operators.SetVariableRef); } } #endregion #region Switching over local variables /// <summary> /// <see cref="SwitchMethod"/> delegate instances stands as a parameter for <see cref="EmitSwitch"/> method. /// </summary> internal delegate void SwitchMethod(IndirectVarUse node, CodeGenerator codeGenerator, VariablesTable.Entry variable, LocalBuilder variableName); void IVariableSwitchEmitter.LoadLocal(IndirectVarUse node, CodeGenerator codeGenerator) { EmitSwitch(node, codeGenerator, new SwitchMethod(LoadLocal)); } /// <summary> /// Emits local variable switch and performs a specified operation on each case. /// </summary> /// <param name="node">Instance.</param> /// <param name="codeGenerator">The code generator.</param> /// <param name="method">The operation performed in each case.</param> internal void EmitSwitch(IndirectVarUse node, CodeGenerator codeGenerator, SwitchMethod method) { ILEmitter il = codeGenerator.IL; Debug.Assert(method != null); Label default_case = il.DefineLabel(); Label end_label = il.DefineLabel(); LocalBuilder ivar_local = il.GetTemporaryLocal(Types.String[0], true); LocalBuilder non_interned_local = il.DeclareLocal(Types.String[0]); VariablesTable variables = codeGenerator.CurrentVariablesTable; Label[] labels = new Label[variables.Count]; // non_interned_local = <name expression>; EmitName(node, codeGenerator); il.Stloc(non_interned_local); // ivar_local = String.IsInterned(non_interned_local) il.Ldloc(non_interned_local); il.Emit(OpCodes.Call, Methods.String_IsInterned); il.Stloc(ivar_local); // switch for every compile-time variable: int i = 0; foreach (VariablesTable.Entry variable in variables) { labels[i] = il.DefineLabel(); // IF (ivar_local == <i-th variable name>) GOTO labels[i]; il.Ldloc(ivar_local); il.Emit(OpCodes.Ldstr, variable.VariableName.ToString()); il.Emit(OpCodes.Beq, labels[i]); i++; } // GOTO default_case: il.Emit(OpCodes.Br, default_case); // operation on each variable: i = 0; foreach (VariablesTable.Entry variable in variables) { // labels[i]: il.MarkLabel(labels[i]); // operation: method(node, codeGenerator, variable, null); // GOTO end; il.Emit(OpCodes.Br, end_label); i++; } // default case - new variable created at runtime: il.MarkLabel(default_case); method(node, codeGenerator, null, non_interned_local); // END: il.MarkLabel(end_label); } /// <summary> /// Loads a value of a specified variable. If the variable is of type <see cref="PhpReference"/>, it is dereferenced. /// </summary> internal static void LoadLocal(IndirectVarUse node, CodeGenerator codeGenerator, VariablesTable.Entry variable, LocalBuilder variableName) { ILEmitter il = codeGenerator.IL; Debug.Assert(variable == null ^ variableName == null); if (variable != null) { // LOAD DEREF <variable>; variable.Variable.EmitLoad(il); if (variable.IsPhpReference) il.Emit(OpCodes.Ldfld, Fields.PhpReference_Value); } else { // LOAD Operators.GetVariable[Unchecked](<script context>, <local variables table>, <variable name>); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); il.Ldloc(variableName); if (codeGenerator.ChainBuilder.QuietRead) il.Emit(OpCodes.Call, Methods.Operators.GetVariableUnchecked); else il.Emit(OpCodes.Call, Methods.Operators.GetVariable); } } /// <summary> /// Loads and address of a specified variable. /// </summary> internal void LoadLocalAddress(IndirectVarUse node, CodeGenerator codeGenerator, VariablesTable.Entry variable, LocalBuilder variableName) { ILEmitter il = codeGenerator.IL; Debug.Assert(variable == null ^ variableName == null); if (variable != null) { if (variable.IsPhpReference) { // LOAD ADDR <variable>.value; variable.Variable.EmitLoad(il); il.Emit(OpCodes.Ldflda, Fields.PhpReference_Value); } else { variable.Variable.EmitLoadAddress(il); } } else { LoadTabledVariableAddress(node, codeGenerator); } } /// <summary> /// Loads a specified reference local variable. /// </summary> internal static void LoadLocalRef(IndirectVarUse node, CodeGenerator codeGenerator, VariablesTable.Entry variable, LocalBuilder variableName) { ILEmitter il = codeGenerator.IL; Debug.Assert(variable == null ^ variableName == null); if (variable != null) { Debug.Assert(variable.IsPhpReference); variable.Variable.EmitLoad(il); } else { codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); il.Ldloc(variableName); il.Emit(OpCodes.Call, Methods.Operators.GetVariableRef); } } ///// <summary> ///// Prepares local variable for a store operation. ///// </summary> //internal void StoreLocalPrepare(CodeGenerator codeGenerator, VariablesTable.Entry variable, LocalBuilder variableName) //{ // Debug.Assert(variable == null ^ variableName == null); //} /// <summary> /// Unsets a specified variable. /// </summary> internal static void UnsetLocal(IndirectVarUse node, CodeGenerator codeGenerator, VariablesTable.Entry variable, LocalBuilder variableName) { ILEmitter il = codeGenerator.IL; Debug.Assert(variable == null ^ variableName == null); if (variable != null) { if (variable.IsPhpReference) { // <variable> = new PhpReference(); il.Emit(OpCodes.Newobj, Constructors.PhpReference_Void); variable.Variable.EmitStore(il); } else { il.Emit(OpCodes.Ldnull); variable.Variable.EmitStore(il); } } else { // CALL Operators.SetVariable(<local variables table>,<name>,null); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); il.Ldloc(variableName); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Call, Methods.Operators.SetVariable); } } /// <summary> /// Stores a value on the top of the stack to a specified variable. /// </summary> internal static void StoreLocalAssign(IndirectVarUse node, CodeGenerator codeGenerator, VariablesTable.Entry variable, LocalBuilder variableName) { ILEmitter il = codeGenerator.IL; Debug.Assert(variable == null ^ variableName == null); LocalBuilder temp; if (variable != null) { if (variable.IsPhpReference) { // temp = STACK temp = il.GetTemporaryLocal(Types.Object[0], true); il.Stloc(temp); // <variable>.value = temp; variable.Variable.EmitLoad(il); il.Ldloc(temp); il.Emit(OpCodes.Stfld, Fields.PhpReference_Value); } else { variable.Variable.EmitStore(il); } } else { // temp = STACK temp = il.GetTemporaryLocal(Types.Object[0], true); il.Stloc(temp); // CALL Operators.SetVariable(<local variables table>,<name>,temp); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); il.Ldloc(variableName); il.Ldloc(temp); il.Emit(OpCodes.Call, Methods.Operators.SetVariable); } } /// <summary> /// Stores a reference on the top of the stack to a specified variable. /// </summary> internal static void StoreLocalRefAssign(IndirectVarUse node, CodeGenerator codeGenerator, VariablesTable.Entry variable, LocalBuilder variableName) { ILEmitter il = codeGenerator.IL; Debug.Assert(variable == null ^ variableName == null); if (variable != null) { Debug.Assert(variable.IsPhpReference); variable.Variable.EmitStore(il); } else { // temp = STACK LocalBuilder temp = il.GetTemporaryLocal(Types.PhpReference[0], true); il.Stloc(temp); // CALL Operators.SetVariableRef(<local variables table>,<name>,temp); codeGenerator.EmitLoadScriptContext(); codeGenerator.EmitLoadRTVariablesTable(); il.Ldloc(variableName); il.Ldloc(temp); il.Emit(OpCodes.Call, Methods.Operators.SetVariableRef); } } #endregion } } #region IVariableSwitchEmitter internal interface IVariableSwitchEmitter { void LoadLocal(IndirectVarUse node, CodeGenerator codeGenerator); } internal static class IndirectVarUseCompilerHelper { public static void EmitSwitch_LoadLocal(this IndirectVarUse node, CodeGenerator codeGenerator) { node.NodeCompiler<IVariableSwitchEmitter>().LoadLocal(node, codeGenerator); } } #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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddSingle() { var test = new SimpleBinaryOpTest__AddSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddSingle { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[ElementCount]; private static Single[] _data2 = new Single[ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single> _dataTable; static SimpleBinaryOpTest__AddSingle() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__AddSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.Add( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.Add( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.Add( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.Add), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AddSingle(); var result = Sse.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(left[0] + right[0]) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.SingleToInt32Bits(left[i] + right[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.Add)}<Single>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Runtime.InteropServices; namespace OpenTK.Math { /// <summary> /// Represents a 4x4 Matrix with double-precision components. /// </summary> [Obsolete("OpenTK.Math functions have been moved to the root OpenTK namespace (reason: XNA compatibility")] [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Matrix4d : IEquatable<Matrix4d> { #region Fields /// <summary> /// Top row of the matrix /// </summary> public Vector4d Row0; /// <summary> /// 2nd row of the matrix /// </summary> public Vector4d Row1; /// <summary> /// 3rd row of the matrix /// </summary> public Vector4d Row2; /// <summary> /// Bottom row of the matrix /// </summary> public Vector4d Row3; /// <summary> /// The identity matrix /// </summary> public static Matrix4d Identity = new Matrix4d(Vector4d .UnitX, Vector4d .UnitY, Vector4d .UnitZ, Vector4d .UnitW); #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="row0">Top row of the matrix</param> /// <param name="row1">Second row of the matrix</param> /// <param name="row2">Third row of the matrix</param> /// <param name="row3">Bottom row of the matrix</param> public Matrix4d(Vector4d row0, Vector4d row1, Vector4d row2, Vector4d row3) { Row0 = row0; Row1 = row1; Row2 = row2; Row3 = row3; } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="m00">First item of the first row.</param> /// <param name="m01">Second item of the first row.</param> /// <param name="m02">Third item of the first row.</param> /// <param name="m03">Fourth item of the first row.</param> /// <param name="m10">First item of the second row.</param> /// <param name="m11">Second item of the second row.</param> /// <param name="m12">Third item of the second row.</param> /// <param name="m13">Fourth item of the second row.</param> /// <param name="m20">First item of the third row.</param> /// <param name="m21">Second item of the third row.</param> /// <param name="m22">Third item of the third row.</param> /// <param name="m23">First item of the third row.</param> /// <param name="m30">Fourth item of the fourth row.</param> /// <param name="m31">Second item of the fourth row.</param> /// <param name="m32">Third item of the fourth row.</param> /// <param name="m33">Fourth item of the fourth row.</param> public Matrix4d( float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { Row0 = new Vector4d(m00, m01, m02, m03); Row1 = new Vector4d(m10, m11, m12, m13); Row2 = new Vector4d(m20, m21, m22, m23); Row3 = new Vector4d(m30, m31, m32, m33); } #endregion #region Public Members #region Properties /// <summary> /// The determinant of this matrix /// </summary> public double Determinant { get { return Row0.X * Row1.Y * Row2.Z * Row3.W - Row0.X * Row1.Y * Row2.W * Row3.Z + Row0.X * Row1.Z * Row2.W * Row3.Y - Row0.X * Row1.Z * Row2.Y * Row3.W + Row0.X * Row1.W * Row2.Y * Row3.Z - Row0.X * Row1.W * Row2.Z * Row3.Y - Row0.Y * Row1.Z * Row2.W * Row3.X + Row0.Y * Row1.Z * Row2.X * Row3.W - Row0.Y * Row1.W * Row2.X * Row3.Z + Row0.Y * Row1.W * Row2.Z * Row3.X - Row0.Y * Row1.X * Row2.Z * Row3.W + Row0.Y * Row1.X * Row2.W * Row3.Z + Row0.Z * Row1.W * Row2.X * Row3.Y - Row0.Z * Row1.W * Row2.Y * Row3.X + Row0.Z * Row1.X * Row2.Y * Row3.W - Row0.Z * Row1.X * Row2.W * Row3.Y + Row0.Z * Row1.Y * Row2.W * Row3.X - Row0.Z * Row1.Y * Row2.X * Row3.W - Row0.W * Row1.X * Row2.Y * Row3.Z + Row0.W * Row1.X * Row2.Z * Row3.Y - Row0.W * Row1.Y * Row2.Z * Row3.X + Row0.W * Row1.Y * Row2.X * Row3.Z - Row0.W * Row1.Z * Row2.X * Row3.Y + Row0.W * Row1.Z * Row2.Y * Row3.X; } } /// <summary> /// The first column of this matrix /// </summary> public Vector4d Column0 { get { return new Vector4d (Row0.X, Row1.X, Row2.X, Row3.X); } } /// <summary> /// The second column of this matrix /// </summary> public Vector4d Column1 { get { return new Vector4d (Row0.Y, Row1.Y, Row2.Y, Row3.Y); } } /// <summary> /// The third column of this matrix /// </summary> public Vector4d Column2 { get { return new Vector4d (Row0.Z, Row1.Z, Row2.Z, Row3.Z); } } /// <summary> /// The fourth column of this matrix /// </summary> public Vector4d Column3 { get { return new Vector4d (Row0.W, Row1.W, Row2.W, Row3.W); } } public double this[int i, int j] { get { if (i < 0 || i > 3) throw new ArgumentOutOfRangeException("i"); if (j < 0 || j > 3) throw new ArgumentOutOfRangeException("j"); unsafe { fixed (Matrix4d* ptr = &this) return *((double*)ptr + i + j * 4); } } set { if (i < 0 || i > 3) throw new ArgumentOutOfRangeException("i"); if (j < 0 || j > 3) throw new ArgumentOutOfRangeException("j"); unsafe { fixed (Matrix4d* ptr = &this) *((double*)ptr + i + j * 4) = value; } } } /// <summary> /// Gets or sets the value at row 1, column 1 of this instance. /// </summary> public double M11 { get { return Row0.X; } set { Row0.X = value; } } /// <summary> /// Gets or sets the value at row 1, column 2 of this instance. /// </summary> public double M12 { get { return Row0.Y; } set { Row0.Y = value; } } /// <summary> /// Gets or sets the value at row 1, column 3 of this instance. /// </summary> public double M13 { get { return Row0.Z; } set { Row0.Z = value; } } /// <summary> /// Gets or sets the value at row 1, column 4 of this instance. /// </summary> public double M14 { get { return Row0.W; } set { Row0.W = value; } } /// <summary> /// Gets or sets the value at row 2, column 1 of this instance. /// </summary> public double M21 { get { return Row1.X; } set { Row1.X = value; } } /// <summary> /// Gets or sets the value at row 2, column 2 of this instance. /// </summary> public double M22 { get { return Row1.Y; } set { Row1.Y = value; } } /// <summary> /// Gets or sets the value at row 2, column 3 of this instance. /// </summary> public double M23 { get { return Row1.Z; } set { Row1.Z = value; } } /// <summary> /// Gets or sets the value at row 2, column 4 of this instance. /// </summary> public double M24 { get { return Row1.W; } set { Row1.W = value; } } /// <summary> /// Gets or sets the value at row 3, column 1 of this instance. /// </summary> public double M31 { get { return Row2.X; } set { Row2.X = value; } } /// <summary> /// Gets or sets the value at row 3, column 2 of this instance. /// </summary> public double M32 { get { return Row2.Y; } set { Row2.Y = value; } } /// <summary> /// Gets or sets the value at row 3, column 3 of this instance. /// </summary> public double M33 { get { return Row2.Z; } set { Row2.Z = value; } } /// <summary> /// Gets or sets the value at row 3, column 4 of this instance. /// </summary> public double M34 { get { return Row2.W; } set { Row2.W = value; } } /// <summary> /// Gets or sets the value at row 4, column 1 of this instance. /// </summary> public double M41 { get { return Row3.X; } set { Row3.X = value; } } /// <summary> /// Gets or sets the value at row 4, column 3 of this instance. /// </summary> public double M42 { get { return Row3.Y; } set { Row3.Y = value; } } /// <summary> /// Gets or sets the value at row 4, column 3 of this instance. /// </summary> public double M43 { get { return Row3.Z; } set { Row3.Z = value; } } /// <summary> /// Gets or sets the value at row 4, column 4 of this instance. /// </summary> public double M44 { get { return Row3.W; } set { Row3.W = value; } } #endregion #region Instance #region public void Invert() public void Invert() { this = Matrix4d.Invert(this); } #endregion #region public void Transpose() public void Transpose() { this = Matrix4d.Transpose(this); } #endregion #endregion #region Static #region CreateTranslation /// <summary> /// Creates a translation matrix. /// </summary> /// <param name="x">X translation.</param> /// <param name="y">Y translation.</param> /// <param name="z">Z translation.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateTranslation(double x, double y, double z, out Matrix4d result) { result = Identity; result.Row3 = new Vector4d(x, y, z, 1); } /// <summary> /// Creates a translation matrix. /// </summary> /// <param name="vector">The translation vector.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateTranslation(ref Vector3d vector, out Matrix4d result) { result = Identity; result.Row3 = new Vector4d(vector.X, vector.Y, vector.Z, 1); } /// <summary> /// Creates a translation matrix. /// </summary> /// <param name="x">X translation.</param> /// <param name="y">Y translation.</param> /// <param name="z">Z translation.</param> /// <returns>The resulting Matrix4d instance.</returns> public static Matrix4d CreateTranslation(double x, double y, double z) { Matrix4d result; CreateTranslation(x, y, z, out result); return result; } /// <summary> /// Creates a translation matrix. /// </summary> /// <param name="vector">The translation vector.</param> /// <returns>The resulting Matrix4d instance.</returns> public static Matrix4d CreateTranslation(Vector3d vector) { Matrix4d result; CreateTranslation(vector.X, vector.Y, vector.Z, out result); return result; } #endregion #region CreateOrthographic /// <summary> /// Creates an orthographic projection matrix. /// </summary> /// <param name="width">The width of the projection volume.</param> /// <param name="height">The height of the projection volume.</param> /// <param name="zNear">The near edge of the projection volume.</param> /// <param name="zFar">The far edge of the projection volume.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateOrthographic(double width, double height, double zNear, double zFar, out Matrix4d result) { CreateOrthographicOffCenter(-width / 2, width / 2, -height / 2, height / 2, zNear, zFar, out result); } /// <summary> /// Creates an orthographic projection matrix. /// </summary> /// <param name="width">The width of the projection volume.</param> /// <param name="height">The height of the projection volume.</param> /// <param name="zNear">The near edge of the projection volume.</param> /// <param name="zFar">The far edge of the projection volume.</param> /// <rereturns>The resulting Matrix4d instance.</rereturns> public static Matrix4d CreateOrthographic(double width, double height, double zNear, double zFar) { Matrix4d result; CreateOrthographicOffCenter(-width / 2, width / 2, -height / 2, height / 2, zNear, zFar, out result); return result; } #endregion #region CreateOrthographicOffCenter /// <summary> /// Creates an orthographic projection matrix. /// </summary> /// <param name="left">The left edge of the projection volume.</param> /// <param name="right">The right edge of the projection volume.</param> /// <param name="bottom">The bottom edge of the projection volume.</param> /// <param name="top">The top edge of the projection volume.</param> /// <param name="zNear">The near edge of the projection volume.</param> /// <param name="zFar">The far edge of the projection volume.</param> /// <param name="result">The resulting Matrix4d instance.</param> public static void CreateOrthographicOffCenter(double left, double right, double bottom, double top, double zNear, double zFar, out Matrix4d result) { result = new Matrix4d(); double invRL = 1 / (right - left); double invTB = 1 / (top - bottom); double invFN = 1 / (zFar - zNear); result.M11 = 2 * invRL; result.M22 = 2 * invTB; result.M33 = -2 * invFN; result.M41 = -(right + left) * invRL; result.M42 = -(top + bottom) * invTB; result.M43 = -(zFar + zNear) * invFN; } /// <summary> /// Creates an orthographic projection matrix. /// </summary> /// <param name="left">The left edge of the projection volume.</param> /// <param name="right">The right edge of the projection volume.</param> /// <param name="bottom">The bottom edge of the projection volume.</param> /// <param name="top">The top edge of the projection volume.</param> /// <param name="zNear">The near edge of the projection volume.</param> /// <param name="zFar">The far edge of the projection volume.</param> /// <returns>The resulting Matrix4d instance.</returns> public static Matrix4d CreateOrthographicOffCenter(double left, double right, double bottom, double top, double zNear, double zFar) { Matrix4d result; CreateOrthographicOffCenter(left, right, bottom, top, zNear, zFar, out result); return result; } #endregion #region Obsolete Functions #region Translation Functions /// <summary> /// Build a translation matrix with the given translation /// </summary> /// <param name="trans">The vector to translate along</param> /// <returns>A Translation matrix</returns> [Obsolete("Use CreateTranslation instead.")] public static Matrix4d Translation(Vector3d trans) { return Translation(trans.X, trans.Y, trans.Z); } /// <summary> /// Build a translation matrix with the given translation /// </summary> /// <param name="x">X translation</param> /// <param name="y">Y translation</param> /// <param name="z">Z translation</param> /// <returns>A Translation matrix</returns> [Obsolete("Use CreateTranslation instead.")] public static Matrix4d Translation(double x, double y, double z) { Matrix4d result = Identity; result.Row3 = new Vector4d(x, y, z, 1.0f); return result; } #endregion #endregion #region Scale Functions /// <summary> /// Build a scaling matrix /// </summary> /// <param name="scale">Single scale factor for x,y and z axes</param> /// <returns>A scaling matrix</returns> public static Matrix4d Scale(double scale) { return Scale(scale, scale, scale); } /// <summary> /// Build a scaling matrix /// </summary> /// <param name="scale">Scale factors for x,y and z axes</param> /// <returns>A scaling matrix</returns> public static Matrix4d Scale(Vector3d scale) { return Scale(scale.X, scale.Y, scale.Z); } /// <summary> /// Build a scaling matrix /// </summary> /// <param name="x">Scale factor for x-axis</param> /// <param name="y">Scale factor for y-axis</param> /// <param name="z">Scale factor for z-axis</param> /// <returns>A scaling matrix</returns> public static Matrix4d Scale(double x, double y, double z) { Matrix4d result; result.Row0 = Vector4d .UnitX * x; result.Row1 = Vector4d .UnitY * y; result.Row2 = Vector4d .UnitZ * z; result.Row3 = Vector4d .UnitW; return result; } #endregion #region Rotation Functions /// <summary> /// Build a rotation matrix that rotates about the x-axis /// </summary> /// <param name="angle">angle in radians to rotate counter-clockwise around the x-axis</param> /// <returns>A rotation matrix</returns> public static Matrix4d RotateX(double angle) { double cos = (double)System.Math.Cos(angle); double sin = (double)System.Math.Sin(angle); Matrix4d result; result.Row0 = Vector4d .UnitX; result.Row1 = new Vector4d (0.0f, cos, sin, 0.0f); result.Row2 = new Vector4d (0.0f, -sin, cos, 0.0f); result.Row3 = Vector4d .UnitW; return result; } /// <summary> /// Build a rotation matrix that rotates about the y-axis /// </summary> /// <param name="angle">angle in radians to rotate counter-clockwise around the y-axis</param> /// <returns>A rotation matrix</returns> public static Matrix4d RotateY(double angle) { double cos = (double)System.Math.Cos(angle); double sin = (double)System.Math.Sin(angle); Matrix4d result; result.Row0 = new Vector4d (cos, 0.0f, -sin, 0.0f); result.Row1 = Vector4d .UnitY; result.Row2 = new Vector4d (sin, 0.0f, cos, 0.0f); result.Row3 = Vector4d .UnitW; return result; } /// <summary> /// Build a rotation matrix that rotates about the z-axis /// </summary> /// <param name="angle">angle in radians to rotate counter-clockwise around the z-axis</param> /// <returns>A rotation matrix</returns> public static Matrix4d RotateZ(double angle) { double cos = (double)System.Math.Cos(angle); double sin = (double)System.Math.Sin(angle); Matrix4d result; result.Row0 = new Vector4d (cos, sin, 0.0f, 0.0f); result.Row1 = new Vector4d (-sin, cos, 0.0f, 0.0f); result.Row2 = Vector4d .UnitZ; result.Row3 = Vector4d .UnitW; return result; } /// <summary> /// Build a rotation matrix to rotate about the given axis /// </summary> /// <param name="axis">the axis to rotate about</param> /// <param name="angle">angle in radians to rotate counter-clockwise (looking in the direction of the given axis)</param> /// <returns>A rotation matrix</returns> public static Matrix4d Rotate(Vector3d axis, double angle) { double cos = (double)System.Math.Cos(-angle); double sin = (double)System.Math.Sin(-angle); double t = 1.0f - cos; axis.Normalize(); Matrix4d result; result.Row0 = new Vector4d (t * axis.X * axis.X + cos, t * axis.X * axis.Y - sin * axis.Z, t * axis.X * axis.Z + sin * axis.Y, 0.0f); result.Row1 = new Vector4d (t * axis.X * axis.Y + sin * axis.Z, t * axis.Y * axis.Y + cos, t * axis.Y * axis.Z - sin * axis.X, 0.0f); result.Row2 = new Vector4d (t * axis.X * axis.Z - sin * axis.Y, t * axis.Y * axis.Z + sin * axis.X, t * axis.Z * axis.Z + cos, 0.0f); result.Row3 = Vector4d .UnitW; return result; } /// <summary> /// Build a rotation matrix from a quaternion /// </summary> /// <param name="q">the quaternion</param> /// <returns>A rotation matrix</returns> public static Matrix4d Rotate(Quaterniond q) { Vector3d axis; double angle; q.ToAxisAngle(out axis, out angle); return Rotate(axis, angle); } #endregion #region Camera Helper Functions /// <summary> /// Build a world space to camera space matrix /// </summary> /// <param name="eye">Eye (camera) position in world space</param> /// <param name="target">Target position in world space</param> /// <param name="up">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param> /// <returns>A Matrix that transforms world space to camera space</returns> public static Matrix4d LookAt(Vector3d eye, Vector3d target, Vector3d up) { Vector3d z = Vector3d.Normalize(eye - target); Vector3d x = Vector3d.Normalize(Vector3d.Cross(up, z)); Vector3d y = Vector3d.Normalize(Vector3d.Cross(z, x)); Matrix4d rot = new Matrix4d(new Vector4d (x.X, y.X, z.X, 0.0f), new Vector4d (x.Y, y.Y, z.Y, 0.0f), new Vector4d (x.Z, y.Z, z.Z, 0.0f), Vector4d .UnitW); Matrix4d trans = Matrix4d.CreateTranslation(-eye); return trans * rot; } /// <summary> /// Build a world space to camera space matrix /// </summary> /// <param name="eyeX">Eye (camera) position in world space</param> /// <param name="eyeY">Eye (camera) position in world space</param> /// <param name="eyeZ">Eye (camera) position in world space</param> /// <param name="targetX">Target position in world space</param> /// <param name="targetY">Target position in world space</param> /// <param name="targetZ">Target position in world space</param> /// <param name="upX">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param> /// <param name="upY">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param> /// <param name="upZ">Up vector in world space (should not be parallel to the camera direction, that is target - eye)</param> /// <returns>A Matrix4 that transforms world space to camera space</returns> public static Matrix4d LookAt(double eyeX, double eyeY, double eyeZ, double targetX, double targetY, double targetZ, double upX, double upY, double upZ) { return LookAt(new Vector3d(eyeX, eyeY, eyeZ), new Vector3d(targetX, targetY, targetZ), new Vector3d(upX, upY, upZ)); } /// <summary> /// Build a projection matrix /// </summary> /// <param name="left">Left edge of the view frustum</param> /// <param name="right">Right edge of the view frustum</param> /// <param name="bottom">Bottom edge of the view frustum</param> /// <param name="top">Top edge of the view frustum</param> /// <param name="near">Distance to the near clip plane</param> /// <param name="far">Distance to the far clip plane</param> /// <returns>A projection matrix that transforms camera space to raster space</returns> public static Matrix4d Frustum(double left, double right, double bottom, double top, double near, double far) { double invRL = 1.0f / (right - left); double invTB = 1.0f / (top - bottom); double invFN = 1.0f / (far - near); return new Matrix4d(new Vector4d (2.0f * near * invRL, 0.0f, 0.0f, 0.0f), new Vector4d (0.0f, 2.0f * near * invTB, 0.0f, 0.0f), new Vector4d ((right + left) * invRL, (top + bottom) * invTB, -(far + near) * invFN, -1.0f), new Vector4d (0.0f, 0.0f, -2.0f * far * near * invFN, 0.0f)); } /// <summary> /// Build a projection matrix /// </summary> /// <param name="fovy">Angle of the field of view in the y direction (in radians)</param> /// <param name="aspect">Aspect ratio of the view (width / height)</param> /// <param name="near">Distance to the near clip plane</param> /// <param name="far">Distance to the far clip plane</param> /// <returns>A projection matrix that transforms camera space to raster space</returns> public static Matrix4d Perspective(double fovy, double aspect, double near, double far) { double yMax = near * (double)System.Math.Tan(0.5f * fovy); double yMin = -yMax; double xMin = yMin * aspect; double xMax = yMax * aspect; return Frustum(xMin, xMax, yMin, yMax, near, far); } #endregion #region Multiply Functions /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication</returns> public static Matrix4d Mult(Matrix4d left, Matrix4d right) { Matrix4d result; Mult(ref left, ref right, out result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication</param> public static void Mult(ref Matrix4d left, ref Matrix4d right, out Matrix4d result) { result = new Matrix4d(); result.M11 = left.M11 * right.M11 + left.M12 * right.M21 + left.M13 * right.M31 + left.M14 * right.M41; result.M12 = left.M11 * right.M12 + left.M12 * right.M22 + left.M13 * right.M32 + left.M14 * right.M42; result.M13 = left.M11 * right.M13 + left.M12 * right.M23 + left.M13 * right.M33 + left.M14 * right.M43; result.M14 = left.M11 * right.M14 + left.M12 * right.M24 + left.M13 * right.M34 + left.M14 * right.M44; result.M21 = left.M21 * right.M11 + left.M22 * right.M21 + left.M23 * right.M31 + left.M24 * right.M41; result.M22 = left.M21 * right.M12 + left.M22 * right.M22 + left.M23 * right.M32 + left.M24 * right.M42; result.M23 = left.M21 * right.M13 + left.M22 * right.M23 + left.M23 * right.M33 + left.M24 * right.M43; result.M24 = left.M21 * right.M14 + left.M22 * right.M24 + left.M23 * right.M34 + left.M24 * right.M44; result.M31 = left.M31 * right.M11 + left.M32 * right.M21 + left.M33 * right.M31 + left.M34 * right.M41; result.M32 = left.M31 * right.M12 + left.M32 * right.M22 + left.M33 * right.M32 + left.M34 * right.M42; result.M33 = left.M31 * right.M13 + left.M32 * right.M23 + left.M33 * right.M33 + left.M34 * right.M43; result.M34 = left.M31 * right.M14 + left.M32 * right.M24 + left.M33 * right.M34 + left.M34 * right.M44; result.M41 = left.M41 * right.M11 + left.M42 * right.M21 + left.M43 * right.M31 + left.M44 * right.M41; result.M42 = left.M41 * right.M12 + left.M42 * right.M22 + left.M43 * right.M32 + left.M44 * right.M42; result.M43 = left.M41 * right.M13 + left.M42 * right.M23 + left.M43 * right.M33 + left.M44 * right.M43; result.M44 = left.M41 * right.M14 + left.M42 * right.M24 + left.M43 * right.M34 + left.M44 * right.M44; } #endregion #region Invert Functions /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns> /// <exception cref="InvalidOperationException">Thrown if the Matrix4d is singular.</exception> public static Matrix4d Invert(Matrix4d mat) { int[] colIdx = { 0, 0, 0, 0 }; int[] rowIdx = { 0, 0, 0, 0 }; int[] pivotIdx = { -1, -1, -1, -1 }; // convert the matrix to an array for easy looping double[,] inverse = {{mat.Row0.X, mat.Row0.Y, mat.Row0.Z, mat.Row0.W}, {mat.Row1.X, mat.Row1.Y, mat.Row1.Z, mat.Row1.W}, {mat.Row2.X, mat.Row2.Y, mat.Row2.Z, mat.Row2.W}, {mat.Row3.X, mat.Row3.Y, mat.Row3.Z, mat.Row3.W} }; int icol = 0; int irow = 0; for (int i = 0; i < 4; i++) { // Find the largest pivot value double maxPivot = 0.0f; for (int j = 0; j < 4; j++) { if (pivotIdx[j] != 0) { for (int k = 0; k < 4; ++k) { if (pivotIdx[k] == -1) { double absVal = System.Math.Abs(inverse[j, k]); if (absVal > maxPivot) { maxPivot = absVal; irow = j; icol = k; } } else if (pivotIdx[k] > 0) { return mat; } } } } ++(pivotIdx[icol]); // Swap rows over so pivot is on diagonal if (irow != icol) { for (int k = 0; k < 4; ++k) { double f = inverse[irow, k]; inverse[irow, k] = inverse[icol, k]; inverse[icol, k] = f; } } rowIdx[i] = irow; colIdx[i] = icol; double pivot = inverse[icol, icol]; // check for singular matrix if (pivot == 0.0f) { throw new InvalidOperationException("Matrix is singular and cannot be inverted."); //return mat; } // Scale row so it has a unit diagonal double oneOverPivot = 1.0f / pivot; inverse[icol, icol] = 1.0f; for (int k = 0; k < 4; ++k) inverse[icol, k] *= oneOverPivot; // Do elimination of non-diagonal elements for (int j = 0; j < 4; ++j) { // check this isn't on the diagonal if (icol != j) { double f = inverse[j, icol]; inverse[j, icol] = 0.0f; for (int k = 0; k < 4; ++k) inverse[j, k] -= inverse[icol, k] * f; } } } for (int j = 3; j >= 0; --j) { int ir = rowIdx[j]; int ic = colIdx[j]; for (int k = 0; k < 4; ++k) { double f = inverse[k, ir]; inverse[k, ir] = inverse[k, ic]; inverse[k, ic] = f; } } mat.Row0 = new Vector4d (inverse[0, 0], inverse[0, 1], inverse[0, 2], inverse[0, 3]); mat.Row1 = new Vector4d (inverse[1, 0], inverse[1, 1], inverse[1, 2], inverse[1, 3]); mat.Row2 = new Vector4d (inverse[2, 0], inverse[2, 1], inverse[2, 2], inverse[2, 3]); mat.Row3 = new Vector4d (inverse[3, 0], inverse[3, 1], inverse[3, 2], inverse[3, 3]); return mat; } #endregion #region Transpose /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <returns>The transpose of the given matrix</returns> public static Matrix4d Transpose(Matrix4d mat) { return new Matrix4d(mat.Column0, mat.Column1, mat.Column2, mat.Column3); } /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <param name="result">The result of the calculation</param> public static void Transpose(ref Matrix4d mat, out Matrix4d result) { result.Row0 = mat.Column0; result.Row1 = mat.Column1; result.Row2 = mat.Column2; result.Row3 = mat.Column3; } #endregion #endregion #region Operators /// <summary> /// Matrix multiplication /// </summary> /// <param name="left">left-hand operand</param> /// <param name="right">right-hand operand</param> /// <returns>A new Matrix44 which holds the result of the multiplication</returns> public static Matrix4d operator *(Matrix4d left, Matrix4d right) { return Matrix4d.Mult(left, right); } public static bool operator ==(Matrix4d left, Matrix4d right) { return left.Equals(right); } public static bool operator !=(Matrix4d left, Matrix4d right) { return !left.Equals(right); } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current Matrix44. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("{0}\n{1}\n{2}\n{3}", Row0, Row1, Row2, Row3); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return Row0.GetHashCode() ^ Row1.GetHashCode() ^ Row2.GetHashCode() ^ Row3.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Matrix4d)) return false; return this.Equals((Matrix4d)obj); } #endregion #endregion #endregion #region IEquatable<Matrix4d> Members /// <summary>Indicates whether the current matrix is equal to another matrix.</summary> /// <param name="other">An matrix to compare with this matrix.</param> /// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns> public bool Equals(Matrix4d other) { return Row0 == other.Row0 && Row1 == other.Row1 && Row2 == other.Row2 && Row3 == other.Row3; } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_REMOVEUNNECESSARYTEMPORARIES namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public static class TransformFinallyBlocksIntoTryBlocks { struct FinallyRange { public ExceptionHandlerBasicBlock Entry; public BasicBlock Exit; public override bool Equals(Object obj) { return (obj is FinallyRange) && (this == (FinallyRange)obj); } public override int GetHashCode() { return Entry.GetHashCode() ^ Exit.GetHashCode(); } public static bool operator ==(FinallyRange x, FinallyRange y) { return (x.Entry == y.Entry) && (x.Entry == y.Entry); } public static bool operator !=(FinallyRange x, FinallyRange y) { return !(x == y); } }; public static void Execute(ControlFlowGraphStateForCodeTransformation cfg) { // This maps finally block ranges to the entry block of their cloned 'normal' region. var clonedRanges = HashTableFactory.New<FinallyRange, BasicBlock>(); while (true) { cfg.TraceToFile( "TransformFinallyBlocksIntoTryBlocks" ); bool fDone = true; foreach (BasicBlock block in cfg.DataFlow_SpanningTree_BasicBlocks) { if (RemoveFinally(cfg, block, clonedRanges)) { fDone = false; break; } } if(fDone) { CHECKS.ASSERT( FindOperation( cfg.DataFlow_SpanningTree_Operators, typeof(EndFinallyControlOperator) ) == null, "Internal error: failed to remove 'endfinally' operators in {0}.", cfg.Method ); break; } } } private static bool RemoveFinally( ControlFlowGraphStateForCodeTransformation cfg, BasicBlock block, GrowOnlyHashTable<FinallyRange, BasicBlock> clonedRanges) { ExceptionHandlerBasicBlock ehBB = block as ExceptionHandlerBasicBlock; if (ehBB == null) { return false; } foreach(ExceptionClause ec in ehBB.HandlerFor) { if(ec.Flags == ExceptionClause.ExceptionFlag.Finally) { GrowOnlySet<BasicBlock> setVisited = SetFactory.NewWithReferenceEquality<BasicBlock>(); // // Collect all the basic blocks that are part of the handler. // CollectFinallyHandler(ehBB, setVisited); // // First, see if there's any nested finally clause. If so, bail out. // foreach (BasicBlock bbSub in setVisited) { if (bbSub != ehBB) { if (RemoveFinally(cfg, bbSub, clonedRanges)) { return true; } } } GrowOnlySet<ControlOperator> setLeave = SetFactory.NewWithReferenceEquality<ControlOperator>(); GrowOnlySet<ControlOperator> setFinally = SetFactory.NewWithReferenceEquality<ControlOperator>(); // // Find all the leave operators in the basic blocks protected by this finally handler. // FindAllLeaveOperators(ehBB, setLeave); // // For each of them: // // 1) Clone the finally handler(s) protecting the leaving block. // 2) Convert the leave to a branch to the cloned handler. // 3) Change endfinally to a leave to the same original target. // foreach (LeaveControlOperator leave in setLeave) { CloningContext context = new CloneForwardGraphButLinkToExceptionHandlers(cfg, cfg, null); var finallyHandlers = new Stack<BasicBlock>(); FinallyRange currentRange = new FinallyRange{ Entry = null, Exit = leave.TargetBranch }; // Unwind all finally blocks that either ehBB itself or protected by it. These are always in // order from innermost to outermost; we can just chain them together until we hit ehBB. foreach (var handler in leave.BasicBlock.ProtectedBy) { foreach (var clause in handler.HandlerFor) { if ((clause.Flags & ExceptionClause.ExceptionFlag.Finally) != 0) { // Set the range's entry block to the first one we encounter. if (currentRange.Entry == null) { currentRange.Entry = handler; } finallyHandlers.Push(handler); break; } } if (handler == ehBB) { break; } } // If we already cloned this range of finally blocks, just reuse the existing entry block. BasicBlock nextBlock; if (!clonedRanges.TryGetValue(currentRange, out nextBlock)) { nextBlock = leave.TargetBranch; // Clone each handler block in reverse order. while (finallyHandlers.Count != 0) { BasicBlock handler = finallyHandlers.Pop(); BasicBlock clonedBlock = context.Clone(handler.FirstSuccessor); setFinally.Clear(); FindAllFinallyOperators(clonedBlock, setFinally); SubstituteFinallyForBranch(setFinally, nextBlock); nextBlock = clonedBlock; } clonedRanges[currentRange] = nextBlock; } var leaveBranch = UnconditionalControlOperator.New(leave.DebugInfo, nextBlock); leave.SubstituteWithOperator(leaveBranch, Operator.SubstitutionFlags.Default); } // To finish, all the endfinally operators should be converted to simple rethrow. setFinally.Clear(); FindAllFinallyOperators(ehBB, setFinally); SubstituteFinallyForRethrow(setFinally); // Convert the finally exception clauses to catch all ones. ExceptionClause ecNew = new ExceptionClause(ExceptionClause.ExceptionFlag.None, null); ehBB.SubstituteHandlerFor(ec, ecNew); return true; } } return false; } private static Operator FindOperation( Operator[] ops , Type match ) { foreach(Operator op in ops) { if(op.GetType() == match) { return op; } } return null; } private static void CollectFinallyHandler( BasicBlock bb , GrowOnlySet< BasicBlock > setVisited ) { setVisited.Insert( bb ); foreach(BasicBlockEdge edge in bb.Successors) { BasicBlock succ = edge.Successor; if(succ is ExceptionHandlerBasicBlock) { // // Don't follow exceptional edges. // } else if(setVisited.Contains( succ ) == false) { CollectFinallyHandler( succ, setVisited ); } } } private static void FindAllLeaveOperators( BasicBlock bb , GrowOnlySet<ControlOperator> setLeave ) { foreach(BasicBlockEdge edge in bb.Predecessors) { BasicBlock pred = edge.Predecessor; LeaveControlOperator ctrl = pred.FlowControl as LeaveControlOperator; if(ctrl != null) { // // Only consider operators leaving the area protected by the handler. // if(pred .IsProtectedBy( bb ) == true && ctrl.TargetBranch.IsProtectedBy( bb ) == false ) { setLeave.Insert( ctrl ); } } } } private static void FindAllFinallyOperators( BasicBlock bb , GrowOnlySet<ControlOperator> setFinally ) { GrowOnlySet< BasicBlock > setVisited = SetFactory.NewWithReferenceEquality< BasicBlock >(); CollectFinallyHandler( bb, setVisited ); foreach(BasicBlock bb2 in setVisited) { ControlOperator ctrl = bb2.FlowControl; if(ctrl is EndFinallyControlOperator) { setFinally.Insert( ctrl ); } } } private static void SubstituteFinallyForBranch(GrowOnlySet<ControlOperator> setFinally, BasicBlock target) { foreach (ControlOperator op in setFinally) { var opNew = UnconditionalControlOperator.New(op.DebugInfo, target); op.SubstituteWithOperator(opNew, Operator.SubstitutionFlags.Default); } } private static void SubstituteFinallyForRethrow( GrowOnlySet<ControlOperator> setFinally ) { foreach(ControlOperator op in setFinally) { RethrowControlOperator opNew = RethrowControlOperator.New( op.DebugInfo ); op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default ); } } } }
// 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. // // The Reflection stack has grown a large legacy of apis that thunk others. // Apis that do little more than wrap another api will be kept here to // keep the main files less cluttered. // using System; using System.IO; using System.Text; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Reflection.Runtime.General; using Internal.LowLevelLinq; namespace System.Reflection.Runtime.Assemblies { internal partial class RuntimeAssembly { public sealed override Type[] GetExportedTypes() => ExportedTypes.ToArray(); public sealed override Module[] GetLoadedModules(bool getResourceModules) => Modules.ToArray(); public sealed override Module[] GetModules(bool getResourceModules) => Modules.ToArray(); public sealed override Type[] GetTypes() => DefinedTypes.ToArray(); // "copiedName" only affects whether CodeBase is set to the assembly location before or after the shadow-copy. // That concept is meaningless on .NET Native. public sealed override AssemblyName GetName(bool copiedName) => GetName(); public sealed override Stream GetManifestResourceStream(Type type, string name) { StringBuilder sb = new StringBuilder(); if (type == null) { if (name == null) throw new ArgumentNullException(nameof(type)); } else { string nameSpace = type.Namespace; if (nameSpace != null) { sb.Append(nameSpace); if (name != null) { sb.Append(Type.Delimiter); } } } if (name != null) { sb.Append(name); } return GetManifestResourceStream(sb.ToString()); } public sealed override string Location => string.Empty; public sealed override string CodeBase { get { throw new PlatformNotSupportedException(); } } public sealed override Assembly GetSatelliteAssembly(CultureInfo culture) { throw new PlatformNotSupportedException(); } public sealed override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { throw new PlatformNotSupportedException(); } public sealed override string ImageRuntimeVersion { get { throw new PlatformNotSupportedException(); } } public sealed override AssemblyName[] GetReferencedAssemblies() { throw new PlatformNotSupportedException(); } public sealed override Module GetModule(string name) { throw new PlatformNotSupportedException(); } } } namespace System.Reflection.Runtime.MethodInfos { internal abstract partial class RuntimeConstructorInfo { public sealed override MethodImplAttributes GetMethodImplementationFlags() => MethodImplementationFlags; // Partial trust doesn't exist in Aot so these legacy apis are meaningless. Will report everything as SecurityCritical by fiat. public sealed override bool IsSecurityCritical => true; public sealed override bool IsSecuritySafeCritical => false; public sealed override bool IsSecurityTransparent => false; } } namespace System.Reflection.Runtime.EventInfos { internal abstract partial class RuntimeEventInfo { public sealed override MethodInfo GetAddMethod(bool nonPublic) => AddMethod.FilterAccessor(nonPublic); public sealed override MethodInfo GetRemoveMethod(bool nonPublic) => RemoveMethod.FilterAccessor(nonPublic); public sealed override MethodInfo GetRaiseMethod(bool nonPublic) => RaiseMethod?.FilterAccessor(nonPublic); } } namespace System.Reflection.Runtime.FieldInfos { internal abstract partial class RuntimeFieldInfo { public sealed override object GetRawConstantValue() { if (!IsLiteral) throw new InvalidOperationException(); object value = GetValue(null); return value.ToRawValue(); } } } namespace System.Reflection.Runtime.MethodInfos { internal abstract partial class RuntimeMethodInfo { public sealed override MethodImplAttributes GetMethodImplementationFlags() => MethodImplementationFlags; public sealed override ICustomAttributeProvider ReturnTypeCustomAttributes => ReturnParameter; // Partial trust doesn't exist in Aot so these legacy apis are meaningless. Will report everything as SecurityCritical by fiat. public sealed override bool IsSecurityCritical => true; public sealed override bool IsSecuritySafeCritical => false; public sealed override bool IsSecurityTransparent => false; } } namespace System.Reflection.Runtime.ParameterInfos { internal abstract partial class RuntimeParameterInfo { public sealed override object RawDefaultValue => DefaultValue.ToRawValue(); } } namespace System.Reflection.Runtime.PropertyInfos { internal abstract partial class RuntimePropertyInfo { public sealed override MethodInfo GetGetMethod(bool nonPublic) => Getter?.FilterAccessor(nonPublic); public sealed override MethodInfo GetSetMethod(bool nonPublic) => Setter?.FilterAccessor(nonPublic); public sealed override MethodInfo[] GetAccessors(bool nonPublic) { MethodInfo getter = GetGetMethod(nonPublic); MethodInfo setter = GetSetMethod(nonPublic); int count = 0; if (getter != null) count++; if (setter != null) count++; MethodInfo[] accessors = new MethodInfo[count]; int index = 0; if (getter != null) accessors[index++] = getter; if (setter != null) accessors[index++] = setter; return accessors; } public sealed override object GetRawConstantValue() => GetConstantValue().ToRawValue(); } } namespace System.Reflection.Runtime.TypeInfos { internal abstract partial class RuntimeTypeInfo { public sealed override Type[] GetGenericArguments() { if (IsConstructedGenericType) return GenericTypeArguments; if (IsGenericTypeDefinition) return GenericTypeParameters; return Array.Empty<Type>(); } public sealed override bool IsGenericType => IsConstructedGenericType || IsGenericTypeDefinition; public sealed override Type[] GetInterfaces() => ImplementedInterfaces.ToArray(); public sealed override string GetEnumName(object value) => Enum.GetName(this, value); public sealed override string[] GetEnumNames() => Enum.GetNames(this); public sealed override Type GetEnumUnderlyingType() => Enum.GetUnderlyingType(this); public sealed override Array GetEnumValues() => Enum.GetValues(this); public sealed override bool IsEnumDefined(object value) => Enum.IsDefined(this, value); // Partial trust doesn't exist in Aot so these legacy apis are meaningless. Will report everything as SecurityCritical by fiat. public sealed override bool IsSecurityCritical => true; public sealed override bool IsSecuritySafeCritical => false; public sealed override bool IsSecurityTransparent => false; public sealed override Type GetInterface(string name, bool ignoreCase) { if (name == null) throw new ArgumentNullException(nameof(name)); string simpleName; string ns; SplitTypeName(name, out simpleName, out ns); Type match = null; foreach (Type ifc in ImplementedInterfaces) { string ifcSimpleName = ifc.Name; bool simpleNameMatches = ignoreCase ? (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(simpleName, ifcSimpleName, CompareOptions.IgnoreCase)) // @todo: This could be expressed simpler but the necessary parts of String api not yet ported. : simpleName.Equals(ifcSimpleName); if (!simpleNameMatches) continue; // This check exists for desktop compat: // (1) caller can optionally omit namespace part of name in pattern- we'll still match. // (2) ignoreCase:true does not apply to the namespace portion. if (ns != null && !ns.Equals(ifc.Namespace)) continue; if (match != null) throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); match = ifc; } return match; } private static void SplitTypeName(string fullname, out string name, out string ns) { Debug.Assert(fullname != null); // Get namespace int nsDelimiter = fullname.LastIndexOf(".", StringComparison.Ordinal); if (nsDelimiter != -1) { ns = fullname.Substring(0, nsDelimiter); int nameLength = fullname.Length - ns.Length - 1; name = fullname.Substring(nsDelimiter + 1, nameLength); Debug.Assert(fullname.Equals(ns + "." + name)); } else { ns = null; name = fullname; } } } }
// 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 System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Performance; using osu.Framework.Graphics.Shaders; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Visualisation; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.IO.Stores; using osu.Framework.Localisation; using osu.Framework.Platform; using osuTK; namespace osu.Framework { public abstract class Game : Container, IKeyBindingHandler<FrameworkAction>, IKeyBindingHandler<PlatformAction>, IHandleGlobalKeyboardInput { public IWindow Window => Host?.Window; public ResourceStore<byte[]> Resources { get; private set; } public TextureStore Textures { get; private set; } protected GameHost Host { get; private set; } private readonly Bindable<bool> isActive = new Bindable<bool>(true); /// <summary> /// Whether the game is active (in the foreground). /// </summary> public IBindable<bool> IsActive => isActive; public AudioManager Audio { get; private set; } public ShaderManager Shaders { get; private set; } /// <summary> /// A store containing fonts accessible game-wide. /// </summary> /// <remarks> /// It is recommended to use <see cref="AddFont"/> when adding new fonts. /// </remarks> public FontStore Fonts { get; private set; } private FontStore localFonts; protected LocalisationManager Localisation { get; private set; } private readonly Container content; private DrawVisualiser drawVisualiser; private TextureVisualiser textureVisualiser; private LogOverlay logOverlay; protected override Container<Drawable> Content => content; protected internal virtual UserInputManager CreateUserInputManager() => new UserInputManager(); /// <summary> /// Provide <see cref="FrameworkSetting"/> defaults which should override those provided by osu-framework. /// <remarks> /// Please check https://github.com/ppy/osu-framework/blob/master/osu.Framework/Configuration/FrameworkConfigManager.cs for expected types. /// </remarks> /// </summary> protected internal virtual IDictionary<FrameworkSetting, object> GetFrameworkConfigDefaults() => null; /// <summary> /// Creates the <see cref="Storage"/> where this <see cref="Game"/> will reside. /// </summary> /// <param name="host">The <see cref="GameHost"/>.</param> /// <param name="defaultStorage">The default <see cref="Storage"/> to be used if a custom <see cref="Storage"/> isn't desired.</param> /// <returns>The <see cref="Storage"/>.</returns> protected internal virtual Storage CreateStorage(GameHost host, Storage defaultStorage) => defaultStorage; protected Game() { RelativeSizeAxes = Axes.Both; AddRangeInternal(new Drawable[] { content = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, }, }); } /// <summary> /// As Load is run post host creation, you can override this method to alter properties of the host before it makes itself visible to the user. /// </summary> /// <param name="host"></param> public virtual void SetHost(GameHost host) { Host = host; host.Exiting += OnExiting; host.Activated += () => isActive.Value = true; host.Deactivated += () => isActive.Value = false; } private DependencyContainer dependencies; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) => dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); [BackgroundDependencyLoader] private void load(FrameworkConfigManager config) { Resources = new ResourceStore<byte[]>(); Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(typeof(Game).Assembly), @"Resources")); Textures = new TextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures"))); Textures.AddStore(Host.CreateTextureLoaderStore(new OnlineStore())); dependencies.Cache(Textures); var tracks = new ResourceStore<byte[]>(); tracks.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Tracks")); tracks.AddStore(new OnlineStore()); var samples = new ResourceStore<byte[]>(); samples.AddStore(new NamespacedResourceStore<byte[]>(Resources, @"Samples")); samples.AddStore(new OnlineStore()); Audio = new AudioManager(Host.AudioThread, tracks, samples) { EventScheduler = Scheduler }; dependencies.Cache(Audio); dependencies.CacheAs(Audio.Tracks); dependencies.CacheAs(Audio.Samples); // attach our bindables to the audio subsystem. config.BindWith(FrameworkSetting.AudioDevice, Audio.AudioDevice); config.BindWith(FrameworkSetting.VolumeUniversal, Audio.Volume); config.BindWith(FrameworkSetting.VolumeEffect, Audio.VolumeSample); config.BindWith(FrameworkSetting.VolumeMusic, Audio.VolumeTrack); Shaders = new ShaderManager(new NamespacedResourceStore<byte[]>(Resources, @"Shaders")); dependencies.Cache(Shaders); var cacheStorage = Host.CacheStorage.GetStorageForDirectory("fonts"); // base store is for user fonts Fonts = new FontStore(useAtlas: true, cacheStorage: cacheStorage); // nested store for framework provided fonts. // note that currently this means there could be two async font load operations. Fonts.AddStore(localFonts = new FontStore(useAtlas: false)); addFont(localFonts, Resources, @"Fonts/OpenSans/OpenSans-Regular"); addFont(localFonts, Resources, @"Fonts/OpenSans/OpenSans-Bold"); addFont(localFonts, Resources, @"Fonts/OpenSans/OpenSans-RegularItalic"); addFont(localFonts, Resources, @"Fonts/OpenSans/OpenSans-BoldItalic"); addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Solid"); addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Regular"); addFont(Fonts, Resources, @"Fonts/FontAwesome5/FontAwesome-Brands"); dependencies.Cache(Fonts); Localisation = new LocalisationManager(config); dependencies.Cache(Localisation); frameSyncMode = config.GetBindable<FrameSync>(FrameworkSetting.FrameSync); executionMode = config.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode); logOverlayVisibility = config.GetBindable<bool>(FrameworkSetting.ShowLogOverlay); logOverlayVisibility.BindValueChanged(visibility => { if (visibility.NewValue) { if (logOverlay == null) { LoadComponentAsync(logOverlay = new LogOverlay { Depth = float.MinValue / 2, }, AddInternal); } logOverlay.Show(); } else { logOverlay?.Hide(); } }, true); } /// <summary> /// Add a font to be globally accessible to the game. /// </summary> /// <param name="store">The backing store with font resources.</param> /// <param name="assetName">The base name of the font.</param> /// <param name="target">An optional target store to add the font to. If not specified, <see cref="Fonts"/> is used.</param> public void AddFont(ResourceStore<byte[]> store, string assetName = null, FontStore target = null) => addFont(target ?? Fonts, store, assetName); private void addFont(FontStore target, ResourceStore<byte[]> store, string assetName = null) => target.AddStore(new RawCachingGlyphStore(store, assetName, Host.CreateTextureLoaderStore(store))); protected override void LoadComplete() { base.LoadComplete(); PerformanceOverlay performanceOverlay; LoadComponentAsync(performanceOverlay = new PerformanceOverlay(Host.Threads) { Margin = new MarginPadding(5), Direction = FillDirection.Vertical, Spacing = new Vector2(10, 10), AutoSizeAxes = Axes.Both, Alpha = 0, Anchor = Anchor.BottomRight, Origin = Anchor.BottomRight, Depth = float.MinValue }, AddInternal); FrameStatistics.BindValueChanged(e => performanceOverlay.State = e.NewValue, true); } protected readonly Bindable<FrameStatisticsMode> FrameStatistics = new Bindable<FrameStatisticsMode>(); private GlobalStatisticsDisplay globalStatistics; private Bindable<bool> logOverlayVisibility; private Bindable<FrameSync> frameSyncMode; private Bindable<ExecutionMode> executionMode; public bool OnPressed(FrameworkAction action) { switch (action) { case FrameworkAction.CycleFrameStatistics: switch (FrameStatistics.Value) { case FrameStatisticsMode.None: FrameStatistics.Value = FrameStatisticsMode.Minimal; break; case FrameStatisticsMode.Minimal: FrameStatistics.Value = FrameStatisticsMode.Full; break; case FrameStatisticsMode.Full: FrameStatistics.Value = FrameStatisticsMode.None; break; } return true; case FrameworkAction.ToggleGlobalStatistics: if (globalStatistics == null) { LoadComponentAsync(globalStatistics = new GlobalStatisticsDisplay { Depth = float.MinValue / 2, Position = new Vector2(100 + ToolWindow.WIDTH, 100) }, AddInternal); } globalStatistics.ToggleVisibility(); return true; case FrameworkAction.ToggleDrawVisualiser: if (drawVisualiser == null) { LoadComponentAsync(drawVisualiser = new DrawVisualiser { ToolPosition = new Vector2(100), Depth = float.MinValue / 2, }, AddInternal); } drawVisualiser.ToggleVisibility(); return true; case FrameworkAction.ToggleAtlasVisualiser: if (textureVisualiser == null) { LoadComponentAsync(textureVisualiser = new TextureVisualiser { Position = new Vector2(100 + 2 * ToolWindow.WIDTH, 100), Depth = float.MinValue / 2, }, AddInternal); } textureVisualiser.ToggleVisibility(); return true; case FrameworkAction.ToggleLogOverlay: logOverlayVisibility.Value = !logOverlayVisibility.Value; return true; case FrameworkAction.ToggleFullscreen: Window?.CycleMode(); return true; case FrameworkAction.CycleFrameSync: var nextFrameSync = frameSyncMode.Value + 1; if (nextFrameSync > FrameSync.Unlimited) nextFrameSync = FrameSync.VSync; frameSyncMode.Value = nextFrameSync; break; case FrameworkAction.CycleExecutionMode: var nextExecutionMode = executionMode.Value + 1; if (nextExecutionMode > ExecutionMode.MultiThreaded) nextExecutionMode = ExecutionMode.SingleThread; executionMode.Value = nextExecutionMode; break; } return false; } public void OnReleased(FrameworkAction action) { } public virtual bool OnPressed(PlatformAction action) { switch (action.ActionType) { case PlatformActionType.Exit: Host.Window?.Close(); return true; } return false; } public virtual void OnReleased(PlatformAction action) { } public void Exit() { if (Host == null) throw new InvalidOperationException("Attempted to exit a game which has not yet been run"); Host.Exit(); } protected virtual bool OnExiting() => false; protected override void Dispose(bool isDisposing) { // ensure any async disposals are completed before we begin to rip components out. // if we were to not wait, async disposals may throw unexpected exceptions. AsyncDisposalQueue.WaitForEmpty(); base.Dispose(isDisposing); // call a second time to protect against anything being potentially async disposed in the base.Dispose call. AsyncDisposalQueue.WaitForEmpty(); Audio?.Dispose(); Audio = null; Fonts?.Dispose(); Fonts = null; localFonts?.Dispose(); localFonts = null; } } }
//----------------------------------------------------------------------- // <copyright file="MainForm.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace TQVaultAE.GUI { using Microsoft.Extensions.DependencyInjection; using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Permissions; using System.Windows.Forms; using TQVaultAE.GUI.Components; using TQVaultAE.GUI.Models; using TQVaultAE.Logs; using TQVaultAE.Domain.Entities; using TQVaultAE.Presentation; using TQVaultAE.Config; using TQVaultAE.Services; using TQVaultAE.Domain.Contracts.Services; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using TQVaultAE.Domain.Results; using System.Collections.Concurrent; using Microsoft.Extensions.Logging; /// <summary> /// Main Dialog class /// </summary> public partial class MainForm : VaultForm { private readonly ILogger Log = null; #region Fields /// <summary> /// Indicates whether the database resources have completed loading. /// </summary> private bool resourcesLoaded; /// <summary> /// Indicates whether the entire load process has completed. /// </summary> private bool loadingComplete; /// <summary> /// Instance of the player panel control /// </summary> private PlayerPanel playerPanel; /// <summary> /// Holds the last sack that had mouse focus /// Used for Automoving /// </summary> private SackCollection lastSackHighlighted; /// <summary> /// Holds the last sack panel that had mouse focus /// Used for Automoving /// /// </summary> private SackPanel lastSackPanelHighlighted; /// <summary> /// Info for the current item being dragged by the mouse /// </summary> private ItemDragInfo DragInfo; /// <summary> /// Used for show/hide table panel layout borders during debug /// </summary> private bool DebugLayoutBorderVisible = false; /// <summary> /// Holds the coordinates of the last drag item /// </summary> private Point lastDragPoint; /// <summary> /// User current data context /// </summary> internal SessionContext userContext; /// <summary> /// Instance of the vault panel control /// </summary> private VaultPanel vaultPanel; /// <summary> /// Instance of the second vault panel control /// This gets toggled with the player panel /// </summary> private VaultPanel secondaryVaultPanel; /// <summary> /// Instance of the stash panel control /// </summary> private StashPanel stashPanel; /// <summary> /// Holds that last stash that had focus /// </summary> private Stash lastStash; /// <summary> /// Bag number of the last bag with focus /// </summary> private int lastBag; /// <summary> /// Holds the current program version /// </summary> private string currentVersion; /// <summary> /// Signals that the configuration UI was loaded and the user changed something in there. /// </summary> private bool configChanged; /// <summary> /// Flag which holds whether we are showing the secondary vault panel or the player panel. /// </summary> private bool showSecondaryVault; /// <summary> /// Form for the splash screen. /// </summary> private SplashScreenForm splashScreen; /// <summary> /// Holds the opacity interval for fading the form. /// </summary> private double fadeInterval; #endregion #if DEBUG // For Design Mode [PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)] public MainForm() => InitForm(); #endif /// <summary> /// Initializes a new instance of the MainForm class. /// </summary> [PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)] public MainForm( IServiceProvider serviceProvider // TODO Refactor : injecting service factory is anti pattern , ILogger<MainForm> log , SessionContext sessionContext , IPlayerService playerService , IVaultService vaultService , IStashService stashService , IFontService fontService ) : base(serviceProvider) { this.userContext = sessionContext; this.playerService = playerService; this.vaultService = vaultService; this.stashService = stashService; Log = log; Log.LogInformation("TQVaultAE Initialization !"); InitForm(); #region Apply custom font & scaling this.exitButton.Font = FontService.GetFontLight(12F, UIService.Scale); ScaleControl(this.UIService, this.exitButton); this.characterComboBox.Font = FontService.GetFontLight(13F, UIService.Scale); ScaleControl(this.UIService, this.characterComboBox, false); this.characterLabel.Font = FontService.GetFontLight(11F, UIService.Scale); ScaleControl(this.UIService, this.characterLabel, false); this.itemText.Font = FontService.GetFontLight(11F, FontStyle.Bold, UIService.Scale); this.vaultListComboBox.Font = FontService.GetFontLight(13F, UIService.Scale); ScaleControl(this.UIService, this.vaultListComboBox, false); this.vaultLabel.Font = FontService.GetFontLight(11F, UIService.Scale); ScaleControl(this.UIService, this.vaultLabel, false); this.configureButton.Font = FontService.GetFontLight(12F, UIService.Scale); ScaleControl(this.UIService, this.configureButton); this.customMapText.Font = FontService.GetFont(11.25F, UIService.Scale); ScaleControl(this.UIService, this.customMapText, false); this.showVaulButton.Font = FontService.GetFontLight(12F, UIService.Scale); ScaleControl(this.UIService, this.showVaulButton); this.secondaryVaultListComboBox.Font = FontService.GetFontLight(11F, UIService.Scale); ScaleControl(this.UIService, this.secondaryVaultListComboBox, false); this.aboutButton.Font = FontService.GetFontLight(8.25F, UIService.Scale); ScaleControl(this.UIService, this.aboutButton); this.titleLabel.Font = FontService.GetFontLight(24F, UIService.Scale); ScaleControl(this.UIService, this.titleLabel); this.searchButton.Font = FontService.GetFontLight(12F, UIService.Scale); ScaleControl(this.UIService, this.searchButton); ScaleControl(this.UIService, this.tableLayoutPanelMain); #endregion if (TQDebug.DebugEnabled) { // Write this version into the debug file. Log.LogDebug( $@"Current TQVault Version: {this.currentVersion} Debug Levels {nameof(TQDebug.ArcFileDebugLevel)}: {TQDebug.ArcFileDebugLevel} {nameof(TQDebug.DatabaseDebugLevel)}: {TQDebug.DatabaseDebugLevel} {nameof(TQDebug.ItemAttributesDebugLevel)}: {TQDebug.ItemAttributesDebugLevel} {nameof(TQDebug.ItemDebugLevel)}: {TQDebug.ItemDebugLevel} "); } // Process the mouse scroll wheel to cycle through the vaults. this.MouseWheel += new MouseEventHandler(this.MainFormMouseWheel); } private void InitForm() { this.Enabled = false; this.ShowInTaskbar = false; this.Opacity = 0; this.Hide(); this.InitializeComponent(); this.SetupFormSize(); // Changed to a global for versions in tqdebug AssemblyName aname = Assembly.GetExecutingAssembly().GetName(); this.currentVersion = aname.Version.ToString(); this.Text = string.Format(CultureInfo.CurrentCulture, "{0} {1}", aname.Name, this.currentVersion); // Setup localized strings. this.characterLabel.Text = Resources.MainFormLabel1; this.vaultLabel.Text = Resources.MainFormLabel2; this.configureButton.Text = Resources.MainFormBtnConfigure; this.exitButton.Text = Resources.GlobalExit; this.showVaulButton.Text = Resources.MainFormBtnPanelSelect; this.Icon = Resources.TQVIcon; this.searchButton.Text = Resources.MainFormSearchButtonText; this.lastDragPoint.X = -1; this.DragInfo = new ItemDragInfo(this.UIService); #if DEBUG this.DebugLayoutBorderVisible = false;// Set here what you want during debug #endif if (!this.DebugLayoutBorderVisible) { this.flowLayoutPanelRightComboBox.BorderStyle = BorderStyle.None; this.flowLayoutPanelVaultSelector.BorderStyle = BorderStyle.None; this.flowLayoutPanelRightPanels.BorderStyle = BorderStyle.None; this.tableLayoutPanelMain.CellBorderStyle = TableLayoutPanelCellBorderStyle.None; } this.CreatePanels(); } #region Mainform Events /// <summary> /// Handler for the ResizeEnd event. Used to scale the internal controls after the window has been resized. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> protected override void ResizeEndCallback(object sender, EventArgs e) // That override Look dumb but needed by Visual Studio WInform Designer => base.ResizeEndCallback(sender, e); /// <summary> /// Handler for the Resize event. Used for handling the maximize and minimize functions. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> protected override void ResizeBeginCallback(object sender, EventArgs e) // That override Look dumb but needed by Visual Studio WInform Designer => base.ResizeBeginCallback(sender, e); /// <summary> /// Handler for closing the main form /// </summary> /// <param name="sender">sender object</param> /// <param name="e">CancelEventArgs data</param> private void MainFormClosing(object sender, CancelEventArgs e) => e.Cancel = !this.DoCloseStuff(); /// <summary> /// Shows things that you may want to know before a close. /// Like holding an item /// </summary> /// <returns>TRUE if none of the conditions exist or the user selected to ignore the message</returns> private bool DoCloseStuff() { bool ok = false; try { // Make sure we are not dragging anything if (this.DragInfo.IsActive) { MessageBox.Show(Resources.MainFormHoldingItem, Resources.MainFormHoldingItem2, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, RightToLeftOptions); return false; } this.SaveAllModifiedFiles(); // Added by VillageIdiot this.SaveConfiguration(); ok = true; } catch (IOException exception) { Log.LogError(exception, "Save files failed !"); MessageBox.Show(Log.FormatException(exception), Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, RightToLeftOptions); } return ok; } /// <summary> /// Handler for loading the main form /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void MainFormLoad(object sender, EventArgs e) { this.splashScreen = this.ServiceProvider.GetService<SplashScreenForm>(); this.splashScreen.MaximumValue = 1; this.splashScreen.FormClosed += new FormClosedEventHandler(this.SplashScreenClosed); if (Config.Settings.Default.LoadAllFiles) this.splashScreen.MaximumValue += LoadAllFilesTotal(); this.splashScreen.Show(); this.splashScreen.Update(); this.splashScreen.BringToFront(); this.backgroundWorkerLoadAllFiles.RunWorkerAsync(); } /// <summary> /// Handler for key presses on the main form /// </summary> /// <param name="sender">sender object</param> /// <param name="e">KeyPressEventArgs data</param> private void MainFormKeyPress(object sender, KeyPressEventArgs e) { // Don't handle this here since we handle key presses within each component. ////if (e.KeyChar != (char)27) ////e.Handled = true; } /// <summary> /// Handler for showing the main form. /// Used to switch focus to the search text box. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void MainFormShown(object sender, EventArgs e) => this.vaultPanel.SackPanel.Focus(); /// <summary> /// Handler for moving the mouse wheel. /// Used to scroll through the vault list. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">MouseEventArgs data</param> private void MainFormMouseWheel(object sender, MouseEventArgs e) { // Force a single line regardless of the delta value. int numberOfTextLinesToMove = ((e.Delta > 0) ? 1 : 0) - ((e.Delta < 0) ? 1 : 0); if (numberOfTextLinesToMove != 0) { int vaultSelection = this.vaultListComboBox.SelectedIndex; vaultSelection -= numberOfTextLinesToMove; if (vaultSelection < 1) vaultSelection = 1; if (vaultSelection >= this.vaultListComboBox.Items.Count) vaultSelection = this.vaultListComboBox.Items.Count - 1; this.vaultListComboBox.SelectedIndex = vaultSelection; } } /// <summary> /// Key Handler for the main form. Most keystrokes should be handled by the individual panels or the search text box. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">KeyEventArgs data</param> private void MainFormKeyDown(object sender, KeyEventArgs e) { if (e.KeyData == (Keys.Control | Keys.F)) this.ActivateSearchCallback(this, new SackPanelEventArgs(null, null)); if (e.KeyData == (Keys.Control | Keys.Add) || e.KeyData == (Keys.Control | Keys.Oemplus)) this.ResizeFormCallback(this, new ResizeEventArgs(0.1F)); if (e.KeyData == (Keys.Control | Keys.Subtract) || e.KeyData == (Keys.Control | Keys.OemMinus)) this.ResizeFormCallback(this, new ResizeEventArgs(-0.1F)); if (e.KeyData == (Keys.Control | Keys.Home)) this.ResizeFormCallback(this, new ResizeEventArgs(1.0F)); } /// <summary> /// Handles Timer ticks for fading in the main form. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void FadeInTimerTick(object sender, EventArgs e) { if (this.Opacity < 1) this.Opacity = Math.Min(1.0F, this.Opacity + this.fadeInterval); else this.fadeInTimer.Stop(); } /// <summary> /// Handler for the exit button. /// Closes the main form /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void ExitButtonClick(object sender, EventArgs e) => this.Close(); #endregion #region About /// <summary> /// Handler for clicking the about button. /// Shows the about dialog box. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void AboutButtonClick(object sender, EventArgs e) { AboutBox dlg = this.ServiceProvider.GetService<AboutBox>(); dlg.Scale(new SizeF(UIService.Scale, UIService.Scale)); dlg.ShowDialog(); } #endregion #region Scaling /// <summary> /// Scales the main form according to the scale factor. /// </summary> /// <param name="scaleFactor">Float which signifies the scale factor of the form. This is an absolute from the original size unless useRelativeScaling is set to true.</param> /// <param name="useRelativeScaling">Indicates whether the scale factor is relative. Used to support a resize operation.</param> protected override void ScaleForm(float scaleFactor, bool useRelativeScaling) { base.ScaleForm(scaleFactor, useRelativeScaling); this.itemText.Text = string.Empty; this.Invalidate(); } /// <summary> /// Sets the size of the main form along with scaling the internal controls for startup. /// </summary> private void SetupFormSize() { this.DrawCustomBorder = true; this.ResizeCustomAllowed = true; this.fadeInterval = Config.Settings.Default.FadeInInterval; Rectangle workingArea = Screen.FromControl(this).WorkingArea; this.ScaleOnResize = false; this.ClientSize = InitialScaling(workingArea); this.ScaleOnResize = true; UIService.Scale = Config.Settings.Default.Scale; this.Log.LogDebug("Config.Settings.Default.Scale changed to {0} !", UIService.Scale); // Save the height / width ratio for resizing. this.FormDesignRatio = (float)this.Height / (float)this.Width; this.FormMaximumSize = new Size(this.Width * 2, this.Height * 2); this.FormMinimumSize = new Size( Convert.ToInt32((float)this.Width * 0.4F), Convert.ToInt32((float)this.Height * 0.4F)); this.OriginalFormSize = this.Size; this.OriginalFormScale = Config.Settings.Default.Scale; if (CurrentAutoScaleDimensions.Width != UIService.DESIGNDPI) { // We do not need to scale the main form controls since autoscaling will handle it. // Scale internally to 96 dpi for the drawing functions. UIService.Scale = this.CurrentAutoScaleDimensions.Width / UIService.DESIGNDPI; this.OriginalFormScale = UIService.Scale; } this.LastFormSize = this.Size; // Set the maximized size but keep the aspect ratio. if (Convert.ToInt32((float)workingArea.Width * this.FormDesignRatio) < workingArea.Height) { this.MaximizedBounds = new Rectangle(0 , (workingArea.Height - Convert.ToInt32((float)workingArea.Width * this.FormDesignRatio)) / 2 , workingArea.Width , Convert.ToInt32((float)workingArea.Width * this.FormDesignRatio) ); } else { this.MaximizedBounds = new Rectangle( (workingArea.Width - Convert.ToInt32((float)workingArea.Height / this.FormDesignRatio)) / 2, 0, Convert.ToInt32((float)workingArea.Height / this.FormDesignRatio), workingArea.Height); } this.Location = new Point(workingArea.Left + Convert.ToInt16((workingArea.Width - this.ClientSize.Width) / 2), workingArea.Top + Convert.ToInt16((workingArea.Height - this.ClientSize.Height) / 2)); } #endregion #region Files /// <summary> /// Counts the number of files which LoadAllFiles will load. Used to set the max value of the progress bar. /// </summary> /// <returns>Total number of files that LoadAllFiles() will load.</returns> private int LoadAllFilesTotal() { int numIT = GamePathResolver.GetCharacterList()?.Count() ?? 0; numIT = numIT * 2;// Assuming that there is 1 stash file per character int numVaults = GamePathResolver.GetVaultList()?.Count() ?? 0; return Math.Max(0, numIT + numVaults - 1); } /// <summary> /// Loads all of the players, stashes, and vaults. /// Shows a progress dialog. /// Used for the searching function. /// </summary> private void LoadAllFiles() { // Check to see if we failed the last time we tried loading all of the files. // If we did fail then turn it off and skip it. if (!Config.Settings.Default.LoadAllFilesCompleted) { if (MessageBox.Show( Resources.MainFormDisableLoadAllFiles, Resources.MainFormDisableLoadAllFilesCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, RightToLeftOptions) == DialogResult.Yes) { Config.Settings.Default.LoadAllFilesCompleted = true; Config.Settings.Default.LoadAllFiles = false; Config.Settings.Default.Save(); return; } } string[] vaults = GamePathResolver.GetVaultList(); var charactersIT = this.characterComboBox.Items.OfType<PlayerSave>().ToArray(); int numIT = charactersIT?.Length ?? 0; int numVaults = vaults?.Length ?? 0; // Since this takes a while, show a progress dialog box. int total = numIT + numVaults - 1; if (total > 0) { // We were successful last time so we reset the flag for this attempt. Config.Settings.Default.LoadAllFilesCompleted = false; Config.Settings.Default.Save(); } else return; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // Load all of the Immortal Throne player files and stashes. var bagPlayer = new ConcurrentBag<LoadPlayerResult>(); var bagPlayerStashes = new ConcurrentBag<LoadPlayerStashResult>(); var bagVault = new ConcurrentBag<LoadVaultResult>(); var lambdacharactersIT = charactersIT.Select(c => (Action)(() => { // Get the player var result = this.playerService.LoadPlayer(c, true); bagPlayer.Add(result); this.backgroundWorkerLoadAllFiles.ReportProgress(1); })).ToArray(); var lambdacharacterStashes = charactersIT.Select(c => (Action)(() => { // Get the player's stash var result = this.stashService.LoadPlayerStash(c); bagPlayerStashes.Add(result); this.backgroundWorkerLoadAllFiles.ReportProgress(1); })).ToArray(); var lambdaVault = vaults.Select(c => (Action)(() => { // Load all of the vaults. var result = this.vaultService.LoadVault(c); bagVault.Add(result); this.backgroundWorkerLoadAllFiles.ReportProgress(1); })).ToArray(); Parallel.Invoke(lambdacharactersIT.Concat(lambdacharacterStashes).Concat(lambdaVault).ToArray());// Parallel loading // Dispay errors bagPlayer.Where(p => p.Player.ArgumentException != null).ToList() .ForEach(result => { if (result.Player.ArgumentException != null) { string msg = string.Format(CultureInfo.CurrentUICulture, "{0}\n{1}\n{2}", Resources.MainFormPlayerReadError, result.PlayerFile, result.Player.ArgumentException.Message); MessageBox.Show(msg, Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, RightToLeftOptions); } }); bagPlayerStashes.Where(p => p.Stash.ArgumentException != null).ToList() .ForEach(result => { if (result.Stash.ArgumentException != null) { string msg = string.Format(CultureInfo.CurrentUICulture, "{0}\n{1}\n{2}", Resources.MainFormPlayerReadError, result.StashFile, result.Stash.ArgumentException.Message); MessageBox.Show(msg, Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, RightToLeftOptions); } }); bagVault.Where(p => p.ArgumentException != null).ToList() .ForEach(result => { if (result.ArgumentException != null) { string msg = string.Format(CultureInfo.CurrentUICulture, "{0}\n{1}\n{2}", Resources.MainFormPlayerReadError, result.Filename, result.ArgumentException.Message); MessageBox.Show(msg, Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, RightToLeftOptions); } }); stopWatch.Stop(); // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; // Format and display the TimeSpan value. Log.LogInformation("LoadTime {0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); // We made it so set the flag to indicate we were successful. Config.Settings.Default.LoadAllFilesCompleted = true; Config.Settings.Default.Save(); } /// <summary> /// Attempts to save all modified files. /// </summary> /// <returns>true if players have been modified</returns> private bool SaveAllModifiedFiles() { bool playersModified = this.SaveAllModifiedPlayers(); this.SaveAllModifiedVaults(); this.SaveAllModifiedStashes(); return playersModified; } #endregion #region SplashScreen & Tooltip /// <summary> /// Handler for closing the splash screen /// </summary> /// <param name="sender">sender object</param> /// <param name="e">FormClosedEventArgs data</param> private void SplashScreenClosed(object sender, FormClosedEventArgs e) { if (this.resourcesLoaded) { if (!this.loadingComplete) this.backgroundWorkerLoadAllFiles.CancelAsync(); this.ShowMainForm(); } else Application.Exit(); } /// <summary> /// Starts the fade in of the main form. /// </summary> private void ShowMainForm() { this.fadeInTimer.Start(); this.ShowInTaskbar = true; this.Enabled = true; this.Show(); this.Activate(); } /// <summary> /// Tooltip callback /// </summary> /// <param name="windowHandle">handle of the main window form</param> /// <returns>tooltip string</returns> private void ToolTipCallback(int windowHandle) { this.vaultPanel.ToolTipCallback(windowHandle); this.playerPanel.ToolTipCallback(windowHandle); this.stashPanel.ToolTipCallback(windowHandle); this.secondaryVaultPanel.ToolTipCallback(windowHandle); // Changed by VillageIdiot // If we are dragging something around, clear the tooltip and text box. if (this.DragInfo.IsActive) this.itemText.Text = string.Empty; } #endregion #region Game Resources /// <summary> /// Loads the resources. /// </summary> /// <param name="worker">Background worker</param> /// <param name="e">DoWorkEventArgs data</param> /// <returns>true when resource loading has completed successfully</returns> private bool LoadResources(BackgroundWorker worker, DoWorkEventArgs e) { // Abort the operation if the user has canceled. // Note that a call to CancelAsync may have set // CancellationPending to true just after the // last invocation of this method exits, so this // code will not have the opportunity to set the // DoWorkEventArgs.Cancel flag to true. This means // that RunWorkerCompletedEventArgs.Cancelled will // not be set to true in your RunWorkerCompleted // event handler. This is a race condition. if (worker.CancellationPending) { e.Cancel = true; return this.resourcesLoaded; } else { if (!Config.Settings.Default.AllowCheats) { Config.Settings.Default.AllowItemCopy = false; Config.Settings.Default.AllowItemEdit = false; Config.Settings.Default.AllowCharacterEdit = false; } CommandLineArgs args = new CommandLineArgs(); // Check to see if we loaded something from the command line. if (args.HasMapName) GamePathResolver.MapName = args.MapName; this.resourcesLoaded = true; this.backgroundWorkerLoadAllFiles.ReportProgress(1); if (Config.Settings.Default.LoadAllFiles) this.LoadAllFiles(); // Notify the form that the resources are loaded. return true; } } /// <summary> /// Background worker call to load the resources. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">DoWorkEventArgs data</param> private void BackgroundWorkerLoadAllFiles_DoWork(object sender, DoWorkEventArgs e) { // Get the BackgroundWorker that raised this event. BackgroundWorker worker = sender as BackgroundWorker; // Assign the result of the resource loader // to the Result property of the DoWorkEventArgs // object. This is will be available to the // RunWorkerCompleted eventhandler. e.Result = this.LoadResources(worker, e); } /// <summary> /// Background worker has finished /// </summary> /// <param name="sender">sender object</param> /// <param name="e">RunWorkerCompletedEventArgs data</param> private void BackgroundWorkerLoadAllFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // First, handle the case where an exception was thrown. if (e.Error != null) { Log.LogError(e.Error, $"resourcesLoaded = {this.resourcesLoaded}"); if (MessageBox.Show( string.Concat(e.Error.Message, Resources.Form1BadLanguage) , Resources.Form1ErrorLoadingResources , MessageBoxButtons.YesNo , MessageBoxIcon.Exclamation , MessageBoxDefaultButton.Button1 , RightToLeftOptions) == DialogResult.Yes ) Application.Restart(); else Application.Exit(); } else if (e.Cancelled && !this.resourcesLoaded) Application.Exit(); else if (e.Result.Equals(true)) { this.loadingComplete = true; this.Enabled = true; this.LoadTransferStash(); this.LoadRelicVaultStash(); if (Config.Settings.Default.EnableHotReload) { var relicPath = GamePathResolver.RelicVaultStashFileFullPath; var transferPath = GamePathResolver.TransferStashFileFullPath; this.fileSystemWatcherRelicStash.EnableRaisingEvents = false; this.fileSystemWatcherRelicStash.Path = Path.GetDirectoryName(relicPath); this.fileSystemWatcherRelicStash.Filter = Path.GetFileName(relicPath); this.fileSystemWatcherRelicStash.EnableRaisingEvents = true; this.fileSystemWatcherTransferStash.EnableRaisingEvents = false; this.fileSystemWatcherTransferStash.Path = Path.GetDirectoryName(transferPath); this.fileSystemWatcherTransferStash.Filter = Path.GetFileName(transferPath); this.fileSystemWatcherTransferStash.EnableRaisingEvents = true; } // Load last character here if selected if (Config.Settings.Default.LoadLastCharacter) { var lastPlayerSave = this.characterComboBox.Items.OfType<PlayerSave>() .FirstOrDefault(ps => ps.Name == Config.Settings.Default.LastCharacterName); if (lastPlayerSave != null) this.characterComboBox.SelectedItem = lastPlayerSave; } string currentVault = VaultService.MAINVAULT; // See if we should load the last loaded vault if (Config.Settings.Default.LoadLastVault) { currentVault = Config.Settings.Default.LastVaultName; // Make sure there is something in the config file to load else load the Main Vault // We do not want to create new here. if (string.IsNullOrEmpty(currentVault) || !File.Exists(GamePathResolver.GetVaultFile(currentVault))) currentVault = VaultService.MAINVAULT; } this.vaultListComboBox.SelectedItem = currentVault; // Finally load Vault this.LoadVault(currentVault, false); this.splashScreen.UpdateText(); this.splashScreen.ShowMainForm = true; CommandLineArgs args = new CommandLineArgs(); // Allows skipping of title screen with setting if (args.IsAutomatic || Config.Settings.Default.SkipTitle == true) { string player = args.Player; int index = this.characterComboBox.FindStringExact(player); if (index != -1) this.characterComboBox.SelectedIndex = index; this.splashScreen.CloseForm(); } } else { Log.LogError(e.Error, $"resourcesLoaded = {this.resourcesLoaded}"); // If for some reason the loading failed, but there was no error raised. MessageBox.Show( Resources.Form1ErrorLoadingResources, Resources.Form1ErrorLoadingResources, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, RightToLeftOptions); Application.Exit(); } } /// <summary> /// Handler for updating the splash screen progress bar. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">ProgressChangedEventArgs data</param> private void BackgroundWorkerLoadAllFiles_ProgressChanged(object sender, ProgressChangedEventArgs e) => this.splashScreen.IncrementValue(); #endregion #region Settings Dialog /// <summary> /// Updates configuration settings /// </summary> private void SaveConfiguration() { // Update last loaded vault if (Config.Settings.Default.LoadLastVault) { // Changed by VillageIdiot // Now check to see if the value is changed since the Main Vault would never auto load if (this.vaultListComboBox.SelectedItem != null && this.vaultListComboBox.SelectedItem.ToString().ToUpperInvariant() != Config.Settings.Default.LastVaultName.ToUpperInvariant()) { Config.Settings.Default.LastVaultName = this.vaultListComboBox.SelectedItem.ToString(); this.configChanged = true; } } // Update last loaded character if (Config.Settings.Default.LoadLastCharacter) { string name = this.characterComboBox.SelectedItem.ToString(); var ps = this.characterComboBox.SelectedItem as PlayerSave; if (ps is not null) name = ps.Name; if (name.ToUpperInvariant() != Config.Settings.Default.LastCharacterName.ToUpperInvariant()) { // Clear the value if no character is selected if (name == Resources.MainFormSelectCharacter) name = string.Empty; Config.Settings.Default.LastCharacterName = name; this.configChanged = true; } } // Update custom map settings if (Config.Settings.Default.ModEnabled) this.configChanged = true; // Clear out the key if we are autodetecting. if (Config.Settings.Default.AutoDetectLanguage) Config.Settings.Default.TQLanguage = string.Empty; // Clear out the settings if auto detecting. if (Config.Settings.Default.AutoDetectGamePath) { Config.Settings.Default.TQITPath = string.Empty; Config.Settings.Default.TQPath = string.Empty; } if (UIService.Scale != 1.0F) { Config.Settings.Default.Scale = UIService.Scale; this.configChanged = true; } if (this.configChanged) Config.Settings.Default.Save(); } /// <summary> /// Handler for clicking the configure button. /// Shows the Settings Dialog. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void ConfigureButtonClick(object sender, EventArgs e) { SettingsDialog settingsDialog = this.ServiceProvider.GetService<SettingsDialog>(); DialogResult result = DialogResult.Cancel; settingsDialog.Scale(new SizeF(UIService.Scale, UIService.Scale)); string title = string.Empty; string message = string.Empty; if (settingsDialog.ShowDialog() == DialogResult.OK && settingsDialog.ConfigurationChanged) { if (settingsDialog.PlayerFilterChanged) { this.characterComboBox.SelectedItem = Resources.MainFormSelectCharacter; if (this.playerPanel.Player != null) this.playerPanel.Player = null; this.GetPlayerList(); } if (settingsDialog.VaultPathChanged) { GamePathResolver.TQVaultSaveFolder = settingsDialog.VaultPath; this.vaultService.UpdateVaultPath(settingsDialog.VaultPath); this.GetVaultList(true); } if (settingsDialog.LanguageChanged || settingsDialog.GamePathChanged || settingsDialog.CustomMapsChanged || settingsDialog.UISettingChanged) { if ((settingsDialog.GamePathChanged && settingsDialog.LanguageChanged) || settingsDialog.UISettingChanged) { title = Resources.MainFormSettingsChanged; message = Resources.MainFormSettingsChangedMsg; } else if (settingsDialog.GamePathChanged) { title = Resources.MainFormPathsChanged; message = Resources.MainFormPathsChangedMsg; } else if (settingsDialog.CustomMapsChanged) { title = Resources.MainFormMapsChanged; message = Resources.MainFormMapsChangedMsg; } else { title = Resources.MainFormLanguageChanged; message = Resources.MainFormLanguageChangedMsg; } result = MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, RightToLeftOptions); } if (settingsDialog.ItemBGColorOpacityChanged || settingsDialog.EnableItemRequirementRestrictionChanged) this.Refresh(); if (settingsDialog.EnableCharacterEditChanged) stashPanel?.UpdatePlayerInfo(); this.configChanged = true; this.SaveConfiguration(); if (result == DialogResult.Yes) { if (this.DoCloseStuff()) Application.Restart(); } } } #endregion } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace UdcxRemediation.Console { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.TemplateEngine.Edge.Template; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Cli.CommandParsing; using Microsoft.TemplateEngine.Utils; namespace Microsoft.TemplateEngine.Cli.HelpAndUsage { internal static class HelpForTemplateResolution { public static CreationResultStatus CoordinateHelpAndUsageDisplay(TemplateListResolutionResult templateResolutionResult, IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, IHostSpecificDataLoader hostDataLoader, ITelemetryLogger telemetryLogger, TemplateCreator templateCreator, string defaultLanguage) { ShowUsageHelp(commandInput, telemetryLogger); // this is just checking if there is an unambiguous group. // the called methods decide whether to get the default language filtered lists, based on what they're doing. // // The empty TemplateName check is for when only 1 template (or group) is installed. // When that occurs, the group is considered partial matches. But the output should be the ambiguous case - list the templates, not help on the singular group. if (!string.IsNullOrEmpty(commandInput.TemplateName) && templateResolutionResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousTemplateGroup) && TemplateListResolver.AreAllTemplatesSameLanguage(unambiguousTemplateGroup)) { // This will often show detailed help on the template group, which only makes sense if they're all the same language. return DisplayHelpForUnambiguousTemplateGroup(templateResolutionResult, environmentSettings, commandInput, hostDataLoader, templateCreator, defaultLanguage); } else { return DisplayHelpForAmbiguousTemplateGroup(templateResolutionResult, environmentSettings, commandInput, hostDataLoader, telemetryLogger, defaultLanguage); } } private static CreationResultStatus DisplayHelpForUnambiguousTemplateGroup(TemplateListResolutionResult templateResolutionResult, IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, IHostSpecificDataLoader hostDataLoader, TemplateCreator templateCreator, string defaultLanguage) { // filter on the default language if needed, the details display should be for a single language group if (!templateResolutionResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousTemplateGroupForDetailDisplay)) { // this is really an error unambiguousTemplateGroupForDetailDisplay = new List<ITemplateMatchInfo>(); } if (commandInput.IsListFlagSpecified) { // because the list flag is present, don't display help for the template group, even though an unambiguous group was resolved. if (!AreAllParamsValidForAnyTemplateInList(unambiguousTemplateGroupForDetailDisplay) && TemplateListResolver.FindHighestPrecedenceTemplateIfAllSameGroupIdentity(unambiguousTemplateGroupForDetailDisplay) != null) { DisplayHelpForAcceptedParameters(commandInput.CommandName); return CreationResultStatus.InvalidParamValues; } // get the group without filtering on default language if (!templateResolutionResult.TryGetUnambiguousTemplateGroupToUse(out IReadOnlyList<ITemplateMatchInfo> unambiguousTemplateGroupForList, true)) { // this is really an error unambiguousTemplateGroupForList = new List<ITemplateMatchInfo>(); } DisplayTemplateList(unambiguousTemplateGroupForList, environmentSettings, commandInput.Language, defaultLanguage); // list flag specified, so no usage examples or detailed help return CreationResultStatus.Success; } else { // not in list context, but Unambiguous // this covers whether or not --help was input, they do the same thing in the unambiguous case return TemplateDetailedHelpForSingularTemplateGroup(unambiguousTemplateGroupForDetailDisplay, environmentSettings, commandInput, hostDataLoader, templateCreator); } } private static CreationResultStatus TemplateDetailedHelpForSingularTemplateGroup(IReadOnlyList<ITemplateMatchInfo> unambiguousTemplateGroup, IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, IHostSpecificDataLoader hostDataLoader, TemplateCreator templateCreator) { // (scp 2017-09-06): parse errors probably can't happen in this context. foreach (string parseErrorMessage in unambiguousTemplateGroup.Where(x => x.HasParseError()).Select(x => x.GetParseError()).ToList()) { Reporter.Error.WriteLine(parseErrorMessage.Bold().Red()); } GetParametersInvalidForTemplatesInList(unambiguousTemplateGroup, out IReadOnlyList<string> invalidForAllTemplates, out IReadOnlyList<string> invalidForSomeTemplates); if (invalidForAllTemplates.Count > 0 || invalidForSomeTemplates.Count > 0) { DisplayInvalidParameters(invalidForAllTemplates); DisplayParametersInvalidForSomeTemplates(invalidForSomeTemplates, LocalizableStrings.SingleTemplateGroupPartialMatchSwitchesNotValidForAllMatches); } bool showImplicitlyHiddenParams = unambiguousTemplateGroup.Count > 1; TemplateDetailsDisplay.ShowTemplateGroupHelp(unambiguousTemplateGroup, environmentSettings, commandInput, hostDataLoader, templateCreator, showImplicitlyHiddenParams); return invalidForAllTemplates.Count > 0 || invalidForSomeTemplates.Count > 0 ? CreationResultStatus.InvalidParamValues : CreationResultStatus.Success; } private static CreationResultStatus DisplayHelpForAmbiguousTemplateGroup(TemplateListResolutionResult templateResolutionResult, IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, IHostSpecificDataLoader hostDataLoader, ITelemetryLogger telemetryLogger, string defaultLanguage) { if (!string.IsNullOrEmpty(commandInput.TemplateName) && templateResolutionResult.GetBestTemplateMatchList(true).Count > 0 && templateResolutionResult.GetBestTemplateMatchList(true).All(x => x.MatchDisposition.Any(d => d.Location == MatchLocation.Language && d.Kind == MatchKind.Mismatch))) { string errorMessage = GetLanguageMismatchErrorMessage(commandInput); Reporter.Error.WriteLine(errorMessage.Bold().Red()); Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, $"{commandInput.CommandName} {commandInput.TemplateName}").Bold().Red()); return CreationResultStatus.NotFound; } // The following occurs when: // --alias <value> is specifed // --help is specified // template (group) can't be resolved if (!string.IsNullOrWhiteSpace(commandInput.Alias)) { Reporter.Error.WriteLine(LocalizableStrings.InvalidInputSwitch.Bold().Red()); Reporter.Error.WriteLine(" " + commandInput.TemplateParamInputFormat("--alias").Bold().Red()); return CreationResultStatus.NotFound; } bool hasInvalidParameters = false; IReadOnlyList<ITemplateMatchInfo> templatesForDisplay = templateResolutionResult.GetBestTemplateMatchList(true); GetParametersInvalidForTemplatesInList(templatesForDisplay, out IReadOnlyList<string> invalidForAllTemplates, out IReadOnlyList<string> invalidForSomeTemplates); if (invalidForAllTemplates.Any() || invalidForSomeTemplates.Any()) { hasInvalidParameters = true; DisplayInvalidParameters(invalidForAllTemplates); DisplayParametersInvalidForSomeTemplates(invalidForSomeTemplates, LocalizableStrings.PartialTemplateMatchSwitchesNotValidForAllMatches); } ShowContextAndTemplateNameMismatchHelp(templateResolutionResult, commandInput.TemplateName, commandInput.TypeFilter); DisplayTemplateList(templatesForDisplay, environmentSettings, commandInput.Language, defaultLanguage); if (!commandInput.IsListFlagSpecified) { TemplateUsageHelp.ShowInvocationExamples(templateResolutionResult, hostDataLoader, commandInput.CommandName); } if (hasInvalidParameters) { return CreationResultStatus.NotFound; } else if (commandInput.IsListFlagSpecified || commandInput.IsHelpFlagSpecified) { return !templateResolutionResult.IsNoTemplatesMatchedState ? CreationResultStatus.Success : CreationResultStatus.NotFound; } else { return CreationResultStatus.OperationNotSpecified; } } // Returns true if any of the input templates has a valid parameter parse result. private static bool AreAllParamsValidForAnyTemplateInList(IReadOnlyList<ITemplateMatchInfo> templateList) { bool anyValidTemplate = false; foreach (ITemplateMatchInfo templateInfo in templateList) { if (templateInfo.GetInvalidParameterNames().Count == 0) { anyValidTemplate = true; break; } } return anyValidTemplate; } private static void DisplayHelpForAcceptedParameters(string commandName) { Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, commandName).Bold().Red()); } // Displays the list of templates in a table, one row per template group. // // The columns displayed are as follows: // Except where noted, the values are taken from the highest-precedence template in the group. The info could vary among the templates in the group, but shouldn't. // (There is no check that the info doesn't vary.) // - Template Name // - Short Name: displays the first short name from the highest precedence template in the group. // - Language: All languages supported by any template in the group are displayed, with the default language in brackets, e.g.: [C#] // - Tags private static void DisplayTemplateList(IReadOnlyList<ITemplateMatchInfo> templates, IEngineEnvironmentSettings environmentSettings, string language, string defaultLanguage) { IReadOnlyList<TemplateGroupForListDisplay> groupsForDisplay = GetTemplateGroupsForListDisplay(templates, language, defaultLanguage); HelpFormatter<TemplateGroupForListDisplay> formatter = HelpFormatter.For(environmentSettings, groupsForDisplay, 6, '-', false) .DefineColumn(t => t.Name, LocalizableStrings.Templates) .DefineColumn(t => t.ShortName, LocalizableStrings.ShortName) .DefineColumn(t => t.Languages, out object languageColumn, LocalizableStrings.Language) .DefineColumn(t => t.Classifications, out object tagsColumn, LocalizableStrings.Tags) .OrderByDescending(languageColumn, new NullOrEmptyIsLastStringComparer()) .OrderBy(tagsColumn); Reporter.Output.WriteLine(formatter.Layout()); } private class TemplateGroupForListDisplay { public string Name { get; set; } public string ShortName { get; set; } public string Languages { get; set; } public string Classifications { get; set; } } private static IReadOnlyList<TemplateGroupForListDisplay> GetTemplateGroupsForListDisplay(IReadOnlyList<ITemplateMatchInfo> templateList, string language, string defaultLanguage) { IEnumerable<IGrouping<string, ITemplateMatchInfo>> grouped = templateList.GroupBy(x => x.Info.GroupIdentity, x => !string.IsNullOrEmpty(x.Info.GroupIdentity)); List<TemplateGroupForListDisplay> templateGroupsForDisplay = new List<TemplateGroupForListDisplay>(); foreach (IGrouping<string, ITemplateMatchInfo> grouping in grouped) { List<string> languageForDisplay = new List<string>(); HashSet<string> uniqueLanguages = new HashSet<string>(StringComparer.OrdinalIgnoreCase); string defaultLanguageDisplay = string.Empty; foreach (ITemplateMatchInfo template in grouping) { if (template.Info.Tags != null && template.Info.Tags.TryGetValue("language", out ICacheTag languageTag)) { foreach (string lang in languageTag.ChoicesAndDescriptions.Keys) { if (uniqueLanguages.Add(lang)) { if (string.IsNullOrEmpty(language) && string.Equals(defaultLanguage, lang, StringComparison.OrdinalIgnoreCase)) { defaultLanguageDisplay = $"[{lang}]"; } else { languageForDisplay.Add(lang); } } } } } languageForDisplay.Sort(StringComparer.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(defaultLanguageDisplay)) { languageForDisplay.Insert(0, defaultLanguageDisplay); } ITemplateMatchInfo highestPrecedenceTemplate = grouping.OrderByDescending(x => x.Info.Precedence).First(); string shortName; if (highestPrecedenceTemplate.Info is IShortNameList highestWithShortNameList) { shortName = highestWithShortNameList.ShortNameList[0]; } else { shortName = highestPrecedenceTemplate.Info.ShortName; } TemplateGroupForListDisplay groupDisplayInfo = new TemplateGroupForListDisplay() { Name = highestPrecedenceTemplate.Info.Name, ShortName = shortName, Languages = string.Join(", ", languageForDisplay), Classifications = highestPrecedenceTemplate.Info.Classifications != null ? string.Join("/", highestPrecedenceTemplate.Info.Classifications) : null }; templateGroupsForDisplay.Add(groupDisplayInfo); } return templateGroupsForDisplay; } public static void DisplayInvalidParameters(IReadOnlyList<string> invalidParams) { if (invalidParams.Count > 0) { Reporter.Error.WriteLine(LocalizableStrings.InvalidInputSwitch.Bold().Red()); foreach (string flag in invalidParams) { Reporter.Error.WriteLine($" {flag}".Bold().Red()); } } } private static void DisplayParametersInvalidForSomeTemplates(IReadOnlyList<string> invalidParams, string messageHeader) { if (invalidParams.Count > 0) { Reporter.Error.WriteLine(messageHeader.Bold().Red()); foreach (string flag in invalidParams) { Reporter.Error.WriteLine($" {flag}".Bold().Red()); } } } private static void ShowContextAndTemplateNameMismatchHelp(TemplateListResolutionResult templateResolutionResult, string templateName, string context) { if (string.IsNullOrEmpty(templateName)) { return; } DisplayPartialNameMatchAndContextProblems(templateName, context, templateResolutionResult); } private static void DisplayPartialNameMatchAndContextProblems(string templateName, string context, TemplateListResolutionResult templateResolutionResult) { if (templateResolutionResult.IsTemplateAmbiguous) { // Unable to determine the desired template from the input template name: {0}.. Reporter.Error.WriteLine(string.Format(LocalizableStrings.AmbiguousInputTemplateName, templateName).Bold().Red()); } else if (templateResolutionResult.IsNoTemplatesMatchedState) { // No templates matched the input template name: {0} Reporter.Error.WriteLine(string.Format(LocalizableStrings.NoTemplatesMatchName, templateName).Bold().Red()); Reporter.Error.WriteLine(); return; } bool anythingReported = false; foreach (IReadOnlyList<ITemplateMatchInfo> templateGroup in templateResolutionResult.ContextProblemMatchGroups) { // all templates in a group should have the same context & name if (templateGroup[0].Info.Tags != null && templateGroup[0].Info.Tags.TryGetValue("type", out ICacheTag typeTag)) { MatchInfo? matchInfo = WellKnownSearchFilters.ContextFilter(context)(templateGroup[0].Info); if ((matchInfo?.Kind ?? MatchKind.Mismatch) == MatchKind.Mismatch) { // {0} matches the specified name, but has been excluded by the --type parameter. Remove or change the --type parameter to use that template Reporter.Error.WriteLine(string.Format(LocalizableStrings.TemplateNotValidGivenTheSpecifiedFilter, templateGroup[0].Info.Name).Bold().Red()); anythingReported = true; } } else { // this really shouldn't ever happen. But better to have a generic error than quietly ignore the partial match. // //{0} cannot be created in the target location Reporter.Error.WriteLine(string.Format(LocalizableStrings.GenericPlaceholderTemplateContextError, templateGroup[0].Info.Name).Bold().Red()); anythingReported = true; } } if (templateResolutionResult.RemainingPartialMatchGroups.Count > 0) { // The following templates partially match the input. Be more specific with the template name and/or language Reporter.Error.WriteLine(LocalizableStrings.TemplateMultiplePartialNameMatches.Bold().Red()); anythingReported = true; } if (anythingReported) { Reporter.Error.WriteLine(); } } // Returns a list of the parameter names that are invalid for every template in the input group. public static void GetParametersInvalidForTemplatesInList(IReadOnlyList<ITemplateMatchInfo> templateList, out IReadOnlyList<string> invalidForAllTemplates, out IReadOnlyList<string> invalidForSomeTemplates) { IDictionary<string, int> invalidCounts = new Dictionary<string, int>(); foreach (ITemplateMatchInfo template in templateList) { foreach (string paramName in template.GetInvalidParameterNames()) { if (!invalidCounts.ContainsKey(paramName)) { invalidCounts[paramName] = 1; } else { invalidCounts[paramName]++; } } } IEnumerable<IGrouping<string, string>> countGroups = invalidCounts.GroupBy(x => x.Value == templateList.Count ? "all" : "some", x => x.Key); invalidForAllTemplates = countGroups.FirstOrDefault(x => string.Equals(x.Key, "all", StringComparison.Ordinal))?.ToList(); if (invalidForAllTemplates == null) { invalidForAllTemplates = new List<string>(); } invalidForSomeTemplates = countGroups.FirstOrDefault(x => string.Equals(x.Key, "some", StringComparison.Ordinal))?.ToList(); if (invalidForSomeTemplates == null) { invalidForSomeTemplates = new List<string>(); } } public static void ShowUsageHelp(INewCommandInput commandInput, ITelemetryLogger telemetryLogger) { if (commandInput.IsHelpFlagSpecified) { telemetryLogger.TrackEvent(commandInput.CommandName + "-Help"); } Reporter.Output.WriteLine(commandInput.HelpText); Reporter.Output.WriteLine(); } public static CreationResultStatus HandleParseError(INewCommandInput commandInput, ITelemetryLogger telemetryLogger) { TemplateListResolver.ValidateRemainingParameters(commandInput, out IReadOnlyList<string> invalidParams); DisplayInvalidParameters(invalidParams); // TODO: get a meaningful error message from the parser if (commandInput.IsHelpFlagSpecified) { // this code path doesn't go through the full help & usage stack, so needs it's own call to ShowUsageHelp(). ShowUsageHelp(commandInput, telemetryLogger); } else { Reporter.Error.WriteLine(string.Format(LocalizableStrings.RunHelpForInformationAboutAcceptedParameters, commandInput.CommandName).Bold().Red()); } return CreationResultStatus.InvalidParamValues; } private static string GetLanguageMismatchErrorMessage(INewCommandInput commandInput) { string inputFlagForm; if (commandInput.Tokens.Contains("-lang")) { inputFlagForm = "-lang"; } else { inputFlagForm = "--language"; } string invalidLanguageErrorText = LocalizableStrings.InvalidTemplateParameterValues; invalidLanguageErrorText += Environment.NewLine + string.Format(LocalizableStrings.InvalidParameterDetail, inputFlagForm, commandInput.Language, "language"); return invalidLanguageErrorText; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using VBSAdmin.Data; using VBSAdmin.Models; using VBSAdmin.Data.VBSAdminModels; using VBSAdmin.Models.TenantViewModels; namespace VBSAdmin.Controllers { [Authorize(Policy = "SystemAdminOnly")] public class TenantsController : BaseController { private readonly UserManager<ApplicationUser> _userManager; private readonly ApplicationDbContext _context; public TenantsController(ApplicationDbContext context, UserManager<ApplicationUser> userManager) : base(context) { _context = context; _userManager = userManager; } // GET: Tenants public async Task<IActionResult> Index() { return View(await _context.Tenants.ToListAsync()); } // GET: Tenants/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var tenant = await _context.Tenants.SingleOrDefaultAsync(m => m.Id == id); if (tenant == null) { return NotFound(); } return View(tenant); } // GET: Tenants/Create public IActionResult Create() { return View(); } // POST: Tenants/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,ChurchName,ContactEmail,ContactName,ContactPhone,Name,Password,ConfirmPassword")] CreateViewModel createModel) { if (ModelState.IsValid) { //TODO: Replace with automapper Tenant tenant = new Data.VBSAdminModels.Tenant(); tenant.ChurchName = createModel.ChurchName; tenant.ContactEmail = createModel.ContactEmail; tenant.ContactName = createModel.ContactName; tenant.ContactPhone = createModel.ContactPhone; tenant.Name = createModel.Name; //Add the new tenant to the database _context.Add(tenant); await _context.SaveChangesAsync(); var tenantId = _context.Tenants.First().Id; //Add the tenant admin user to the system var user = new ApplicationUser { UserName = createModel.ContactEmail, Email = createModel.ContactEmail }; var result = await _userManager.CreateAsync(user, createModel.Password); if (result.Succeeded) { var claimResult = await _userManager.AddClaimAsync(user, new Claim(Constants.TenantClaim, tenantId.ToString())); claimResult = await _userManager.AddClaimAsync(user, new Claim(Constants.TenantAdminClaim, "True")); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); } AddErrors(result); return RedirectToAction("Index"); } return View(createModel); } // GET: Tenants/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var tenant = await _context.Tenants.SingleOrDefaultAsync(m => m.Id == id); if (tenant == null) { return NotFound(); } return View(tenant); } // POST: Tenants/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,ChurchName,ContactEmail,ContactName,ContactPhone,Name")] Tenant tenant) { if (id != tenant.Id) { return NotFound(); } if (ModelState.IsValid) { try { var origTenant = _context.Tenants.AsNoTracking().First<Tenant>(t => t.Id == id); var currentEmail = origTenant.ContactEmail; _context.Update(tenant); await _context.SaveChangesAsync(); //Update the user username and email if the email address changed. if (currentEmail != tenant.ContactEmail) { var user = await _userManager.FindByEmailAsync(currentEmail); var changeEmailToken = await _userManager.GenerateChangeEmailTokenAsync(user, tenant.ContactEmail); var result = await _userManager.ChangeEmailAsync(user, tenant.ContactEmail, changeEmailToken); result = await _userManager.SetUserNameAsync(user, tenant.ContactEmail); } } catch (DbUpdateConcurrencyException) { if (!TenantExists(tenant.Id)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } return View(tenant); } // GET: Tenants/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var tenant = await _context.Tenants.SingleOrDefaultAsync(m => m.Id == id); if (tenant == null) { return NotFound(); } return View(tenant); } // POST: Tenants/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var tenant = await _context.Tenants.SingleOrDefaultAsync(m => m.Id == id); _context.Tenants.Remove(tenant); await _context.SaveChangesAsync(); //Need to remove all users associated with this tenant //For now we'll just delete the tenant admin user var user = await _userManager.FindByEmailAsync(tenant.ContactEmail); if(user != null) { await _userManager.DeleteAsync(user); } return RedirectToAction("Index"); } private bool TenantExists(int id) { return _context.Tenants.Any(e => e.Id == id); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } }
#region LICENSE /* Copyright 2014 - 2015 LeagueSharp Orbwalking.cs is part of EloBuddy.Common. EloBuddy.Common is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. EloBuddy.Common is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with EloBuddy.Common. If not, see <http://www.gnu.org/licenses/>. */ #endregion #region using System; using System.Collections.Generic; using System.Linq; using EloBuddy; using SharpDX; using Color = System.Drawing.Color; #endregion namespace EloBuddy.Common { using SharpDX.Direct3D9; /// <summary> /// This class offers everything related to auto-attacks and orbwalking. /// </summary> public static class Orbwalking { /// <summary> /// Delegate AfterAttackEvenH /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> public delegate void AfterAttackEvenH(AttackableUnit unit, AttackableUnit target); /// <summary> /// Delegate BeforeAttackEvenH /// </summary> /// <param name="args">The <see cref="BeforeAttackEventArgs"/> instance containing the event data.</param> public delegate void BeforeAttackEvenH(BeforeAttackEventArgs args); /// <summary> /// Delegate OnAttackEvenH /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> public delegate void OnAttackEvenH(AttackableUnit unit, AttackableUnit target); /// <summary> /// Delegate OnNonKillableMinionH /// </summary> /// <param name="minion">The minion.</param> public delegate void OnNonKillableMinionH(AttackableUnit minion); /// <summary> /// Delegate OnTargetChangeH /// </summary> /// <param name="oldTarget">The old target.</param> /// <param name="newTarget">The new target.</param> public delegate void OnTargetChangeH(AttackableUnit oldTarget, AttackableUnit newTarget); /// <summary> /// The orbwalking mode. /// </summary> public enum OrbwalkingMode { /// <summary> /// The orbalker will only last hit minions. /// </summary> LastHit, /// <summary> /// The orbwalker will alternate between last hitting and auto attacking champions. /// </summary> Mixed, /// <summary> /// The orbwalker will clear the lane of minions as fast as possible while attempting to get the last hit. /// </summary> LaneClear, /// <summary> /// The orbwalker will only attack the target. /// </summary> Combo, /// <summary> /// The orbwalker does nothing. /// </summary> None } /// <summary> /// Spells that reset the attack timer. /// </summary> private static readonly string[] AttackResets = { "dariusnoxiantacticsonh", "fioraflurry", "garenq", "hecarimrapidslash", "jaxempowertwo", "jaycehypercharge", "leonashieldofdaybreak", "luciane", "lucianq", "monkeykingdoubleattack", "mordekaisermaceofspades", "nasusq", "nautiluspiercinggaze", "netherblade", "parley", "poppydevastatingblow", "powerfist", "renektonpreexecute", "rengarq", "shyvanadoubleattack", "sivirw", "takedown", "talonnoxiandiplomacy", "trundletrollsmash", "vaynetumble", "vie", "volibearq", "xenzhaocombotarget", "yorickspectral", "reksaiq", "itemtitanichydracleave" }; /// <summary> /// Spells that are not attacks even if they have the "attack" word in their name. /// </summary> private static readonly string[] NoAttacks = { "volleyattack", "volleyattackwithsound", "jarvanivcataclysmattack", "monkeykingdoubleattack", "shyvanadoubleattack", "shyvanadoubleattackdragon", "zyragraspingplantattack", "zyragraspingplantattack2", "zyragraspingplantattackfire", "zyragraspingplantattack2fire", "viktorpowertransfer", "sivirwattackbounce", "asheqattacknoonhit", "elisespiderlingbasicattack", "heimertyellowbasicattack", "heimertyellowbasicattack2", "heimertbluebasicattack", "annietibbersbasicattack", "annietibbersbasicattack2", "yorickdecayedghoulbasicattack", "yorickravenousghoulbasicattack", "yorickspectralghoulbasicattack", "malzaharvoidlingbasicattack", "malzaharvoidlingbasicattack2", "malzaharvoidlingbasicattack3", "kindredwolfbasicattack", "kindredbasicattackoverridelightbombfinal" }; /// <summary> /// Spells that are attacks even if they dont have the "attack" word in their name. /// </summary> private static readonly string[] Attacks = { "caitlynheadshotmissile", "frostarrow", "garenslash2", "kennenmegaproc", "lucianpassiveattack", "masteryidoublestrike", "quinnwenhanced", "renektonexecute", "renektonsuperexecute", "rengarnewpassivebuffdash", "trundleq", "xenzhaothrust", "xenzhaothrust2", "xenzhaothrust3", "viktorqbuff" }; /// <summary> /// Champs whose auto attacks can't be cancelled /// </summary> private static readonly string[] NoCancelChamps = { "Kalista" }; /// <summary> /// The last auto attack tick /// </summary> public static int LastAATick; /// <summary> /// <c>true</c> if the orbwalker will attack. /// </summary> public static bool Attack = true; /// <summary> /// <c>true</c> if the orbwalker will skip the next attack. /// </summary> public static bool DisableNextAttack; /// <summary> /// <c>true</c> if the orbwalker will move. /// </summary> public static bool Move = true; /// <summary> /// The tick the most recent move command was sent. /// </summary> public static int LastMoveCommandT; /// <summary> /// The last move command position /// </summary> public static Vector3 LastMoveCommandPosition = Vector3.Zero; /// <summary> /// The last target /// </summary> private static AttackableUnit _lastTarget; /// <summary> /// The player /// </summary> private static readonly AIHeroClient player; /// <summary> /// The delay /// </summary> private static int _delay; /// <summary> /// The minimum distance /// </summary> private static float _minDistance = 400; /// <summary> /// <c>true</c> if the auto attack missile was launched from the player. /// </summary> private static bool _missileLaunched; /// <summary> /// The champion name /// </summary> private static string _championName; /// <summary> /// The random /// </summary> private static readonly Random _random = new Random(DateTime.Now.Millisecond); /// <summary> /// Initializes static members of the <see cref="Orbwalking"/> class. /// </summary> static Orbwalking() { player = ObjectManager.Player; _championName = player.ChampionName; Obj_AI_Base.OnProcessSpellCast += OnProcessSpell; Obj_AI_Base.OnSpellCast += Obj_AI_Base_OnDoCast; Spellbook.OnStopCast += SpellbookOnStopCast; } /// <summary> /// This event is fired before the player auto attacks. /// </summary> public static event BeforeAttackEvenH BeforeAttack; /// <summary> /// This event is fired when a unit is about to auto-attack another unit. /// </summary> public static event OnAttackEvenH OnAttack; /// <summary> /// This event is fired after a unit finishes auto-attacking another unit (Only works with player for now). /// </summary> public static event AfterAttackEvenH AfterAttack; /// <summary> /// Gets called on target changes /// </summary> public static event OnTargetChangeH OnTargetChange; ///<summary> /// Occurs when a minion is not killable by an auto attack. /// </summary> public static event OnNonKillableMinionH OnNonKillableMinion; /// <summary> /// Fires the before attack event. /// </summary> /// <param name="target">The target.</param> private static void FireBeforeAttack(AttackableUnit target) { if (BeforeAttack != null) { BeforeAttack(new BeforeAttackEventArgs { Target = target }); } else { DisableNextAttack = false; } } /// <summary> /// Fires the on attack event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> private static void FireOnAttack(AttackableUnit unit, AttackableUnit target) { if (OnAttack != null) { OnAttack(unit, target); } } /// <summary> /// Fires the after attack event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> private static void FireAfterAttack(AttackableUnit unit, AttackableUnit target) { if (AfterAttack != null && Utility.IsValidTarget(target)) { AfterAttack(unit, target); } } /// <summary> /// Fires the on target switch event. /// </summary> /// <param name="newTarget">The new target.</param> private static void FireOnTargetSwitch(AttackableUnit newTarget) { if (OnTargetChange != null && (!_lastTarget.IsValidTarget() || _lastTarget != newTarget)) { OnTargetChange(_lastTarget, newTarget); } } /// <summary> /// Fires the on non killable minion event. /// </summary> /// <param name="minion">The minion.</param> private static void FireOnNonKillableMinion(AttackableUnit minion) { if (OnNonKillableMinion != null) { OnNonKillableMinion(minion); } } /// <summary> /// Returns true if the spellname resets the attack timer. /// </summary> /// <param name="name">The name.</param> /// <returns><c>true</c> if the specified name is an auto attack reset; otherwise, <c>false</c>.</returns> public static bool IsAutoAttackReset(string name) { return AttackResets.Contains(name.ToLower()); } /// <summary> /// Returns true if the unit is melee /// </summary> /// <param name="unit">The unit.</param> /// <returns><c>true</c> if the specified unit is melee; otherwise, <c>false</c>.</returns> public static bool IsMelee(this Obj_AI_Base unit) { return unit.CombatType == GameObjectCombatType.Melee; } /// <summary> /// Returns true if the spellname is an auto-attack. /// </summary> /// <param name="name">The name.</param> /// <returns><c>true</c> if the name is an auto attack; otherwise, <c>false</c>.</returns> public static bool IsAutoAttack(string name) { return (name.ToLower().Contains("attack") && !NoAttacks.Contains(name.ToLower())) || Attacks.Contains(name.ToLower()); } /// <summary> /// Returns the auto-attack range of local player with respect to the target. /// </summary> /// <param name="target">The target.</param> /// <returns>System.Single.</returns> public static float GetRealAutoAttackRange(AttackableUnit target) { var result = player.AttackRange + player.BoundingRadius; if (target.IsValidTarget()) { return result + target.BoundingRadius; } return result; } /// <summary> /// Returns the auto-attack range of the target. /// </summary> /// <param name="target">The target.</param> /// <returns>System.Single.</returns> public static float GetAttackRange(AIHeroClient target) { var result = target.AttackRange + target.BoundingRadius; return result; } /// <summary> /// Returns true if the target is in auto-attack range. /// </summary> /// <param name="target">The target.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public static bool InAutoAttackRange(AttackableUnit target) { if (!target.IsValidTarget()) { return false; } var myRange = GetRealAutoAttackRange(target); return Vector2.DistanceSquared( (target is Obj_AI_Base) ? ((Obj_AI_Base)target).ServerPosition.To2D() : target.Position.To2D(), player.ServerPosition.To2D()) <= myRange * myRange; } /// <summary> /// Returns player auto-attack missile speed. /// </summary> /// <returns>System.Single.</returns> public static float GetMyProjectileSpeed() { return IsMelee(player) || _championName == "Azir" || _championName == "Velkoz" || _championName == "Viktor" && player.HasBuff("ViktorPowerTransferReturn") ? float.MaxValue : player.BasicAttack.MissileSpeed; } /// <summary> /// Returns if the player's auto-attack is ready. /// </summary> /// <returns><c>true</c> if this instance can attack; otherwise, <c>false</c>.</returns> public static bool CanAttack() { return Utils.GameTimeTickCount + Game.Ping / 2 + 25 >= LastAATick + player.AttackDelay * 1000 && Attack; } /// <summary> /// Returns true if moving won't cancel the auto-attack. /// </summary> /// <param name="extraWindup">The extra windup.</param> /// <returns><c>true</c> if this instance can move the specified extra windup; otherwise, <c>false</c>.</returns> public static bool CanMove(float extraWindup) { if (!Move) { return false; } if (_missileLaunched && Orbwalker.MissileCheck) { return true; } var localExtraWindup = 0; if(_championName == "Rengar" && (player.HasBuff("rengarqbase") || player.HasBuff("rengarqemp"))) { localExtraWindup = 200; } return NoCancelChamps.Contains(_championName) || (Utils.GameTimeTickCount + Game.Ping / 2 >= LastAATick + player.AttackCastDelay * 1000 + extraWindup + localExtraWindup); } /// <summary> /// Sets the movement delay. /// </summary> /// <param name="delay">The delay.</param> public static void SetMovementDelay(int delay) { _delay = delay; } /// <summary> /// Sets the minimum orbwalk distance. /// </summary> /// <param name="d">The d.</param> public static void SetMinimumOrbwalkDistance(float d) { _minDistance = d; } /// <summary> /// Gets the last move time. /// </summary> /// <returns>System.Single.</returns> public static float GetLastMoveTime() { return LastMoveCommandT; } /// <summary> /// Gets the last move position. /// </summary> /// <returns>Vector3.</returns> public static Vector3 GetLastMovePosition() { return LastMoveCommandPosition; } /// <summary> /// Moves to the position. /// </summary> /// <param name="position">The position.</param> /// <param name="holdAreaRadius">The hold area radius.</param> /// <param name="overrideTimer">if set to <c>true</c> [override timer].</param> /// <param name="useFixedDistance">if set to <c>true</c> [use fixed distance].</param> /// <param name="randomizeMinDistance">if set to <c>true</c> [randomize minimum distance].</param> public static void MoveTo(Vector3 position, float holdAreaRadius = 0, bool overrideTimer = false, bool useFixedDistance = true, bool randomizeMinDistance = true) { var playerPosition = player.ServerPosition; if (playerPosition.Distance(position, true) < holdAreaRadius * holdAreaRadius) { if (player.Path.Length > 0) { EloBuddy.Player.IssueOrder(GameObjectOrder.Stop, playerPosition); LastMoveCommandPosition = playerPosition; LastMoveCommandT = Utils.GameTimeTickCount - 70; } return; } var point = position; if(player.Distance(point, true) < 150 * 150) { point = playerPosition.Extend(position, (randomizeMinDistance ? (_random.NextFloat(0.6f, 1) + 0.2f) * _minDistance : _minDistance)); } var angle = 0f; var currentPath = player.GetWaypoints(); if (currentPath.Count > 1 && currentPath.PathLength() > 100) { var movePath = player.GetPath(point); if(movePath.Length > 1) { var v1 = currentPath[1] - currentPath[0]; var v2 = movePath[1] - movePath[0]; angle = v1.AngleBetween(v2.To2D()); var distance = movePath.Last().To2D().Distance(currentPath.Last(), true); if ((angle < 10 && distance < 500*500) || distance < 50*50) { return; } } } if (Utils.GameTimeTickCount - LastMoveCommandT < (70 + Math.Min(60, Game.Ping)) && !overrideTimer && angle < 60) { return; } if(angle >= 60 && Utils.GameTimeTickCount - LastMoveCommandT < 60) { return; } Player.IssueOrder(GameObjectOrder.MoveTo, point); LastMoveCommandPosition = point; LastMoveCommandT = Utils.GameTimeTickCount; } /// <summary> /// Orbwalks a target while moving to Position. /// </summary> /// <param name="target">The target.</param> /// <param name="position">The position.</param> /// <param name="extraWindup">The extra windup.</param> /// <param name="holdAreaRadius">The hold area radius.</param> /// <param name="useFixedDistance">if set to <c>true</c> [use fixed distance].</param> /// <param name="randomizeMinDistance">if set to <c>true</c> [randomize minimum distance].</param> public static void Orbwalk(AttackableUnit target, Vector3 position, float extraWindup = 90, float holdAreaRadius = 0, bool useFixedDistance = true, bool randomizeMinDistance = true) { try { if (target.IsValidTarget() && CanAttack()) { DisableNextAttack = false; FireBeforeAttack(target); if (!DisableNextAttack) { if (!NoCancelChamps.Contains(_championName)) { LastAATick = Utils.GameTimeTickCount + Game.Ping + 100 - (int)(ObjectManager.Player.AttackCastDelay * 1000f); _missileLaunched = false; var d = GetRealAutoAttackRange(target) - 65; if (player.Distance(target, true) > d * d && !player.IsMelee) { LastAATick = Utils.GameTimeTickCount + Game.Ping + 400 - (int)(ObjectManager.Player.AttackCastDelay * 1000f); } } if (!Player.IssueOrder(GameObjectOrder.AttackUnit, target)) { ResetAutoAttackTimer(); } LastMoveCommandT = 0; _lastTarget = target; return; } } if (CanMove(extraWindup)) { MoveTo(position, holdAreaRadius, false, useFixedDistance, randomizeMinDistance); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } /// <summary> /// Resets the Auto-Attack timer. /// </summary> public static void ResetAutoAttackTimer() { LastAATick = 0; } /// <summary> /// Fired when the spellbook stops casting a spell. /// </summary> /// <param name="spellbook">The spellbook.</param> /// <param name="args">The <see cref="SpellbookStopCastEventArgs"/> instance containing the event data.</param> private static void SpellbookOnStopCast(Obj_AI_Base sender, SpellbookStopCastEventArgs args) { if (sender.IsValid && sender.IsMe && args.DestroyMissile && args.StopAnimation) { ResetAutoAttackTimer(); } } /// <summary> /// Fired when an auto attack is fired. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="GameObjectProcessSpellCastEventArgs"/> instance containing the event data.</param> private static void Obj_AI_Base_OnDoCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if(sender.IsMe && IsAutoAttack(args.SData.Name)) { if(Game.Ping <= 30) //First world problems kappa { Utility.DelayAction.Add(30, () => Obj_AI_Base_OnDoCast_Delayed(sender, args)); return; } Obj_AI_Base_OnDoCast_Delayed(sender, args); } } /// <summary> /// Fired 30ms after an auto attack is launched. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="GameObjectProcessSpellCastEventArgs"/> instance containing the event data.</param> private static void Obj_AI_Base_OnDoCast_Delayed(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { FireAfterAttack(sender, args.Target as AttackableUnit); _missileLaunched = true; } /// <summary> /// Handles the <see cref="E:ProcessSpell" /> event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="Spell">The <see cref="GameObjectProcessSpellCastEventArgs"/> instance containing the event data.</param> private static void OnProcessSpell(Obj_AI_Base unit, GameObjectProcessSpellCastEventArgs Spell) { try { var spellName = Spell.SData.Name; if (IsAutoAttackReset(spellName) && unit.IsMe) { Utility.DelayAction.Add(250, ResetAutoAttackTimer); } if (!IsAutoAttack(spellName)) { return; } if (unit.IsMe && (Spell.Target is Obj_AI_Base || Spell.Target is Obj_BarracksDampener || Spell.Target is Obj_HQ)) { LastAATick = Utils.GameTimeTickCount - Game.Ping / 2; _missileLaunched = false; if (Spell.Target is Obj_AI_Base) { var target = (Obj_AI_Base)Spell.Target; if (target.IsValid) { FireOnTargetSwitch(target); _lastTarget = target; } } } FireOnAttack(unit, _lastTarget); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// The before attack event arguments. /// </summary> public class BeforeAttackEventArgs : EventArgs { /// <summary> /// <c>true</c> if the orbwalker should continue with the attack. /// </summary> private bool _process = true; /// <summary> /// The target /// </summary> public AttackableUnit Target; /// <summary> /// The unit /// </summary> public Obj_AI_Base Unit = ObjectManager.Player; /// <summary> /// Gets or sets a value indicating whether this <see cref="BeforeAttackEventArgs"/> should continue with the attack. /// </summary> /// <value><c>true</c> if the orbwalker should continue with the attack; otherwise, <c>false</c>.</value> public bool Process { get { return _process; } set { DisableNextAttack = !value; _process = value; } } } /// <summary> /// This class allows you to add an instance of "Orbwalker" to your assembly in order to control the orbwalking in an /// easy way. /// </summary> public class Orbwalker { /// <summary> /// The lane clear wait time modifier. /// </summary> private const float LaneClearWaitTimeMod = 2f; /// <summary> /// The configuration /// </summary> private static Menu _config; /// <summary> /// The player /// </summary> private readonly AIHeroClient Player; /// <summary> /// The forced target /// </summary> private Obj_AI_Base _forcedTarget; /// <summary> /// The orbalker mode /// </summary> private OrbwalkingMode _mode = OrbwalkingMode.None; /// <summary> /// The orbwalking point /// </summary> private Vector3 _orbwalkingPoint; /// <summary> /// The previous minion the orbwalker was targeting. /// </summary> private Obj_AI_Minion _prevMinion; /// <summary> /// The instances of the orbwalker. /// </summary> public static List<Orbwalker> Instances = new List<Orbwalker>(); /// <summary> /// Initializes a new instance of the <see cref="Orbwalker"/> class. /// </summary> /// <param name="attachToMenu">The menu the orbwalker should attach to.</param> public Orbwalker(Menu attachToMenu) { _config = attachToMenu; /* Drawings submenu */ var drawings = new Menu("Drawings", "drawings"); drawings.AddItem( new MenuItem("AACircle", "AACircle").SetShared() .SetValue(new Circle(true, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem( new MenuItem("AACircle2", "Enemy AA circle").SetShared() .SetValue(new Circle(false, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem( new MenuItem("HoldZone", "HoldZone").SetShared() .SetValue(new Circle(false, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem( new MenuItem("AALineWidth", "Line Width")).SetShared() .SetValue(new Slider(2, 1, 6)); _config.AddSubMenu(drawings); /* Misc options */ var misc = new Menu("Misc", "Misc"); misc.AddItem( new MenuItem("HoldPosRadius", "Hold Position Radius").SetShared().SetValue(new Slider(0, 0, 250))); misc.AddItem(new MenuItem("PriorizeFarm", "Priorize farm over harass").SetShared().SetValue(true)); misc.AddItem(new MenuItem("AttackWards", "Auto attack wards").SetShared().SetValue(false)); misc.AddItem(new MenuItem("AttackPetsnTraps", "Auto attack pets & traps").SetShared().SetValue(true)); misc.AddItem(new MenuItem("Smallminionsprio", "Jungle clear small first").SetShared().SetValue(false)); _config.AddSubMenu(misc); /* Missile check */ _config.AddItem(new MenuItem("MissileCheck", "Use Missile Check").SetShared().SetValue(true)); /* Delay sliders */ _config.AddItem( new MenuItem("ExtraWindup", "Extra windup time").SetShared().SetValue(new Slider(80, 0, 200))); _config.AddItem(new MenuItem("FarmDelay", "Farm delay").SetShared().SetValue(new Slider(30, 0, 200))); /*Load the menu*/ _config.AddItem( new MenuItem("LastHit", "Last hit").SetShared().SetValue(new KeyBind('X', KeyBindType.Press))); _config.AddItem(new MenuItem("Farm", "Mixed").SetShared().SetValue(new KeyBind('C', KeyBindType.Press))); _config.AddItem( new MenuItem("LaneClear", "LaneClear").SetShared().SetValue(new KeyBind('V', KeyBindType.Press))); _config.AddItem( new MenuItem("Orbwalk", "Combo").SetShared().SetValue(new KeyBind(32, KeyBindType.Press))); Player = ObjectManager.Player; Game.OnUpdate += GameOnOnGameUpdate; Drawing.OnDraw += DrawingOnOnDraw; Instances.Add(this); } /// <summary> /// Determines if a target is in auto attack range. /// </summary> /// <param name="target">The target.</param> /// <returns><c>true</c> if a target is in auto attack range, <c>false</c> otherwise.</returns> public virtual bool InAutoAttackRange(AttackableUnit target) { return Orbwalking.InAutoAttackRange(target); } /// <summary> /// Gets the farm delay. /// </summary> /// <value>The farm delay.</value> private int FarmDelay { get { return _config.Item("FarmDelay").GetValue<Slider>().Value; } } /// <summary> /// Gets a value indicating whether the orbwalker is orbwalking by checking the missiles. /// </summary> /// <value><c>true</c> if the orbwalker is orbwalking by checking the missiles; otherwise, <c>false</c>.</value> public static bool MissileCheck { get { return _config.Item("MissileCheck").GetValue<bool>(); } } /// <summary> /// Gets or sets the active mode. /// </summary> /// <value>The active mode.</value> public OrbwalkingMode ActiveMode { get { if (_mode != OrbwalkingMode.None) { return _mode; } if (_config.Item("Orbwalk").GetValue<KeyBind>().Active) { return OrbwalkingMode.Combo; } if (_config.Item("LaneClear").GetValue<KeyBind>().Active) { return OrbwalkingMode.LaneClear; } if (_config.Item("Farm").GetValue<KeyBind>().Active) { return OrbwalkingMode.Mixed; } if (_config.Item("LastHit").GetValue<KeyBind>().Active) { return OrbwalkingMode.LastHit; } return OrbwalkingMode.None; } set { _mode = value; } } /// <summary> /// Enables or disables the auto-attacks. /// </summary> /// <param name="b">if set to <c>true</c> the orbwalker will attack units.</param> public void SetAttack(bool b) { Attack = b; } /// <summary> /// Enables or disables the movement. /// </summary> /// <param name="b">if set to <c>true</c> the orbwalker will move.</param> public void SetMovement(bool b) { Move = b; } /// <summary> /// Forces the orbwalker to attack the set target if valid and in range. /// </summary> /// <param name="target">The target.</param> public void ForceTarget(Obj_AI_Base target) { _forcedTarget = target; } /// <summary> /// Forces the orbwalker to move to that point while orbwalking (Game.CursorPos by default). /// </summary> /// <param name="point">The point.</param> public void SetOrbwalkingPoint(Vector3 point) { _orbwalkingPoint = point; } /// <summary> /// Determines if the orbwalker should wait before attacking a minion. /// </summary> /// <returns><c>true</c> if the orbwalker should wait before attacking a minion, <c>false</c> otherwise.</returns> private bool ShouldWait() { return ObjectManager.Get<Obj_AI_Minion>() .Any( minion => minion.IsValidTarget() && minion.Team != GameObjectTeam.Neutral && InAutoAttackRange(minion) && MinionManager.IsMinion(minion, false) && HealthPrediction.LaneClearHealthPrediction( minion, (int)((Player.AttackDelay * 1000) * LaneClearWaitTimeMod), FarmDelay) <= Player.GetAutoAttackDamage(minion)); } /// <summary> /// Gets the target. /// </summary> /// <returns>AttackableUnit.</returns> public virtual AttackableUnit GetTarget() { AttackableUnit result = null; if ((ActiveMode == OrbwalkingMode.Mixed || ActiveMode == OrbwalkingMode.LaneClear) && !_config.Item("PriorizeFarm").GetValue<bool>()) { var target = TargetSelector.GetTarget(-1, TargetSelector.DamageType.Physical); if (target != null && InAutoAttackRange(target)) { return target; } } /*Killable Minion*/ if (ActiveMode == OrbwalkingMode.LaneClear || ActiveMode == OrbwalkingMode.Mixed || ActiveMode == OrbwalkingMode.LastHit) { var MinionList = ObjectManager.Get<Obj_AI_Minion>() .Where( minion => minion.IsValidTarget() && InAutoAttackRange(minion)) .OrderByDescending(minion => minion.BaseSkinName.Contains("Siege")) .ThenBy(minion => minion.BaseSkinName.Contains("Super")) .ThenBy(minion => minion.Health) .ThenByDescending(minion => minion.MaxHealth); foreach (var minion in MinionList) { var t = (int)(Player.AttackCastDelay * 1000) - 100 + Game.Ping / 2 + 1000 * (int) Math.Max(0, Player.Distance(minion) - Player.BoundingRadius) / (int)GetMyProjectileSpeed(); var predHealth = HealthPrediction.GetHealthPrediction(minion, t, FarmDelay); if (minion.Team != GameObjectTeam.Neutral && (_config.Item("AttackPetsnTraps").GetValue<bool>() && minion.BaseSkinName != "jarvanivstandard" || MinionManager.IsMinion(minion, _config.Item("AttackWards").GetValue<bool>()) )) { if (predHealth <= 0) { FireOnNonKillableMinion(minion); } if (predHealth > 0 && predHealth <= Player.GetAutoAttackDamage(minion, true)) { return minion; } } } } //Forced target if (_forcedTarget.IsValidTarget() && InAutoAttackRange(_forcedTarget)) { return _forcedTarget; } /* turrets / inhibitors / nexus */ if (ActiveMode == OrbwalkingMode.LaneClear) { /* turrets */ foreach (var turret in ObjectManager.Get<Obj_AI_Turret>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return turret; } /* inhibitor */ foreach (var turret in ObjectManager.Get<Obj_BarracksDampener>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return turret; } /* nexus */ foreach (var nexus in ObjectManager.Get<Obj_HQ>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return nexus; } } /*Champions*/ if (ActiveMode != OrbwalkingMode.LastHit) { var target = TargetSelector.GetTarget(-1, TargetSelector.DamageType.Physical); if (target.IsValidTarget() && InAutoAttackRange(target)) { return target; } } /*Jungle minions*/ if (ActiveMode == OrbwalkingMode.LaneClear || ActiveMode == OrbwalkingMode.Mixed) { var jminions = ObjectManager.Get<Obj_AI_Minion>() .Where( mob => mob.IsValidTarget() && mob.Team == GameObjectTeam.Neutral && this.InAutoAttackRange(mob) && mob.BaseSkinName != "gangplankbarrel"); result = _config.Item("Smallminionsprio").GetValue<bool>() ? jminions.MinOrDefault(mob => mob.MaxHealth) : jminions.MaxOrDefault(mob => mob.MaxHealth); if (result != null) { return result; } } /*Lane Clear minions*/ if (ActiveMode == OrbwalkingMode.LaneClear) { if (!ShouldWait()) { if (_prevMinion.IsValidTarget() && InAutoAttackRange(_prevMinion)) { var predHealth = HealthPrediction.LaneClearHealthPrediction( _prevMinion, (int)((Player.AttackDelay * 1000) * LaneClearWaitTimeMod), FarmDelay); if (predHealth >= 2 * Player.GetAutoAttackDamage(_prevMinion) || Math.Abs(predHealth - _prevMinion.Health) < float.Epsilon) { return _prevMinion; } } result = (from minion in ObjectManager.Get<Obj_AI_Minion>() .Where(minion => minion.IsValidTarget() && InAutoAttackRange(minion) && (_config.Item("AttackWards").GetValue<bool>() || !MinionManager.IsWard(minion.BaseSkinName.ToLower())) && (_config.Item("AttackPetsnTraps").GetValue<bool>() && minion.BaseSkinName != "jarvanivstandard" || MinionManager.IsMinion(minion, _config.Item("AttackWards").GetValue<bool>())) && minion.BaseSkinName != "gangplankbarrel") let predHealth = HealthPrediction.LaneClearHealthPrediction( minion, (int)((Player.AttackDelay * 1000) * LaneClearWaitTimeMod), FarmDelay) where predHealth >= 2 * Player.GetAutoAttackDamage(minion) || Math.Abs(predHealth - minion.Health) < float.Epsilon select minion).MaxOrDefault(m => !MinionManager.IsMinion(m, true) ? float.MaxValue : m.Health); if (result != null) { _prevMinion = (Obj_AI_Minion)result; } } } return result; } /// <summary> /// Fired when the game is updated. /// </summary> /// <param name="args">The <see cref="EventArgs"/> instance containing the event data.</param> private void GameOnOnGameUpdate(EventArgs args) { try { if (ActiveMode == OrbwalkingMode.None) { return; } //Prevent canceling important spells if (Player.IsCastingInterruptableSpell(true)) { return; } var target = GetTarget(); Orbwalk( target, (_orbwalkingPoint.To2D().IsValid()) ? _orbwalkingPoint : Game.CursorPos, _config.Item("ExtraWindup").GetValue<Slider>().Value, _config.Item("HoldPosRadius").GetValue<Slider>().Value); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// Fired when the game is drawn. /// </summary> /// <param name="args">The <see cref="EventArgs"/> instance containing the event data.</param> private void DrawingOnOnDraw(EventArgs args) { if (_config.Item("AACircle").GetValue<Circle>().Active) { Render.Circle.DrawCircle( Player.Position, GetRealAutoAttackRange(null) + 65, _config.Item("AACircle").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value); } if (_config.Item("AACircle2").GetValue<Circle>().Active) { foreach (var target in HeroManager.Enemies.FindAll(target => target.IsValidTarget(1175))) { Render.Circle.DrawCircle( target.Position, GetAttackRange(target), _config.Item("AACircle2").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value); } } if (_config.Item("HoldZone").GetValue<Circle>().Active) { Render.Circle.DrawCircle( Player.Position, _config.Item("HoldPosRadius").GetValue<Slider>().Value, _config.Item("HoldZone").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value, true); } } } } }
using System; using System.Xml; using System.Collections; using System.Reflection; using System.Text; using System.Text.RegularExpressions; namespace WikiEngine { #region Entry base declarations [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal class EntryAttribute : Attribute { public EntryAttribute(string NodeName) { this.NodeName = NodeName; } public string NodeName; } internal class WikiParseException : Exception { public WikiParseException(string Message) : base(Message) { } } internal class WikiParseEntryException : Exception { public WikiParseEntryException(string Message, Exception InnerException) : base(Message, InnerException) { } } internal class WikiParseDebugBreak : Exception { public string CurrentData; public WikiParseDebugBreak(string CurrentData) : base() { this.CurrentData = CurrentData; } } internal abstract class Entry { public static Entry LoadEntry(XmlElement Node, Entry Parent, Engine Owner) { foreach (System.Type t in Assembly.GetExecutingAssembly().GetTypes()) foreach (EntryAttribute a in t.GetCustomAttributes(typeof(EntryAttribute), true)) if (a.NodeName == Node.Name) { Entry e = t.GetConstructor(System.Type.EmptyTypes).Invoke(new object[0]) as Entry; e.Owner = Owner; e.Parent = Parent; //e.NextEntry=NextEntry;//? e.InitNode(Node); e.Load(Node);//try? if (e is EntryByPass) return (e as EntryByPass).PassThrough; else return e; } throw new WikiParseException("Unknown WikiParseXml element <" + Node.Name + ">"); } private string EntryId; private string EntryName; internal Entry Parent = null; internal Engine Owner = null; internal Entry NextEntry = null; public virtual void LoadElement(XmlElement Node) { //inheritants: parse children } public void InitNode(XmlElement Node) { EntryName = Node.Name; EntryId = Node.GetAttribute("id"); if (EntryId != "") Owner.AddNamedEntry(Node.OwnerDocument, this, EntryId); } public virtual void Load(XmlElement Node) { foreach (XmlNode n in Node.ChildNodes) if (n.NodeType == XmlNodeType.Element) LoadElement(n as XmlElement); //inheritants override and don't call inherited to deviate } public abstract string Render(string Data); public static string RenderSequence(Entry Start, string Data) { string res = Data; Entry e = Start; while (e != null) { res = e.Render(res); e = e.NextEntry; } return res; } protected bool XmlToBool(XmlElement Node) { if (Node == null) return false; return Node.InnerText == "1"; } protected void Throw(string Message, Exception InnerException) { throw new WikiParseEntryException("[WikiParse]<" + EntryName + (EntryId == "" ? "" : " id=\"" + EntryId + "\"") + ">" + Message, InnerException); } protected void Throw(string Message) { Throw(Message, null); } protected Entry LoadEntries(XmlElement Node, Engine Owner) { Entry LastEntry = null; Entry FirstEntry = null; foreach (XmlNode n in Node.ChildNodes) if (n.NodeType == XmlNodeType.Element) { Entry e = LoadEntry(n as XmlElement, this, Owner); if (LastEntry == null) FirstEntry = e; else LastEntry.NextEntry = e; LastEntry = e; } return FirstEntry; } } internal abstract class EntryRegEx : Entry { protected bool Global = true; protected string Pattern; //property on set FRegEx=null? protected bool PatternSet = false; protected RegexOptions Options = RegexOptions.IgnoreCase | RegexOptions.Multiline; internal Match CurrentMatch; private void SetOption(RegexOptions ro, bool rs) { if (rs) Options |= ro; else Options ^= ro; } public override void LoadElement(XmlElement Node) { switch (Node.Name) { case "pattern": Pattern = Node.InnerText; PatternSet = true; break; case "global": Global = XmlToBool(Node); break; case "ignorecase": SetOption(RegexOptions.IgnoreCase, XmlToBool(Node)); break; case "multiline": SetOption(RegexOptions.Multiline, XmlToBool(Node)); break; default: base.LoadElement(Node); break; } } private Regex FRegex = null; protected Regex GetRegex() { //RegexOptions.Compiled? other? if (FRegex == null) FRegex = new Regex(Pattern, Options); return FRegex; } } internal abstract class EntrySimpleText : Entry { protected string Text; public override void Load(XmlElement Node) { //base.Load (Node); //no child items expected, take text! Text = Node.InnerText; } } internal abstract class EntryByPass : Entry { internal Entry PassThrough = null; public override void Load(XmlElement Node) { base.Load(Node); //inheritants set PassThrough to another entry to replace the current entry in the flow } public override sealed string Render(string Data) { Throw("EntrySimplePassThrough should have been by-passed but got Render() called!"); return null; } } #endregion [Entry("replace")] internal class wpReplace : EntryRegEx { protected string ReplaceBy; public override void LoadElement(XmlElement Node) { switch (Node.Name) { case "with": ReplaceBy = Node.InnerText; break; default: base.LoadElement(Node); break; } } public override string Render(string Data) { if (Global) return GetRegex().Replace(Data, ReplaceBy); else return GetRegex().Replace(Data, ReplaceBy, 1); } } [Entry("replaceif")] internal class wpReplaceIf : wpReplace { Entry CheckDo; Entry CheckElse; public override void LoadElement(XmlElement Node) { switch (Node.Name) { case "do": CheckDo = LoadEntries(Node, Owner); break; case "else": CheckElse = LoadEntries(Node, Owner); break; default: base.LoadElement(Node); break; } } public override string Render(string Data) { Regex re = GetRegex(); if (re.IsMatch(Data)) return RenderSequence(CheckDo, re.Replace(Data, ReplaceBy)); else return RenderSequence(CheckElse, Data); } } [Entry("split")] internal class wpSplit : EntryRegEx { protected Entry Match; protected Entry Inbetween; protected bool Required = false; public override void LoadElement(XmlElement Node) { switch (Node.Name) { case "match": Match = LoadEntries(Node, Owner); break; case "inbetween": Inbetween = LoadEntries(Node, Owner); break; case "required": Required = XmlToBool(Node); break; default: base.LoadElement(Node); break; } } public override string Render(string Data) { Regex re = GetRegex(); int Position = 0; MatchCollection mc = re.Matches(Data); if (mc.Count == 0) { return Required ? Data : RenderSequence(Inbetween, Data); } else { StringBuilder res = new StringBuilder(Data.Length); Match pm = CurrentMatch; foreach (Match m in mc) { CurrentMatch = m; //preceding bit res.Append(RenderSequence(Inbetween, Data.Substring(Position, m.Index - Position))); //match res.Append(RenderSequence(Match, m.Value)); Position = m.Index + m.Length; } CurrentMatch = pm; //last bit res.Append(RenderSequence(Inbetween, Data.Substring(Position, Data.Length - Position))); return res.ToString(); } } } [Entry("extract")] internal class wpExtract : EntryRegEx { protected Entry Match; protected Entry Inbetween; protected bool Required = false; private string FPrefix = "%%"; private string FSuffix = "#"; public override void LoadElement(XmlElement Node) { switch (Node.Name) { case "match": Match = LoadEntries(Node, Owner); break; case "inbetween": Inbetween = LoadEntries(Node, Owner); break; case "required": Required = XmlToBool(Node); break; case "prefix": FPrefix = Node.InnerText; break; case "suffix": FSuffix = Node.InnerText; break; default: base.LoadElement(Node); break; } } public static string RegexPatternSafe(string Text) { StringBuilder s = new StringBuilder(Text.Length); foreach (char c in Text) switch (c) { case '$': case '(': case ')': case '*': case '+': case '-': case '.': case '[': case '\\': case ']': case '^': case '{': case '|': case '}': s.Append('\\'); s.Append(c); break; default: s.Append(c); break; } return s.ToString(); } protected string Marker(int Index) { return FPrefix + Index.ToString() + FSuffix; } public override string Render(string Data) { Regex re = GetRegex(); Regex reOpen = new Regex(RegexPatternSafe(FPrefix)); Regex reClose = new Regex(RegexPatternSafe(FPrefix) + "([0-9]+?)" + RegexPatternSafe(FSuffix)); string Marker0 = Marker(0); int Position = 0; MatchCollection mc = re.Matches(Data); if (mc.Count == 0) { return Required ? Data : RenderSequence(Inbetween, Data); } else { StringBuilder res = new StringBuilder(Data.Length); Match pm = CurrentMatch; int mi; for (mi = 0; mi < mc.Count; mi++) { Match m = mc[mi]; CurrentMatch = m; //preceding bit, securing markers res.Append(reOpen.Replace(Data.Substring(Position, m.Index - Position), Marker0)); //match res.Append(Marker(mi + 1)); Position = m.Index + m.Length; } CurrentMatch = pm; //last bit res.Append(reOpen.Replace(Data.Substring(Position, Data.Length - Position), Marker0)); //perform action string x = RenderSequence(Inbetween, res.ToString()); res = new StringBuilder(); //re-word extracted matches Position = 0; MatchCollection mc2 = reClose.Matches(x); pm = CurrentMatch; foreach (Match m2 in mc2) { //preceding bit res.Append(x.Substring(Position, m2.Index - Position)); //find match mi = Convert.ToInt32(m2.Groups[1].Value); if (mi == 0) res.Append(FPrefix);//restore marker else if (mi > mc.Count) Throw("Incorrect extraction marker found, check prefix/suffix '" + m2.Value + "'"); else { CurrentMatch = mc[mi - 1]; res.Append(RenderSequence(Match, CurrentMatch.Value)); } Position = m2.Index + m2.Length; } CurrentMatch = pm; //last bit res.Append(x.Substring(Position, x.Length - Position)); return res.ToString(); } } } [Entry("submatch")] internal class wpSubMatch : Entry { private int Number = -1; private int RepeatNumber = -1; public override void LoadElement(XmlElement Node) { switch (Node.Name) { case "id": case "index": case "number": Number = Convert.ToInt32(Node.InnerText); break; case "repeat": RepeatNumber = Convert.ToInt32(Node.InnerText); break; default: base.LoadElement(Node); break; } } public override string Render(string Data) { Entry pe = Parent; while (pe != null && !(pe is EntryRegEx)) pe = pe.Parent; if (pe == null) Throw("No parent RegEx operation found"); Match m = (pe as EntryRegEx).CurrentMatch; if (m == null) Throw("Parent RegEx operation is not processing a match"); StringBuilder res = new StringBuilder(); if (Number == -1) foreach (Group g in m.Groups) res.Append(g.Value); else { try { res.Append(m.Groups[Number].Value); } catch (IndexOutOfRangeException e) { Throw("Unable to retrieve submatch " + Number.ToString(), e); } } if (RepeatNumber != -1) { int rl = 0; try { rl = m.Groups[RepeatNumber].Length; } catch (IndexOutOfRangeException e) { Throw("Unable to retrieve submatch " + Number.ToString(), e); } string x = res.ToString(); for (int i = 1; i < rl; i++) res.Append(x); } return res.ToString(); } } [Entry("group")] internal class wpGroup : Entry { Entry GroupFirst; public override void Load(XmlElement Node) { //base.Load (Node); //deviate: children are entries GroupFirst = LoadEntries(Node, Owner); } public override string Render(string Data) { return RenderSequence(GroupFirst, Data); } } [Entry("check")] internal class wpCheck : EntryRegEx { private string Text; private bool TextSet = false; Entry CheckDo; Entry CheckElse; public override void LoadElement(XmlElement Node) { switch (Node.Name) { case "value": Text = Node.InnerText; TextSet = true; break; case "do": CheckDo = LoadEntries(Node, Owner); break; case "else": CheckElse = LoadEntries(Node, Owner); break; default: base.LoadElement(Node); break; } } public override string Render(string Data) { bool ChecksOut; if (TextSet) ChecksOut = Data == Text; else if (PatternSet) ChecksOut = GetRegex().IsMatch(Data); else ChecksOut = Data.Length != 0; //default return RenderSequence(ChecksOut ? CheckDo : CheckElse, Data); } } [Entry("text")] internal class wpText : EntrySimpleText { public override string Render(string Data) { return Text; } } [Entry("noop"), Entry("skip")] internal class wpNoop : Entry { public override string Render(string Data) { return Data; } } [Entry("uppercase")] internal class wpUpperCase : Entry { public override string Render(string Data) { return Data.ToUpper(); } } [Entry("lowercase")] internal class wpLowerCase : Entry { public override string Render(string Data) { return Data.ToLower(); } } [Entry("prepend")] internal class wpPrepend : EntrySimpleText { public override string Render(string Data) { return Text + Data; } } [Entry("append")] internal class wpAppend : EntrySimpleText { public override string Render(string Data) { return Data + Text; } } [Entry("length")] internal class wpLength : Entry { public override string Render(string Data) { return Data.Length.ToString(); } } [Entry("concat")] internal class wpConcat : Entry { Entry ConcatFirst; public override void Load(XmlElement Node) { //base.Load (Node); //children are entries ConcatFirst = LoadEntries(Node, Owner); } public override string Render(string Data) { StringBuilder res = new StringBuilder(); Entry e = ConcatFirst; while (e != null) { res.Append(e.Render(Data)); e = e.NextEntry; } return res.ToString(); } } [Entry("process")] internal class wpProcess : EntryRegEx { Entry CheckDo; Entry CheckElse; public override void LoadElement(XmlElement Node) { switch (Node.Name) { case "do": CheckDo = LoadEntries(Node, Owner); break; case "else": CheckElse = LoadEntries(Node, Owner); break; default: base.LoadElement(Node); break; } } public override string Render(string Data) { MatchCollection mc = GetRegex().Matches(Data); if (mc.Count == 0) return RenderSequence(CheckElse, Data); else { string res = Data; Match pm = CurrentMatch; foreach (Match m in mc) { CurrentMatch = m; res = RenderSequence(CheckDo, res); } CurrentMatch = pm; return res; } } } [Entry("debug")] internal class wpDebugBreak : Entry { int SkipCount; Entry DebugDo; public override void LoadElement(XmlElement Node) { switch (Node.Name) { case "do": DebugDo = LoadEntries(Node, Owner); break; case "skip": SkipCount = Convert.ToInt32(Node.InnerText); break; default: base.LoadElement(Node); break; } } public override string Render(string Data) { if (SkipCount == 0) throw new WikiParseDebugBreak(RenderSequence(DebugDo, Data)); else { SkipCount--; return Data; } } } [Entry("jump")] internal class wpJump : EntryByPass { public override void Load(XmlElement Node) { PassThrough = Owner.GetNamedEntry(Node.OwnerDocument, Node.InnerText); if (PassThrough == null) Throw("Jump target '" + Node.InnerText + "' not found"); } } [Entry("htmlencode")] internal class wpHtmlEncode : Entry { public override string Render(string Data) { return Data.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("\r\n", "<br />"); } } [Entry("urlencode")] internal class wpUrlEncode : Entry { const string Hex = "0123456789ABCDEF"; public override string Render(string Data) { StringBuilder s = new StringBuilder(Data.Length); //parameter: select encoding? Encoding.GetEncoding( foreach (byte b in Encoding.UTF8.GetBytes(Data)) { char c = (char)b; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) s.Append(c); else switch (c) { //http://www.ietf.org/rfc/rfc2396.txt '-_.!~*''()' //['0'..'9','A'..'Z','a'..'z','?','&','=','#',':','/',';','-','_','.','!','~','*','''','(',')'] then case ' ': s.Append('+'); break; case '\'': case '(': case ')': case '*': case '-': case '.': case '_': case '!': s.Append(c); break; default: s.Append('%'); s.Append(Hex[b >> 4]); s.Append(Hex[b & 0x0F]); break; } } return s.ToString(); } } [Entry("include")] internal class wpInclude : EntrySimpleText { protected Entry FMainEntry; public override void Load(XmlElement Node) { base.Load(Node); //relative URL/Path? XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(Text); XmlNode FirstEntry = doc.DocumentElement.FirstChild; while (FirstEntry != null && FirstEntry.NodeType != XmlNodeType.Element) FirstEntry = FirstEntry.NextSibling; FMainEntry = LoadEntry(FirstEntry as XmlElement, this, Owner);//parent null? } public override string Render(string Data) { return FMainEntry.Render(Data); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; 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.Channels.Tcp; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; namespace Apache.Geode.DUnitFramework { using NUnit.Framework; public class UnitProcess : ClientBase { #region Public constants and accessors public const string ClientProcName = "FwkClient.exe"; public string SshArgs { get { return m_sshArgs; } } public string PsexecArgs { get { return m_psexecArgs; } } public override string StartDir { get { return m_startDir; } } #endregion #region Private members private static int m_clientId = 0; private static int m_clientPort = Util.RandPort(20000, 40000) - 1; internal static Dictionary<string, ManualResetEvent> ProcessIDMap = new Dictionary<string, ManualResetEvent>(); public const int MaxStartWaitMillis = 300000; public const int MaxEndWaitMillis = 3000000; private Process m_process; private string m_sshPath; private string m_sshArgs; private string m_psexecPath; private string m_psexecArgs; private string m_hostName; private string m_sharePath; private string m_shareName; private string m_startDir; private Dictionary<string, string> m_envs; private IClientComm m_clientComm; private bool m_timeout; private volatile bool m_exiting; private ManualResetEvent m_clientEvent = new ManualResetEvent(false); #endregion // Using static constructor since it is guaranteed // to be called on first access. static UnitProcess() { // Create the server side channels (required only once) // NOTE: This is required so that remote client receives custom exceptions RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; RegisterChannel(true); RegisterChannel(false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(DriverComm), CommConstants.DriverService, WellKnownObjectMode.SingleCall); if (Util.ExternalBBServer == null) { RemotingConfiguration.RegisterWellKnownServiceType(typeof(BBComm), CommConstants.BBService, WellKnownObjectMode.SingleCall); Util.SetEnvironmentVariable(CommConstants.BBAddrEnvVar, Util.IPAddressString + ':' + Util.DriverPort.ToString()); } } #region Private functions private static void RegisterChannel(bool ipc) { BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider(); Dictionary<string, string> properties = new Dictionary<string, string>(); IChannel channel; if (ipc) { properties["portName"] = CommConstants.ServerIPC + Util.DriverPort.ToString(); properties["name"] = "GFIpcChannel"; channel = new IpcChannel(properties, clientProvider, serverProvider); } else { properties["port"] = Util.DriverPort.ToString(); properties["name"] = "GFTcpChannel"; channel = new TcpChannel(properties, clientProvider, serverProvider); } ChannelServices.RegisterChannel(channel, false); } private void ExitClient(int waitMillis, bool force) { if (m_clientComm != null) { Thread killThread = new Thread(ExitClient); killThread.Start(); if (waitMillis > 0) { if (!killThread.Join(waitMillis)) { Util.Log(Util.LogLevel.Error, "Timed out waiting for client {0} to exit.", ID); } } if (m_process != null && !m_process.HasExited) { if (waitMillis > 0) { m_process.WaitForExit(waitMillis); } } if (m_process != null && !m_process.HasExited) { try { m_process.Kill(); } catch { } if (waitMillis > 0) { m_process.WaitForExit(waitMillis); } } m_clientComm = null; } } private void ExitClient() { ExitClient(false); } private void ExitClient(bool force) { try { m_clientComm.Exit(force); } catch { // Client cannot be reached or already forcibly closed. // Nothing required to be done. } } #endregion #region Public non-overriding methods public static void Init() { // Do nothing; just ensures that the static constructor is invoked. } public static int GetClientId() { Interlocked.Increment(ref m_clientId); return m_clientId; } public static int GetClientPort() { Interlocked.Increment(ref m_clientPort); return m_clientPort; } private UnitProcess(string clientId) { if (clientId == null) { clientId = GetClientId().ToString(); } this.ID = clientId; } public UnitProcess() : this(null, null) { } public UnitProcess(string clientId, string startDir) { string clientIPC = CommConstants.ClientIPC + GetClientPort().ToString(); if (clientId == null) { clientId = GetClientId().ToString(); } this.ID = clientId; string localArgs = "--id=" + clientId + " --driver=ipc://" + CommConstants.ServerIPC + Util.DriverPort + '/' + CommConstants.DriverService + " --bbServer="; if (Util.ExternalBBServer != null) { localArgs += Util.ExternalBBServer + ' ' + clientIPC; } else { localArgs += "ipc://" + CommConstants.ServerIPC + Util.DriverPort + '/' + CommConstants.BBService + ' ' + clientIPC; } lock (((ICollection)ProcessIDMap).SyncRoot) { ProcessIDMap[clientId] = m_clientEvent; } bool procStarted; bool hasCoverage = "true".Equals(Environment.GetEnvironmentVariable( "COVERAGE_ENABLED")); if (hasCoverage) { string coveragePrefix = "coverage-" + clientId; procStarted = Util.StartProcess("ncover.console.exe", "//x " + coveragePrefix + ".xml " + ClientProcName + " " + localArgs, Util.LogFile == null, startDir, true, true, true, out m_process); } else { procStarted = Util.StartProcess(ClientProcName, localArgs, Util.LogFile == null, startDir, false, false, false, true, out m_process); } if (!procStarted) { throw new AssertionException("FATAL: Could not start client: " + ClientProcName); } m_clientComm = ServerConnection<IClientComm>.Connect("ipc://" + clientIPC + '/' + CommConstants.ClientService); m_timeout = false; m_exiting = false; m_startDir = startDir; } public UnitProcess(string clientId, int clientNum, string sshPath, string sshArgs, string hostName, string sharePath, string shareName, string startDir, Dictionary<string, string> envs) { string clientProcPath = ClientProcName; string remoteArgs; string runDir = null; if (sharePath != null) { runDir = Util.AssemblyDir.Replace(sharePath.ToLower(), shareName); clientProcPath = runDir + Path.DirectorySeparatorChar + ClientProcName; clientProcPath = clientProcPath.Replace('\\', '/'); } int clientPort = GetClientPort(); if (clientId == null) { clientId = GetClientId().ToString(); } this.ID = clientId; string envStr = string.Empty; if (envs != null) { m_envs = envs; foreach (KeyValuePair<string, string> envNameValue in envs) { string envValue = envNameValue.Value.Replace(sharePath, shareName); envStr += " '--env:" + envNameValue.Key + '=' + envValue + '\''; } } string bbServer; if (Util.ExternalBBServer != null) { bbServer = Util.ExternalBBServer; } else { bbServer = "tcp://" + Util.IPAddressString + ':' + Util.DriverPort + '/' + CommConstants.BBService; } remoteArgs = sshArgs + ' ' + hostName + " '" + clientProcPath + "' --id=" + clientId + " --num=" + clientNum + envStr + " '--startdir=" + (startDir == null ? runDir : startDir) + "' '--driver=tcp://" + Util.IPAddressString + ':' + Util.DriverPort + '/' + CommConstants.DriverService + "' '--bbServer=" + bbServer + "' " + clientPort; try { lock (((ICollection)ProcessIDMap).SyncRoot) { ProcessIDMap[clientId] = m_clientEvent; } if (!Util.StartProcess(sshPath, remoteArgs, Util.LogFile == null, null, false, false, false, out m_process)) { throw new AssertionException("Failed to start the client."); } if (!m_clientEvent.WaitOne(MaxStartWaitMillis, false)) { throw new AssertionException("Timed out waiting for client to start."); } m_clientComm = ServerConnection<IClientComm>.Connect("tcp://" + hostName + ':' + clientPort + '/' + CommConstants.ClientService); m_process = m_clientComm.GetClientProcess(); m_sshPath = sshPath; m_sshArgs = sshArgs; m_hostName = hostName; m_timeout = false; m_exiting = false; m_sharePath = sharePath; m_shareName = shareName; m_startDir = startDir; } catch (Exception ex) { throw new AssertionException(string.Format("FATAL: Could not start " + "client: {1}{0}\ton host: {2}{0}\tusing remote shell: {3}{0}" + "\tException: {4}", Environment.NewLine, clientProcPath, hostName, sshPath, ex)); } } /// <summary> /// Create a UnitProcess object by launching a client using a launcher. The /// launcher is launched on the remote host using psexec. /// </summary> public UnitProcess(string clientId, int clientNum, string psexecPath, string psexecArgs, string hostName, string sharePath, string shareName, string startDir, Dictionary<string, string> envs, int launcherPort, Dictionary<string, UnitProcess> launcherProcesses, string logPath) { UnitProcess launcherProcess = null; if (!launcherProcesses.ContainsKey(hostName)) { launcherProcess = CreateLauncherUsingPsexec(GetClientId().ToString(), psexecPath, psexecArgs, hostName, sharePath, shareName, startDir, launcherPort, logPath); launcherProcesses.Add(hostName, launcherProcess); } else { launcherProcess = launcherProcesses[hostName]; } string clientProcPath = ClientProcName; string remoteArgs; string runDir = null; if (sharePath != null) { runDir = Util.AssemblyDir.Replace(sharePath.ToLower(), shareName); clientProcPath = runDir + Path.DirectorySeparatorChar + ClientProcName; clientProcPath = clientProcPath.Replace('/', '\\'); } int clientPort = GetClientPort(); if (clientId == null) { clientId = GetClientId().ToString(); } this.ID = clientId; string envStr = string.Empty; if (envs != null) { m_envs = envs; foreach (KeyValuePair<string, string> envNameValue in envs) { string envValue = envNameValue.Value.Replace(sharePath, shareName); envStr += " --env:" + envNameValue.Key + "=\"" + envValue + '\"'; } } string bbServer; if (Util.ExternalBBServer != null) { bbServer = Util.ExternalBBServer; } else { bbServer = "tcp://" + Util.IPAddressString + ':' + Util.DriverPort + '/' + CommConstants.BBService; } remoteArgs = " --id=" + clientId + " --num=" + clientNum + envStr + " --startdir=\"" + (startDir == null ? runDir : startDir) + "\" --driver=tcp://" + Util.IPAddressString + ':' + Util.DriverPort + '/' + CommConstants.DriverService + " --bbServer=\"" + bbServer + "\" " + clientPort; try { IClientCommV2 clientComm = launcherProcess.m_clientComm as IClientCommV2; Process proc; if (!clientComm.LaunchNewClient(clientProcPath, remoteArgs, out proc)) { throw new AssertionException("Failed to start client: " + clientId); } m_process = proc; lock (((ICollection)ProcessIDMap).SyncRoot) { ProcessIDMap[clientId] = m_clientEvent; } if (!m_clientEvent.WaitOne(MaxStartWaitMillis, false)) { throw new AssertionException("Timed out waiting for client to start."); } m_clientComm = ServerConnection<IClientComm>.Connect("tcp://" + hostName + ':' + clientPort + '/' + CommConstants.ClientService); m_process = m_clientComm.GetClientProcess(); m_psexecPath = psexecPath; m_psexecArgs = psexecArgs; m_hostName = hostName; m_timeout = false; m_exiting = false; m_sharePath = sharePath; m_shareName = shareName; m_startDir = startDir; } catch (Exception ex) { throw new AssertionException(string.Format("FATAL: Could not start " + "client: {1}{0}\ton host: {2}{0}\tusing: FwkLauncher{0}" + "\tException: {3}", Environment.NewLine, clientProcPath, hostName, ex)); } } public static UnitProcess Create() { return new UnitProcess(); } public static UnitProcess Create(string clientId, string startDir) { return new UnitProcess(clientId, startDir); } public static UnitProcess Create(string clientId, int clientNum, string sshPath, string sshArgs, string hostName, string sharePath, string shareName, string startDir, Dictionary<string, string> envs) { return new UnitProcess(clientId, clientNum, sshPath, sshArgs, hostName, sharePath, shareName, startDir, envs); } public static List<UnitProcess> Create(List<string> clientIds, int startClientNum, string sshPath, string sshArgs, string hostName, string sharePath, string shareName, string startDir, Dictionary<string, string> envs) { if (clientIds != null && clientIds.Count > 0) { string clientProcPath = ClientProcName; string clientsCmd = string.Empty; string runDir = null; string clientId; List<UnitProcess> unitProcs = new List<UnitProcess>(); UnitProcess unitProc; if (sharePath != null) { runDir = Util.AssemblyDir.Replace(sharePath.ToLower(), shareName); clientProcPath = runDir + Path.DirectorySeparatorChar + ClientProcName; clientProcPath = clientProcPath.Replace('\\', '/'); } string envStr = string.Empty; if (envs != null) { foreach (KeyValuePair<string, string> envNameValue in envs) { string envValue = envNameValue.Value.Replace(sharePath, shareName); envStr += " '--env:" + envNameValue.Key + '=' + envValue + '\''; } } List<int> clientPorts = new List<int>(); lock (((ICollection)ProcessIDMap).SyncRoot) { for (int i = 0; i < clientIds.Count; i++, startClientNum++) { int clientPort = GetClientPort(); clientId = clientIds[i]; if (clientId == null) { clientId = GetClientId().ToString(); clientIds[i] = clientId; } string bbServer; if (Util.ExternalBBServer != null) { bbServer = Util.ExternalBBServer; } else { bbServer = "tcp://" + Util.IPAddressString + ':' + Util.DriverPort + '/' + CommConstants.BBService; } clientsCmd += '\'' + clientProcPath + "' --bg --id=" + clientId + " --num=" + startClientNum + envStr + " '--startdir=" + (startDir == null ? runDir : startDir) + "' '--driver=tcp://" + Util.IPAddressString + ':' + Util.DriverPort + '/' + CommConstants.DriverService + "' '--bbServer=" + bbServer + "' " + clientPort + " ; "; clientPorts.Add(clientPort); unitProc = new UnitProcess(clientId); ProcessIDMap[clientId] = unitProc.m_clientEvent; unitProcs.Add(unitProc); } } try { Process proc; //string sshAllArgs = sshArgs + ' ' + hostName + // " \"" + " NCover.Console.exe //x Coverage.xml //at coverage.trend " + clientsCmd + '"'; string sshAllArgs = sshArgs + ' ' + hostName + " \"" + clientsCmd + '"'; Util.RawLog(string.Format("Running remote command: {0} {1}{2}", sshPath, Util.HideSshPassword(sshAllArgs), Environment.NewLine)); if (!Util.StartProcess(sshPath, sshAllArgs, Util.LogFile == null, null, false, false, false, out proc)) { throw new AssertionException("Failed to start the clients."); } for (int i = 0; i < clientIds.Count; i++) { clientId = clientIds[i]; unitProc = (UnitProcess)unitProcs[i]; if (!unitProc.m_clientEvent.WaitOne(MaxStartWaitMillis, false)) { throw new AssertionException("Timed out waiting for client: " + clientId); } unitProc.m_clientComm = ServerConnection<IClientComm>.Connect("tcp://" + hostName + ':' + clientPorts[i] + '/' + CommConstants.ClientService); unitProc.m_process = unitProc.m_clientComm.GetClientProcess(); unitProc.m_sshPath = sshPath; unitProc.m_sshArgs = sshArgs; unitProc.m_hostName = hostName; unitProc.m_timeout = false; unitProc.m_exiting = false; unitProc.m_sharePath = sharePath; unitProc.m_shareName = shareName; unitProc.m_startDir = startDir; unitProc.m_envs = envs; } } catch (Exception ex) { unitProcs.Clear(); unitProcs = null; clientPorts.Clear(); clientPorts = null; throw new AssertionException(string.Format("FATAL: Could not start " + "client: {1}{0}\ton host: {2}{0}\tusing remote shell: {3}{0}" + "\tException: {4}", Environment.NewLine, clientProcPath, hostName, sshPath, ex)); } return unitProcs; } return null; } /// <summary> /// Create clients on the remote host using FwkLauncher. /// </summary> public static List<UnitProcess> CreateClientsUsingLauncher(List<string> clientIds, int startClientNum, string psexecPath, string psexecArgs, string hostName, string sharePath, string shareName, string startDir, Dictionary<string, string> envs, int launcherPort, Dictionary<string, UnitProcess> launcherProcesses, string logPath) { if (clientIds != null && clientIds.Count > 0) { UnitProcess launcherProcess = null; if (!launcherProcesses.ContainsKey(hostName)) { launcherProcess = CreateLauncherUsingPsexec(GetClientId().ToString(), psexecPath, psexecArgs, hostName, sharePath, shareName, startDir, launcherPort, logPath); launcherProcesses.Add(hostName, launcherProcess); } else { launcherProcess = launcherProcesses[hostName]; } string clientProcPath = ClientProcName; string runDir = null; string clientId; List<UnitProcess> unitProcs = new List<UnitProcess>(); if (sharePath != null) { runDir = Util.AssemblyDir.Replace(sharePath.ToLower(), shareName); clientProcPath = runDir + Path.DirectorySeparatorChar + ClientProcName; clientProcPath = clientProcPath.Replace('\\', '/'); } string envStr = string.Empty; if (envs != null) { foreach (KeyValuePair<string, string> envNameValue in envs) { string envValue = envNameValue.Value.Replace(sharePath, shareName); envStr += " --env:" + envNameValue.Key + "=\"" + envValue + '\"'; } } List<int> clientPorts = new List<int>(); try { for (int i = 0; i < clientIds.Count; i++, startClientNum++) { string clientsCmd = string.Empty; int clientPort = GetClientPort(); clientId = clientIds[i]; if (clientId == null) { clientId = GetClientId().ToString(); clientIds[i] = clientId; } string bbServer; if (Util.ExternalBBServer != null) { bbServer = Util.ExternalBBServer; } else { bbServer = "tcp://" + Util.IPAddressString + ':' + Util.DriverPort + '/' + CommConstants.BBService; } clientsCmd = " --id=" + clientId + " --num=" + startClientNum + envStr + " --startdir=\"" + (startDir == null ? runDir : startDir) + "\" --driver=\"tcp://" + Util.IPAddressString + ':' + Util.DriverPort + '/' + CommConstants.DriverService + "\" --bbServer=\"" + bbServer + "\" " + clientPort; clientPorts.Add(clientPort); IClientCommV2 clientComm = launcherProcess.m_clientComm as IClientCommV2; Process proc; UnitProcess unitProc; unitProc = new UnitProcess(clientId); lock (((ICollection)ProcessIDMap).SyncRoot) { ProcessIDMap[clientId] = unitProc.m_clientEvent; unitProcs.Add(unitProc); } if (!clientComm.LaunchNewClient(clientProcPath, clientsCmd, out proc)) { throw new AssertionException("Failed to start client: " + clientId); } unitProc.m_process = proc; } for (int i = 0; i < clientIds.Count; i++) { clientId = clientIds[i]; UnitProcess unitProc = (UnitProcess)unitProcs[i]; if (!unitProc.m_clientEvent.WaitOne(MaxStartWaitMillis, false)) { throw new AssertionException("Timed out waiting for client: " + clientId); } unitProc.m_clientComm = ServerConnection<IClientComm>.Connect("tcp://" + hostName + ':' + clientPorts[i] + '/' + CommConstants.ClientService); unitProc.m_process = unitProc.m_clientComm.GetClientProcess(); unitProc.m_psexecPath = psexecPath; unitProc.m_psexecArgs = psexecArgs; unitProc.m_hostName = hostName; unitProc.m_timeout = false; unitProc.m_exiting = false; unitProc.m_sharePath = sharePath; unitProc.m_shareName = shareName; unitProc.m_startDir = startDir; unitProc.m_envs = envs; } } catch (Exception ex) { unitProcs.Clear(); unitProcs = null; clientPorts.Clear(); clientPorts = null; throw new AssertionException(string.Format("FATAL: Could not start " + "client: {1}{0}\ton host: {2}{0}\tusing: FwkLauncher{0}" + "\tException: {3}", Environment.NewLine, clientProcPath, hostName, ex)); } return unitProcs; } return null; } /// <summary> /// If not already created, Create a launcher process on the remote host using /// psexec. This launcher is used to launch the FwkClients on the host. /// </summary> private static UnitProcess CreateLauncherUsingPsexec(string clientId, string psexecPath, string psexecArgs, string hostName, string sharePath, string shareName, string startDir, int launcherPort, string logPath) { if (clientId != null) { string clientProcPath = "FwkLauncher.exe"; string clientsCmd = string.Empty; string runDir = null; bool newProcCreated = false; UnitProcess unitProc; Process proc = null; try { lock (((ICollection)ProcessIDMap).SyncRoot) { unitProc = new UnitProcess(clientId); ProcessIDMap[clientId] = unitProc.m_clientEvent; } if (launcherPort == 0) // i.e. launcher is not running { launcherPort = GetClientPort(); if (sharePath != null) { runDir = Util.AssemblyDir.Replace(sharePath.ToLower(), shareName); clientProcPath = runDir + Path.DirectorySeparatorChar + clientProcPath; clientProcPath = clientProcPath.Replace('/', '\\'); } clientsCmd = " cmd.exe /C \"\"" + clientProcPath + "\" --id=" + clientId + " --bg --port=" + launcherPort + " --driver=\"tcp://" + Util.IPAddressString + ':' + Util.DriverPort + '/' + CommConstants.DriverService + "\"\""; string psexecAllArgs = psexecArgs + "\\\\" + hostName + " " + clientsCmd; Util.Log(string.Format("Running remote command: {0} {1}{2}", psexecPath, Util.HidePsexecPassword(psexecAllArgs), Environment.NewLine)); if (!Util.StartProcess(psexecPath, psexecAllArgs, Util.LogFile == null, null, false, false, false, out proc)) { throw new AssertionException("Failed to start the launcher."); } if (!unitProc.m_clientEvent.WaitOne(90000, false)) { throw new AssertionException("Timed out waiting for launcher: " + clientId); } newProcCreated = true; } unitProc.m_clientComm = (IClientComm)ServerConnection<IClientCommV2>.Connect("tcp://" + hostName + ':' + launcherPort + '/' + CommConstants.ClientService); unitProc.m_process = unitProc.m_clientComm.GetClientProcess(); unitProc.m_psexecPath = psexecPath; unitProc.m_psexecArgs = psexecArgs; unitProc.m_hostName = hostName; unitProc.m_timeout = false; unitProc.m_exiting = false; unitProc.m_sharePath = sharePath; unitProc.m_shareName = shareName; unitProc.m_startDir = startDir; if (newProcCreated) { logPath += "/" + "Launcher" + "_" + hostName + "_" + clientId + ".log"; Util.Log("Launcher log path {0}", logPath); unitProc.SetLogLevel(Util.CurrentLogLevel); unitProc.SetLogFile(logPath); } } catch (Exception ex) { throw new AssertionException(string.Format("FATAL: Could not start " + "launcher: {1}{0}\ton host: {2}{0}" + "\tException: {3}", Environment.NewLine, clientProcPath, hostName, ex)); } return unitProc; } return null; } #endregion #region ClientBase Members public override void RemoveObjectID(int objectID) { if (m_clientComm != null) { m_clientComm.RemoveObjectID(objectID); } } public override void CallFn(Delegate deleg, object[] paramList) { string assemblyName, typeName, methodName; int objectId; ClientBase.GetDelegateInfo(deleg, out assemblyName, out typeName, out methodName, out objectId); Exception callEx = null; for (int numTries = 1; numTries <= 5; numTries++) { if (m_clientComm != null) { try { m_clientComm.Call(objectId, assemblyName, typeName, methodName, paramList); return; } catch (Exception ex) { callEx = ex; if (m_exiting) { throw new ClientExitedException("Process exited while calling '." + deleg.Method.ToString() + '\''); } else if (m_timeout) { throw new ClientTimeoutException("Timeout occured while calling '" + deleg.Method.ToString() + '\''); } else if (ex is RemotingException || ex is System.Net.Sockets.SocketException) { Thread.Sleep(numTries * 1000); } else { break; } } } } if (callEx != null) { throw callEx; } } public override object CallFnR(Delegate deleg, object[] paramList) { string assemblyName, typeName, methodName; int objectId; ClientBase.GetDelegateInfo(deleg, out assemblyName, out typeName, out methodName, out objectId); Exception callEx = null; for (int numTries = 1; numTries <= 5; numTries++) { if (m_clientComm != null) { try { return m_clientComm.CallR(objectId, assemblyName, typeName, methodName, paramList); } catch (Exception ex) { callEx = ex; if (m_exiting) { throw new ClientExitedException("Process exited while calling '." + deleg.Method.ToString() + '\''); } else if (m_timeout) { throw new ClientTimeoutException("Timeout occured while calling '" + deleg.Method.ToString() + '\''); } else if (ex is RemotingException || ex is System.Net.Sockets.SocketException) { Thread.Sleep(numTries * 1000); } else { break; } } } } if (callEx != null) { throw callEx; } return null; } public override string HostName { get { return (m_hostName == null ? "localhost" : m_hostName); } } /// <summary> /// Set the log file for the client. /// </summary> /// <param name="logPath">The path of the log file.</param> public override void SetLogFile(string logPath) { if (m_clientComm != null) { m_clientComm.SetLogFile(logPath); } } /// <summary> /// Set logging level for the client. /// </summary> /// <param name="logLevel">The logging level to set.</param> public override void SetLogLevel(Util.LogLevel logLevel) { if (m_clientComm != null) { m_clientComm.SetLogLevel(logLevel); } } public override void DumpStackTrace() { if (m_clientComm != null) { m_clientComm.DumpStackTrace(); } } public override void ForceKill(int waitMillis) { if (m_clientComm != null) { m_timeout = true; Util.Log("Forcing kill for client {0}", this.ID); ExitClient(waitMillis, true); Util.Log("Done kill for client {0}", this.ID); } } public override ClientBase CreateNew(string clientId) { UnitProcess newProc; if (clientId == null) { clientId = GetClientId().ToString(); } if (m_sshPath != null) { int clientPort = GetClientPort(); m_clientEvent.Reset(); lock (((ICollection)ProcessIDMap).SyncRoot) { ProcessIDMap[clientId] = m_clientEvent; } if (!m_clientComm.CreateNew(clientId, clientPort)) { throw new AssertionException("FATAL: Could not start client: " + ClientProcName); } if (!m_clientEvent.WaitOne(MaxStartWaitMillis, false)) { throw new AssertionException("FATAL: Timed out waiting for client to start: " + ClientProcName); } newProc = new UnitProcess(clientId); newProc.m_sshPath = m_sshPath; newProc.m_sshArgs = m_sshArgs; newProc.m_hostName = m_hostName; newProc.m_clientComm = ServerConnection<IClientComm>.Connect("tcp://" + m_hostName + ':' + clientPort + '/' + CommConstants.ClientService); newProc.m_process = newProc.m_clientComm.GetClientProcess(); newProc.m_timeout = false; newProc.m_exiting = false; newProc.m_sharePath = m_sharePath; newProc.m_shareName = m_shareName; newProc.m_startDir = m_startDir; newProc.m_envs = m_envs; } else { newProc = new UnitProcess(clientId, m_startDir); } return newProc; } public override void TestCleanup() { if (m_clientComm != null) { m_clientComm.TestCleanup(); } } public override void Exit() { if (m_clientComm != null) { m_exiting = true; ExitClient(MaxEndWaitMillis, false); } } #endregion } }
using System.Collections; using System.Globalization; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.Asn1.TeleTrust { /** * elliptic curves defined in "ECC Brainpool Standard Curves and Curve Generation" * http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt */ public class TeleTrusTNamedCurves { internal class BrainpoolP160r1Holder : X9ECParametersHolder { private BrainpoolP160r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP160r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620F", 16), // q new BigInteger("340E7BE2A280EB74E2BE61BADA745D97E8F7C300", 16), // a new BigInteger("1E589A8595423412134FAA2DBDEC95C8D8675E58", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04BED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC31667CB477A1A8EC338F94741669C976316DA6321")), // G new BigInteger("E95E4A5F737059DC60DF5991D45029409E60FC09", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP160t1Holder : X9ECParametersHolder { private BrainpoolP160t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP160t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( // new BigInteger("24DBFF5DEC9B986BBFE5295A29BFBAE45E0F5D0B", 16), // Z new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620F", 16), // q new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620C", 16), // a' new BigInteger("7A556B6DAE535B7B51ED2C4D7DAA7A0B5C55F380", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04B199B13B9B34EFC1397E64BAEB05ACC265FF2378ADD6718B7C7C1961F0991B842443772152C9E0AD")), // G new BigInteger("E95E4A5F737059DC60DF5991D45029409E60FC09", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP192r1Holder : X9ECParametersHolder { private BrainpoolP192r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP192r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", 16), // q new BigInteger("6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF", 16), // a new BigInteger("469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04C0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD614B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F")), // G new BigInteger("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP192t1Holder : X9ECParametersHolder { private BrainpoolP192t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP192t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( //new BigInteger("1B6F5CC8DB4DC7AF19458A9CB80DC2295E5EB9C3732104CB") //Z new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", 16), // q new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86294", 16), // a' new BigInteger("13D56FFAEC78681E68F9DEB43B35BEC2FB68542E27897B79", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("043AE9E58C82F63C30282E1FE7BBF43FA72C446AF6F4618129097E2C5667C2223A902AB5CA449D0084B7E5B3DE7CCC01C9")), // G' new BigInteger("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP224r1Holder : X9ECParametersHolder { private BrainpoolP224r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP224r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", 16), // q new BigInteger("68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43", 16), // a new BigInteger("2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("040D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD")), // G new BigInteger("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", 16), //n new BigInteger("01", 16)); // n } } internal class BrainpoolP224t1Holder : X9ECParametersHolder { private BrainpoolP224t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP224t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( //new BigInteger("2DF271E14427A346910CF7A2E6CFA7B3F484E5C2CCE1C8B730E28B3F") //Z new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", 16), // q new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FC", 16), // a' new BigInteger("4B337D934104CD7BEF271BF60CED1ED20DA14C08B3BB64F18A60888D", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("046AB1E344CE25FF3896424E7FFE14762ECB49F8928AC0C76029B4D5800374E9F5143E568CD23F3F4D7C0D4B1E41C8CC0D1C6ABD5F1A46DB4C")), // G' new BigInteger("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP256r1Holder : X9ECParametersHolder { private BrainpoolP256r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP256r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16), // q new BigInteger("7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9", 16), // a new BigInteger("26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997")), // G new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP256t1Holder : X9ECParametersHolder { private BrainpoolP256t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP256t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( //new BigInteger("3E2D4BD9597B58639AE7AA669CAB9837CF5CF20A2C852D10F655668DFC150EF0") //Z new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16), // q new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5374", 16), // a' new BigInteger("662C61C430D84EA4FE66A7733D0B76B7BF93EBC4AF2F49256AE58101FEE92B04", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04A3E8EB3CC1CFE7B7732213B23A656149AFA142C47AAFBC2B79A191562E1305F42D996C823439C56D7F7B22E14644417E69BCB6DE39D027001DABE8F35B25C9BE")), // G' new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP320r1Holder : X9ECParametersHolder { private BrainpoolP320r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP320r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", 16), // q new BigInteger("3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9F492F375A97D860EB4", 16), // a new BigInteger("520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539816F5EB4AC8FB1F1A6", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("0443BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599C710AF8D0D39E2061114FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6AC7D35245D1692E8EE1")), // G new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP320t1Holder : X9ECParametersHolder { private BrainpoolP320t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP320t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( //new BigInteger("15F75CAF668077F7E85B42EB01F0A81FF56ECD6191D55CB82B7D861458A18FEFC3E5AB7496F3C7B1") //Z new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", 16), // q new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E24", 16), // a' new BigInteger("A7F561E038EB1ED560B3D147DB782013064C19F27ED27C6780AAF77FB8A547CEB5B4FEF422340353", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04925BE9FB01AFC6FB4D3E7D4990010F813408AB106C4F09CB7EE07868CC136FFF3357F624A21BED5263BA3A7A27483EBF6671DBEF7ABB30EBEE084E58A0B077AD42A5A0989D1EE71B1B9BC0455FB0D2C3")), // G' new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP384r1Holder : X9ECParametersHolder { private BrainpoolP384r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP384r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16), // q new BigInteger("7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826", 16), // a new BigInteger("4A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("041D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315")), // G new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP384t1Holder : X9ECParametersHolder { private BrainpoolP384t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP384t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( //new BigInteger("41DFE8DD399331F7166A66076734A89CD0D2BCDB7D068E44E1F378F41ECBAE97D2D63DBC87BCCDDCCC5DA39E8589291C") //Z new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16), // q new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC50", 16), // a' new BigInteger("7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE1D2074AA263B88805CED70355A33B471EE", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("0418DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AABFFC4FF191B946A5F54D8D0AA2F418808CC25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CCFE469408584DC2B2912675BF5B9E582928")), // G' new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP512r1Holder : X9ECParametersHolder { private BrainpoolP512r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP512r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16), // q new BigInteger("7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA", 16), // a new BigInteger("3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("0481AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F8227DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892")), // G new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP512t1Holder : X9ECParametersHolder { private BrainpoolP512t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP512t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FPCurve( //new BigInteger("12EE58E6764838B69782136F0F2D3BA06E27695716054092E60A80BEDB212B64E585D90BCE13761F85C3F1D2A64E3BE8FEA2220F01EBA5EEB0F35DBD29D922AB") //Z new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16), // q new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F0", 16), // a' new BigInteger("7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36A62BCDFA2304976540F6450085F2DAE145C22553B465763689180EA2571867423E", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C0313D82BA51735CDB3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CEE9D9932184BEEF216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332")), // G' new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16), //n new BigInteger("01", 16)); // h } } private static readonly IDictionary objIds = Platform.CreateHashtable(); private static readonly IDictionary curves = Platform.CreateHashtable(); private static readonly IDictionary names = Platform.CreateHashtable(); private static void DefineCurve( string name, DerObjectIdentifier oid, X9ECParametersHolder holder) { objIds.Add(name, oid); names.Add(oid, name); curves.Add(oid, holder); } static TeleTrusTNamedCurves() { DefineCurve("brainpoolp160r1", TeleTrusTObjectIdentifiers.BrainpoolP160R1, BrainpoolP160r1Holder.Instance); DefineCurve("brainpoolp160t1", TeleTrusTObjectIdentifiers.BrainpoolP160T1, BrainpoolP160t1Holder.Instance); DefineCurve("brainpoolp192r1", TeleTrusTObjectIdentifiers.BrainpoolP192R1, BrainpoolP192r1Holder.Instance); DefineCurve("brainpoolp192t1", TeleTrusTObjectIdentifiers.BrainpoolP192T1, BrainpoolP192t1Holder.Instance); DefineCurve("brainpoolp224r1", TeleTrusTObjectIdentifiers.BrainpoolP224R1, BrainpoolP224r1Holder.Instance); DefineCurve("brainpoolp224t1", TeleTrusTObjectIdentifiers.BrainpoolP224T1, BrainpoolP224t1Holder.Instance); DefineCurve("brainpoolp256r1", TeleTrusTObjectIdentifiers.BrainpoolP256R1, BrainpoolP256r1Holder.Instance); DefineCurve("brainpoolp256t1", TeleTrusTObjectIdentifiers.BrainpoolP256T1, BrainpoolP256t1Holder.Instance); DefineCurve("brainpoolp320r1", TeleTrusTObjectIdentifiers.BrainpoolP320R1, BrainpoolP320r1Holder.Instance); DefineCurve("brainpoolp320t1", TeleTrusTObjectIdentifiers.BrainpoolP320T1, BrainpoolP320t1Holder.Instance); DefineCurve("brainpoolp384r1", TeleTrusTObjectIdentifiers.BrainpoolP384R1, BrainpoolP384r1Holder.Instance); DefineCurve("brainpoolp384t1", TeleTrusTObjectIdentifiers.BrainpoolP384T1, BrainpoolP384t1Holder.Instance); DefineCurve("brainpoolp512r1", TeleTrusTObjectIdentifiers.BrainpoolP512R1, BrainpoolP512r1Holder.Instance); DefineCurve("brainpoolp512t1", TeleTrusTObjectIdentifiers.BrainpoolP512T1, BrainpoolP512t1Holder.Instance); } public static X9ECParameters GetByName( string name) { DerObjectIdentifier oid = (DerObjectIdentifier) objIds[Platform.StringToLower(name)]; return oid == null ? null : GetByOid(oid); } /** * return the X9ECParameters object for the named curve represented by * the passed in object identifier. Null if the curve isn't present. * * @param oid an object identifier representing a named curve, if present. */ public static X9ECParameters GetByOid( DerObjectIdentifier oid) { X9ECParametersHolder holder = (X9ECParametersHolder) curves[oid]; return holder == null ? null : holder.Parameters; } /** * return the object identifier signified by the passed in name. Null * if there is no object identifier associated with name. * * @return the object identifier associated with name, if present. */ public static DerObjectIdentifier GetOid( string name) { return (DerObjectIdentifier) objIds[Platform.StringToLower(name)]; } /** * return the named curve name represented by the given object identifier. */ public static string GetName( DerObjectIdentifier oid) { return (string) names[oid]; } /** * returns an enumeration containing the name strings for curves * contained in this structure. */ public static IEnumerable Names { get { return new EnumerableProxy(objIds.Keys); } } public static DerObjectIdentifier GetOid( short curvesize, bool twisted) { return GetOid("brainpoolP" + curvesize + (twisted ? "t" : "r") + "1"); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the datapipeline-2012-10-29.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.DataPipeline.Model; namespace Amazon.DataPipeline { /// <summary> /// Interface for accessing DataPipeline /// /// AWS Data Pipeline configures and manages a data-driven workflow called a pipeline. /// AWS Data Pipeline handles the details of scheduling and ensuring that data dependencies /// are met so that your application can focus on processing the data. /// /// /// <para> /// AWS Data Pipeline provides a JAR implementation of a task runner called AWS Data Pipeline /// Task Runner. AWS Data Pipeline Task Runner provides logic for common data management /// scenarios, such as performing database queries and running data analysis using Amazon /// Elastic MapReduce (Amazon EMR). You can use AWS Data Pipeline Task Runner as your /// task runner, or you can write your own task runner to provide custom data management. /// </para> /// /// <para> /// AWS Data Pipeline implements two main sets of functionality. Use the first set to /// create a pipeline and define data sources, schedules, dependencies, and the transforms /// to be performed on the data. Use the second set in your task runner application to /// receive the next task ready for processing. The logic for performing the task, such /// as querying the data, running data analysis, or converting the data from one format /// to another, is contained within the task runner. The task runner performs the task /// assigned to it by the web service, reporting progress to the web service as it does /// so. When the task is done, the task runner reports the final success or failure of /// the task to the web service. /// </para> /// </summary> public partial interface IAmazonDataPipeline : IDisposable { #region ActivatePipeline /// <summary> /// Initiates the asynchronous execution of the ActivatePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ActivatePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ActivatePipelineResponse> ActivatePipelineAsync(ActivatePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region AddTags /// <summary> /// Adds or modifies tags for the specified pipeline. /// </summary> /// <param name="pipelineId">The ID of the pipeline.</param> /// <param name="tags">The tags to add, as key/value pairs.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the AddTags service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> Task<AddTagsResponse> AddTagsAsync(string pipelineId, List<Tag> tags, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the AddTags operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AddTags operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<AddTagsResponse> AddTagsAsync(AddTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreatePipeline /// <summary> /// Initiates the asynchronous execution of the CreatePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreatePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreatePipelineResponse> CreatePipelineAsync(CreatePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeactivatePipeline /// <summary> /// Initiates the asynchronous execution of the DeactivatePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeactivatePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeactivatePipelineResponse> DeactivatePipelineAsync(DeactivatePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeletePipeline /// <summary> /// Initiates the asynchronous execution of the DeletePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeletePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeletePipelineResponse> DeletePipelineAsync(DeletePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeObjects /// <summary> /// Initiates the asynchronous execution of the DescribeObjects operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeObjects operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeObjectsResponse> DescribeObjectsAsync(DescribeObjectsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribePipelines /// <summary> /// Retrieves metadata about one or more pipelines. The information retrieved includes /// the name of the pipeline, the pipeline identifier, its current state, and the user /// account that owns the pipeline. Using account credentials, you can retrieve metadata /// about pipelines that you or your IAM users have created. If you are using an IAM user /// account, you can retrieve metadata about only those pipelines for which you have read /// permissions. /// /// /// <para> /// To retrieve the full pipeline definition instead of metadata about the pipeline, call /// <a>GetPipelineDefinition</a>. /// </para> /// </summary> /// <param name="pipelineIds">The IDs of the pipelines to describe. You can pass as many as 25 identifiers in a single call. To obtain pipeline IDs, call <a>ListPipelines</a>.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribePipelines service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> Task<DescribePipelinesResponse> DescribePipelinesAsync(List<string> pipelineIds, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribePipelines operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribePipelines operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribePipelinesResponse> DescribePipelinesAsync(DescribePipelinesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region EvaluateExpression /// <summary> /// Initiates the asynchronous execution of the EvaluateExpression operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the EvaluateExpression operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<EvaluateExpressionResponse> EvaluateExpressionAsync(EvaluateExpressionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetPipelineDefinition /// <summary> /// Initiates the asynchronous execution of the GetPipelineDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetPipelineDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetPipelineDefinitionResponse> GetPipelineDefinitionAsync(GetPipelineDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListPipelines /// <summary> /// Lists the pipeline identifiers for all active pipelines that you have permission to /// access. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListPipelines service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> Task<ListPipelinesResponse> ListPipelinesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the ListPipelines operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListPipelines operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListPipelinesResponse> ListPipelinesAsync(ListPipelinesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PollForTask /// <summary> /// Initiates the asynchronous execution of the PollForTask operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PollForTask operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PollForTaskResponse> PollForTaskAsync(PollForTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutPipelineDefinition /// <summary> /// Initiates the asynchronous execution of the PutPipelineDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutPipelineDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutPipelineDefinitionResponse> PutPipelineDefinitionAsync(PutPipelineDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region QueryObjects /// <summary> /// Initiates the asynchronous execution of the QueryObjects operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the QueryObjects operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<QueryObjectsResponse> QueryObjectsAsync(QueryObjectsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RemoveTags /// <summary> /// Removes existing tags from the specified pipeline. /// </summary> /// <param name="pipelineId">The ID of the pipeline.</param> /// <param name="tagKeys">The keys of the tags to remove.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the RemoveTags service method, as returned by DataPipeline.</returns> /// <exception cref="Amazon.DataPipeline.Model.InternalServiceErrorException"> /// An internal service error occurred. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.InvalidRequestException"> /// The request was not valid. Verify that your request was properly formatted, that the /// signature was generated with the correct credentials, and that you haven't exceeded /// any of the service limits for your account. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineDeletedException"> /// The specified pipeline has been deleted. /// </exception> /// <exception cref="Amazon.DataPipeline.Model.PipelineNotFoundException"> /// The specified pipeline was not found. Verify that you used the correct user and account /// identifiers. /// </exception> Task<RemoveTagsResponse> RemoveTagsAsync(string pipelineId, List<string> tagKeys, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the RemoveTags operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RemoveTags operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RemoveTagsResponse> RemoveTagsAsync(RemoveTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ReportTaskProgress /// <summary> /// Initiates the asynchronous execution of the ReportTaskProgress operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReportTaskProgress operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ReportTaskProgressResponse> ReportTaskProgressAsync(ReportTaskProgressRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ReportTaskRunnerHeartbeat /// <summary> /// Initiates the asynchronous execution of the ReportTaskRunnerHeartbeat operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReportTaskRunnerHeartbeat operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ReportTaskRunnerHeartbeatResponse> ReportTaskRunnerHeartbeatAsync(ReportTaskRunnerHeartbeatRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetStatus /// <summary> /// Initiates the asynchronous execution of the SetStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetStatusResponse> SetStatusAsync(SetStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetTaskStatus /// <summary> /// Initiates the asynchronous execution of the SetTaskStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetTaskStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetTaskStatusResponse> SetTaskStatusAsync(SetTaskStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ValidatePipelineDefinition /// <summary> /// Initiates the asynchronous execution of the ValidatePipelineDefinition operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ValidatePipelineDefinition operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ValidatePipelineDefinitionResponse> ValidatePipelineDefinitionAsync(ValidatePipelineDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
using WPAppStudio.Entities.Base; using WPAppStudio.Localization; using WPAppStudio.Services.Interfaces; using Microsoft.Phone.Controls; using Microsoft.Phone.Tasks; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Media.PhoneExtensions; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Windows; using System.Windows.Resources; namespace WPAppStudio.Services { /// <summary> /// Implementation of the Share service. /// </summary> public class ShareService : IShareService { private IProximityService _proximityService; private enum ShareTypeEnum { TapSend, ShareLink, ShareImage, ShareStatus, ShareByEmail } public const string IMAGES = "Images/"; public ShareService(IProximityService proximityService) { _proximityService = proximityService; } /// <summary> /// Executes the Share service. /// </summary> /// <param name="title">The title shared.</param> /// <param name="message">The message shared.</param> /// <param name="link">The link shared.</param> /// <param name="type">The image shared.</param> public void Share(string title, string message, string link = "", string image = "") { var availableShareTypes = GetAvailableShareTypes(title, message, link, image); OpenShareTypeSelector(availableShareTypes, title, message, link, image); } /// <summary> /// Check if current app exist in marketplace. /// </summary> public bool AppExistInMarketPlace() { var result = false; try { var link = Windows.ApplicationModel.Store.CurrentApp.LinkUri; WebClient client = new WebClient(); client.OpenReadCompleted += (s, e) => { if (e.Error == null) { result = true; } }; client.OpenReadAsync(link); } catch { } return result; } private List<ShareTypeEnum> GetAvailableShareTypes(string title, string message, string link = "", string image = "") { var result = new List<ShareTypeEnum>(); if (Uri.IsWellFormedUriString(link, UriKind.Absolute) && _proximityService.IsProximityAvailable) result.Add(ShareTypeEnum.TapSend); if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(message) && Uri.IsWellFormedUriString(link, UriKind.Absolute)) result.Add(ShareTypeEnum.ShareLink); if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(message)) result.Add(ShareTypeEnum.ShareByEmail); // Commenting out because this seems to not be working //if (!string.IsNullOrEmpty(image) // && IsValidMedia(image)) // result.Add(ShareTypeEnum.ShareImage); // End commenting // Commenting out because I don't want the Share Status to be there. Only link //if (!string.IsNullOrEmpty(title) // || !string.IsNullOrEmpty(message)) // result.Add(ShareTypeEnum.ShareStatus); // End commenting return result; } private void OpenShareTypeSelector(List<ShareTypeEnum> availableShareTypes, string title, string message, string link = "", string image = "") { var listSelector = new System.Windows.Controls.ListBox { ItemsSource = availableShareTypes, ItemTemplate = App.Current.Resources["SelectorItemTemplate"] as DataTemplate }; listSelector.SelectionChanged += (sender, e) => { var selectedItem = (ShareTypeEnum)e.AddedItems[0]; switch (selectedItem) { case ShareTypeEnum.TapSend: _proximityService.ShareUri(link); break; case ShareTypeEnum.ShareLink: ShareLink(title, message, link); break; case ShareTypeEnum.ShareImage: ShareMedia(image); break; //case ShareTypeEnum.ShareStatus: // ShareStatus(string.IsNullOrEmpty(message) ? title : message); // break; case ShareTypeEnum.ShareByEmail: ShareByEmail(title, message, link); break; default: break; } }; var customMessageBox = new CustomMessageBox { Message = AppResources.ShareMessage, Content = listSelector, IsLeftButtonEnabled = false, IsRightButtonEnabled = false, IsFullScreen = true }; customMessageBox.Show(); } /// <summary> /// Executes the Share Link service. /// </summary> /// <param name="title">The title shared.</param> /// <param name="message">The message shared.</param> /// <param name="link">The link shared.</param> private void ShareLink(string title, string message, string link = "") { title = string.IsNullOrEmpty(title) ? string.Empty : HtmlUtil.CleanHtml(title); message = string.IsNullOrEmpty(message) ? string.Empty : HtmlUtil.CleanHtml(message); var linkUri = string.IsNullOrEmpty(link) ? new System.Uri(AppResources.HomeUrl) : new System.Uri(link, System.UriKind.Absolute); var shareLinkTask = new ShareLinkTask { Title = title, Message = title + " // via @GadgtSpot", LinkUri = linkUri }; shareLinkTask.Show(); } /// <summary> /// Executes the Share Status service. /// </summary> /// <param name="status">The status to share.</param> //private void ShareStatus(string status) //{ // ShareStatusTask shareStatusTask = new ShareStatusTask(); // shareStatusTask.Status = status; // shareStatusTask.Show(); //} /// <summary> /// Executes the Compose Mail service. /// </summary> /// <param name="subject">The message subject.</param> /// <param name="body">The message body.</param> /// <param name="to">The email of the recipient.</param> private void ShareByEmail(string subject, string body, string link = "") { EmailComposeTask emailComposeTask = new EmailComposeTask(); emailComposeTask.Subject = subject; if (string.IsNullOrEmpty(link)) emailComposeTask.Body = body; else emailComposeTask.Body = string.Format("{0}{1}{1}{2}{1}{1}Sent via the GadgtSpot.com Windows Phone app. Get it here <insert url to app>", subject, Environment.NewLine, link); emailComposeTask.Show(); } /// <summary> /// Executes the Share Media service. /// </summary> /// <param name="media">The media to share.</param> private void ShareMedia(string media) { if (media.StartsWith("http")) DownloadToMediaLibraryAndShare(media); else SaveToMediaLibraryAndShare(media); } private bool IsValidMedia(string media) { return media.StartsWith("http") || GetLocalResource(media) != null; } private StreamResourceInfo GetLocalResource(string media) { var uri = new Uri(IMAGES + Path.GetFileName(media), UriKind.RelativeOrAbsolute); return App.GetResourceStream(uri); } private void DownloadToMediaLibraryAndShare(string media) { try { WebClient client = new WebClient(); client.OpenReadCompleted += (s, e) => { if (e.Error == null) { var picture = SaveToMediaLibrary(media, e.Result); Share(picture.GetPath()); } }; client.OpenReadAsync(new Uri(media, UriKind.Absolute)); } catch (Exception ex) { Debug.WriteLine("{0} {1}", AppResources.Error, ex.ToString()); } } private void SaveToMediaLibraryAndShare(string media) { try { var resource = GetLocalResource(media); if (resource != null) { using (var stream = resource.Stream) { var picture = SaveToMediaLibrary(media, stream); Share(picture.GetPath()); } } } catch (Exception ex) { Debug.WriteLine("{0} {1}", AppResources.Error, ex.ToString()); } } private Picture SaveToMediaLibrary(string media, Stream stream) { MediaLibrary library = new MediaLibrary(); var picture = library.SavePicture(Path.GetFileName(media), stream); return picture; } private void Share(string media) { ShareMediaTask mediaTask = new ShareMediaTask(); mediaTask.FilePath = media; mediaTask.Show(); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapSearchRequest.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.Ldap.Asn1; using Novell.Directory.Ldap.Rfc2251; namespace Novell.Directory.Ldap { /// <summary> Represents an Ldap Search request. /// /// </summary> /// <seealso cref="LdapConnection.SendRequest"> /// </seealso> /* * SearchRequest ::= [APPLICATION 3] SEQUENCE { * baseObject LdapDN, * scope ENUMERATED { * baseObject (0), * singleLevel (1), * wholeSubtree (2) }, * derefAliases ENUMERATED { * neverDerefAliases (0), * derefInSearching (1), * derefFindingBaseObj (2), * derefAlways (3) }, * sizeLimit INTEGER (0 .. maxInt), * timeLimit INTEGER (0 .. maxInt), * typesOnly BOOLEAN, * filter Filter, * attributes AttributeDescriptionList } */ public class LdapSearchRequest:LdapMessage { /// <summary> Retrieves the Base DN for a search request. /// /// </summary> /// <returns> the base DN for a search request /// </returns> virtual public System.String DN { get { return Asn1Object.RequestDN; } } /// <summary> Retrieves the scope of a search request.</summary> /// <returns> scope of a search request /// /// </returns> /// <seealso cref="Novell.Directory.Ldap.LdapConnection.SCOPE_BASE"> /// </seealso> /// <seealso cref="Novell.Directory.Ldap.LdapConnection.SCOPE_ONE"> /// </seealso> /// <seealso cref="Novell.Directory.Ldap.LdapConnection.SCOPE_SUB"> /// </seealso> virtual public int Scope { get { //element number one stores the scope return ((Asn1Enumerated) ((RfcSearchRequest) (this.Asn1Object).get_Renamed(1)).get_Renamed(1)).intValue(); } } /// <summary> Retrieves the behaviour of dereferencing aliases on a search request.</summary> /// <returns> integer representing how to dereference aliases /// /// </returns> /// <seealso cref="Novell.Directory.Ldap.LdapSearchConstraints.DEREF_ALWAYS"> /// </seealso> /// <seealso cref="Novell.Directory.Ldap.LdapSearchConstraints.DEREF_FINDING"> /// </seealso> /// <seealso cref="Novell.Directory.Ldap.LdapSearchConstraints.DEREF_NEVER"> /// </seealso> /// <seealso cref="Novell.Directory.Ldap.LdapSearchConstraints.DEREF_SEARCHING"> /// </seealso> virtual public int Dereference { get { //element number two stores the dereference return ((Asn1Enumerated) ((RfcSearchRequest) (this.Asn1Object).get_Renamed(1)).get_Renamed(2)).intValue(); } } /// <summary> Retrieves the maximum number of entries to be returned on a search. /// /// </summary> /// <returns> Maximum number of search entries. /// </returns> virtual public int MaxResults { get { //element number three stores the max results return ((Asn1Integer) ((RfcSearchRequest) (this.Asn1Object).get_Renamed(1)).get_Renamed(3)).intValue(); } } /// <summary> Retrieves the server time limit for a search request. /// /// </summary> /// <returns> server time limit in nanoseconds. /// </returns> virtual public int ServerTimeLimit { get { //element number four stores the server time limit return ((Asn1Integer) ((RfcSearchRequest) (this.Asn1Object).get_Renamed(1)).get_Renamed(4)).intValue(); } } /// <summary> Retrieves whether attribute values or only attribute types(names) should /// be returned in a search request. /// </summary> /// <returns> true if only attribute types (names) are returned, false if /// attributes types and values are to be returned. /// </returns> virtual public bool TypesOnly { get { //element number five stores types value return ((Asn1Boolean) ((RfcSearchRequest) (this.Asn1Object).get_Renamed(1)).get_Renamed(5)).booleanValue(); } } /// <summary> Retrieves an array of attribute names to request for in a search.</summary> /// <returns> Attribute names to be searched /// </returns> virtual public System.String[] Attributes { get { RfcAttributeDescriptionList attrs = (RfcAttributeDescriptionList) ((RfcSearchRequest) (this.Asn1Object).get_Renamed(1)).get_Renamed(7); System.String[] rAttrs = new System.String[attrs.size()]; for (int i = 0; i < rAttrs.Length; i++) { rAttrs[i] = ((RfcAttributeDescription) attrs.get_Renamed(i)).stringValue(); } return rAttrs; } } /// <summary> Creates a string representation of the filter in this search request.</summary> /// <returns> filter string for this search request /// </returns> virtual public System.String StringFilter { get { return this.RfcFilter.filterToString(); } } /// <summary> Retrieves an SearchFilter object representing a filter for a search request</summary> /// <returns> filter object for a search request. /// </returns> private RfcFilter RfcFilter { get { return (RfcFilter) ((RfcSearchRequest) (this.Asn1Object).get_Renamed(1)).get_Renamed(6); } } /// <summary> Retrieves an Iterator object representing the parsed filter for /// this search request. /// /// The first object returned from the Iterator is an Integer indicating /// the type of filter component. One or more values follow the component /// type as subsequent items in the Iterator. The pattern of Integer /// component type followed by values continues until the end of the /// filter. /// /// Values returned as a byte array may represent UTF-8 characters or may /// be binary values. The possible Integer components of a search filter /// and the associated values that follow are: /// <ul> /// <li>AND - followed by an Iterator value</li> /// <li>OR - followed by an Iterator value</li> /// <li>NOT - followed by an Iterator value</li> /// <li>EQUALITY_MATCH - followed by the attribute name represented as a /// String, and by the attribute value represented as a byte array</li> /// <li>GREATER_OR_EQUAL - followed by the attribute name represented as a /// String, and by the attribute value represented as a byte array</li> /// <li>LESS_OR_EQUAL - followed by the attribute name represented as a /// String, and by the attribute value represented as a byte array</li> /// <li>APPROX_MATCH - followed by the attribute name represented as a /// String, and by the attribute value represented as a byte array</li> /// <li>PRESENT - followed by a attribute name respresented as a String</li> /// <li>EXTENSIBLE_MATCH - followed by the name of the matching rule /// represented as a String, by the attribute name represented /// as a String, and by the attribute value represented as a /// byte array.</li> /// <li>SUBSTRINGS - followed by the attribute name represented as a /// String, by one or more SUBSTRING components (INITIAL, ANY, /// or FINAL) followed by the SUBSTRING value.</li> /// </ul> /// /// </summary> /// <returns> Iterator representing filter components /// </returns> virtual public System.Collections.IEnumerator SearchFilter { get { return RfcFilter.getFilterIterator(); } } //************************************************************************* // Public variables for Filter //************************************************************************* /// <summary> Search Filter Identifier for an AND component.</summary> public const int AND = 0; /// <summary> Search Filter Identifier for an OR component.</summary> public const int OR = 1; /// <summary> Search Filter Identifier for a NOT component.</summary> public const int NOT = 2; /// <summary> Search Filter Identifier for an EQUALITY_MATCH component.</summary> public const int EQUALITY_MATCH = 3; /// <summary> Search Filter Identifier for a SUBSTRINGS component.</summary> public const int SUBSTRINGS = 4; /// <summary> Search Filter Identifier for a GREATER_OR_EQUAL component.</summary> public const int GREATER_OR_EQUAL = 5; /// <summary> Search Filter Identifier for a LESS_OR_EQUAL component.</summary> public const int LESS_OR_EQUAL = 6; /// <summary> Search Filter Identifier for a PRESENT component.</summary> public const int PRESENT = 7; /// <summary> Search Filter Identifier for an APPROX_MATCH component.</summary> public const int APPROX_MATCH = 8; /// <summary> Search Filter Identifier for an EXTENSIBLE_MATCH component.</summary> public const int EXTENSIBLE_MATCH = 9; /// <summary> Search Filter Identifier for an INITIAL component of a SUBSTRING. /// Note: An initial SUBSTRING is represented as "value*". /// </summary> public const int INITIAL = 0; /// <summary> Search Filter Identifier for an ANY component of a SUBSTRING. /// Note: An ANY SUBSTRING is represented as "*value*". /// </summary> public const int ANY = 1; /// <summary> Search Filter Identifier for a FINAL component of a SUBSTRING. /// Note: A FINAL SUBSTRING is represented as "*value". /// </summary> public const int FINAL = 2; /// <summary> Constructs an Ldap Search Request. /// /// </summary> /// <param name="base"> The base distinguished name to search from. /// /// </param> /// <param name="scope"> The scope of the entries to search. The following /// are the valid options: /// <ul> /// <li>SCOPE_BASE - searches only the base DN</li> /// /// <li>SCOPE_ONE - searches only entries under the base DN</li> /// /// <li>SCOPE_SUB - searches the base DN and all entries /// within its subtree</li> /// </ul> /// </param> /// <param name="filter"> The search filter specifying the search criteria. /// /// </param> /// <param name="attrs"> The names of attributes to retrieve. /// operation exceeds the time limit. /// /// </param> /// <param name="dereference">Specifies when aliases should be dereferenced. /// Must be one of the constants defined in /// LdapConstraints, which are DEREF_NEVER, /// DEREF_FINDING, DEREF_SEARCHING, or DEREF_ALWAYS. /// /// </param> /// <param name="maxResults">The maximum number of search results to return /// for a search request. /// The search operation will be terminated by the server /// with an LdapException.SIZE_LIMIT_EXCEEDED if the /// number of results exceed the maximum. /// /// </param> /// <param name="serverTimeLimit">The maximum time in seconds that the server /// should spend returning search results. This is a /// server-enforced limit. A value of 0 means /// no time limit. /// /// </param> /// <param name="typesOnly"> If true, returns the names but not the values of /// the attributes found. If false, returns the /// names and values for attributes found. /// /// </param> /// <param name="cont"> Any controls that apply to the search request. /// or null if none. /// /// </param> /// <seealso cref="Novell.Directory.Ldap.LdapConnection.Search"> /// </seealso> /// <seealso cref="Novell.Directory.Ldap.LdapSearchConstraints"> /// </seealso> public LdapSearchRequest(System.String base_Renamed, int scope, System.String filter, System.String[] attrs, int dereference, int maxResults, int serverTimeLimit, bool typesOnly, LdapControl[] cont):base(LdapMessage.SEARCH_REQUEST, new RfcSearchRequest(new RfcLdapDN(base_Renamed), new Asn1Enumerated(scope), new Asn1Enumerated(dereference), new Asn1Integer(maxResults), new Asn1Integer(serverTimeLimit), new Asn1Boolean(typesOnly), new RfcFilter(filter), new RfcAttributeDescriptionList(attrs)), cont) { return ; } /// <summary> Constructs an Ldap Search Request with a filter in Asn1 format. /// /// </summary> /// <param name="base"> The base distinguished name to search from. /// /// </param> /// <param name="scope"> The scope of the entries to search. The following /// are the valid options: /// <ul> /// <li>SCOPE_BASE - searches only the base DN</li> /// /// <li>SCOPE_ONE - searches only entries under the base DN</li> /// /// <li>SCOPE_SUB - searches the base DN and all entries /// within its subtree</li> /// </ul> /// </param> /// <param name="filter"> The search filter specifying the search criteria. /// /// </param> /// <param name="attrs"> The names of attributes to retrieve. /// operation exceeds the time limit. /// /// </param> /// <param name="dereference">Specifies when aliases should be dereferenced. /// Must be either one of the constants defined in /// LdapConstraints, which are DEREF_NEVER, /// DEREF_FINDING, DEREF_SEARCHING, or DEREF_ALWAYS. /// /// </param> /// <param name="maxResults">The maximum number of search results to return /// for a search request. /// The search operation will be terminated by the server /// with an LdapException.SIZE_LIMIT_EXCEEDED if the /// number of results exceed the maximum. /// /// </param> /// <param name="serverTimeLimit">The maximum time in seconds that the server /// should spend returning search results. This is a /// server-enforced limit. A value of 0 means /// no time limit. /// /// </param> /// <param name="typesOnly"> If true, returns the names but not the values of /// the attributes found. If false, returns the /// names and values for attributes found. /// /// </param> /// <param name="cont"> Any controls that apply to the search request. /// or null if none. /// /// </param> /// <seealso cref="Novell.Directory.Ldap.LdapConnection.Search"> /// </seealso> /// <seealso cref="Novell.Directory.Ldap.LdapSearchConstraints"> /// </seealso> public LdapSearchRequest(System.String base_Renamed, int scope, RfcFilter filter, System.String[] attrs, int dereference, int maxResults, int serverTimeLimit, bool typesOnly, LdapControl[] cont):base(LdapMessage.SEARCH_REQUEST, new RfcSearchRequest(new RfcLdapDN(base_Renamed), new Asn1Enumerated(scope), new Asn1Enumerated(dereference), new Asn1Integer(maxResults), new Asn1Integer(serverTimeLimit), new Asn1Boolean(typesOnly), filter, new RfcAttributeDescriptionList(attrs)), cont) { return ; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapAttribute.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.Net.Http; using ArrayEnumeration = Novell.Directory.Ldap.Utilclass.ArrayEnumeration; using Base64 = Novell.Directory.Ldap.Utilclass.Base64; namespace Novell.Directory.Ldap { /// <summary> The name and values of one attribute of a directory entry. /// /// LdapAttribute objects are used when searching for, adding, /// modifying, and deleting attributes from the directory. /// LdapAttributes are often used in conjunction with an /// {@link LdapAttributeSet} when retrieving or adding multiple /// attributes to an entry. /// /// /// /// </summary> /// <seealso cref="LdapEntry"> /// </seealso> /// <seealso cref="LdapAttributeSet"> /// </seealso> /// <seealso cref="LdapModification"> /// </seealso> public class LdapAttribute : IComparable { class URLData { private void InitBlock(LdapAttribute enclosingInstance) { this.enclosingInstance = enclosingInstance; } private LdapAttribute enclosingInstance; public LdapAttribute Enclosing_Instance { get { return enclosingInstance; } } private int length; private sbyte[] data; public URLData(LdapAttribute enclosingInstance, sbyte[] data, int length) { InitBlock(enclosingInstance); this.length = length; this.data = data; } public int getLength() { return length; } public sbyte[] getData() { return data; } } /// <summary> Returns an enumerator for the values of the attribute in byte format. /// /// </summary> /// <returns> The values of the attribute in byte format. /// Note: All string values will be UTF-8 encoded. To decode use the /// String constructor. Example: new String( byteArray, "UTF-8" ); /// </returns> virtual public System.Collections.IEnumerator ByteValues { get { return new ArrayEnumeration(ByteValueArray); } } /// <summary> Returns an enumerator for the string values of an attribute. /// /// </summary> /// <returns> The string values of an attribute. /// </returns> virtual public System.Collections.IEnumerator StringValues { get { return new ArrayEnumeration(StringValueArray); } } /// <summary> Returns the values of the attribute as an array of bytes. /// /// </summary> /// <returns> The values as an array of bytes or an empty array if there are /// no values. /// </returns> [CLSCompliantAttribute(false)] virtual public sbyte[][] ByteValueArray { get { if (null == values) return new sbyte[0][]; int size = values.Length; sbyte[][] bva = new sbyte[size][]; // Deep copy so application cannot change values for (int i = 0, u = size; i < u; i++) { bva[i] = new sbyte[((sbyte[])values[i]).Length]; Array.Copy((Array)values[i], 0, (Array)bva[i], 0, bva[i].Length); } return bva; } } /// <summary> Returns the values of the attribute as an array of strings. /// /// </summary> /// <returns> The values as an array of strings or an empty array if there are /// no values /// </returns> virtual public string[] StringValueArray { get { if (null == values) return new string[0]; int size = values.Length; string[] sva = new string[size]; for (int j = 0; j < size; j++) { try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); char[] dchar = encoder.GetChars(SupportClass.ToByteArray((sbyte[])values[j])); // char[] dchar = encoder.GetChars((byte[])values[j]); sva[j] = new string(dchar); // sva[j] = new String((sbyte[]) values[j], "UTF-8"); } catch (System.IO.IOException uee) { // Exception should NEVER get thrown but just in case it does ... throw new Exception(uee.ToString()); } } return sva; } } /// <summary> Returns the the first value of the attribute as a <code>String</code>. /// /// </summary> /// <returns> The UTF-8 encoded<code>String</code> value of the attribute's /// value. If the value wasn't a UTF-8 encoded <code>String</code> /// to begin with the value of the returned <code>String</code> is /// non deterministic. /// /// If <code>this</code> attribute has more than one value the /// first value is converted to a UTF-8 encoded <code>String</code> /// and returned. It should be noted, that the directory may /// return attribute values in any order, so that the first /// value may vary from one call to another. /// /// If the attribute has no values <code>null</code> is returned /// </returns> virtual public string StringValue { get { string rval = null; if (values != null) { try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); char[] dchar = encoder.GetChars(SupportClass.ToByteArray((sbyte[])values[0])); // char[] dchar = encoder.GetChars((byte[]) this.values[0]); rval = new string(dchar); } catch (System.IO.IOException use) { throw new Exception(use.ToString()); } } return rval; } } /// <summary> Returns the the first value of the attribute as a byte array. /// /// </summary> /// <returns> The binary value of <code>this</code> attribute or /// <code>null</code> if <code>this</code> attribute doesn't have a value. /// /// If the attribute has no values <code>null</code> is returned /// </returns> [CLSCompliantAttribute(false)] virtual public sbyte[] ByteValue { get { sbyte[] bva = null; if (values != null) { // Deep copy so app can't change the value bva = new sbyte[((sbyte[])values[0]).Length]; Array.Copy((Array)values[0], 0, (Array)bva, 0, bva.Length); } return bva; } } /// <summary> Returns the language subtype of the attribute, if any. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns the string, lang-ja. /// /// </summary> /// <returns> The language subtype of the attribute or null if the attribute /// has none. /// </returns> virtual public string LangSubtype { get { if (subTypes != null) { for (int i = 0; i < subTypes.Length; i++) { if (subTypes[i].StartsWith("lang-")) { return subTypes[i]; } } } return null; } } /// <summary> Returns the name of the attribute. /// /// </summary> /// <returns> The name of the attribute. /// </returns> virtual public string Name { get { return name; } } /// <summary> Replaces all values with the specified value. This protected method is /// used by sub-classes of LdapSchemaElement because the value cannot be set /// with a contructor. /// </summary> virtual protected internal string Value { set { values = null; try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(value); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); add(sbytes); } catch (System.IO.IOException ue) { throw new Exception(ue.ToString()); } } } private string name; // full attribute name private string baseName; // cn of cn;lang-ja;phonetic private string[] subTypes = null; // lang-ja of cn;lang-ja private object[] values = null; // Array of byte[] attribute values /// <summary> Constructs an attribute with copies of all values of the input /// attribute. /// /// </summary> /// <param name="attr"> An LdapAttribute to use as a template. /// /// @throws IllegalArgumentException if attr is null /// </param> public LdapAttribute(LdapAttribute attr) { if (attr == null) { throw new ArgumentException("LdapAttribute class cannot be null"); } // Do a deep copy of the LdapAttribute template name = attr.name; baseName = attr.baseName; if (null != attr.subTypes) { subTypes = new string[attr.subTypes.Length]; Array.Copy((Array)attr.subTypes, 0, (Array)subTypes, 0, subTypes.Length); } // OK to just copy attributes, as the app only sees a deep copy of them if (null != attr.values) { values = new object[attr.values.Length]; Array.Copy((Array)attr.values, 0, (Array)values, 0, values.Length); } } /// <summary> Constructs an attribute with no values. /// /// </summary> /// <param name="attrName">Name of the attribute. /// /// @throws IllegalArgumentException if attrName is null /// </param> public LdapAttribute(string attrName) { if ((object)attrName == null) { throw new ArgumentException("Attribute name cannot be null"); } name = attrName; baseName = getBaseName(attrName); subTypes = getSubtypes(attrName); } /// <summary> Constructs an attribute with a byte-formatted value. /// /// </summary> /// <param name="attrName">Name of the attribute. /// </param> /// <param name="attrBytes">Value of the attribute as raw bytes. /// /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// /// @throws IllegalArgumentException if attrName or attrBytes is null /// </param> [CLSCompliantAttribute(false)] public LdapAttribute(string attrName, sbyte[] attrBytes) : this(attrName) { if (attrBytes == null) { throw new ArgumentException("Attribute value cannot be null"); } // Make our own copy of the byte array to prevent app from changing it sbyte[] tmp = new sbyte[attrBytes.Length]; Array.Copy((Array)attrBytes, 0, (Array)tmp, 0, attrBytes.Length); add(tmp); } /// <summary> Constructs an attribute with a single string value. /// /// </summary> /// <param name="attrName">Name of the attribute. /// </param> /// <param name="attrString">Value of the attribute as a string. /// /// @throws IllegalArgumentException if attrName or attrString is null /// </param> public LdapAttribute(string attrName, string attrString) : this(attrName) { if ((object)attrString == null) { throw new ArgumentException("Attribute value cannot be null"); } try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrString); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); add(sbytes); } catch (System.IO.IOException e) { throw new Exception(e.ToString()); } } /// <summary> Constructs an attribute with an array of string values. /// /// </summary> /// <param name="attrName">Name of the attribute. /// </param> /// <param name="attrStrings">Array of values as strings. /// /// @throws IllegalArgumentException if attrName, attrStrings, or a member /// of attrStrings is null /// </param> public LdapAttribute(string attrName, string[] attrStrings) : this(attrName) { if (attrStrings == null) { throw new ArgumentException("Attribute values array cannot be null"); } for (int i = 0, u = attrStrings.Length; i < u; i++) { try { if ((object)attrStrings[i] == null) { throw new ArgumentException("Attribute value " + "at array index " + i + " cannot be null"); } System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrStrings[i]); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); add(sbytes); // this.add(attrStrings[i].getBytes("UTF-8")); } catch (System.IO.IOException e) { throw new Exception(e.ToString()); } } } /// <summary> Returns a clone of this LdapAttribute. /// /// </summary> /// <returns> clone of this LdapAttribute. /// </returns> public object Clone() { try { object newObj = MemberwiseClone(); if (values != null) { Array.Copy((Array)values, 0, (Array)((LdapAttribute)newObj).values, 0, values.Length); } return newObj; } catch (Exception ce) { throw new Exception("Internal error, cannot create clone"); } } /// <summary> Adds a string value to the attribute. /// /// </summary> /// <param name="attrString">Value of the attribute as a String. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addValue(string attrString) { if ((object)attrString == null) { throw new ArgumentException("Attribute value cannot be null"); } try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrString); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); add(sbytes); // this.add(attrString.getBytes("UTF-8")); } catch (System.IO.IOException ue) { throw new Exception(ue.ToString()); } } /// <summary> Adds a byte-formatted value to the attribute. /// /// </summary> /// <param name="attrBytes">Value of the attribute as raw bytes. /// /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// /// @throws IllegalArgumentException if attrBytes is null /// </param> [CLSCompliantAttribute(false)] public virtual void addValue(sbyte[] attrBytes) { if (attrBytes == null) { throw new ArgumentException("Attribute value cannot be null"); } add(attrBytes); } /// <summary> Adds a base64 encoded value to the attribute. /// The value will be decoded and stored as bytes. String /// data encoded as a base64 value must be UTF-8 characters. /// /// </summary> /// <param name="attrString">The base64 value of the attribute as a String. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addBase64Value(string attrString) { if ((object)attrString == null) { throw new ArgumentException("Attribute value cannot be null"); } add(Base64.decode(attrString)); } /// <summary> Adds a base64 encoded value to the attribute. /// The value will be decoded and stored as bytes. Character /// data encoded as a base64 value must be UTF-8 characters. /// /// </summary> /// <param name="attrString">The base64 value of the attribute as a StringBuffer. /// </param> /// <param name="start"> The start index of base64 encoded part, inclusive. /// </param> /// <param name="end"> The end index of base encoded part, exclusive. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addBase64Value(System.Text.StringBuilder attrString, int start, int end) { if (attrString == null) { throw new ArgumentException("Attribute value cannot be null"); } add(Base64.decode(attrString, start, end)); } /// <summary> Adds a base64 encoded value to the attribute. /// The value will be decoded and stored as bytes. Character /// data encoded as a base64 value must be UTF-8 characters. /// /// </summary> /// <param name="attrChars">The base64 value of the attribute as an array of /// characters. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addBase64Value(char[] attrChars) { if (attrChars == null) { throw new ArgumentException("Attribute value cannot be null"); } add(Base64.decode(attrChars)); } /// <summary> Adds a URL, indicating a file or other resource that contains /// the value of the attribute. /// /// </summary> /// <param name="url">String value of a URL pointing to the resource containing /// the value of the attribute. /// /// @throws IllegalArgumentException if url is null /// </param> public virtual void addURLValue(string url) { if ((object)url == null) { throw new ArgumentException("Attribute URL cannot be null"); } addURLValue(new Uri(url)); } /// <summary> Adds a URL, indicating a file or other resource that contains /// the value of the attribute. /// /// </summary> /// <param name="url">A URL class pointing to the resource containing the value /// of the attribute. /// /// @throws IllegalArgumentException if url is null /// </param> public virtual void addURLValue(Uri url) { // Class to encapsulate the data bytes and the length if (url == null) { throw new ArgumentException("Attribute URL cannot be null"); } try { using (var httpClient = new HttpClient()) { // Get InputStream from the URL System.IO.Stream in_Renamed = httpClient.GetStreamAsync(url).Result; // Read the bytes into buffers and store the them in an arraylist System.Collections.ArrayList bufs = new System.Collections.ArrayList(); sbyte[] buf = new sbyte[4096]; int len, totalLength = 0; while ((len = SupportClass.ReadInput(in_Renamed, ref buf, 0, 4096)) != -1) { bufs.Add(new URLData(this, buf, len)); buf = new sbyte[4096]; totalLength += len; } /* * Now that the length is known, allocate an array to hold all * the bytes of data and copy the data to that array, store * it in this LdapAttribute */ sbyte[] data = new sbyte[totalLength]; int offset = 0; // for (int i = 0; i < bufs.Count; i++) { URLData b = (URLData)bufs[i]; len = b.getLength(); Array.Copy((Array)b.getData(), 0, (Array)data, offset, len); offset += len; } add(data); } } catch (System.IO.IOException ue) { throw new Exception(ue.ToString()); } } /// <summary> Returns the base name of the attribute. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns cn. /// /// </summary> /// <returns> The base name of the attribute. /// </returns> public virtual string getBaseName() { return baseName; } /// <summary> Returns the base name of the specified attribute name. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns cn. /// /// </summary> /// <param name="attrName">Name of the attribute from which to extract the /// base name. /// /// </param> /// <returns> The base name of the attribute. /// /// @throws IllegalArgumentException if attrName is null /// </returns> public static string getBaseName(string attrName) { if ((object)attrName == null) { throw new ArgumentException("Attribute name cannot be null"); } int idx = attrName.IndexOf((Char)';'); if (-1 == idx) { return attrName; } return attrName.Substring(0, (idx) - (0)); } /// <summary> Extracts the subtypes from the attribute name. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns an array containing lang-ja and phonetic. /// /// </summary> /// <returns> An array subtypes or null if the attribute has none. /// </returns> public virtual string[] getSubtypes() { return subTypes; } /// <summary> Extracts the subtypes from the specified attribute name. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns an array containing lang-ja and phonetic. /// /// </summary> /// <param name="attrName"> Name of the attribute from which to extract /// the subtypes. /// /// </param> /// <returns> An array subtypes or null if the attribute has none. /// /// @throws IllegalArgumentException if attrName is null /// </returns> public static string[] getSubtypes(string attrName) { if ((object)attrName == null) { throw new ArgumentException("Attribute name cannot be null"); } SupportClass.Tokenizer st = new SupportClass.Tokenizer(attrName, ";"); string[] subTypes = null; int cnt = st.Count; if (cnt > 0) { st.NextToken(); // skip over basename subTypes = new string[cnt - 1]; int i = 0; while (st.HasMoreTokens()) { subTypes[i++] = st.NextToken(); } } return subTypes; } /// <summary> Reports if the attribute name contains the specified subtype. /// /// For example, if you check for the subtype lang-en and the /// attribute name is cn;lang-en, this method returns true. /// /// </summary> /// <param name="subtype"> The single subtype to check for. /// /// </param> /// <returns> True, if the attribute has the specified subtype; /// false, if it doesn't. /// /// @throws IllegalArgumentException if subtype is null /// </returns> public virtual bool hasSubtype(string subtype) { if ((object)subtype == null) { throw new ArgumentException("subtype cannot be null"); } if (null != subTypes) { for (int i = 0; i < subTypes.Length; i++) { if (subTypes[i].ToUpper().Equals(subtype.ToUpper())) return true; } } return false; } /// <summary> Reports if the attribute name contains all the specified subtypes. /// /// For example, if you check for the subtypes lang-en and phonetic /// and if the attribute name is cn;lang-en;phonetic, this method /// returns true. If the attribute name is cn;phonetic or cn;lang-en, /// this method returns false. /// /// </summary> /// <param name="subtypes"> An array of subtypes to check for. /// /// </param> /// <returns> True, if the attribute has all the specified subtypes; /// false, if it doesn't have all the subtypes. /// /// @throws IllegalArgumentException if subtypes is null or if array member /// is null. /// </returns> public virtual bool hasSubtypes(string[] subtypes) { if (subtypes == null) { throw new ArgumentException("subtypes cannot be null"); } for (int i = 0; i < subtypes.Length; i++) { for (int j = 0; j < subTypes.Length; j++) { if ((object)subTypes[j] == null) { throw new ArgumentException("subtype " + "at array index " + i + " cannot be null"); } if (subTypes[j].ToUpper().Equals(subtypes[i].ToUpper())) { goto gotSubType; } } return false; gotSubType:; } return true; } /// <summary> Removes a string value from the attribute. /// /// </summary> /// <param name="attrString"> Value of the attribute as a string. /// /// Note: Removing a value which is not present in the attribute has /// no effect. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void removeValue(string attrString) { if (null == (object)attrString) { throw new ArgumentException("Attribute value cannot be null"); } try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrString); sbyte[] sbytes = SupportClass.ToSByteArray(ibytes); removeValue(sbytes); // this.removeValue(attrString.getBytes("UTF-8")); } catch (System.IO.IOException uee) { // This should NEVER happen but just in case ... throw new Exception(uee.ToString()); } } /// <summary> Removes a byte-formatted value from the attribute. /// /// </summary> /// <param name="attrBytes"> Value of the attribute as raw bytes. /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// Example: <code>String.getBytes("UTF-8");</code> /// /// Note: Removing a value which is not present in the attribute has /// no effect. /// /// @throws IllegalArgumentException if attrBytes is null /// </param> [CLSCompliantAttribute(false)] public virtual void removeValue(sbyte[] attrBytes) { if (null == attrBytes) { throw new ArgumentException("Attribute value cannot be null"); } for (int i = 0; i < values.Length; i++) { if (equals(attrBytes, (sbyte[])values[i])) { if (0 == i && 1 == values.Length) { // Optimize if first element of a single valued attr values = null; return; } if (values.Length == 1) { values = null; } else { int moved = values.Length - i - 1; object[] tmp = new object[values.Length - 1]; if (i != 0) { Array.Copy((Array)values, 0, (Array)tmp, 0, i); } if (moved != 0) { Array.Copy((Array)values, i + 1, (Array)tmp, i, moved); } values = tmp; tmp = null; } break; } } } /// <summary> Returns the number of values in the attribute. /// /// </summary> /// <returns> The number of values in the attribute. /// </returns> public virtual int size() { return null == values ? 0 : values.Length; } /// <summary> Compares this object with the specified object for order. /// /// Ordering is determined by comparing attribute names (see /// {@link #getName() }) using the method compareTo() of the String class. /// /// /// </summary> /// <param name="attribute"> The LdapAttribute to be compared to this object. /// /// </param> /// <returns> Returns a negative integer, zero, or a positive /// integer as this object is less than, equal to, or greater than the /// specified object. /// </returns> public virtual int CompareTo(object attribute) { return name.CompareTo(((LdapAttribute)attribute).name); } /// <summary> Adds an object to <code>this</code> object's list of attribute values /// /// </summary> /// <param name="bytes"> Ultimately all of this attribute's values are treated /// as binary data so we simplify the process by requiring /// that all data added to our list is in binary form. /// /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// </param> private void add(sbyte[] bytes) { if (null == values) { values = new object[] { bytes }; } else { // Duplicate attribute values not allowed for (int i = 0; i < values.Length; i++) { if (equals(bytes, (sbyte[])values[i])) { return; // Duplicate, don't add } } object[] tmp = new object[values.Length + 1]; Array.Copy((Array)values, 0, (Array)tmp, 0, values.Length); tmp[values.Length] = bytes; values = tmp; tmp = null; } } /// <summary> Returns true if the two specified arrays of bytes are equal to each /// another. Matches the logic of Arrays.equals which is not available /// in jdk 1.1.x. /// /// </summary> /// <param name="e1">the first array to be tested /// </param> /// <param name="e2">the second array to be tested /// </param> /// <returns> true if the two arrays are equal /// </returns> private bool equals(sbyte[] e1, sbyte[] e2) { // If same object, they compare true if (e1 == e2) return true; // If either but not both are null, they compare false if (e1 == null || e2 == null) return false; // If arrays have different length, they compare false int length = e1.Length; if (e2.Length != length) return false; // If any of the bytes are different, they compare false for (int i = 0; i < length; i++) { if (e1[i] != e2[i]) return false; } return true; } /// <summary> Returns a string representation of this LdapAttribute /// /// </summary> /// <returns> a string representation of this LdapAttribute /// </returns> public override string ToString() { System.Text.StringBuilder result = new System.Text.StringBuilder("LdapAttribute: "); try { result.Append("{type='" + name + "'"); if (values != null) { result.Append(", "); if (values.Length == 1) { result.Append("value='"); } else { result.Append("values='"); } for (int i = 0; i < values.Length; i++) { if (i != 0) { result.Append("','"); } if (((sbyte[])values[i]).Length == 0) { continue; } System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); // char[] dchar = encoder.GetChars((byte[]) values[i]); char[] dchar = encoder.GetChars(SupportClass.ToByteArray((sbyte[])values[i])); string sval = new string(dchar); // System.String sval = new String((sbyte[]) values[i], "UTF-8"); if (sval.Length == 0) { // didn't decode well, must be binary result.Append("<binary value, length:" + sval.Length); continue; } result.Append(sval); } result.Append("'"); } result.Append("}"); } catch (Exception e) { throw new Exception(e.ToString()); } return result.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Factories; using System.IO; using System.Linq; using System.Linq.Expressions; using System.UnitTesting; using System.ComponentModel.Composition.Primitives; using System.Reflection; using Xunit; namespace System.ComponentModel.Composition { // This is a glorious do nothing ReflectionContext public class DirectoryCatalogTestsReflectionContext : ReflectionContext { public override Assembly MapAssembly(Assembly assembly) { return assembly; } #if FEATURE_INTERNAL_REFLECTIONCONTEXT public override Type MapType(Type type) #else public override TypeInfo MapType(TypeInfo type) #endif { return type; } } public class DirectoryCatalogTests { internal const string NonExistentSearchPattern = "*.NonExistentSearchPattern"; public static void Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull(Func<ReflectionContext, DirectoryCatalog> catalogCreator) { Assert.Throws<ArgumentNullException>("reflectionContext", () => { var catalog = catalogCreator(null); }); } public static void Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull(Func<ICompositionElement, DirectoryCatalog> catalogCreator) { Assert.Throws<ArgumentNullException>("definitionOrigin", () => { var catalog = catalogCreator(null); }); } [Fact] public void Constructor2_NullReflectionContextArgument_ShouldThrowArgumentNull() { DirectoryCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) => { return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), rc); }); } [Fact] public void Constructor3_NullDefinitionOriginArgument_ShouldThrowArgumentNull() { DirectoryCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) => { return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), dO); }); } [Fact] public void Constructor4_NullReflectionContextArgument_ShouldThrowArgumentNull() { DirectoryCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) => { return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), rc, CreateDirectoryCatalog()); }); } [Fact] public void Constructor4_NullDefinitionOriginArgument_ShouldThrowArgumentNull() { DirectoryCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) => { return new DirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory(), new DirectoryCatalogTestsReflectionContext(), dO); }); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.IO.DirectoryNotFoundException : Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/'. public void ICompositionElementDisplayName_ShouldIncludeCatalogTypeNameAndDirectoryPath() { var paths = GetPathExpectations(); foreach (var path in paths) { var catalog = (ICompositionElement)CreateDirectoryCatalog(path, NonExistentSearchPattern); string expected = string.Format("DirectoryCatalog (Path=\"{0}\")", path); Assert.Equal(expected, catalog.DisplayName); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.IO.DirectoryNotFoundException : Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/'. public void ICompositionElementDisplayName_ShouldIncludeDerivedCatalogTypeNameAndAssemblyFullName() { var paths = GetPathExpectations(); foreach (var path in paths) { var catalog = (ICompositionElement)new DerivedDirectoryCatalog(path, NonExistentSearchPattern); string expected = string.Format("DerivedDirectoryCatalog (Path=\"{0}\")", path); Assert.Equal(expected, catalog.DisplayName); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.IO.DirectoryNotFoundException : Could not find a part of the path '/HOME/HELIXBOT/DOTNETBUILD/WORK/E77C2FB6-5244-4437-8E27-6DD709101152/WORK/D9EBA0EA-A511-4F42-AC8B-AC8054AAF606/UNZIP/'. public void ToString_ShouldReturnICompositionElementDisplayName() { var paths = GetPathExpectations(); foreach (var path in paths) { var catalog = (ICompositionElement)CreateDirectoryCatalog(path, NonExistentSearchPattern); Assert.Equal(catalog.DisplayName, catalog.ToString()); } } [Fact] public void ICompositionElementDisplayName_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); var displayName = ((ICompositionElement)catalog).DisplayName; } [Fact] public void ICompositionElementOrigin_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); var origin = ((ICompositionElement)catalog).Origin; } [Fact] public void Parts_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); ExceptionAssert.ThrowsDisposed(catalog, () => { var parts = catalog.Parts; }); } [Fact] public void GetExports_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); var definition = ImportDefinitionFactory.Create(); ExceptionAssert.ThrowsDisposed(catalog, () => { catalog.GetExports(definition); }); } [Fact] public void Refresh_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); ExceptionAssert.ThrowsDisposed(catalog, () => { catalog.Refresh(); }); } [Fact] public void ToString_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); catalog.ToString(); } [Fact] public void GetExports_NullAsConstraintArgument_ShouldThrowArgumentNull() { var catalog = CreateDirectoryCatalog(); Assert.Throws<ArgumentNullException>("definition", () => { catalog.GetExports((ImportDefinition)null); }); } [Fact] public void Dispose_ShouldNotThrow() { using (var catalog = CreateDirectoryCatalog()) { } } [Fact] public void Dispose_CanBeCalledMultipleTimes() { var catalog = CreateDirectoryCatalog(); catalog.Dispose(); catalog.Dispose(); catalog.Dispose(); } [Fact] public void AddAssembly1_NullPathArgument_ShouldThrowArugmentNull() { Assert.Throws<ArgumentNullException>(() => new DirectoryCatalog((string)null)); } [Fact] public void AddAssembly1_EmptyPathArgument_ShouldThrowArugment() { Assert.Throws<ArgumentException>(() => new DirectoryCatalog("")); } [Fact] [ActiveIssue(25498)] public void AddAssembly1_TooLongPathNameArgument_ShouldThrowPathTooLongException() { Assert.Throws<PathTooLongException>(() => { var c1 = new DirectoryCatalog(@"c:\This is a very long path\And Just to make sure\We will continue to make it very long\This is a very long path\And Just to make sure\We will continue to make it very long\This is a very long path\And Just to make sure\We will continue to make it very long\myassembly.dll"); }); } [Fact] [ActiveIssue(25498)] public void Parts() { var catalog = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); Assert.NotNull(catalog.Parts); Assert.True(catalog.Parts.Count() > 0); } [Fact] [ActiveIssue(25498)] public void Parts_ShouldSetDefinitionOriginToCatalogItself() { var catalog = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); Assert.True(catalog.Parts.Count() > 0); foreach (ICompositionElement definition in catalog.Parts) { Assert.Same(catalog, definition.Origin); } } [Fact] [ActiveIssue(25498)] public void Path_ValidPath_ShouldBeFine() { var expectations = new ExpectationCollection<string, string>(); expectations.Add(".", "."); expectations.Add(TemporaryFileCopier.RootTemporaryDirectoryName, TemporaryFileCopier.RootTemporaryDirectoryName); expectations.Add(TemporaryFileCopier.GetRootTemporaryDirectory(), TemporaryFileCopier.GetRootTemporaryDirectory()); expectations.Add(TemporaryFileCopier.GetTemporaryDirectory(), TemporaryFileCopier.GetTemporaryDirectory()); foreach (var e in expectations) { var cat = CreateDirectoryCatalog(e.Input, NonExistentSearchPattern); Assert.Equal(e.Output, cat.Path); } } [Fact] [ActiveIssue(25498)] public void FullPath_ValidPath_ShouldBeFine() { var expectations = new ExpectationCollection<string, string>(); // Ensure the path is always normalized properly. string rootTempPath = Path.GetFullPath(TemporaryFileCopier.GetRootTemporaryDirectory()).ToUpperInvariant(); // Note: These relative paths work properly because the unit test temporary directories are always // created as a subfolder off the AppDomain.CurrentDomain.BaseDirectory. expectations.Add(".", Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ".")).ToUpperInvariant()); expectations.Add(TemporaryFileCopier.RootTemporaryDirectoryName, rootTempPath); expectations.Add(TemporaryFileCopier.GetRootTemporaryDirectory(), rootTempPath); expectations.Add(TemporaryFileCopier.GetTemporaryDirectory(), Path.GetFullPath(TemporaryFileCopier.GetTemporaryDirectory()).ToUpperInvariant()); foreach (var e in expectations) { var cat = CreateDirectoryCatalog(e.Input, NonExistentSearchPattern); Assert.Equal(e.Output, cat.FullPath); } } [Fact] public void LoadedFiles_EmptyDirectory_ShouldBeFine() { var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); Assert.Equal(0, cat.LoadedFiles.Count); } [Fact] public void LoadedFiles_ContainsMultipleDllsAndSomeNonDll_ShouldOnlyContainDlls() { // Add one text file using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.txt"))) { } // Add two dll's string dll1 = Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test1.dll"); string dll2 = Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test2.dll"); File.Copy(Assembly.GetExecutingAssembly().Location, dll1); File.Copy(Assembly.GetExecutingAssembly().Location, dll2); var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); EqualityExtensions.CheckEquals(new string[] { dll1.ToUpperInvariant(), dll2.ToUpperInvariant() }, cat.LoadedFiles); } [Fact] public void LoadedFiles_NonStaticallyReferencedAssembly() { string testAssembly = "System.ComponentModel.Composition.Noop.Assembly.dll"; var directory = TemporaryFileCopier.GetNewTemporaryDirectory(); Directory.CreateDirectory(directory); var finalPath = Path.Combine(directory, testAssembly); var sourcePath = Path.Combine(Directory.GetCurrentDirectory(), testAssembly); File.Copy(sourcePath, finalPath); var catalog = new DirectoryCatalog(directory, "*.dll"); Assert.NotEmpty(catalog); } [Fact] public void Constructor_InvalidAssembly_ShouldBeFine() { using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll"))) { } var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); } [Fact] public void Constructor_NonExistentDirectory_ShouldThrow() { Assert.Throws<DirectoryNotFoundException>(() => new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory() + @"\NonexistentDirectoryWithoutEndingSlash")); Assert.Throws<DirectoryNotFoundException>(() => new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory() + @"\NonexistentDirectoryWithEndingSlash\")); } [Fact] [ActiveIssue(25498)] public void Constructor_PassExistingFileName_ShouldThrow() { using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.txt"))) { } Assert.Throws<IOException>(() => new DirectoryCatalog(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.txt"))); } [Fact] public void Constructor_PassNonExistingFileName_ShouldThrow() { Assert.Throws<DirectoryNotFoundException>(() => new DirectoryCatalog(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "NonExistingFile.txt"))); } [Fact] [ActiveIssue(25498)] public void Refresh_AssemblyAdded_ShouldFireOnChanged() { bool changedFired = false; bool changingFired = false; var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); Assert.Equal(0, cat.Parts.Count()); cat.Changing += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) => { Assert.Equal(0, cat.Parts.Count()); changingFired = true; }); cat.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) => { Assert.NotEqual(0, cat.Parts.Count()); changedFired = true; }); File.Copy(Assembly.GetExecutingAssembly().Location, Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll")); cat.Refresh(); Assert.True(changingFired); Assert.True(changedFired); } [Fact] [ActiveIssue(25498)] public void Refresh_AssemblyRemoved_ShouldFireOnChanged() { string file = Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll"); File.Copy(Assembly.GetExecutingAssembly().Location, file); bool changedFired = false; var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); cat.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) => changedFired = true); // This assembly can be deleted because it was already loaded by the CLR in another context // in another location so it isn't locked on disk. File.Delete(file); cat.Refresh(); Assert.True(changedFired); } [Fact] public void Refresh_NoChanges_ShouldNotFireOnChanged() { var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); cat.Changed += new EventHandler<ComposablePartCatalogChangeEventArgs>((o, e) => Assert.False(true)); cat.Refresh(); } [Fact] [ActiveIssue(25498)] public void Refresh_DirectoryRemoved_ShouldThrowDirectoryNotFound() { DirectoryCatalog cat; cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); ExceptionAssert.Throws<DirectoryNotFoundException>(RetryMode.DoNotRetry, () => cat.Refresh()); } [Fact] public void GetExports() { var catalog = new AggregateCatalog(); Expression<Func<ExportDefinition, bool>> constraint = (ExportDefinition exportDefinition) => exportDefinition.ContractName == AttributedModelServices.GetContractName(typeof(MyExport)); IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> matchingExports = null; matchingExports = catalog.GetExports(constraint); Assert.NotNull(matchingExports); Assert.True(matchingExports.Count() == 0); var testsDirectoryCatalog = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); catalog.Catalogs.Add(testsDirectoryCatalog); matchingExports = catalog.GetExports(constraint); Assert.NotNull(matchingExports); Assert.True(matchingExports.Count() >= 0); IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> expectedMatchingExports = catalog.Parts .SelectMany(part => part.ExportDefinitions, (part, export) => new Tuple<ComposablePartDefinition, ExportDefinition>(part, export)) .Where(partAndExport => partAndExport.Item2.ContractName == AttributedModelServices.GetContractName(typeof(MyExport))); Assert.True(matchingExports.SequenceEqual(expectedMatchingExports)); catalog.Catalogs.Remove(testsDirectoryCatalog); matchingExports = catalog.GetExports(constraint); Assert.NotNull(matchingExports); Assert.True(matchingExports.Count() == 0); } [Fact] [ActiveIssue(25498)] public void AddAndRemoveDirectory() { var cat = new AggregateCatalog(); var container = new CompositionContainer(cat); Assert.False(container.IsPresent<MyExport>()); var dir1 = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); cat.Catalogs.Add(dir1); Assert.True(container.IsPresent<MyExport>()); cat.Catalogs.Remove(dir1); Assert.False(container.IsPresent<MyExport>()); } [Fact] public void AddDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { var cat = new DirectoryCatalog("Directory That Should Never Exist tadfasdfasdfsdf"); }); } [Fact] public void ExecuteOnCreationThread() { // Add a proper test for event notification on caller thread } private DirectoryCatalog CreateDirectoryCatalog() { return CreateDirectoryCatalog(TemporaryFileCopier.GetNewTemporaryDirectory()); } private DirectoryCatalog CreateDirectoryCatalog(string path) { return new DirectoryCatalog(path); } private DirectoryCatalog CreateDirectoryCatalog(string path, string searchPattern) { return new DirectoryCatalog(path, searchPattern); } public IEnumerable<string> GetPathExpectations() { yield return AppDomain.CurrentDomain.BaseDirectory; yield return AppDomain.CurrentDomain.BaseDirectory + @"\"; yield return "."; } private class DerivedDirectoryCatalog : DirectoryCatalog { public DerivedDirectoryCatalog(string path, string searchPattern) : base(path, searchPattern) { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Routing; using Autofac; using JetBrains.Annotations; using Moq; using NUnit.Framework; using Orchard.Caching; using Orchard.ContentManagement.Aspects; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.Drivers.Coordinators; using Orchard.ContentManagement.MetaData; using Orchard.Core.Common.Drivers; using Orchard.Core.Common.Handlers; using Orchard.Core.Common.Models; using Orchard.ContentManagement; using Orchard.ContentManagement.Handlers; using Orchard.ContentManagement.Records; using Orchard.Core.Common.OwnerEditor; using Orchard.Core.Common.Services; using Orchard.Core.Scheduling.Models; using Orchard.Core.Scheduling.Services; using Orchard.DisplayManagement; using Orchard.DisplayManagement.Descriptors; using Orchard.DisplayManagement.Descriptors.ShapeAttributeStrategy; using Orchard.DisplayManagement.Descriptors.ShapePlacementStrategy; using Orchard.DisplayManagement.Implementation; using Orchard.Environment.Extensions; using Orchard.Environment.Extensions.Models; using Orchard.FileSystems.VirtualPath; using Orchard.Localization; using Orchard.Security; using Orchard.Tasks.Scheduling; using Orchard.Tests.DisplayManagement; using Orchard.Tests.DisplayManagement.Descriptors; using Orchard.Tests.Modules; using System.Web.Mvc; using Orchard.Tests.Stubs; using Orchard.Themes; using Orchard.UI.PageClass; namespace Orchard.Core.Tests.Common.Providers { [TestFixture] public class CommonPartProviderTests : DatabaseEnabledTestsBase { private Mock<IAuthenticationService> _authn; private Mock<IAuthorizationService> _authz; private Mock<IMembershipService> _membership; private Mock<IContentDefinitionManager> _contentDefinitionManager; public override void Register(ContainerBuilder builder) { builder.RegisterType<DefaultContentManager>().As<IContentManager>(); builder.RegisterType<Signals>().As<ISignals>(); builder.RegisterType<DefaultContentManagerSession>().As<IContentManagerSession>(); builder.RegisterType<TestHandler>().As<IContentHandler>(); builder.RegisterType<CommonPartHandler>().As<IContentHandler>(); builder.RegisterType<CommonPartDriver>().As<IContentPartDriver>(); builder.RegisterType<OwnerEditorDriver>().As<IContentPartDriver>(); builder.RegisterType<ContentPartDriverCoordinator>().As<IContentHandler>(); builder.RegisterType<CommonService>().As<ICommonService>(); builder.RegisterType<ScheduledTaskManager>().As<IScheduledTaskManager>(); builder.RegisterType<DefaultShapeFactory>().As<IShapeFactory>(); builder.RegisterType<StubExtensionManager>().As<IExtensionManager>(); builder.RegisterType<StubCacheManager>().As<ICacheManager>(); builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>(); builder.RegisterType<StubThemeService>().As<IThemeManager>(); builder.RegisterInstance(new Mock<IOrchardServices>().Object); builder.RegisterInstance(new RequestContext(new StubHttpContext(), new RouteData())); builder.RegisterInstance(new Orchard.Environment.Work<IEnumerable<IShapeTableEventHandler>>(resolve => _container.Resolve<IEnumerable<IShapeTableEventHandler>>())).AsSelf(); builder.RegisterType<DefaultShapeTableManager>().As<IShapeTableManager>(); builder.RegisterType<ShapeTableLocator>().As<IShapeTableLocator>(); builder.RegisterType<DefaultShapeFactory>().As<IShapeFactory>(); // IContentDisplay var workContext = new DefaultDisplayManagerTests.TestWorkContext { CurrentTheme = new ExtensionDescriptor { Id = "Hello" } }; builder.RegisterInstance<DefaultDisplayManagerTests.TestWorkContextAccessor>(new DefaultDisplayManagerTests.TestWorkContextAccessor(workContext)).As<IWorkContextAccessor>(); builder.RegisterInstance(new Mock<IPageClassBuilder>().Object); builder.RegisterType<DefaultContentDisplay>().As<IContentDisplay>(); DefaultShapeTableManagerTests.TestShapeProvider.FeatureShapes = new Dictionary<Feature, IEnumerable<string>> { { TestFeature(), new[] { "Parts_Common_Owner_Edit" } } }; builder.RegisterType<DefaultShapeTableManagerTests.TestShapeProvider>().As<IShapeTableProvider>() .As<DefaultShapeTableManagerTests.TestShapeProvider>() .InstancePerLifetimeScope(); builder.RegisterInstance(new RouteCollection()); builder.RegisterModule(new ShapeAttributeBindingModule()); _authn = new Mock<IAuthenticationService>(); _authz = new Mock<IAuthorizationService>(); _membership = new Mock<IMembershipService>(); _contentDefinitionManager = new Mock<IContentDefinitionManager>(); builder.RegisterInstance(_authn.Object); builder.RegisterInstance(_authz.Object); builder.RegisterInstance(_membership.Object); builder.RegisterInstance(_contentDefinitionManager.Object); var virtualPathProviderMock = new Mock<IVirtualPathProvider>(); virtualPathProviderMock.Setup(a => a.ToAppRelative(It.IsAny<string>())).Returns("~/yadda"); builder.RegisterInstance(virtualPathProviderMock.Object); } static Feature TestFeature() { return new Feature { Descriptor = new FeatureDescriptor { Id = "Testing", Dependencies = Enumerable.Empty<string>(), Extension = new ExtensionDescriptor { Id = "Testing", ExtensionType = DefaultExtensionTypes.Module, } } }; } protected override IEnumerable<Type> DatabaseTypes { get { return new[] { typeof(ContentTypeRecord), typeof(ContentItemRecord), typeof(ContentItemVersionRecord), typeof(CommonPartRecord), typeof(CommonPartVersionRecord), typeof(ScheduledTaskRecord), }; } } [UsedImplicitly] class TestHandler : ContentHandler { public TestHandler() { Filters.Add(new ActivatingFilter<CommonPart>("test-item")); Filters.Add(new ActivatingFilter<ContentPart<CommonPartVersionRecord>>("test-item")); Filters.Add(new ActivatingFilter<TestUser>("User")); } } class TestUser : ContentPart, IUser { public new int Id { get { return 6655321; } } public string UserName { get { return "x"; } } public string Email { get { return "y"; } } } [Test] public void OwnerShouldBeNullAndZeroByDefault() { var contentManager = _container.Resolve<IContentManager>(); var item = contentManager.Create<CommonPart>("test-item", init => { }); ClearSession(); Assert.That(item.Owner, Is.Null); Assert.That(item.Record.OwnerId, Is.EqualTo(0)); } [Test] public void PublishingShouldFailIfOwnerIsUnknown() { var contentManager = _container.Resolve<IContentManager>(); var updateModel = new Mock<IUpdateModel>(); var user = contentManager.New<IUser>("User"); _authn.Setup(x => x.GetAuthenticatedUser()).Returns(user); var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); var viewModel = new OwnerEditorViewModel { Owner = "User" }; updateModel.Setup(x => x.TryUpdateModel(viewModel, "", null, null)).Returns(true); contentManager.UpdateEditor(item.ContentItem, updateModel.Object); } class UpdatModelStub : IUpdateModel { ModelStateDictionary _modelState = new ModelStateDictionary(); public ModelStateDictionary ModelErrors { get { return _modelState; } } public string Owner { get; set; } public bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) where TModel : class { (model as OwnerEditorViewModel).Owner = Owner; return true; } public void AddModelError(string key, LocalizedString errorMessage) { _modelState.AddModelError(key, errorMessage.ToString()); } } class StubThemeService : IThemeManager { private readonly ExtensionDescriptor _theme = new ExtensionDescriptor { Id = "SafeMode", Name = "SafeMode", Location = "~/Themes", }; public ExtensionDescriptor GetRequestTheme(RequestContext requestContext) { return _theme; } } [Test] public void PublishingShouldNotThrowExceptionIfOwnerIsNull() { var contentManager = _container.Resolve<IContentManager>(); var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); var user = contentManager.New<IUser>("User"); _authn.Setup(x => x.GetAuthenticatedUser()).Returns(user); _authz.Setup(x => x.TryCheckAccess(StandardPermissions.SiteOwner, user, item)).Returns(true); item.Owner = user; var updater = new UpdatModelStub() { Owner = null }; contentManager.UpdateEditor(item.ContentItem, updater); } [Test] public void PublishingShouldFailIfOwnerIsEmpty() { var contentManager = _container.Resolve<IContentManager>(); var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); var user = contentManager.New<IUser>("User"); _authn.Setup(x => x.GetAuthenticatedUser()).Returns(user); _authz.Setup(x => x.TryCheckAccess(StandardPermissions.SiteOwner, user, item)).Returns(true); item.Owner = user; var updater = new UpdatModelStub() { Owner = "" }; _container.Resolve<DefaultShapeTableManagerTests.TestShapeProvider>().Discover = b => b.Describe("Parts_Common_Owner_Edit").From(TestFeature()) .Placement(ctx => new PlacementInfo { Location = "Content" }); contentManager.UpdateEditor(item.ContentItem, updater); Assert.That(updater.ModelErrors.ContainsKey("OwnerEditor.Owner"), Is.True); } [Test] public void PublishingShouldNotFailIfOwnerIsEmptyAndShapeIsHidden() { var contentManager = _container.Resolve<IContentManager>(); var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); var user = contentManager.New<IUser>("User"); _authn.Setup(x => x.GetAuthenticatedUser()).Returns(user); _authz.Setup(x => x.TryCheckAccess(StandardPermissions.SiteOwner, user, item)).Returns(true); item.Owner = user; var updater = new UpdatModelStub() { Owner = "" }; _container.Resolve<DefaultShapeTableManagerTests.TestShapeProvider>().Discover = b => b.Describe("Parts_Common_Owner_Edit").From(TestFeature()) .Placement(ctx => new PlacementInfo { Location = "-" }); contentManager.UpdateEditor(item.ContentItem, updater); Assert.That(updater.ModelErrors.ContainsKey("OwnerEditor.Owner"), Is.False); } [Test] public void CreatingShouldSetCreatedAndModifiedUtc() { var contentManager = _container.Resolve<IContentManager>(); var createUtc = _clock.UtcNow; var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.Null); } [Test] public void PublishingShouldSetPublishUtcAndShouldNotChangeModifiedUtc() { var contentManager = _container.Resolve<IContentManager>(); var createUtc = _clock.UtcNow; var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.Null); _clock.Advance(TimeSpan.FromMinutes(1)); var publishUtc = _clock.UtcNow; contentManager.Publish(item.ContentItem); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.EqualTo(publishUtc)); } [Test] public void PublishingTwiceShouldKeepSettingPublishUtcAndShouldNotChangeModifiedUtc() { var contentManager = _container.Resolve<IContentManager>(); var createUtc = _clock.UtcNow; var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.Null); _clock.Advance(TimeSpan.FromMinutes(1)); var publishUtc1 = _clock.UtcNow; contentManager.Publish(item.ContentItem); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.EqualTo(publishUtc1)); contentManager.Unpublish(item.ContentItem); _clock.Advance(TimeSpan.FromMinutes(1)); var publishUtc2 = _clock.UtcNow; contentManager.Publish(item.ContentItem); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.EqualTo(publishUtc2)); } [Test] public void UnpublishingShouldNotChangePublishUtcAndModifiedUtc() { var contentManager = _container.Resolve<IContentManager>(); var createUtc = _clock.UtcNow; var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.Null); _clock.Advance(TimeSpan.FromMinutes(1)); var publishUtc = _clock.UtcNow; contentManager.Publish(item.ContentItem); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.EqualTo(publishUtc)); contentManager.Unpublish(item.ContentItem); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.EqualTo(publishUtc)); } [Test] public void EditingShouldSetModifiedUtc() { var contentManager = _container.Resolve<IContentManager>(); var createUtc = _clock.UtcNow; var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); contentManager.Publish(item.ContentItem); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.EqualTo(createUtc)); _clock.Advance(TimeSpan.FromMinutes(1)); var editUtc = _clock.UtcNow; var updater = new UpdatModelStub() { Owner = "" }; contentManager.UpdateEditor(item.ContentItem, updater); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.ModifiedUtc, Is.EqualTo(editUtc)); Assert.That(item.PublishedUtc, Is.EqualTo(createUtc)); Assert.That(updater.ModelErrors.Count, Is.EqualTo(0)); } [Test] public void VersioningItemShouldCreatedAndPublishedUtcValuesPerVersion() { var contentManager = _container.Resolve<IContentManager>(); var createUtc = _clock.UtcNow; var item1 = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); Assert.That(item1.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item1.PublishedUtc, Is.Null); _clock.Advance(TimeSpan.FromMinutes(1)); var publish1Utc = _clock.UtcNow; contentManager.Publish(item1.ContentItem); // db records need to be updated before demanding draft as item2 below _session.Flush(); _clock.Advance(TimeSpan.FromMinutes(1)); var draftUtc = _clock.UtcNow; var item2 = contentManager.GetDraftRequired<ICommonPart>(item1.ContentItem.Id); _clock.Advance(TimeSpan.FromMinutes(1)); var publish2Utc = _clock.UtcNow; contentManager.Publish(item2.ContentItem); // both instances non-versioned dates show it was created upfront Assert.That(item1.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item2.CreatedUtc, Is.EqualTo(createUtc)); // both instances non-versioned dates show the most recent publish Assert.That(item1.PublishedUtc, Is.EqualTo(publish2Utc)); Assert.That(item2.PublishedUtc, Is.EqualTo(publish2Utc)); // version1 versioned dates show create was upfront and publish was oldest Assert.That(item1.VersionCreatedUtc, Is.EqualTo(createUtc)); Assert.That(item1.VersionPublishedUtc, Is.EqualTo(publish1Utc)); // version2 versioned dates show create was midway and publish was most recent Assert.That(item2.VersionCreatedUtc, Is.EqualTo(draftUtc)); Assert.That(item2.VersionPublishedUtc, Is.EqualTo(publish2Utc)); } [Test] public void UnpublishShouldClearFlagButLeaveMostrecentPublishDatesIntact() { var contentManager = _container.Resolve<IContentManager>(); var createUtc = _clock.UtcNow; var item = contentManager.Create<ICommonPart>("test-item", VersionOptions.Draft, init => { }); Assert.That(item.CreatedUtc, Is.EqualTo(createUtc)); Assert.That(item.PublishedUtc, Is.Null); _clock.Advance(TimeSpan.FromMinutes(1)); var publishUtc = _clock.UtcNow; contentManager.Publish(item.ContentItem); // db records need to be updated before seeking by published flags _session.Flush(); _clock.Advance(TimeSpan.FromMinutes(1)); var unpublishUtc = _clock.UtcNow; contentManager.Unpublish(item.ContentItem); // db records need to be updated before seeking by published flags ClearSession(); var publishedItem = contentManager.Get<ICommonPart>(item.ContentItem.Id, VersionOptions.Published); var latestItem = contentManager.Get<ICommonPart>(item.ContentItem.Id, VersionOptions.Latest); var draftItem = contentManager.Get<ICommonPart>(item.ContentItem.Id, VersionOptions.Draft); var allVersions = contentManager.GetAllVersions(item.ContentItem.Id); Assert.That(publishedItem, Is.Null); Assert.That(latestItem, Is.Not.Null); Assert.That(draftItem, Is.Not.Null); Assert.That(allVersions.Count(), Is.EqualTo(1)); Assert.That(publishUtc, Is.Not.EqualTo(unpublishUtc)); Assert.That(latestItem.PublishedUtc, Is.EqualTo(publishUtc)); Assert.That(latestItem.VersionPublishedUtc, Is.EqualTo(publishUtc)); Assert.That(latestItem.ContentItem.VersionRecord.Latest, Is.True); Assert.That(latestItem.ContentItem.VersionRecord.Published, Is.False); } } }
// 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 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// ManagementLocksOperations operations. /// </summary> public partial interface IManagementLocksOperations { /// <summary> /// Create or update a management lock at the resource group level. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='lockName'> /// The lock name. /// </param> /// <param name='parameters'> /// The management lock parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ManagementLockObject>> CreateOrUpdateAtResourceGroupLevelWithHttpMessagesAsync(string resourceGroupName, string lockName, ManagementLockObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or update a management lock at the resource level or any /// level below resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='lockName'> /// The name of lock. /// </param> /// <param name='parameters'> /// Create or update management lock parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ManagementLockObject>> CreateOrUpdateAtResourceLevelWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string lockName, ManagementLockObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the management lock of a resource or any level below /// resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='lockName'> /// The name of lock. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteAtResourceLevelWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or update a management lock at the subscription level. /// </summary> /// <param name='lockName'> /// The name of lock. /// </param> /// <param name='parameters'> /// The management lock parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ManagementLockObject>> CreateOrUpdateAtSubscriptionLevelWithHttpMessagesAsync(string lockName, ManagementLockObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the management lock of a subscription. /// </summary> /// <param name='lockName'> /// The name of lock. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteAtSubscriptionLevelWithHttpMessagesAsync(string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the management lock of a scope. /// </summary> /// <param name='lockName'> /// Name of the management lock. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ManagementLockObject>> GetWithHttpMessagesAsync(string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the management lock of a resource group. /// </summary> /// <param name='resourceGroup'> /// The resource group names. /// </param> /// <param name='lockName'> /// The name of lock. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteAtResourceGroupLevelWithHttpMessagesAsync(string resourceGroup, string lockName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the management locks of a resource group. /// </summary> /// <param name='resourceGroupName'> /// Resource group name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtResourceGroupLevelWithHttpMessagesAsync(string resourceGroupName, ODataQuery<ManagementLockObject> odataQuery = default(ODataQuery<ManagementLockObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the management locks of a resource or any level below /// resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtResourceLevelWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<ManagementLockObject> odataQuery = default(ODataQuery<ManagementLockObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a list of management locks at resource level or below. /// </summary> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the management locks of a subscription. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtSubscriptionLevelWithHttpMessagesAsync(ODataQuery<ManagementLockObject> odataQuery = default(ODataQuery<ManagementLockObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the management locks of a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtResourceGroupLevelNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the management locks of a resource or any level below /// resource. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtResourceLevelNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a list of management locks at resource level or below. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListNextNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the management locks of a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<ManagementLockObject>>> ListAtSubscriptionLevelNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Threading; using System.Collections; using System.Diagnostics; namespace System.DirectoryServices.Protocols { internal class LdapPartialResultsProcessor { private readonly ArrayList _resultList = new ArrayList(); private readonly ManualResetEvent _workThreadWaitHandle = null; private bool _workToDo = false; private int _currentIndex = 0; internal LdapPartialResultsProcessor(ManualResetEvent eventHandle) { _workThreadWaitHandle = eventHandle; } public void Add(LdapPartialAsyncResult asyncResult) { lock (this) { _resultList.Add(asyncResult); if (!_workToDo) { // Need to wake up the workthread if it is not running already. _workThreadWaitHandle.Set(); _workToDo = true; } } } public void Remove(LdapPartialAsyncResult asyncResult) { // Called by Abort operation. lock (this) { if (!_resultList.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } // Remove this async operation from the list. _resultList.Remove(asyncResult); } } public void RetrievingSearchResults() { LdapPartialAsyncResult asyncResult = null; AsyncCallback tmpCallback = null; lock (this) { int count = _resultList.Count; if (count == 0) { // No asynchronous operation pending, begin to wait. _workThreadWaitHandle.Reset(); _workToDo = false; return; } // Might have work to do. int i = 0; while (true) { if (_currentIndex >= count) { // Some element is moved after last iteration. _currentIndex = 0; } asyncResult = (LdapPartialAsyncResult)_resultList[_currentIndex]; i++; _currentIndex++; // Have work to do. if (asyncResult._resultStatus != ResultsStatus.Done) { break; } if (i >= count) { // All the operations are done just waiting for the user to pick up the results. _workToDo = false; _workThreadWaitHandle.Reset(); return; } } // Try to get the results availabe for this asynchronous operation . GetResultsHelper(asyncResult); // If we are done with the asynchronous search, we need to fire callback and signal the waitable object. if (asyncResult._resultStatus == ResultsStatus.Done) { asyncResult._manualResetEvent.Set(); asyncResult._completed = true; if (asyncResult._callback != null) { tmpCallback = asyncResult._callback; } } else if (asyncResult._callback != null && asyncResult._partialCallback) { // The user specified a callback to be called even when partial results become available. if (asyncResult._response != null && (asyncResult._response.Entries.Count > 0 || asyncResult._response.References.Count > 0)) { tmpCallback = asyncResult._callback; } } } tmpCallback?.Invoke(asyncResult); } private void GetResultsHelper(LdapPartialAsyncResult asyncResult) { LdapConnection connection = asyncResult._con; ResultAll resultType = ResultAll.LDAP_MSG_RECEIVED; if (asyncResult._resultStatus == ResultsStatus.CompleteResult) { resultType = ResultAll.LDAP_MSG_POLLINGALL; } try { SearchResponse response = (SearchResponse)connection.ConstructResponse(asyncResult._messageID, LdapOperation.LdapSearch, resultType, asyncResult._requestTimeout, false); // This should only happen in the polling thread case. if (response == null) { // Only when request time out has not yet expiered. if ((asyncResult._startTime.Ticks + asyncResult._requestTimeout.Ticks) > DateTime.Now.Ticks) { // This is expected, just the client does not have the result yet . return; } else { // time out, now we need to throw proper exception throw new LdapException((int)LdapError.TimeOut, LdapErrorMappings.MapResultCode((int)LdapError.TimeOut)); } } if (asyncResult._response != null) { AddResult(asyncResult._response, response); } else { asyncResult._response = response; } // If search is done, set the flag. if (response.searchDone) { asyncResult._resultStatus = ResultsStatus.Done; } } catch (Exception exception) { if (exception is DirectoryOperationException directoryOperationException) { SearchResponse response = (SearchResponse)directoryOperationException.Response; if (asyncResult._response != null) { AddResult(asyncResult._response, response); } else { asyncResult._response = response; } // Set the response back to the exception so it holds all the results up to now. directoryOperationException.Response = asyncResult._response; } else if (exception is LdapException ldapException) { if (asyncResult._response != null) { // add previous retrieved entries if available if (asyncResult._response.Entries != null) { for (int i = 0; i < asyncResult._response.Entries.Count; i++) { ldapException.PartialResults.Add(asyncResult._response.Entries[i]); } } // add previous retrieved references if available if (asyncResult._response.References != null) { for (int i = 0; i < asyncResult._response.References.Count; i++) { ldapException.PartialResults.Add(asyncResult._response.References[i]); } } } } // Exception occurs, this operation is done. asyncResult._exception = exception; asyncResult._resultStatus = ResultsStatus.Done; // Need to abandon this request. Wldap32.ldap_abandon(connection._ldapHandle, asyncResult._messageID); } } public void NeedCompleteResult(LdapPartialAsyncResult asyncResult) { lock (this) { if (_resultList.Contains(asyncResult)) { // We don't need partial results anymore, polling for complete results. if (asyncResult._resultStatus == ResultsStatus.PartialResult) asyncResult._resultStatus = ResultsStatus.CompleteResult; } else { throw new ArgumentException(SR.InvalidAsyncResult); } } } public PartialResultsCollection GetPartialResults(LdapPartialAsyncResult asyncResult) { lock (this) { if (!_resultList.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } if (asyncResult._exception != null) { // Remove this async operation // The async operation basically failed, we won't do it any more, so throw // exception to the user and remove it from the list. _resultList.Remove(asyncResult); throw asyncResult._exception; } var collection = new PartialResultsCollection(); if (asyncResult._response != null) { if (asyncResult._response.Entries != null) { for (int i = 0; i < asyncResult._response.Entries.Count; i++) { collection.Add(asyncResult._response.Entries[i]); } asyncResult._response.Entries.Clear(); } if (asyncResult._response.References != null) { for (int i = 0; i < asyncResult._response.References.Count; i++) { collection.Add(asyncResult._response.References[i]); } asyncResult._response.References.Clear(); } } return collection; } } public DirectoryResponse GetCompleteResult(LdapPartialAsyncResult asyncResult) { lock (this) { if (!_resultList.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } Debug.Assert(asyncResult._resultStatus == ResultsStatus.Done); _resultList.Remove(asyncResult); if (asyncResult._exception != null) { throw asyncResult._exception; } else { return asyncResult._response; } } } private void AddResult(SearchResponse partialResults, SearchResponse newResult) { if (newResult == null) { return; } if (newResult.Entries != null) { for (int i = 0; i < newResult.Entries.Count; i++) { partialResults.Entries.Add(newResult.Entries[i]); } } if (newResult.References != null) { for (int i = 0; i < newResult.References.Count; i++) { partialResults.References.Add(newResult.References[i]); } } } } internal class PartialResultsRetriever { private readonly ManualResetEvent _workThreadWaitHandle = null; private readonly LdapPartialResultsProcessor _processor = null; internal PartialResultsRetriever(ManualResetEvent eventHandle, LdapPartialResultsProcessor processor) { _workThreadWaitHandle = eventHandle; _processor = processor; // Start the thread. var thread = new Thread(new ThreadStart(ThreadRoutine)) { IsBackground = true }; thread.Start(); } private void ThreadRoutine() { while (true) { // Make sure there is work to do. _workThreadWaitHandle.WaitOne(); // Do the real work. try { _processor.RetrievingSearchResults(); } catch (Exception e) { // We catch the exception here as we don't really want our worker thread to die because it // encounter certain exception when processing a single async operation. Debug.WriteLine(e.Message); } // Voluntarily gives up the CPU time. Thread.Sleep(250); } } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace SharpDX.Direct3D9 { /// <summary> /// D3DX constants and methods /// </summary> public static class D3DX { /// <summary> /// The value used to signify that the default value for a parameter should be used. /// </summary> /// <unmanaged>D3DX_DEFAULT</unmanaged> public const int Default = -1; /// <summary> /// The default value for non power-of-two textures. /// </summary> /// <unmanaged>D3DX_DEFAULT_NONPOW2</unmanaged> public const int DefaultNonPowerOf2 = -2; /// <summary> /// Indicates that the method should format from file. /// </summary> /// <unmanaged>D3DFMT_FROM_FILE</unmanaged> public const int FormatFromFile = -3; /// <summary> /// Indicates that the method should load from file. /// </summary> /// <unmanaged>D3DX_FROM_FILE</unmanaged> public const int FromFile = -3; /// <summary> /// Checks the D3DX runtime version against this compiled version. /// </summary> /// <returns>True if version are compatible</returns> /// <unmanaged>BOOL D3DXCheckVersion([In] unsigned int D3DSdkVersion,[In] unsigned int D3DXSdkVersion)</unmanaged> public static bool CheckVersion() { return D3DX9.CheckVersion(D3D9.SdkVersion, D3DX9.SdkVersion); } /// <summary> /// Get and set debug mute mode. /// </summary> /// <param name="mute">if set to <c>true</c> [mute].</param> /// <returns>Return the debug mute mode</returns> /// <unmanaged>BOOL D3DXDebugMute([In] BOOL Mute)</unmanaged> public static bool DebugMute(bool mute) { return D3DX9.DebugMute(mute); } /// <summary> /// Converts a declarator from a flexible vertex format (FVF) code. /// </summary> /// <param name="fvf">Combination of <see cref="VertexFormat"/> that describes the FVF from which to generate the returned declarator array..</param> /// <returns> /// A declarator from a flexible vertex format (FVF) code. /// </returns> /// <unmanaged>HRESULT D3DXDeclaratorFromFVF([In] D3DFVF FVF,[In, Buffer] D3DVERTEXELEMENT9* pDeclarator)</unmanaged> public static VertexElement[] DeclaratorFromFVF(VertexFormat fvf) { var vertices = new VertexElement[(int)VertexFormatDeclaratorCount.Max]; var result = D3DX9.DeclaratorFromFVF(fvf, vertices); if (result.Failure) return null; var copy = new VertexElement[D3DX9.GetDeclLength(vertices) + 1]; Array.Copy(vertices, copy, copy.Length); copy[copy.Length - 1] = VertexElement.VertexDeclarationEnd; return copy; } /// <summary> /// Converts a flexible vertex format (FVF) code from a declarator. /// </summary> /// <param name="declarator">The declarator array.</param> /// <returns>A <see cref="VertexFormat"/> that describes the vertex format returned from the declarator.</returns> /// <unmanaged>HRESULT D3DXFVFFromDeclarator([In, Buffer] const D3DVERTEXELEMENT9* pDeclarator,[Out] D3DFVF* pFVF)</unmanaged> public static VertexFormat FVFFromDeclarator(VertexElement[] declarator) { return D3DX9.FVFFromDeclarator(declarator); } /// <summary> /// Generates an output vertex declaration from the input declaration. The output declaration is intended for use by the mesh tessellation functions. /// </summary> /// <param name="declaration">The input declaration.</param> /// <returns>The output declaration</returns> /// <unmanaged>HRESULT D3DXGenerateOutputDecl([In, Buffer] D3DVERTEXELEMENT9* pOutput,[In, Buffer] const D3DVERTEXELEMENT9* pInput)</unmanaged> public static VertexElement[] GenerateOutputDeclaration(VertexElement[] declaration) { var vertices = new VertexElement[(int)VertexFormatDeclaratorCount.Max]; var result = D3DX9.GenerateOutputDecl(vertices, declaration); if (result.Failure) return null; var copy = new VertexElement[D3DX9.GetDeclLength(vertices) + 1]; Array.Copy(vertices, copy, copy.Length); copy[copy.Length - 1] = VertexElement.VertexDeclarationEnd; return copy; } /// <summary> /// Gets the number of elements in the vertex declaration. /// </summary> /// <param name="declaration">The declaration.</param> /// <returns>The number of elements in the vertex declaration.</returns> /// <unmanaged>unsigned int D3DXGetDeclLength([In, Buffer] const D3DVERTEXELEMENT9* pDecl)</unmanaged> public static int GetDeclarationLength(VertexElement[] declaration) { return D3DX9.GetDeclLength(declaration); } /// <summary> /// Gets the size of a vertex from the vertex declaration. /// </summary> /// <param name="elements">The elements.</param> /// <param name="stream">The stream.</param> /// <returns>The vertex declaration size, in bytes.</returns> /// <unmanaged>unsigned int D3DXGetDeclVertexSize([In, Buffer] const D3DVERTEXELEMENT9* pDecl,[In] unsigned int Stream)</unmanaged> public static int GetDeclarationVertexSize(VertexElement[] elements, int stream) { return D3DX9.GetDeclVertexSize(elements, stream); } /// <summary> /// Returns the size of a vertex for a flexible vertex format (FVF). /// </summary> /// <param name="fvf">The vertex format.</param> /// <returns>The FVF vertex size, in bytes.</returns> /// <unmanaged>unsigned int D3DXGetFVFVertexSize([In] D3DFVF FVF)</unmanaged> public static int GetFVFVertexSize(VertexFormat fvf) { return D3DX9.GetFVFVertexSize(fvf); } /// <summary> /// Gets the size of the rectangle patch. /// </summary> /// <param name="segmentCount">The segment count.</param> /// <param name="triangleCount">The triangle count.</param> /// <param name="vertexCount">The vertex count.</param> /// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns> /// <unmanaged>HRESULT D3DXRectPatchSize([In] const float* pfNumSegs,[In] unsigned int* pdwTriangles,[In] unsigned int* pdwVertices)</unmanaged> public static Result GetRectanglePatchSize(float segmentCount, out int triangleCount, out int vertexCount) { return D3DX9.RectPatchSize(segmentCount, out triangleCount, out vertexCount); } /// <summary> /// Gets the size of the triangle patch. /// </summary> /// <param name="segmentCount">The segment count.</param> /// <param name="triangleCount">The triangle count.</param> /// <param name="vertexCount">The vertex count.</param> /// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns> /// <unmanaged>HRESULT D3DXTriPatchSize([In] const float* pfNumSegs,[In] unsigned int* pdwTriangles,[In] unsigned int* pdwVertices)</unmanaged> public static Result GetTrianglePatchSize(float segmentCount, out int triangleCount, out int vertexCount) { return D3DX9.TriPatchSize(segmentCount, out triangleCount, out vertexCount); } /// <summary> /// Gets an array of <see cref="Vector3"/> from a <see cref="DataStream"/>. /// </summary> /// <param name="stream">The stream.</param> /// <param name="vertexCount">The vertex count.</param> /// <param name="format">The format.</param> /// <returns>An array of <see cref="Vector3"/> </returns> public static Vector3[] GetVectors(DataStream stream, int vertexCount, VertexFormat format) { int stride = GetFVFVertexSize(format); return GetVectors(stream, vertexCount, stride); } /// <summary> /// Gets an array of <see cref="Vector3"/> from a <see cref="DataStream"/>. /// </summary> /// <param name="stream">The stream.</param> /// <param name="vertexCount">The vertex count.</param> /// <param name="stride">The stride.</param> /// <returns>An array of <see cref="Vector3"/> </returns> public static Vector3[] GetVectors(DataStream stream, int vertexCount, int stride) { unsafe { var results = new Vector3[vertexCount]; for (int i = 0; i < vertexCount; i++) { results[i] = stream.Read<Vector3>(); stream.Position += stride - sizeof(Vector3); } return results; } } /// <summary> /// Creates a FOURCC Format code from bytes description. /// </summary> /// <param name="c1">The c1.</param> /// <param name="c2">The c2.</param> /// <param name="c3">The c3.</param> /// <param name="c4">The c4.</param> /// <returns>A Format FourCC</returns> /// <unmanaged>MAKEFOURCC</unmanaged> public static Format MakeFourCC(byte c1, byte c2, byte c3, byte c4) { return (Format)((((((c4 << 8) | c3) << 8) | c2) << 8) | c1); } /// <summary> /// Generates an optimized face remapping for a triangle list. /// </summary> /// <param name="indices">The indices.</param> /// <param name="faceCount">The face count.</param> /// <param name="vertexCount">The vertex count.</param> /// <returns>The original mesh face that was split to generate the current face.</returns> /// <unmanaged>HRESULT D3DXOptimizeFaces([In] const void* pbIndices,[In] unsigned int cFaces,[In] unsigned int cVertices,[In] BOOL b32BitIndices,[In, Buffer] int* pFaceRemap)</unmanaged> public static int[] OptimizeFaces(short[] indices, int faceCount, int vertexCount) { unsafe { var faces = new int[faceCount]; Result result; fixed (void* pIndices = indices) result = D3DX9.OptimizeFaces((IntPtr)pIndices, faceCount, indices.Length, false, faces); if (result.Failure) return null; return faces; } } /// <summary> /// Generates an optimized vertex remapping for a triangle list. This function is commonly used after applying the face remapping generated by D3DXOptimizeFaces. /// </summary> /// <param name="indices">The indices.</param> /// <param name="faceCount">The face count.</param> /// <param name="vertexCount">The vertex count.</param> /// <returns>The original mesh face that was split to generate the current face.</returns> /// <unmanaged>HRESULT D3DXOptimizeFaces([In] const void* pbIndices,[In] unsigned int cFaces,[In] unsigned int cVertices,[In] BOOL b32BitIndices,[In, Buffer] int* pFaceRemap)</unmanaged> public static int[] OptimizeFaces(int[] indices, int faceCount, int vertexCount) { unsafe { var faces = new int[faceCount]; Result result; fixed (void* pIndices = indices) result = D3DX9.OptimizeFaces((IntPtr)pIndices, faceCount, indices.Length, true, faces); if (result.Failure) return null; return faces; } } /// <summary> /// Generates an optimized vertex remapping for a triangle list. This function is commonly used after applying the face remapping generated by <see cref="OptimizeFaces(short[],int,int)"/>. /// </summary> /// <param name="indices">The indices.</param> /// <param name="faceCount">The face count.</param> /// <param name="vertexCount">The vertex count.</param> /// <returns>A buffer that will contain the new index for each vertex. The value stored in pVertexRemap for a given element is the source vertex location in the new vertex ordering.</returns> /// <unmanaged>HRESULT D3DXOptimizeVertices([In] const void* pbIndices,[In] unsigned int cFaces,[In] unsigned int cVertices,[In] BOOL b32BitIndices,[In, Buffer] int* pVertexRemap)</unmanaged> public static int[] OptimizeVertices(short[] indices, int faceCount, int vertexCount) { unsafe { var faces = new int[faceCount]; Result result; fixed (void* pIndices = indices) result = D3DX9.OptimizeVertices((IntPtr)pIndices, faceCount, indices.Length, false, faces); if (result.Failure) return null; return faces; } } /// <summary> /// Generates an optimized vertex remapping for a triangle list. This function is commonly used after applying the face remapping generated by <see cref="OptimizeFaces(int[],int,int)"/>. /// </summary> /// <param name="indices">The indices.</param> /// <param name="faceCount">The face count.</param> /// <param name="vertexCount">The vertex count.</param> /// <returns>A buffer that will contain the new index for each vertex. The value stored in pVertexRemap for a given element is the source vertex location in the new vertex ordering.</returns> /// <unmanaged>HRESULT D3DXOptimizeVertices([In] const void* pbIndices,[In] unsigned int cFaces,[In] unsigned int cVertices,[In] BOOL b32BitIndices,[In, Buffer] int* pVertexRemap)</unmanaged> public static int[] OptimizeVertices(int[] indices, int faceCount, int vertexCount) { unsafe { var faces = new int[faceCount]; Result result; fixed (void* pIndices = indices) result = D3DX9.OptimizeVertices((IntPtr)pIndices, faceCount, indices.Length, true, faces); if (result.Failure) return null; return faces; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Typewriter.Generation.Controllers { /// <summary> /// Same as Queue except Dequeue function blocks until there is an object to return. /// Note: This class does not need to be synchronized /// </summary> public class BlockingQueue<T> : ICollection { private Queue<T> _base; private bool _open; /// <summary> /// Create new BlockingQueue. /// </summary> /// <param name="col">The System.Collections.ICollection to copy elements from</param> //public BlockingQueue(ICollection<T> col) //{ // _base = new Queue<T>(col); // _open = true; //} /// <summary> /// Create new BlockingQueue. /// </summary> /// <param name="capacity">The initial number of elements that the queue can contain</param> public BlockingQueue(int capacity) { _base = new Queue<T>(capacity); _open = true; } /// <summary> /// Create new BlockingQueue. /// </summary> public BlockingQueue() { _base = new Queue<T>(); _open = true; } /// <summary> /// BlockingQueue Destructor (Close queue, resume any waiting thread). /// </summary> ~BlockingQueue() { Close(); } /// <summary> /// Remove all objects from the Queue. /// </summary> public void Clear() { lock (_SyncRoot) { _base.Clear(); } } /// <summary> /// Remove all objects from the Queue, resume all dequeue threads. /// </summary> public void Close() { lock (_SyncRoot) { if (_open) { _open = false; _base.Clear(); // resume any waiting threads Monitor.PulseAll(_SyncRoot); } } } /// <summary> /// Removes and returns the object at the beginning of the Queue. /// </summary> /// <returns>Object in queue.</returns> public T Dequeue() { return Dequeue(Timeout.Infinite); } /// <summary> /// Removes and returns the object at the beginning of the Queue. /// </summary> /// <param name="timeout">time to wait before returning</param> /// <returns>Object in queue.</returns> public T Dequeue(TimeSpan timeout) { return Dequeue(timeout.Milliseconds); } /// <summary> /// Removes and returns the object at the beginning of the Queue. /// </summary> /// <param name="timeout">time to wait before returning (in milliseconds)</param> /// <returns>Object in queue.</returns> public T Dequeue(int timeout) { lock (_SyncRoot) { while (_open && (_base.Count == 0)) { if (!Monitor.Wait(_SyncRoot, timeout)) { throw new InvalidOperationException("Timeout"); } } if (_open) { return _base.Dequeue(); } throw new InvalidOperationException("Queue Closed"); } } public T Peek() { lock (_SyncRoot) { while (_open && (_base.Count == 0)) { if (!Monitor.Wait(_SyncRoot, Timeout.Infinite)) { throw new InvalidOperationException("Timeout"); } } if (_open) { return _base.Peek(); } throw new InvalidOperationException("Queue Closed"); } } /// <summary> /// Adds an object to the end of the Queue. /// </summary> /// <param name="obj">Object to put in queue</param> public void Enqueue(T obj) { lock (_SyncRoot) { _base.Enqueue(obj); Monitor.Pulse(_SyncRoot); } } public bool EnqueueIfNotContains(T obj) { bool added = false; lock (_SyncRoot) { if (!_base.Contains(obj)) { _base.Enqueue(obj); added = true; } Monitor.Pulse(_SyncRoot); } return added; } public bool EnqueueIfNotContains(T obj, IEqualityComparer<T> comparer) { bool added = false; lock (_SyncRoot) { if (!_base.Contains(obj, comparer)) { _base.Enqueue(obj); added = true; //Else // Trace.WriteLine("Already in Queue") } Monitor.Pulse(_SyncRoot); } return added; } /// <summary> /// Open Queue. /// </summary> public void Open() { lock (_SyncRoot) { _open = true; } } /// <summary> /// Gets flag indicating if queue has been closed. /// </summary> public bool Closed { get { return !_open; } } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get { return _base.Count; } } public bool IsSynchronized { get { return true; } } private object _SyncRoot = new object(); public object SyncRoot { get { return _SyncRoot; } } public System.Collections.IEnumerator GetEnumerator() { return _base.GetEnumerator(); } } }
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 BdsTipoDonante class. /// </summary> [Serializable] public partial class BdsTipoDonanteCollection : ActiveList<BdsTipoDonante, BdsTipoDonanteCollection> { public BdsTipoDonanteCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>BdsTipoDonanteCollection</returns> public BdsTipoDonanteCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { BdsTipoDonante 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 BDS_TipoDonante table. /// </summary> [Serializable] public partial class BdsTipoDonante : ActiveRecord<BdsTipoDonante>, IActiveRecord { #region .ctors and Default Settings public BdsTipoDonante() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public BdsTipoDonante(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public BdsTipoDonante(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public BdsTipoDonante(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("BDS_TipoDonante", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdTipoDonante = new TableSchema.TableColumn(schema); colvarIdTipoDonante.ColumnName = "idTipoDonante"; colvarIdTipoDonante.DataType = DbType.Int32; colvarIdTipoDonante.MaxLength = 0; colvarIdTipoDonante.AutoIncrement = true; colvarIdTipoDonante.IsNullable = false; colvarIdTipoDonante.IsPrimaryKey = true; colvarIdTipoDonante.IsForeignKey = false; colvarIdTipoDonante.IsReadOnly = false; colvarIdTipoDonante.DefaultSetting = @""; colvarIdTipoDonante.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTipoDonante); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("BDS_TipoDonante",schema); } } #endregion #region Props [XmlAttribute("IdTipoDonante")] [Bindable(true)] public int IdTipoDonante { get { return GetColumnValue<int>(Columns.IdTipoDonante); } set { SetColumnValue(Columns.IdTipoDonante, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #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 varNombre) { BdsTipoDonante item = new BdsTipoDonante(); item.Nombre = varNombre; 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 varIdTipoDonante,string varNombre) { BdsTipoDonante item = new BdsTipoDonante(); item.IdTipoDonante = varIdTipoDonante; item.Nombre = varNombre; 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 IdTipoDonanteColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdTipoDonante = @"idTipoDonante"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// <copyright file="NotifyCollectionChangedInvokerBase.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using JetBrains.Annotations; namespace IX.StandardExtensions.ComponentModel; /// <summary> /// A base class for collections that notify of changes. /// </summary> /// <seealso cref="IX.StandardExtensions.ComponentModel.NotifyPropertyChangedBase" /> /// <seealso cref="INotifyCollectionChanged" /> [PublicAPI] public class NotifyCollectionChangedInvokerBase : NotifyPropertyChangedBase, INotifyCollectionChanged { #region Constructors and destructors /// <summary> /// Initializes a new instance of the <see cref="NotifyCollectionChangedInvokerBase" /> class. /// </summary> protected NotifyCollectionChangedInvokerBase() { } /// <summary> /// Initializes a new instance of the <see cref="NotifyCollectionChangedInvokerBase" /> class. /// </summary> /// <param name="synchronizationContext">The specific synchronization context to use.</param> protected NotifyCollectionChangedInvokerBase(SynchronizationContext synchronizationContext) : base(synchronizationContext) { } #endregion #region Events /// <summary> /// Occurs when the collection changes. /// </summary> public event NotifyCollectionChangedEventHandler? CollectionChanged; #endregion #region Methods /// <summary> /// Sends a notification to all the viewers of an observable collection inheriting this base class that their view /// should be refreshed. /// </summary> /// <remarks> /// This method is not affected by a notification suppression context, which means that it will send notifications even /// if there currently is an ambient notification suppression context. /// </remarks> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] public void RefreshViewers() { if (this.CollectionChanged != null) { this.Invoke(this.CollectionResetInvocationMethod); } } /// <summary> /// Asynchronously sends a notification to all the viewers of an observable collection inheriting this base class /// that their view should be refreshed. /// </summary> /// <remarks> /// This method is not affected by a notification suppression context, which means that it will send notifications even /// if there currently is an ambient notification suppression context. /// </remarks> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] public void RefreshViewersAsynchronously() { if (this.CollectionChanged != null) { this.InvokePost(this.CollectionResetInvocationMethod); } } /// <summary> /// Synchronously sends a notification to all the viewers of an observable collection inheriting this base class /// that their view should be refreshed. /// </summary> /// <remarks> /// This method is not affected by a notification suppression context, which means that it will send notifications even /// if there currently is an ambient notification suppression context. /// </remarks> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] public void RefreshViewersSynchronously() { if (this.CollectionChanged != null) { this.InvokeSend(this.CollectionResetInvocationMethod); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection reset event. /// </summary> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] [SuppressMessage( "Design", "CA1030:Use events where appropriate", Justification = "This is used to raise the event.")] protected void RaiseCollectionReset() { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.Invoke(this.CollectionResetInvocationMethod); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection reset event asynchronously. /// </summary> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void PostCollectionReset() { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokePost(this.CollectionResetInvocationMethod); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection reset event synchronously. /// </summary> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void SendCollectionReset() { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokeSend(this.CollectionResetInvocationMethod); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection addition event of one element. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the item was added.</param> /// <param name="item">The item that was added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] [SuppressMessage( "Design", "CA1030:Use events where appropriate", Justification = "This is used to raise the event.")] protected void RaiseCollectionAdd<T>( int index, T item) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.Invoke( this.CollectionAddItemInvocationMethod, index, item); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection addition event of one element asynchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the item was added.</param> /// <param name="item">The item that was added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void PostCollectionAdd<T>( int index, T item) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokePost( this.CollectionAddItemInvocationMethod, index, item); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection addition event of one element synchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the item was added.</param> /// <param name="item">The item that was added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void SendCollectionAdd<T>( int index, T item) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokeSend( this.CollectionAddItemInvocationMethod, index, item); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection addition event of multiple elements. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the items were added.</param> /// <param name="items">The items that were added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] [SuppressMessage( "Design", "CA1030:Use events where appropriate", Justification = "This is used to raise the event.")] protected void RaiseCollectionAdd<T>( int index, IEnumerable<T> items) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.Invoke( this.CollectionAddItemsInvocationMethod, index, items); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection addition event of multiple elements /// asynchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the items were added.</param> /// <param name="items">The items that were added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void PostCollectionAdd<T>( int index, IEnumerable<T> items) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokePost( this.CollectionAddItemsInvocationMethod, index, items); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection addition event of multiple elements /// synchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the items were added.</param> /// <param name="items">The items that were added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void SendCollectionAdd<T>( int index, IEnumerable<T> items) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokeSend( this.CollectionAddItemsInvocationMethod, index, items); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection removal event of one element. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the item was removed.</param> /// <param name="item">The item that was added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] [SuppressMessage( "Design", "CA1030:Use events where appropriate", Justification = "This is used to raise the event.")] protected void RaiseCollectionRemove<T>( int index, T item) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.Invoke( this.CollectionRemoveItemInvocationMethod, index, item); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection removal event of one element asynchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the item was removed.</param> /// <param name="item">The item that was added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void PostCollectionRemove<T>( int index, T item) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokePost( this.CollectionRemoveItemInvocationMethod, index, item); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection removal event of one element synchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the item was removed.</param> /// <param name="item">The item that was added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void SendCollectionRemove<T>( int index, T item) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokeSend( this.CollectionRemoveItemInvocationMethod, index, item); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection removal event of multiple elements. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the items were removed.</param> /// <param name="items">The items that were removed.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] [SuppressMessage( "Design", "CA1030:Use events where appropriate", Justification = "This is used to raise the event.")] protected void RaiseCollectionRemove<T>( int index, IEnumerable<T> items) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.Invoke( this.CollectionRemoveItemsInvocationMethod, index, items); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection removal event of multiple elements /// asynchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the items were removed.</param> /// <param name="items">The items that were removed.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void PostCollectionRemove<T>( int index, IEnumerable<T> items) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokePost( this.CollectionRemoveItemsInvocationMethod, index, items); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection removal event of multiple elements /// synchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the items were removed.</param> /// <param name="items">The items that were removed.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void SendCollectionRemove<T>( int index, IEnumerable<T> items) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokeSend( this.CollectionRemoveItemsInvocationMethod, index, items); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection move event of one element. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="oldIndex">The index from which the item was moved.</param> /// <param name="newIndex">The index at which the item was moved.</param> /// <param name="item">The item that was added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] [SuppressMessage( "Design", "CA1030:Use events where appropriate", Justification = "This is used to raise the event.")] protected void RaiseCollectionMove<T>( int oldIndex, int newIndex, T item) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.Invoke( this.CollectionMoveItemInvocationMethod, oldIndex, newIndex, item); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection move event of one element asynchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="oldIndex">The index from which the item was moved.</param> /// <param name="newIndex">The index at which the item was moved.</param> /// <param name="item">The item that was added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void PostCollectionMove<T>( int oldIndex, int newIndex, T item) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokePost( this.CollectionMoveItemInvocationMethod, oldIndex, newIndex, item); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection move event of one element synchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="oldIndex">The index from which the item was moved.</param> /// <param name="newIndex">The index at which the item was moved.</param> /// <param name="item">The item that was added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void SendCollectionMove<T>( int oldIndex, int newIndex, T item) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokeSend( this.CollectionMoveItemInvocationMethod, oldIndex, newIndex, item); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection move event of multiple elements. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="oldIndex">The index from which the items were moved.</param> /// <param name="newIndex">The index at which the items were moved.</param> /// <param name="items">The items that were added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] [SuppressMessage( "Design", "CA1030:Use events where appropriate", Justification = "This is used to raise the event.")] protected void RaiseCollectionMove<T>( int oldIndex, int newIndex, IEnumerable<T> items) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.Invoke( this.CollectionMoveItemsInvocationMethod, oldIndex, newIndex, items); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection move event of multiple elements asynchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="oldIndex">The index from which the items were moved.</param> /// <param name="newIndex">The index at which the items were moved.</param> /// <param name="items">The items that were added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void PostCollectionMove<T>( int oldIndex, int newIndex, IEnumerable<T> items) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokePost( this.CollectionMoveItemsInvocationMethod, oldIndex, newIndex, items); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection move event of multiple elements synchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="oldIndex">The index from which the items were moved.</param> /// <param name="newIndex">The index at which the items were moved.</param> /// <param name="items">The items that were added.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void SendCollectionMove<T>( int oldIndex, int newIndex, IEnumerable<T> items) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokeSend( this.CollectionMoveItemsInvocationMethod, oldIndex, newIndex, items); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection replacement event of one element. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the item was added.</param> /// <param name="oldItem">The original item.</param> /// <param name="newItem">The new item.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] [SuppressMessage( "Design", "CA1030:Use events where appropriate", Justification = "This is used to raise the event.")] protected void RaiseCollectionReplace<T>( int index, T oldItem, T newItem) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.Invoke( this.CollectionReplaceItemInvocationMethod, index, oldItem, newItem); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection replacement event of one element /// asynchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the item was added.</param> /// <param name="oldItem">The original item.</param> /// <param name="newItem">The new item.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void PostCollectionReplace<T>( int index, T oldItem, T newItem) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokePost( this.CollectionReplaceItemInvocationMethod, index, oldItem, newItem); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection replacement event of one element synchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the item was added.</param> /// <param name="oldItem">The original item.</param> /// <param name="newItem">The new item.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void SendCollectionReplace<T>( int index, T oldItem, T newItem) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokeSend( this.CollectionReplaceItemInvocationMethod, index, oldItem, newItem); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection replacement event of multiple elements. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the items were added.</param> /// <param name="oldItems">The original items.</param> /// <param name="newItems">The new items.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] [SuppressMessage( "Design", "CA1030:Use events where appropriate", Justification = "This is used to raise the event.")] protected void RaiseCollectionReplace<T>( int index, IEnumerable<T> oldItems, IEnumerable<T> newItems) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.Invoke( this.CollectionReplaceItemsInvocationMethod, index, oldItems, newItems); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection replacement event of multiple elements /// asynchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the items were added.</param> /// <param name="oldItems">The original items.</param> /// <param name="newItems">The new items.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void PostCollectionReplace<T>( int index, IEnumerable<T> oldItems, IEnumerable<T> newItems) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokePost( this.CollectionReplaceItemsInvocationMethod, index, oldItems, newItems); } } /// <summary> /// Triggers the <see cref="CollectionChanged" /> event as a collection replacement event of multiple elements /// synchronously. /// </summary> /// <typeparam name="T">The type of the item of the collection.</typeparam> /// <param name="index">The index at which the items were added.</param> /// <param name="oldItems">The original items.</param> /// <param name="newItems">The new items.</param> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "This is how the invoker works.")] protected void SendCollectionReplace<T>( int index, IEnumerable<T> oldItems, IEnumerable<T> newItems) { if (SuppressNotificationsContext.AmbientSuppressionActive.Value) { return; } if (this.CollectionChanged != null) { this.InvokeSend( this.CollectionReplaceItemsInvocationMethod, index, oldItems, newItems); } } private void CollectionResetInvocationMethod() => this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); [SuppressMessage( "Design", "CA1031:Do not catch general exception types", Justification = "We have to catch Exception here, as that is the point of the invoker.")] [SuppressMessage( "Performance", "HAA0601:Value type to reference type conversion causing boxing allocation", Justification = "We're sending it through an event, unavoidable.")] private void CollectionAddItemInvocationMethod<T>( int internalIndex, T internalItem) { try { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, internalItem, internalIndex)); } catch (Exception) when (EnvironmentSettings.ResetOnCollectionChangeNotificationException) { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } [SuppressMessage( "Design", "CA1031:Do not catch general exception types", Justification = "We have to catch Exception here, as that is the point of the invoker.")] private void CollectionAddItemsInvocationMethod<T>( int internalIndex, IEnumerable<T> internalItems) { try { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, internalItems.ToList(), internalIndex)); } catch (Exception) when (EnvironmentSettings.ResetOnCollectionChangeNotificationException) { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } [SuppressMessage( "Design", "CA1031:Do not catch general exception types", Justification = "We have to catch Exception here, as that is the point of the invoker.")] [SuppressMessage( "Performance", "HAA0601:Value type to reference type conversion causing boxing allocation", Justification = "We're sending it through an event, unavoidable.")] private void CollectionRemoveItemInvocationMethod<T>( int internalIndex, T internalItem) { try { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, internalItem, internalIndex)); } catch (Exception) when (EnvironmentSettings.ResetOnCollectionChangeNotificationException) { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } [SuppressMessage( "Design", "CA1031:Do not catch general exception types", Justification = "We have to catch Exception here, as that is the point of the invoker.")] private void CollectionRemoveItemsInvocationMethod<T>( int internalIndex, IEnumerable<T> internalItems) { try { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, internalItems.ToList(), internalIndex)); } catch (Exception) when (EnvironmentSettings.ResetOnCollectionChangeNotificationException) { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } [SuppressMessage( "Design", "CA1031:Do not catch general exception types", Justification = "We have to catch Exception here, as that is the point of the invoker.")] [SuppressMessage( "Performance", "HAA0601:Value type to reference type conversion causing boxing allocation", Justification = "We're sending it through an event, unavoidable.")] private void CollectionMoveItemInvocationMethod<T>( int internalOldIndex, int internalNewIndex, T internalItem) { try { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, internalItem, internalNewIndex, internalOldIndex)); } catch (Exception) when (EnvironmentSettings.ResetOnCollectionChangeNotificationException) { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } [SuppressMessage( "Design", "CA1031:Do not catch general exception types", Justification = "We have to catch Exception here, as that is the point of the invoker.")] private void CollectionMoveItemsInvocationMethod<T>( int internalOldIndex, int internalNewIndex, IEnumerable<T> internalItems) { try { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Move, internalItems.ToList(), internalNewIndex, internalOldIndex)); } catch (Exception) when (EnvironmentSettings.ResetOnCollectionChangeNotificationException) { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } [SuppressMessage( "Design", "CA1031:Do not catch general exception types", Justification = "We have to catch Exception here, as that is the point of the invoker.")] [SuppressMessage( "Performance", "HAA0601:Value type to reference type conversion causing boxing allocation", Justification = "We're sending it through an event, unavoidable.")] private void CollectionReplaceItemInvocationMethod<T>( int internalIndex, T internalOldItem, T internalNewItem) { try { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, internalNewItem, internalOldItem, internalIndex)); } catch (Exception) when (EnvironmentSettings.ResetOnCollectionChangeNotificationException) { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } [SuppressMessage( "Design", "CA1031:Do not catch general exception types", Justification = "We have to catch Exception here, as that is the point of the invoker.")] private void CollectionReplaceItemsInvocationMethod<T>( int internalIndex, IEnumerable<T> internalOldItems, IEnumerable<T> internalNewItems) { try { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, internalNewItems.ToList(), internalOldItems.ToList(), internalIndex)); } catch (Exception) when (EnvironmentSettings.ResetOnCollectionChangeNotificationException) { this.CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } #endregion }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Content; using IRTaktiks.Components.Config; using IRTaktiks.Input; using IRTaktiks.Input.EventArgs; namespace IRTaktiks.Components.Manager { /// <summary> /// Manager of the configuration. /// </summary> public class ConfigurationManager : DrawableGameComponent { #region Event /// <summary> /// The delegate of methods that will handle the touched event. /// </summary> public delegate void ConfiguratedEventHandler(); /// <summary> /// Event fired when a player end the configuration of the items. /// </summary> public event ConfiguratedEventHandler Configurated; #endregion #region Properties /// <summary> /// The index of the player. /// </summary> private PlayerIndex PlayerIndexField; /// <summary> /// The index of the player. /// </summary> public PlayerIndex PlayerIndex { get { return PlayerIndexField; } } /// <summary> /// The value of the base position. /// </summary> private Vector2 BasePositionField; /// <summary> /// The value of the base position. /// </summary> public Vector2 BasePosition { get { return BasePositionField; } } /// <summary> /// The actual selected item. /// </summary> private Configurable SelectedItemField; /// <summary> /// The actual selected item. /// </summary> public Configurable SelectedItem { get { return SelectedItemField; } } /// <summary> /// The config keyboard. /// </summary> private Keyboard KeyboardField; /// <summary> /// The config keyboard. /// </summary> public Keyboard Keyboard { get { return KeyboardField; } } /// <summary> /// The config of player. /// </summary> private PlayerConfig PlayerConfigField; /// <summary> /// The config of player. /// </summary> public PlayerConfig PlayerConfig { get { return PlayerConfigField; } } /// <summary> /// The list of the config of unit /// </summary> private List<UnitConfig> UnitsConfigField; /// <summary> /// The list of the config of unit /// </summary> public List<UnitConfig> UnitsConfig { get { return UnitsConfigField; } } /// <summary> /// Indicate that the game is ready to start; /// </summary> private bool ReadyToStart; #endregion #region Constructor /// <summary> /// Constructor of class. /// </summary> /// <param name="game">The instance of game that is running.</param> public ConfigurationManager(Game game, PlayerIndex playerIndex) : base(game) { this.PlayerIndexField = playerIndex; switch (playerIndex) { case PlayerIndex.One: this.BasePositionField = new Vector2(0, 0); break; case PlayerIndex.Two: this.BasePositionField = new Vector2(640, 0); break; } // Items creation this.KeyboardField = new Keyboard(game, playerIndex); this.PlayerConfigField = new PlayerConfig(game, playerIndex); // Units config creation this.UnitsConfigField = new List<UnitConfig>(); for (int index = 0; index < IRTSettings.Default.UnitsPerPlayer; index++) { UnitConfig unitConfig = new UnitConfig(game, playerIndex, index); unitConfig.Touched += new Configurable.TouchedEventHandler(Configurable_Touched); this.UnitsConfig.Add(unitConfig); } // Event handling this.Keyboard.Typed += new Keyboard.TypedEventHandler(Keyboard_Typed); this.PlayerConfig.Touched += new Configurable.TouchedEventHandler(Configurable_Touched); InputManager.Instance.CursorDown += new EventHandler<CursorDownArgs>(CursorDown); } #endregion #region Component Methods /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { base.Initialize(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { this.ReadyToStart = this.Keyboard.Configurated && this.PlayerConfig.Configurated && this.UnitsConfig.FindAll( delegate(UnitConfig unitConfig) { return unitConfig.Configurated; } ).Count == this.UnitsConfig.Count; base.Update(gameTime); } /// <summary> /// Called when the DrawableGameComponent needs to be drawn. Override this method /// with component-specific drawing code. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Draw(GameTime gameTime) { if (this.ReadyToStart) { IRTGame game = this.Game as IRTGame; game.SpriteManager.Draw(TextureManager.Instance.Sprites.Config.Start, new Vector2(this.BasePositionField.X + 39, this.BasePositionField.Y + 655), Color.White, 30); } base.Draw(gameTime); } #endregion #region Methods /// <summary> /// Handle the CursorDown event. /// </summary> private void CursorDown(object sender, CursorDownArgs e) { if (this.ReadyToStart) { if ((e.Position.X > 39 && e.Position.X < (39 + TextureManager.Instance.Sprites.Config.Start.Width)) && (e.Position.Y > 655 && e.Position.Y < (655 + TextureManager.Instance.Sprites.Config.Start.Height))) { this.Configurated(); } } } /// <summary> /// Unregister all events of the item. /// </summary> public void Unregister() { InputManager.Instance.CursorDown -= CursorDown; } #endregion #region Event Handling /// <summary> /// Handle the pressed event of the keyboard. /// </summary> /// <param name="letter">The letther that was touched on the keyboard.</param> private void Keyboard_Typed(string letter) { if (this.SelectedItem != null) { if (letter != null) { this.SelectedItem.DisplayText.Append(letter); } else { if (this.SelectedItem.DisplayText.Length > 0) { this.SelectedItem.DisplayText.Remove(this.SelectedItem.DisplayText.Length - 1, 1); } } } } /// <summary> /// Handle the touched event of the items. /// </summary> /// <param name="item">The item touched</param> private void Configurable_Touched(Configurable item) { if (item.Selected) { this.SelectedItemField = null; item.Selected = false; } else { this.Keyboard.Selected = false; this.PlayerConfig.Selected = false; for (int index = 0; index < this.UnitsConfig.Count; index++) { this.UnitsConfig[index].Selected = false; } this.SelectedItemField = item; item.Selected = true; } } #endregion } }
// The MIT License // // Copyright (c) 2013 Jordan E. Terrell // // 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 FluentAssertions; using NUnit.Framework; using iSynaptic.Commons; namespace iSynaptic { [TestFixture] public class LogicalTypeTests { [Test] public void Equivalence_ImplementedCorrectly() { var type1 = new LogicalType("tst", "Foo"); var type2 = new LogicalType("tst", "foo"); var type3 = new LogicalType("sts", "Bar"); Object type4 = new LogicalType("sts", "Bar"); var type5 = new LogicalType("tst", "Foo", 0, 1.ToMaybe()); var type6 = new LogicalType("tst", "Foo", 0, 1.ToMaybe()); var type7 = new LogicalType("tst", "Foo", 0, 2.ToMaybe()); var type8 = new LogicalType("tst", "Foo", 1, Maybe.NoValue); var type9 = new LogicalType("tst", "Foo", 1, Maybe.NoValue); var type10 = new LogicalType("tst", "Foo", 1, 1.ToMaybe()); var type11 = new LogicalType("tst", "Foo", 1, 1.ToMaybe()); var type12 = new LogicalType("tst", "Foo", 1, 2.ToMaybe()); var type13 = new LogicalType("tst", "Foo", new[] { type1 }, Maybe.NoValue); var type14 = new LogicalType("tst", "Foo", new[] { type1 }, Maybe.NoValue); var type15 = new LogicalType("tst", "Foo", new[] { type1 }, 1.ToMaybe()); var type16 = new LogicalType("tst", "Foo", new[] { type1 }, 2.ToMaybe()); var type17 = new LogicalType("tst", "Foo", new[] { type2 }, Maybe.NoValue); var type18 = new LogicalType("tst", "Foo", new[] { type1, type3 }, Maybe.NoValue); LogicalType nullType = null; (type1 == type2).Should().BeTrue(); (type1 != type3).Should().BeTrue(); (type3.Equals(type4)).Should().BeTrue(); (type5 == type6).Should().BeTrue(); (type1 != type5).Should().BeTrue(); (type6 != type7).Should().BeTrue(); (type7 != type8).Should().BeTrue(); (type8 == type9).Should().BeTrue(); (type9 != type10).Should().BeTrue(); (type10 == type11).Should().BeTrue(); (type11 != type12).Should().BeTrue(); (type8 != type13).Should().BeTrue(); (type13 == type14).Should().BeTrue(); (type14 != type15).Should().BeTrue(); (type15 != type16).Should().BeTrue(); (type14 == type17).Should().BeTrue(); (type13 != type18).Should().BeTrue(); (nullType == null).Should().BeTrue(); (type1 != nullType).Should().BeTrue(); } [Test] public void NamespaceAlias_IsValidated() { Action act = () => new LogicalType("28f;[]';,.", "Foo"); act.ShouldThrow<ArgumentOutOfRangeException>(); } [Test] public void TypeName_IsValidated() { Action act = () => new LogicalType("tst", "28f;[]';,."); act.ShouldThrow<ArgumentOutOfRangeException>(); } [Test] public void QualifiedTypeName_IsPermitted() { var logicalType = new LogicalType("tst", "Outer.Inner"); logicalType.TypeName.Should().Be("Outer.Inner"); } [Test] public void PartiallyOpenLogicalType_ThrowsException() { Action act = () => new LogicalType("tst", "Result", new[] { new LogicalType("tst", "MainId"), new LogicalType("tst", "Obs", 1, Maybe.NoValue) }, Maybe.NoValue); act.ShouldThrow<ArgumentException>(); act = () => new LogicalType("tst", "Result", new[] { new LogicalType("tst", "MainId"), new LogicalType("tst", "Obs", new [] { new LogicalType("tst", "Error", 2, Maybe.NoValue)}, Maybe.NoValue) }, Maybe.NoValue); act.ShouldThrow<ArgumentException>(); } [Test] public void Parse_WithCorrectFormatAndNoVersion_ReturnsLogicalType() { String input = "tst:Foo"; var logicalType = LogicalType.Parse(input); logicalType.Should().NotBeNull(); logicalType.NamespaceAlias.Should().Be("tst"); logicalType.TypeName.Should().Be("Foo"); logicalType.Version.HasValue.Should().BeFalse(); } [Test] public void Parse_WithCorrectFormatAndVersion_ReturnsLogicalType() { String input = "tst:Foo:v42"; var logicalType = LogicalType.Parse(input); logicalType.Should().NotBeNull(); logicalType.NamespaceAlias.Should().Be("tst"); logicalType.TypeName.Should().Be("Foo"); logicalType.Version.HasValue.Should().BeTrue(); logicalType.Version.Value.Should().Be(42); } [Test] public void Parse_WithIncorrectFormat_ThrowsException() { String input = "63^*^*:8*&&(&"; Action act = () => LogicalType.Parse(input); act.ShouldThrow<ArgumentException>(); } [Test] public void TryParse_WithCorrectFormatAndNoVersion_ReturnsLogicalType() { String input = "tst:Foo"; var logicalType = LogicalType.TryParse(input); logicalType.HasValue.Should().BeTrue(); logicalType.Value.NamespaceAlias.Should().Be("tst"); logicalType.Value.TypeName.Should().Be("Foo"); logicalType.Value.Version.HasValue.Should().BeFalse(); } [Test] public void TryParse_WithCorrectFormatAndVersion_ReturnsLogicalType() { String input = "tst:Foo:v42"; var logicalType = LogicalType.TryParse(input); logicalType.HasValue.Should().BeTrue(); logicalType.Value.NamespaceAlias.Should().Be("tst"); logicalType.Value.TypeName.Should().Be("Foo"); logicalType.Value.Version.HasValue.Should().BeTrue(); logicalType.Value.Version.Value.Should().Be(42); } [Test] public void TryParse_WithIncorrectFormat_ReturnsNoValue() { String input = "63^*^*:8*&&(&"; var logicalType = LogicalType.TryParse(input); logicalType.HasValue.Should().BeFalse(); } [Test] public void TryParse_WithArity_ReturnsLogicalType() { String input = "tst:Foo`2"; var logicalType = LogicalType.TryParse(input); logicalType.HasValue.Should().BeTrue(); (logicalType.Value == new LogicalType("tst", "Foo", 2, Maybe.NoValue)).Should().BeTrue(); } [Test] public void TryParse_WithArityAndVersion_ReturnsLogicalType() { String input = "tst:Foo`2:v42"; var logicalType = LogicalType.TryParse(input); logicalType.HasValue.Should().BeTrue(); (logicalType.Value == new LogicalType("tst", "Foo", 2, 42.ToMaybe())).Should().BeTrue(); } [Test] public void TryParse_WithOneTypeArgument_ReturnsLogicalType() { String input = "tst:Foo<sys:Int32>"; var logicalType = LogicalType.TryParse(input); logicalType.HasValue.Should().BeTrue(); var arg = new LogicalType("sys", "Int32"); (logicalType.Value == new LogicalType("tst", "Foo", new[] {arg}, Maybe.NoValue)).Should().BeTrue(); } [Test] public void TryParse_WithMultipleTypeArguments_ReturnsLogicalType() { String input = "tst:Foo<sys:Int32, sys:String, sys:DateTime>"; var logicalType = LogicalType.TryParse(input); logicalType.HasValue.Should().BeTrue(); var arg1 = new LogicalType("sys", "Int32"); var arg2 = new LogicalType("sys", "String"); var arg3 = new LogicalType("sys", "DateTime"); (logicalType.Value == new LogicalType("tst", "Foo", new[] { arg1, arg2, arg3 }, Maybe.NoValue)).Should().BeTrue(); } [Test] public void TryParse_SuperComplex_ReturnsLogicalType() { String input = "tst:Result<sys:Tuple<sys:Int32, tst:ComplexType:v47>, tst:Observation<tst:Error>>:v42"; var logicalType = LogicalType.TryParse(input); logicalType.HasValue.Should().BeTrue(); var expected = new LogicalType("tst", "Result", new[] { new LogicalType("sys", "Tuple", new [] { new LogicalType("sys", "Int32"), new LogicalType("tst", "ComplexType", 0, 47.ToMaybe()) }, Maybe.NoValue), new LogicalType("tst", "Observation", new [] { new LogicalType("tst", "Error")}, Maybe.NoValue) }, 42.ToMaybe()); logicalType.Value.Equals(expected).Should().BeTrue(); } [Test] public void NoTypeArgumentsAndZeroArity_IsNotOpenType() { var logicalType = new LogicalType("tst", "Foo"); logicalType.IsOpenType.Should().BeFalse(); } [Test] public void NoTypeArgumentsAndNonZeroArity_IsOpenType() { var logicalType = new LogicalType("tst", "Foo", 1, Maybe.NoValue); logicalType.IsOpenType.Should().BeTrue(); } [Test] public void TypeArguments_IsNotOpenType() { var arguments = new[] { new LogicalType("sys", "Int32"), new LogicalType("sys", "String") }; var logicalType = new LogicalType("tst", "Foo", arguments, Maybe.NoValue); logicalType.IsOpenType.Should().BeFalse(); } [Test] public void GetOpenType() { var logicalType = new LogicalType("tst", "Result", new[] { new LogicalType("sys", "Int32"), new LogicalType("sys", "String") }, Maybe.NoValue); var openLogicalType = logicalType.GetOpenType(); openLogicalType.Equals(LogicalType.Parse("tst:Result`2")).Should().BeTrue(); } [Test] public void MakeClosedType() { var openLogicalType = new LogicalType("tst", "Result", 2, Maybe.NoValue); var args = new[] { new LogicalType("sys", "Int32"), new LogicalType("sys", "String") }; var logicalType = openLogicalType.MakeClosedType(args); logicalType.Equals(LogicalType.Parse("tst:Result<sys:Int32, sys:String>")).Should().BeTrue(); } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Talent.V4Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedJobServiceClientTest { [xunit::FactAttribute] public void CreateJobRequestObject() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateJobRequest request = new CreateJobRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job response = client.CreateJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateJobRequestObjectAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateJobRequest request = new CreateJobRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.CreateJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.CreateJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateJob() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateJobRequest request = new CreateJobRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job response = client.CreateJob(request.Parent, request.Job); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateJobAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateJobRequest request = new CreateJobRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.CreateJobAsync(request.Parent, request.Job, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.CreateJobAsync(request.Parent, request.Job, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateJobResourceNames1() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateJobRequest request = new CreateJobRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job response = client.CreateJob(request.ParentAsTenantName, request.Job); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateJobResourceNames1Async() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateJobRequest request = new CreateJobRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.CreateJobAsync(request.ParentAsTenantName, request.Job, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.CreateJobAsync(request.ParentAsTenantName, request.Job, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateJobResourceNames2() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateJobRequest request = new CreateJobRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job response = client.CreateJob(request.ParentAsProjectName, request.Job); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateJobResourceNames2Async() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateJobRequest request = new CreateJobRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.CreateJobAsync(request.ParentAsProjectName, request.Job, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.CreateJobAsync(request.ParentAsProjectName, request.Job, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetJobRequestObject() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job response = client.GetJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetJobRequestObjectAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.GetJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.GetJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetJob() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job response = client.GetJob(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetJobAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.GetJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.GetJobAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetJobResourceNames() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job response = client.GetJob(request.JobName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetJobResourceNamesAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetJobRequest request = new GetJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.GetJobAsync(request.JobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.GetJobAsync(request.JobName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateJobRequestObject() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateJobRequest request = new UpdateJobRequest { Job = new Job(), UpdateMask = new wkt::FieldMask(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.UpdateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job response = client.UpdateJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateJobRequestObjectAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateJobRequest request = new UpdateJobRequest { Job = new Job(), UpdateMask = new wkt::FieldMask(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.UpdateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.UpdateJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.UpdateJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateJob() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateJobRequest request = new UpdateJobRequest { Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.UpdateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job response = client.UpdateJob(request.Job); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateJobAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateJobRequest request = new UpdateJobRequest { Job = new Job(), }; Job expectedResponse = new Job { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), CompanyAsCompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"), RequisitionId = "requisition_id21c2f0af", Title = "title17dbd3d5", Description = "description2cf9da67", Addresses = { "addresses2f3a3e96", }, ApplicationInfo = new Job.Types.ApplicationInfo(), JobBenefits = { JobBenefit.Dental, }, CompensationInfo = new CompensationInfo(), CustomAttributes = { { "key8a0b6e3c", new CustomAttribute() }, }, DegreeTypes = { DegreeType.PrimaryEducation, }, Department = "departmentca9f9d45", EmploymentTypes = { EmploymentType.OtherEmploymentType, }, Incentives = "incentives80814488", LanguageCode = "language_code2f6c7160", JobLevel = JobLevel.Director, PromotionValue = 899484920, Qualifications = "qualifications920abb76", Responsibilities = "responsibilities978e5c9b", PostingRegion = PostingRegion.AdministrativeArea, #pragma warning disable CS0612 Visibility = Visibility.SharedWithPublic, #pragma warning restore CS0612 JobStartTime = new wkt::Timestamp(), JobEndTime = new wkt::Timestamp(), PostingPublishTime = new wkt::Timestamp(), PostingExpireTime = new wkt::Timestamp(), PostingCreateTime = new wkt::Timestamp(), PostingUpdateTime = new wkt::Timestamp(), CompanyDisplayName = "company_display_name07e5990f", DerivedInfo = new Job.Types.DerivedInfo(), ProcessingOptions = new Job.Types.ProcessingOptions(), }; mockGrpcClient.Setup(x => x.UpdateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.UpdateJobAsync(request.Job, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.UpdateJobAsync(request.Job, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteJobRequestObject() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); client.DeleteJob(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteJobRequestObjectAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteJobAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteJob() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); client.DeleteJob(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteJobAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteJobAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteJobAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteJobResourceNames() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); client.DeleteJob(request.JobName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteJobResourceNamesAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteJobRequest request = new DeleteJobRequest { JobName = JobName.FromProjectTenantJob("[PROJECT]", "[TENANT]", "[JOB]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteJobAsync(request.JobName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteJobAsync(request.JobName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchDeleteJobsRequestObject() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteJobsRequest request = new BatchDeleteJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Filter = "filtere47ac9b2", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteJobs(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); client.BatchDeleteJobs(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchDeleteJobsRequestObjectAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteJobsRequest request = new BatchDeleteJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Filter = "filtere47ac9b2", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteJobsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); await client.BatchDeleteJobsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.BatchDeleteJobsAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchDeleteJobs() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteJobsRequest request = new BatchDeleteJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Filter = "filtere47ac9b2", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteJobs(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); client.BatchDeleteJobs(request.Parent, request.Filter); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchDeleteJobsAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteJobsRequest request = new BatchDeleteJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Filter = "filtere47ac9b2", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteJobsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); await client.BatchDeleteJobsAsync(request.Parent, request.Filter, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.BatchDeleteJobsAsync(request.Parent, request.Filter, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchDeleteJobsResourceNames1() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteJobsRequest request = new BatchDeleteJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Filter = "filtere47ac9b2", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteJobs(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); client.BatchDeleteJobs(request.ParentAsTenantName, request.Filter); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchDeleteJobsResourceNames1Async() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteJobsRequest request = new BatchDeleteJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Filter = "filtere47ac9b2", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteJobsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); await client.BatchDeleteJobsAsync(request.ParentAsTenantName, request.Filter, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.BatchDeleteJobsAsync(request.ParentAsTenantName, request.Filter, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchDeleteJobsResourceNames2() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteJobsRequest request = new BatchDeleteJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Filter = "filtere47ac9b2", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteJobs(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); client.BatchDeleteJobs(request.ParentAsProjectName, request.Filter); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchDeleteJobsResourceNames2Async() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteJobsRequest request = new BatchDeleteJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), Filter = "filtere47ac9b2", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteJobsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); await client.BatchDeleteJobsAsync(request.ParentAsProjectName, request.Filter, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.BatchDeleteJobsAsync(request.ParentAsProjectName, request.Filter, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SearchJobsRequestObject() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchJobsRequest request = new SearchJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), SearchMode = SearchJobsRequest.Types.SearchMode.FeaturedJobSearch, RequestMetadata = new RequestMetadata(), JobQuery = new JobQuery(), EnableBroadening = false, RequirePreciseResultSize = false, HistogramQueries = { new HistogramQuery(), }, JobView = JobView.Small, Offset = 1472300666, PageSize = -226905851, PageToken = "page_tokenf09e5538", OrderBy = "order_byb4d33ada", DiversificationLevel = SearchJobsRequest.Types.DiversificationLevel.Disabled, CustomRankingInfo = new SearchJobsRequest.Types.CustomRankingInfo(), DisableKeywordMatch = true, }; SearchJobsResponse expectedResponse = new SearchJobsResponse { MatchingJobs = { new SearchJobsResponse.Types.MatchingJob(), }, HistogramQueryResults = { new HistogramQueryResult(), }, NextPageToken = "next_page_tokendbee0940", LocationFilters = { new Location(), }, EstimatedTotalSize = 1828561437, TotalSize = 1202968108, Metadata = new ResponseMetadata(), BroadenedQueryJobsCount = 2131480093, SpellCorrection = new SpellingCorrection(), }; mockGrpcClient.Setup(x => x.SearchJobs(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); SearchJobsResponse response = client.SearchJobs(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchJobsRequestObjectAsync() { moq::Mock<JobService.JobServiceClient> mockGrpcClient = new moq::Mock<JobService.JobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchJobsRequest request = new SearchJobsRequest { ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), SearchMode = SearchJobsRequest.Types.SearchMode.FeaturedJobSearch, RequestMetadata = new RequestMetadata(), JobQuery = new JobQuery(), EnableBroadening = false, RequirePreciseResultSize = false, HistogramQueries = { new HistogramQuery(), }, JobView = JobView.Small, Offset = 1472300666, PageSize = -226905851, PageToken = "page_tokenf09e5538", OrderBy = "order_byb4d33ada", DiversificationLevel = SearchJobsRequest.Types.DiversificationLevel.Disabled, CustomRankingInfo = new SearchJobsRequest.Types.CustomRankingInfo(), DisableKeywordMatch = true, }; SearchJobsResponse expectedResponse = new SearchJobsResponse { MatchingJobs = { new SearchJobsResponse.Types.MatchingJob(), }, HistogramQueryResults = { new HistogramQueryResult(), }, NextPageToken = "next_page_tokendbee0940", LocationFilters = { new Location(), }, EstimatedTotalSize = 1828561437, TotalSize = 1202968108, Metadata = new ResponseMetadata(), BroadenedQueryJobsCount = 2131480093, SpellCorrection = new SpellingCorrection(), }; mockGrpcClient.Setup(x => x.SearchJobsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchJobsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobServiceClient client = new JobServiceClientImpl(mockGrpcClient.Object, null); SearchJobsResponse responseCallSettings = await client.SearchJobsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchJobsResponse responseCancellationToken = await client.SearchJobsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MessageHub.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
namespace JoinerSplitter.Pages { using System; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using JetBrains.Annotations; using Control = System.Windows.Controls.Control; using DataFormats = System.Windows.DataFormats; using DataObject = System.Windows.DataObject; using DragDropEffects = System.Windows.DragDropEffects; using DragEventArgs = System.Windows.DragEventArgs; using ListViewItem = System.Windows.Controls.ListViewItem; using MessageBox = System.Windows.MessageBox; using MouseEventArgs = System.Windows.Input.MouseEventArgs; using OpenFileDialog = Microsoft.Win32.OpenFileDialog; using Path = System.IO.Path; using SaveFileDialog = Microsoft.Win32.SaveFileDialog; /// <summary> /// Interaction logic for MainWindow.xaml. /// </summary> [UsedImplicitly] public partial class MainWindow { private static readonly string[] AllowedExtensions = { "mov", "mp4", "avi", "wmv", "mkv", "mts", "m2ts" }; private static readonly string DialogFilterString = $"Video files|{string.Join(";", AllowedExtensions.Select(s => "*." + s))}|All files|*.*"; private static readonly char[] ProhibitedFilenameChars = { '\\', '/', ':', '*', '?', '\"', '<', '>', '|' }; private bool changingSlider; private Point? dragStartPoint; private ListViewInsertMarkAdorner insertAdorner; private Storyboard storyboard; private bool wasPaused; public MainWindow() { InitializeComponent(); DataObject.AddPastingHandler(OutputFilenameBox, OutputFilenameBox_Paste); FFMpeg.Instance.FFMpegPath = Path.Combine(Environment.CurrentDirectory, "ffmpeg\\ffmpeg.exe"); FFMpeg.Instance.FFProbePath = Path.Combine(Environment.CurrentDirectory, "ffmpeg\\ffprobe.exe"); } private AppModel Data => (AppModel)DataContext; public static ContentControl GetItemAt(Visual listView, Point point) { var hitTestResult = VisualTreeHelper.HitTest(listView, point); var item = hitTestResult.VisualHit; while (item != null) { switch (item) { case ListViewItem listViewItem: return listViewItem; case GroupItem groupItem: return groupItem; } item = VisualTreeHelper.GetParent(item); } return null; } public static double GetListViewHeaderHeight(DependencyObject view) { return ((Control)VisualTreeHelper.GetChild( VisualTreeHelper.GetChild( VisualTreeHelper.GetChild( VisualTreeHelper.GetChild( VisualTreeHelper.GetChild(view, 0), 0), 0), 0), 0)).ActualHeight; } private static TItemContainer GetContainerAtPoint<TItemContainer>(ItemsControl control, Point p) where TItemContainer : DependencyObject { var result = VisualTreeHelper.HitTest(control, p); var obj = result.VisualHit; if (obj != null) { while ((VisualTreeHelper.GetParent(obj) != null) && !(obj is TItemContainer)) { obj = VisualTreeHelper.GetParent(obj); if (obj == null) { return null; } } } // Will return null if not found return obj as TItemContainer; } private async Task AddFiles(string[] files, VideoFile before = null, int groupIndex = -1) { var infoBox = InfoBox.Show(this, Properties.Resources.ReadingFile); try { await Data.AddFiles(files, before, groupIndex); } catch (Exception ex) { MessageBox.Show(ex.Message, "File format error"); } finally { infoBox.Close(); } } private async void Button_AddVideo(object sender, RoutedEventArgs e) { var dlg = new OpenFileDialog { Filter = DialogFilterString, Multiselect = true }; var result = dlg.ShowDialog(); if (result == false) { return; } await AddFiles(dlg.FileNames); } private void Button_Delete(object sender, RoutedEventArgs e) { Data.DeleteVideos(FilesList.SelectedItems); RefreshList(); } private void Button_Duplicate(object sender, RoutedEventArgs e) { Data.DuplicateVideos(FilesList.SelectedItems); RefreshList(); } private void Button_End(object sender, RoutedEventArgs e) { Seek(TimeSpan.FromSeconds(Slider.SelectionEnd - 0.05)); } private void Button_MoveDown(object sender, RoutedEventArgs e) { Data.MoveVideosDown(FilesList.SelectedItems); RefreshList(); } private void Button_MoveUp(object sender, RoutedEventArgs e) { Data.MoveVideosUp(FilesList.SelectedItems); RefreshList(); } private void Button_OpenPresets(object sender, RoutedEventArgs e) { EncodingPresetsWindow.Show(this, Data); } private void Button_Play(object sender, RoutedEventArgs e) { PlayPause(); } private void Button_SelEnd(object sender, RoutedEventArgs e) { if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) { Slider.SelectionEnd = Slider.Value; } else { var splitTime = Data.CurrentFile.KeyFrames?.Where(f => f >= Slider.Value).DefaultIfEmpty(Data.CurrentFile.Duration).First() ?? Slider.Value; Slider.SelectionEnd = splitTime; } } private void Button_SelStart(object sender, RoutedEventArgs e) { if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { Slider.SelectionStart = Slider.Value; } else { var splitTime = Data.CurrentFile.KeyFrames?.Where(f => f <= Slider.Value).DefaultIfEmpty(0).Last() ?? Slider.Value; Slider.SelectionStart = splitTime - 0.1; } } private void Button_SplitFiles(object sender, RoutedEventArgs e) { Data.SplitGroup(); RefreshList(); } private void Button_Start(object sender, RoutedEventArgs e) { Seek(TimeSpan.FromSeconds(Slider.SelectionStart)); } private void FilesList_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent(typeof(VideoFile[]))) { insertAdorner = new ListViewInsertMarkAdorner(FilesList); AdornerLayer.GetAdornerLayer(FilesList).Add(insertAdorner); } } private void FilesList_DragLeave(object sender, DragEventArgs e) { if (insertAdorner != null) { AdornerLayer.GetAdornerLayer(FilesList).Remove(insertAdorner); insertAdorner = null; } } private void FilesList_DragOver(object sender, DragEventArgs e) { e.Effects = DragDropEffects.None; if (insertAdorner != null) { e.Effects = DragDropEffects.Copy | DragDropEffects.Move; var control = GetItemAt(FilesList, e.GetPosition(FilesList)); if (control != null) { insertAdorner.Offset = control.TransformToAncestor(FilesList).Transform(new Point(0, -4)).Y; } else { if (FilesList.Items.Count == 0) { insertAdorner.Offset = GetListViewHeaderHeight(FilesList); } else { var item = FilesList.ItemContainerGenerator.ContainerFromItem(FilesList.Items[FilesList.Items.Count - 1]) as ListViewItem; insertAdorner.Offset = item.TransformToAncestor(FilesList).Transform(new Point(0, item.ActualHeight - 4)).Y; } } } } private async void FilesList_Drop(object sender, DragEventArgs e) { if (insertAdorner != null) { GetBeforeAndGroup(e.GetPosition(FilesList), out var before, out var groupIndex); if (e.Data.GetDataPresent(DataFormats.FileDrop)) { var files = (string[])e.Data.GetData(DataFormats.FileDrop); await AddFiles(files, before, groupIndex); } else if (e.Data.GetDataPresent(typeof(VideoFile[]))) { var files = (VideoFile[])e.Data.GetData(typeof(VideoFile[])); MoveFiles(files, before, groupIndex); } AdornerLayer.GetAdornerLayer(FilesList).Remove(insertAdorner); insertAdorner = null; } } private void FilesList_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.OriginalSource is Rectangle || e.OriginalSource is Border) { return; } dragStartPoint = e.GetPosition(null); if (!(Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl) || Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))) { var result = GetContainerAtPoint<ListViewItem>(FilesList, e.GetPosition(FilesList)); if ((result != null) && !FilesList.SelectedItems.Contains(result.Content)) { FilesList.SelectedItem = result.Content; } } e.Handled = true; } private void FilesList_MouseMove(object sender, MouseEventArgs e) { if (e.OriginalSource is Rectangle || e.OriginalSource is Border) { return; } if ((e.LeftButton == MouseButtonState.Pressed) && (dragStartPoint != null)) { var drag = (Vector)(e.GetPosition(null) - dragStartPoint); if ((drag.X > SystemParameters.MinimumHorizontalDragDistance) || (drag.Y > SystemParameters.MinimumVerticalDragDistance)) { var selected = FilesList.SelectedItems.Cast<VideoFile>().OrderBy(f => Data.CurrentJob.Files.IndexOf(f)).ToArray(); if (!selected.Any()) { return; } DragDrop.DoDragDrop(FilesList, selected, DragDropEffects.Move); dragStartPoint = null; } } } private void FilesList_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { using (Dispatcher.DisableProcessing()) { if (dragStartPoint != null) { var drag = (Vector)(e.GetPosition(null) - dragStartPoint); if ((drag.X <= SystemParameters.MinimumHorizontalDragDistance) && (drag.Y <= SystemParameters.MinimumVerticalDragDistance)) { var selected = GetItem(e.GetPosition(FilesList)); if (selected != null) { if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { if (FilesList.SelectedItems.Contains(selected)) { FilesList.SelectedItems.Remove(selected); } else { FilesList.SelectedItems.Add(selected); } } else if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) { var start = Data.CurrentJob.Files.IndexOf((VideoFile)FilesList.SelectedItem); var count = Data.CurrentJob.Files.IndexOf(selected) - start; if (count < 0) { start += count; count = -count; } FilesList.SelectedItems.Clear(); foreach (var item in Data.CurrentJob.Files.Skip(start).Take(count + 1).ToList()) { FilesList.SelectedItems.Add(item); } } else { if (FilesList.SelectedItems.Count > 1) { FilesList.SelectedItems.Clear(); } FilesList.SelectedItem = selected; } } } dragStartPoint = null; } } } private void GetBeforeAndGroup(Point point, out VideoFile before, out int groupIndex) { var result = GetItemAt(FilesList, point); before = null; groupIndex = -1; switch (result) { case null: return; case ListViewItem listItem: before = (VideoFile)listItem.Content; groupIndex = before.GroupIndex; return; case GroupItem group: var items = ((CollectionViewGroup)group.Content).Items; before = (VideoFile)items.FirstOrDefault(); groupIndex = before.GroupIndex - 1; if (groupIndex < 0) { groupIndex = 0; } return; } } private VideoFile GetItem(Point point) { var result = GetItemAt(FilesList, point); switch (result) { case null: return null; case ListViewItem listItem: return listItem.Content as VideoFile; } return null; } private async void MainWindow_OnClosing(object sender, CancelEventArgs e) { if (Data.CurrentJob.Changed) { var result = MessageBox.Show(Properties.Resources.UnsavedChanges, Properties.Resources.UnsavedChangesTitle, MessageBoxButton.YesNoCancel); switch (result) { case MessageBoxResult.Yes: await SaveJob(); return; case MessageBoxResult.Cancel: case MessageBoxResult.None: e.Cancel = true; return; } } } private void MediaElement_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { PlayPause(); } private void MoveFiles(VideoFile[] files, VideoFile before, int groupIndex) { Data.MoveFiles(files, before, groupIndex); RefreshList(); } private void NewJob(object sender, RoutedEventArgs e) { Data.CurrentJob = new Job(); Data.CurrentFile = null; } private async Task OpenJob(string path) { try { await Data.OpenJob(path); } catch (AggregateException ex) { MessageBox.Show(this, string.Join("\r\n", ex.InnerExceptions.Select(e => e.Message)), "Can not open Job"); } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Can not open Job"); } } private async void OpenJob(object sender, RoutedEventArgs e) { var dlg = new OpenFileDialog { Filter = "JoinerSplitter job file (*.jsj)|*.jsj", DefaultExt = ".jsj", Multiselect = false, }; var result = dlg.ShowDialog(); if (result == false) { return; } var infoBox = InfoBox.Show(this, Properties.Resources.ReadingFile); await OpenJob(dlg.FileName); infoBox.Close(); } private void OpenVideo(VideoFile video) { storyboard?.Stop(MainGrid); storyboard = new Storyboard(); var timeline = new MediaTimeline(video.FileUri); storyboard.Children.Add(timeline); Storyboard.SetTarget(timeline, MediaElement); storyboard.CurrentTimeInvalidated += Storyboard_CurrentTimeInvalidated; Data.CurrentFile = video; storyboard.Begin(MainGrid, true); } private void OutputFilenameBox_Paste(object sender, DataObjectPastingEventArgs e) { if (!e.DataObject.GetDataPresent(e.FormatToApply)) { return; } var text = e.DataObject.GetData(e.FormatToApply).ToString(); if (ProhibitedFilenameChars.Any(text.Contains)) { e.CancelCommand(); } } private void OutputFilenameBox_TextInput(object sender, TextCompositionEventArgs e) { if (ProhibitedFilenameChars.Any(e.Text.Contains)) { e.Handled = true; } } private void OutputFolderBox_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { using (var dlg = new FolderBrowserDialog()) { if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } Data.SelectedOutputFolder = dlg.SelectedPath; } } else if (e.ChangedButton == MouseButton.Right) { Data.SelectedOutputFolder = null; } } private void OutputList_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (FilesList.SelectedItem != null) { var output = FilesList.SelectedItem as VideoFile; OpenVideo(output); storyboard.Seek(MainGrid, TimeSpan.FromSeconds(output.Start), TimeSeekOrigin.BeginTime); } else { Data.CurrentFile = null; storyboard.Stop(MainGrid); } } private void PlayPause() { if (storyboard.GetIsPaused(MainGrid)) { storyboard.Resume(MainGrid); } else { storyboard.Pause(MainGrid); } } private async void ProcessButton_Click(object sender, RoutedEventArgs e) { storyboard?.Pause(MainGrid); var job = Data.CurrentJob; if (string.IsNullOrWhiteSpace(job.OutputFolder)) { if (string.IsNullOrWhiteSpace(Data.OutputFolder)) { using (var dlg = new FolderBrowserDialog()) { if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) { MessageBox.Show(Properties.Resources.NeedOutputFolder, "Folder is required"); return; } Data.SelectedOutputFolder = dlg.SelectedPath; } } job.OutputFolder = Data.OutputFolder; } var progress = ProgressWindow.Show(this); try { await FFMpeg.Instance.DoJob( job, cur => { Dispatcher.Invoke(() => { progress.Progress.Value = cur.Current * 100; if (cur.Estimated.TotalHours >= 1) { progress.EstimatedTime.Text = $"{Math.Floor(cur.Estimated.TotalHours)}:{cur.Estimated.Minutes:00}:{cur.Estimated.Seconds:00}"; } else { progress.EstimatedTime.Text = $"{cur.Estimated.Minutes:00}:{cur.Estimated.Seconds:00}"; } }); }, progress.CancellationToken); } catch (Exception ex) { MessageBox.Show(ex.Message, "Processing failed"); } finally { progress.Close(); } } private void RefreshList() { var view = CollectionViewSource.GetDefaultView(FilesList.ItemsSource); view.Refresh(); } private async void SaveJob(object sender, RoutedEventArgs e) { await SaveJob(); } private async Task SaveJob() { if (string.IsNullOrWhiteSpace(Data.CurrentJob.JobFilePath)) { await SaveJobAs(); } else { await Data.SaveJob(Data.CurrentJob.JobFilePath); } } private async void OnSaveJobAs(object sender = null, RoutedEventArgs e = null) { await SaveJobAs(); } private async Task SaveJobAs() { var dlg = new SaveFileDialog { Filter = "JoinerSplitter job file (*.jsj)|*.jsj", DefaultExt = ".jsj", OverwritePrompt = true, }; if (!string.IsNullOrWhiteSpace(Data.CurrentJob.JobFilePath)) { dlg.FileName = Path.GetFileNameWithoutExtension(Data.CurrentJob.JobFilePath); dlg.InitialDirectory = Path.GetDirectoryName(Data.CurrentJob.JobFilePath); } else { var firstFile = Data.CurrentJob.Files.FirstOrDefault()?.FilePath; if (!string.IsNullOrWhiteSpace(firstFile)) { var folder = Path.GetDirectoryName(firstFile); if (!string.IsNullOrWhiteSpace(folder)) { dlg.FileName = Path.GetFileNameWithoutExtension(Path.GetFileName(folder)); dlg.InitialDirectory = folder; } } } var result = dlg.ShowDialog(); if (result == false) { return; } await Data.SaveJob(dlg.FileName); } private void Seek(TimeSpan timeSpan, TimeSeekOrigin origin = TimeSeekOrigin.BeginTime) { try { wasPaused = storyboard.GetIsPaused(MainGrid); storyboard.SeekAlignedToLastTick(MainGrid, timeSpan, origin); } catch (InvalidOperationException) { // Ignore if file selection happened; } } private void Slider_PreviewMouseDown(object sender, MouseButtonEventArgs e) { wasPaused = storyboard.GetIsPaused(MainGrid); storyboard.Pause(MainGrid); } private void Slider_PreviewMouseUp(object sender, MouseButtonEventArgs e) { if (!wasPaused) { storyboard.Resume(MainGrid); } } private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { if (!changingSlider) { Seek(TimeSpan.FromSeconds(e.NewValue)); } } private void SplitButton_Click(object sender, RoutedEventArgs e) { Data.SplitCurrentVideo(Slider.Value); RefreshList(); } private void Storyboard_CurrentTimeInvalidated(object sender, EventArgs e) { changingSlider = true; Slider.Value = ((ClockGroup)sender).CurrentTime?.TotalSeconds ?? 0; changingSlider = false; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BitConverter ** ** ** Purpose: Allows developers to view the base data types as ** an arbitrary array of bits. ** ** ===========================================================*/ namespace System { using System; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; using System.Security; // The BitConverter class contains methods for // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. // // Only statics, does not need to be marked with the serializable attribute public static class BitConverter { // This field indicates the "endianess" of the architecture. // The value is set to true if the architecture is // little endian; false if it is big endian. #if BIGENDIAN public static readonly bool IsLittleEndian /* = false */; #else public static readonly bool IsLittleEndian = true; #endif // Converts a byte into an array of bytes with length one. public static byte[] GetBytes(bool value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 1); byte[] r = new byte[1]; r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False ); return r; } // Converts a char into an array of bytes with length two. public static byte[] GetBytes(char value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts a short into an array of bytes with length // two. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(short value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); byte[] bytes = new byte[2]; fixed(byte* b = bytes) *((short*)b) = value; return bytes; } // Converts an int into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(int value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); byte[] bytes = new byte[4]; fixed(byte* b = bytes) *((int*)b) = value; return bytes; } // Converts a long into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(long value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); byte[] bytes = new byte[8]; fixed(byte* b = bytes) *((long*)b) = value; return bytes; } // Converts an ushort into an array of bytes with // length two. [CLSCompliant(false)] public static byte[] GetBytes(ushort value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 2); return GetBytes((short)value); } // Converts an uint into an array of bytes with // length four. [CLSCompliant(false)] public static byte[] GetBytes(uint value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes((int)value); } // Converts an unsigned long into an array of bytes with // length eight. [CLSCompliant(false)] public static byte[] GetBytes(ulong value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes((long)value); } // Converts a float into an array of bytes with length // four. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(float value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 4); return GetBytes(*(int*)&value); } // Converts a double into an array of bytes with length // eight. [System.Security.SecuritySafeCritical] // auto-generated public unsafe static byte[] GetBytes(double value) { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 8); return GetBytes(*(long*)&value); } // Converts an array of bytes into a char. public static char ToChar(byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint)startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 2) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); return (char)ToInt16(value, startIndex); } // Converts an array of bytes into a short. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe short ToInt16(byte[] value, int startIndex) { if( value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint) startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length -2) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed( byte * pbyte = &value[startIndex]) { if( startIndex % 2 == 0) { // data is aligned return *((short *) pbyte); } else { if( IsLittleEndian) { return (short)((*pbyte) | (*(pbyte + 1) << 8)) ; } else { return (short)((*pbyte << 8) | (*(pbyte + 1))); } } } } // Converts an array of bytes into an int. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe int ToInt32 (byte[] value, int startIndex) { if( value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint) startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length -4) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed( byte * pbyte = &value[startIndex]) { if( startIndex % 4 == 0) { // data is aligned return *((int *) pbyte); } else { if( IsLittleEndian) { return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); } else { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } } } // Converts an array of bytes into a long. [System.Security.SecuritySafeCritical] // auto-generated public static unsafe long ToInt64 (byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint) startIndex >= value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length -8) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Contract.EndContractBlock(); fixed( byte * pbyte = &value[startIndex]) { if( startIndex % 8 == 0) { // data is aligned return *((long *) pbyte); } else { if( IsLittleEndian) { int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); int i2 = (*(pbyte+4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); return (uint)i1 | ((long)i2 << 32); } else { int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte+4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } } } // Converts an array of bytes into an ushort. // [CLSCompliant(false)] public static ushort ToUInt16(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (ushort)ToInt16(value, startIndex); } // Converts an array of bytes into an uint. // [CLSCompliant(false)] public static uint ToUInt32(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 4) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (uint)ToInt32(value, startIndex); } // Converts an array of bytes into an unsigned long. // [CLSCompliant(false)] public static ulong ToUInt64(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 8) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); return (ulong)ToInt64(value, startIndex); } // Converts an array of bytes into a float. [System.Security.SecuritySafeCritical] // auto-generated unsafe public static float ToSingle (byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 4) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); int val = ToInt32(value, startIndex); return *(float*)&val; } // Converts an array of bytes into a double. [System.Security.SecuritySafeCritical] // auto-generated unsafe public static double ToDouble (byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if ((uint)startIndex >= value.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - 8) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); Contract.EndContractBlock(); long val = ToInt64(value, startIndex); return *(double*)&val; } private static char GetHexValue(int i) { Contract.Assert( i >=0 && i <16, "i is out of range."); if (i<10) { return (char)(i + '0'); } return (char)(i - 10 + 'A'); } // Converts an array of bytes into a String. public static String ToString (byte[] value, int startIndex, int length) { if (value == null) { throw new ArgumentNullException("byteArray"); } if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array. throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); } if (length < 0) { throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); } if (startIndex > value.Length - length) { throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall")); } Contract.EndContractBlock(); if (length == 0) { return string.Empty; } if (length > (Int32.MaxValue / 3)) { // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3))); } int chArrayLength = length * 3; char[] chArray = new char[chArrayLength]; int i = 0; int index = startIndex; for (i = 0; i < chArrayLength; i += 3) { byte b = value[index++]; chArray[i]= GetHexValue(b/16); chArray[i+1] = GetHexValue(b%16); chArray[i+2] = '-'; } // We don't need the last '-' character return new String(chArray, 0, chArray.Length - 1); } // Converts an array of bytes into a String. public static String ToString(byte [] value) { if (value == null) throw new ArgumentNullException("value"); Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return ToString(value, 0, value.Length); } // Converts an array of bytes into a String. public static String ToString (byte [] value, int startIndex) { if (value == null) throw new ArgumentNullException("value"); Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); return ToString(value, startIndex, value.Length - startIndex); } /*==================================ToBoolean=================================== **Action: Convert an array of bytes to a boolean value. We treat this array ** as if the first 4 bytes were an Int4 an operate on this value. **Returns: True if the Int4 value of the first 4 bytes is non-zero. **Arguments: value -- The byte array ** startIndex -- The position within the array. **Exceptions: See ToInt4. ==============================================================================*/ // Converts an array of bytes into a boolean. public static bool ToBoolean(byte[] value, int startIndex) { if (value==null) throw new ArgumentNullException("value"); if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (startIndex > value.Length - 1) throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); return (value[startIndex]==0)?false:true; } [SecuritySafeCritical] public static unsafe long DoubleToInt64Bits(double value) { // If we're on a big endian machine, what should this method do? You could argue for // either big endian or little endian, depending on whether you are writing to a file that // should be used by other programs on that processor, or for compatibility across multiple // formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile. // If we ever run on big endian machines, produce two versions where endianness is specified. Contract.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec."); return *((long *)&value); } [SecuritySafeCritical] public static unsafe double Int64BitsToDouble(long value) { // If we're on a big endian machine, what should this method do? You could argue for // either big endian or little endian, depending on whether you are writing to a file that // should be used by other programs on that processor, or for compatibility across multiple // formats. Because this is ambiguous, we're excluding this from the Portable Library & Win8 Profile. // If we ever run on big endian machines, produce two versions where endianness is specified. Contract.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec."); return *((double*)&value); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.DataFactories; using Microsoft.Azure.Management.DataFactories.Models; using Microsoft.WindowsAzure; namespace Microsoft.Azure.Management.DataFactories { public static partial class DataFactoryOperationsExtensions { /// <summary> /// Create or update a data factory. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public static DataFactoryCreateOrUpdateResponse BeginCreateOrUpdate(this IDataFactoryOperations operations, string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataFactoryOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or update a data factory. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public static Task<DataFactoryCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IDataFactoryOperations operations, string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Create or update a data factory. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public static DataFactoryCreateOrUpdateResponse CreateOrUpdate(this IDataFactoryOperations operations, string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataFactoryOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or update a data factory. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public static Task<DataFactoryCreateOrUpdateResponse> CreateOrUpdateAsync(this IDataFactoryOperations operations, string resourceGroupName, DataFactoryCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Delete a data factory instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Delete(this IDataFactoryOperations operations, string resourceGroupName, string dataFactoryName) { return Task.Factory.StartNew((object s) => { return ((IDataFactoryOperations)s).DeleteAsync(resourceGroupName, dataFactoryName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete a data factory instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteAsync(this IDataFactoryOperations operations, string resourceGroupName, string dataFactoryName) { return operations.DeleteAsync(resourceGroupName, dataFactoryName, CancellationToken.None); } /// <summary> /// Gets a data factory instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <returns> /// The Get data factory operation response. /// </returns> public static DataFactoryGetResponse Get(this IDataFactoryOperations operations, string resourceGroupName, string dataFactoryName) { return Task.Factory.StartNew((object s) => { return ((IDataFactoryOperations)s).GetAsync(resourceGroupName, dataFactoryName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a data factory instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <returns> /// The Get data factory operation response. /// </returns> public static Task<DataFactoryGetResponse> GetAsync(this IDataFactoryOperations operations, string resourceGroupName, string dataFactoryName) { return operations.GetAsync(resourceGroupName, dataFactoryName, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public static DataFactoryCreateOrUpdateResponse GetCreateOrUpdateStatus(this IDataFactoryOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IDataFactoryOperations)s).GetCreateOrUpdateStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The create or update data factory operation response. /// </returns> public static Task<DataFactoryCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(this IDataFactoryOperations operations, string operationStatusLink) { return operations.GetCreateOrUpdateStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Gets the first page of data factory instances with the link to the /// next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factories. /// </param> /// <returns> /// The List data factories operation response. /// </returns> public static DataFactoryListResponse List(this IDataFactoryOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IDataFactoryOperations)s).ListAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the first page of data factory instances with the link to the /// next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factories. /// </param> /// <returns> /// The List data factories operation response. /// </returns> public static Task<DataFactoryListResponse> ListAsync(this IDataFactoryOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Gets the next page of data factory instances with the link to the /// next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next data factories page. /// </param> /// <returns> /// The List data factories operation response. /// </returns> public static DataFactoryListResponse ListNext(this IDataFactoryOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IDataFactoryOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the next page of data factory instances with the link to the /// next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.IDataFactoryOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next data factories page. /// </param> /// <returns> /// The List data factories operation response. /// </returns> public static Task<DataFactoryListResponse> ListNextAsync(this IDataFactoryOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Reflection; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// TestCaseAttribute is used to mark parameterized test cases /// and provide them with their arguments. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)] public class TestCaseAttribute : NUnitAttribute, ITestBuilder, ITestCaseData, IImplyFixture { #region Constructors /// <summary> /// Construct a TestCaseAttribute with a list of arguments. /// This constructor is not CLS-Compliant /// </summary> /// <param name="arguments"></param> public TestCaseAttribute(params object[] arguments) { RunState = RunState.Runnable; if (arguments == null) Arguments = new object[] { null }; else Arguments = arguments; Properties = new PropertyBag(); } /// <summary> /// Construct a TestCaseAttribute with a single argument /// </summary> /// <param name="arg"></param> public TestCaseAttribute(object arg) { RunState = RunState.Runnable; Arguments = new object[] { arg }; Properties = new PropertyBag(); } /// <summary> /// Construct a TestCaseAttribute with a two arguments /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> public TestCaseAttribute(object arg1, object arg2) { RunState = RunState.Runnable; Arguments = new object[] { arg1, arg2 }; Properties = new PropertyBag(); } /// <summary> /// Construct a TestCaseAttribute with a three arguments /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> /// <param name="arg3"></param> public TestCaseAttribute(object arg1, object arg2, object arg3) { RunState = RunState.Runnable; Arguments = new object[] { arg1, arg2, arg3 }; Properties = new PropertyBag(); } #endregion #region ITestData Members /// <summary> /// Gets or sets the name of the test. /// </summary> /// <value>The name of the test.</value> public string TestName { get; set; } /// <summary> /// Gets or sets the RunState of this test case. /// </summary> public RunState RunState { get; private set; } /// <summary> /// Gets the list of arguments to a test case /// </summary> public object[] Arguments { get; private set; } /// <summary> /// Gets the properties of the test case /// </summary> public IPropertyBag Properties { get; private set; } #endregion #region ITestCaseData Members /// <summary> /// Gets or sets the expected result. /// </summary> /// <value>The result.</value> public object ExpectedResult { get { return _expectedResult; } set { _expectedResult = value; HasExpectedResult = true; } } private object _expectedResult; /// <summary> /// Returns true if the expected result has been set /// </summary> public bool HasExpectedResult { get; private set; } #endregion #region Other Properties /// <summary> /// Gets or sets the description. /// </summary> /// <value>The description.</value> public string Description { get { return Properties.Get(PropertyNames.Description) as string; } set { Properties.Set(PropertyNames.Description, value); } } /// <summary> /// The author of this test /// </summary> public string Author { get { return Properties.Get(PropertyNames.Author) as string; } set { Properties.Set(PropertyNames.Author, value); } } /// <summary> /// The type that this test is testing /// </summary> public Type TestOf { get { return _testOf; } set { _testOf = value; Properties.Set(PropertyNames.TestOf, value.FullName); } } private Type _testOf; /// <summary> /// Gets or sets the reason for ignoring the test /// </summary> public string Ignore { get { return IgnoreReason; } set { IgnoreReason = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestCaseAttribute"/> is explicit. /// </summary> /// <value> /// <c>true</c> if explicit; otherwise, <c>false</c>. /// </value> public bool Explicit { get { return RunState == RunState.Explicit; } set { RunState = value ? RunState.Explicit : RunState.Runnable; } } /// <summary> /// Gets or sets the reason for not running the test. /// </summary> /// <value>The reason.</value> public string Reason { get { return Properties.Get(PropertyNames.SkipReason) as string; } set { Properties.Set(PropertyNames.SkipReason, value); } } /// <summary> /// Gets or sets the ignore reason. When set to a non-null /// non-empty value, the test is marked as ignored. /// </summary> /// <value>The ignore reason.</value> public string IgnoreReason { get { return Reason; } set { RunState = RunState.Ignored; Reason = value; } } #if !PORTABLE /// <summary> /// Comma-delimited list of platforms to run the test for /// </summary> public string IncludePlatform { get; set; } /// <summary> /// Comma-delimited list of platforms to not run the test for /// </summary> public string ExcludePlatform { get; set; } #endif /// <summary> /// Gets and sets the category for this test case. /// May be a comma-separated list of categories. /// </summary> public string Category { get { return Properties.Get(PropertyNames.Category) as string; } set { foreach (string cat in value.Split(new char[] { ',' }) ) Properties.Add(PropertyNames.Category, cat); } } #endregion #region Helper Methods private TestCaseParameters GetParametersForTestCase(IMethodInfo method) { TestCaseParameters parms; try { #if NETCF var tmethod = method.MakeGenericMethodEx(Arguments); if (tmethod == null) throw new NotSupportedException("Cannot determine generic types from probing"); method = tmethod; #endif IParameterInfo[] parameters = method.GetParameters(); int argsNeeded = parameters.Length; int argsProvided = Arguments.Length; parms = new TestCaseParameters(this); // Special handling for params arguments if (argsNeeded > 0 && argsProvided >= argsNeeded - 1) { IParameterInfo lastParameter = parameters[argsNeeded - 1]; Type lastParameterType = lastParameter.ParameterType; Type elementType = lastParameterType.GetElementType(); if (lastParameterType.IsArray && lastParameter.IsDefined<ParamArrayAttribute>(false)) { if (argsProvided == argsNeeded) { Type lastArgumentType = parms.Arguments[argsProvided - 1].GetType(); if (!lastParameterType.IsAssignableFrom(lastArgumentType)) { Array array = Array.CreateInstance(elementType, 1); array.SetValue(parms.Arguments[argsProvided - 1], 0); parms.Arguments[argsProvided - 1] = array; } } else { object[] newArglist = new object[argsNeeded]; for (int i = 0; i < argsNeeded && i < argsProvided; i++) newArglist[i] = parms.Arguments[i]; int length = argsProvided - argsNeeded + 1; Array array = Array.CreateInstance(elementType, length); for (int i = 0; i < length; i++) array.SetValue(parms.Arguments[argsNeeded + i - 1], i); newArglist[argsNeeded - 1] = array; parms.Arguments = newArglist; argsProvided = argsNeeded; } } } //if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) // parms.Arguments = new object[]{parms.Arguments}; // Special handling when sole argument is an object[] if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) { if (argsProvided > 1 || argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[])) { parms.Arguments = new object[] { parms.Arguments }; } } if (argsProvided == argsNeeded) PerformSpecialConversions(parms.Arguments, parameters); } catch (Exception ex) { parms = new TestCaseParameters(ex); } return parms; } /// <summary> /// Performs several special conversions allowed by NUnit in order to /// permit arguments with types that cannot be used in the constructor /// of an Attribute such as TestCaseAttribute or to simplify their use. /// </summary> /// <param name="arglist">The arguments to be converted</param> /// <param name="parameters">The ParameterInfo array for the method</param> private static void PerformSpecialConversions(object[] arglist, IParameterInfo[] parameters) { for (int i = 0; i < arglist.Length; i++) { object arg = arglist[i]; Type targetType = parameters[i].ParameterType; if (arg == null) continue; if (arg is SpecialValue && (SpecialValue)arg == SpecialValue.Null) { arglist[i] = null; continue; } if (targetType.IsAssignableFrom(arg.GetType())) continue; #if !PORTABLE if (arg is DBNull) { arglist[i] = null; continue; } #endif bool convert = false; if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte)) convert = arg is int; else if (targetType == typeof(decimal)) convert = arg is double || arg is string || arg is int; else if (targetType == typeof(DateTime) || targetType == typeof(TimeSpan)) convert = arg is string; if (convert) arglist[i] = Convert.ChangeType(arg, targetType, System.Globalization.CultureInfo.InvariantCulture); } } #endregion #region ITestBuilder Members /// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The MethodInfo for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite) { TestMethod test = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, GetParametersForTestCase(method)); #if !PORTABLE if (test.RunState != RunState.NotRunnable && test.RunState != RunState.Ignored) { PlatformHelper platformHelper = new PlatformHelper(); if (!platformHelper.IsPlatformSupported(this)) { test.RunState = RunState.Skipped; test.Properties.Add(PropertyNames.SkipReason, platformHelper.Reason); } } #endif yield return test; } #endregion } }
using System; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class PageLoadingTest : DriverTestFixture { private IWebDriver localDriver; [SetUp] public void RestartOriginalDriver() { driver = EnvironmentManager.Instance.GetCurrentDriver(); } [TearDown] public void QuitAdditionalDriver() { if (localDriver != null) { localDriver.Quit(); localDriver = null; } } [Test] public void NoneStrategyShouldNotWaitForPageToLoad() { InitLocalDriver(PageLoadStrategy.None); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); DateTime start = DateTime.Now; localDriver.Url = slowPage; DateTime end = DateTime.Now; TimeSpan duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'get' operation should not wait. Assert.That(duration.TotalMilliseconds, Is.LessThan(1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] public void NoneStrategyShouldNotWaitForPageToRefresh() { InitLocalDriver(PageLoadStrategy.None); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5"); // We discard the element, but want a check to make sure the page is loaded WaitFor(() => localDriver.FindElement(By.TagName("body")), TimeSpan.FromSeconds(10), "did not find body"); DateTime start = DateTime.Now; localDriver.Navigate().Refresh(); DateTime end = DateTime.Now; TimeSpan duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'refresh' operation should not wait. Assert.That(duration.TotalMilliseconds, Is.LessThan(1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver does not support eager page load strategy")] public void EagerStrategyShouldNotWaitForResources() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("slowLoadingResourcePage.html"); DateTime start = DateTime.Now; localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime end = DateTime.Now; // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. TimeSpan duration = end - start; Assert.That(duration.TotalMilliseconds, Is.LessThan(5 * 1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver does not support eager page load strategy")] public void EagerStrategyShouldNotWaitForResourcesOnRefresh() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("slowLoadingResourcePage.html"); localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime start = DateTime.Now; localDriver.Navigate().Refresh(); // We discard the element, but want a check to make sure the GET actually // completed. WaitFor(() => localDriver.FindElement(By.Id("peas")), TimeSpan.FromSeconds(10), "did not find element"); DateTime end = DateTime.Now; // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. TimeSpan duration = end - start; Assert.That(duration.TotalMilliseconds, Is.LessThan(5 * 1000), "Took too long to load page: " + duration.TotalMilliseconds); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver does not support eager page load strategy")] public void EagerStrategyShouldWaitForDocumentToBeLoaded() { InitLocalDriver(PageLoadStrategy.Eager); string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=3"); localDriver.Url = slowPage; // We discard the element, but want a check to make sure the GET actually completed. WaitFor(() => localDriver.FindElement(By.TagName("body")), TimeSpan.FromSeconds(10), "did not find body"); } [Test] public void NormalStrategyShouldWaitForDocumentToBeLoaded() { driver.Url = simpleTestPage; Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldFollowRedirectsSentInTheHttpResponseHeaders() { driver.Url = redirectPage; Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldFollowMetaRedirects() { driver.Url = metaRedirectPage; WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToGetAFragmentOnTheCurrentPage() { if (TestUtilities.IsMarionette(driver)) { // Don't run this test on Marionette. Assert.Ignore("Marionette doesn't see subsequent navigation to a fragment as a new navigation."); } driver.Url = xhtmlTestPage; driver.Url = xhtmlTestPage + "#text"; driver.FindElement(By.Id("id1")); } [Test] public void ShouldReturnWhenGettingAUrlThatDoesNotResolve() { try { // Of course, we're up the creek if this ever does get registered driver.Url = "http://www.thisurldoesnotexist.comx/"; } catch (Exception e) { if (!IsIeDriverTimedOutException(e)) { throw e; } } } [Test] [IgnoreBrowser(Browser.Safari, "Safari driver does not throw on malformed URL, causing long delay awaiting timeout")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldThrowIfUrlIsMalformed() { Assert.That(() => driver.Url = "www.test.com", Throws.InstanceOf<WebDriverException>()); } [Test] [IgnoreBrowser(Browser.Safari, "Safari driver does not throw on malformed URL")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldThrowIfUrlIsMalformedInPortPart() { Assert.That(() => driver.Url = "http://localhost:30001bla", Throws.InstanceOf<WebDriverException>()); } [Test] public void ShouldReturnWhenGettingAUrlThatDoesNotConnect() { // Here's hoping that there's nothing here. There shouldn't be driver.Url = "http://localhost:3001"; } [Test] public void ShouldReturnUrlOnNotExistedPage() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("not_existed_page.html"); driver.Url = url; Assert.AreEqual(url, driver.Url); } [Test] public void ShouldBeAbleToLoadAPageWithFramesetsAndWaitUntilAllFramesAreLoaded() { driver.Url = framesetPage; driver.SwitchTo().Frame(0); IWebElement pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "1"); driver.SwitchTo().DefaultContent().SwitchTo().Frame(1); pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']")); Assert.AreEqual(pageNumber.Text.Trim(), "2"); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void ShouldDoNothingIfThereIsNothingToGoBackTo() { string originalTitle = driver.Title; driver.Url = formsPage; driver.Navigate().Back(); // We may have returned to the browser's home page string currentTitle = driver.Title; Assert.That(currentTitle, Is.EqualTo(originalTitle).Or.EqualTo("We Leave From Here")); if (driver.Title == originalTitle) { driver.Navigate().Back(); Assert.AreEqual(originalTitle, driver.Title); } } [Test] public void ShouldBeAbleToNavigateBackInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); } [Test] public void ShouldBeAbleToNavigateBackInTheBrowserHistoryInPresenceOfIframes() { driver.Url = xhtmlTestPage; driver.FindElement(By.Name("sameWindow")).Click(); WaitFor(TitleToBeEqualTo("This page has iframes"), "Browser title was not 'This page has iframes'"); Assert.AreEqual(driver.Title, "This page has iframes"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Browser title was not 'XHTML Test Page'"); Assert.AreEqual(driver.Title, "XHTML Test Page"); } [Test] public void ShouldBeAbleToNavigateForwardsInTheBrowserHistory() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Submit(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); driver.Navigate().Back(); WaitFor(TitleToBeEqualTo("We Leave From Here"), "Browser title was not 'We Leave From Here'"); Assert.AreEqual(driver.Title, "We Leave From Here"); driver.Navigate().Forward(); WaitFor(TitleToBeEqualTo("We Arrive Here"), "Browser title was not 'We Arrive Here'"); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [IgnoreBrowser(Browser.IE, "Browser does not support using insecure SSL certs")] [IgnoreBrowser(Browser.Safari, "Browser does not support using insecure SSL certs")] [IgnoreBrowser(Browser.Edge, "Browser does not support using insecure SSL certs")] public void ShouldBeAbleToAccessPagesWithAnInsecureSslCertificate() { String url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("simpleTest.html"); driver.Url = url; // This should work Assert.AreEqual(driver.Title, "Hello WebDriver"); } [Test] public void ShouldBeAbleToRefreshAPage() { driver.Url = xhtmlTestPage; driver.Navigate().Refresh(); Assert.AreEqual(driver.Title, "XHTML Test Page"); } /// <summary> /// see <a href="http://code.google.com/p/selenium/issues/detail?id=208">Issue 208</a> /// </summary> [Test] [IgnoreBrowser(Browser.IE, "Browser does, in fact, hang in this case.")] [IgnoreBrowser(Browser.Firefox, "Browser does, in fact, hang in this case.")] public void ShouldNotHangIfDocumentOpenCallIsNeverFollowedByDocumentCloseCall() { driver.Url = documentWrite; // If this command succeeds, then all is well. driver.FindElement(By.XPath("//body")); } [Test] [IgnoreBrowser(Browser.Safari)] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void PageLoadTimeoutCanBeChanged() { TestPageLoadTimeoutIsEnforced(2); TestPageLoadTimeoutIsEnforced(3); } [Test] [IgnoreBrowser(Browser.Safari)] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void CanHandleSequentialPageLoadTimeouts() { long pageLoadTimeout = 2; long pageLoadTimeBuffer = 10; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (pageLoadTimeout + pageLoadTimeBuffer)); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, pageLoadTimeout, pageLoadTimeBuffer); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, pageLoadTimeout, pageLoadTimeBuffer); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToLoad() { try { TestPageLoadTimeoutIsEnforced(2); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [IgnoreBrowser(Browser.Edge, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToLoadAfterClick() { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("page_with_link_to_slow_loading_page.html"); IWebElement link = WaitFor(() => driver.FindElement(By.Id("link-to-slow-loading-page")), "Could not find link"); try { AssertPageLoadTimeoutIsEnforced(() => link.Click(), 2, 3); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldTimeoutIfAPageTakesTooLongToRefresh() { // Get the sleeping servlet with a pause of 5 seconds long pageLoadTimeout = 2; long pageLoadTimeBuffer = 0; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (pageLoadTimeout + pageLoadTimeBuffer)); driver.Url = slowLoadingPageUrl; driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2); try { AssertPageLoadTimeoutIsEnforced(() => driver.Navigate().Refresh(), 2, 4); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } // Load another page after get() timed out but before test HTTP server served previous page. driver.Url = xhtmlTestPage; WaitFor(TitleToBeEqualTo("XHTML Test Page"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Edge, "Test hangs browser.")] [IgnoreBrowser(Browser.Chrome, "Chrome driver does, in fact, stop loading page after a timeout.")] [IgnoreBrowser(Browser.Opera, "Not implemented for browser")] [IgnoreBrowser(Browser.Safari, "Safari behaves correctly with page load timeout, but getting text does not propertly trim, leading to a test run time of over 30 seconds")] [NeedsFreshDriver(IsCreatedAfterTest = true)] public void ShouldNotStopLoadingPageAfterTimeout() { try { TestPageLoadTimeoutIsEnforced(1); } finally { driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300); } WaitFor(() => { try { string text = driver.FindElement(By.TagName("body")).Text; return text == "Slept for 11s"; } catch (NoSuchElementException) { } catch (StaleElementReferenceException) { } return false; }, TimeSpan.FromSeconds(30), "Did not find expected text"); } private Func<bool> TitleToBeEqualTo(string expectedTitle) { return () => { return driver.Title == expectedTitle; }; } /** * Sets given pageLoadTimeout to the {@link #driver} and asserts that attempt to navigate to a * page that takes much longer (10 seconds longer) to load results in a TimeoutException. * <p> * Side effects: 1) {@link #driver} is configured to use given pageLoadTimeout, * 2) test HTTP server still didn't serve the page to browser (some browsers may still * be waiting for the page to load despite the fact that driver responded with the timeout). */ private void TestPageLoadTimeoutIsEnforced(long webDriverPageLoadTimeoutInSeconds) { // Test page will load this many seconds longer than WD pageLoadTimeout. long pageLoadTimeBufferInSeconds = 10; string slowLoadingPageUrl = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=" + (webDriverPageLoadTimeoutInSeconds + pageLoadTimeBufferInSeconds)); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(webDriverPageLoadTimeoutInSeconds); AssertPageLoadTimeoutIsEnforced(() => driver.Url = slowLoadingPageUrl, webDriverPageLoadTimeoutInSeconds, pageLoadTimeBufferInSeconds); } private void AssertPageLoadTimeoutIsEnforced(TestDelegate delegateToTest, long webDriverPageLoadTimeoutInSeconds, long pageLoadTimeBufferInSeconds) { DateTime start = DateTime.Now; Assert.That(delegateToTest, Throws.InstanceOf<WebDriverTimeoutException>(), "I should have timed out after " + webDriverPageLoadTimeoutInSeconds + " seconds"); DateTime end = DateTime.Now; TimeSpan duration = end - start; Assert.That(duration.TotalSeconds, Is.GreaterThan(webDriverPageLoadTimeoutInSeconds)); Assert.That(duration.TotalSeconds, Is.LessThan(webDriverPageLoadTimeoutInSeconds + pageLoadTimeBufferInSeconds)); } private void InitLocalDriver(PageLoadStrategy strategy) { EnvironmentManager.Instance.CloseCurrentDriver(); if (localDriver != null) { localDriver.Quit(); } PageLoadStrategyOptions options = new PageLoadStrategyOptions(); options.PageLoadStrategy = strategy; localDriver = EnvironmentManager.Instance.CreateDriverInstance(options); } private class PageLoadStrategyOptions : DriverOptions { [Obsolete] public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { } public override ICapabilities ToCapabilities() { return null; } } } }
// 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; using System.Diagnostics; namespace System.Text { [Serializable] internal sealed class DecoderDBCS : Decoder { private readonly Encoding _encoding; private readonly byte[] _leadByteRanges = new byte[10]; // Max 5 ranges private int _rangesCount; private byte _leftOverLeadByte; internal DecoderDBCS(Encoding encoding) { _encoding = encoding; _rangesCount = Interop.Kernel32.GetLeadByteRanges(_encoding.CodePage, _leadByteRanges); Reset(); } private bool IsLeadByte(byte b) { if (b < _leadByteRanges[0]) return false; int i = 0; while (i < _rangesCount) { if (b >= _leadByteRanges[i] && b <= _leadByteRanges[i + 1]) return true; i += 2; } return false; } public override void Reset() { _leftOverLeadByte = 0; } public override unsafe int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (count == 0 && (_leftOverLeadByte == 0 || !flush)) return 0; fixed (byte* pBytes = bytes) { byte dummyByte; byte* pBuffer = pBytes == null ? &dummyByte : pBytes + index; return GetCharCount(pBuffer, count, flush); } } private unsafe int ConvertWithLeftOverByte(byte* bytes, int count, char* chars, int charCount) { Debug.Assert(_leftOverLeadByte != 0); byte* pTempBuffer = stackalloc byte[2]; pTempBuffer[0] = _leftOverLeadByte; int index = 0; if (count > 0) { pTempBuffer[1] = bytes[0]; index++; } int result = OSEncoding.MultiByteToWideChar(_encoding.CodePage, pTempBuffer, index+1, chars, charCount); if (count - index > 0) result += OSEncoding.MultiByteToWideChar( _encoding.CodePage, bytes + index, count - index, chars == null ? null : chars + result, chars == null ? 0 : charCount - result); return result; } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); bool excludeLastByte = count > 0 && !flush && IsLastByteALeadByte(bytes, count); if (excludeLastByte) count--; if (_leftOverLeadByte == 0) { if (count <= 0) return 0; return OSEncoding.MultiByteToWideChar(_encoding.CodePage, bytes, count, null, 0); } if (count == 0 && !excludeLastByte && !flush) return 0; return ConvertWithLeftOverByte(bytes, count, null, 0); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); if (chars.Length == 0) return 0; if (byteCount == 0 && (_leftOverLeadByte == 0 || !flush)) return 0; fixed (char* pChars = &chars[0]) fixed (byte* pBytes = bytes) { byte dummyByte; byte* pBuffer = pBytes == null ? &dummyByte : pBytes + byteIndex; return GetChars(pBuffer, byteCount, pChars + charIndex, chars.Length - charIndex, flush); } } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (charCount == 0) return 0; byte lastByte = byteCount > 0 && !flush && IsLastByteALeadByte(bytes, byteCount) ? bytes[byteCount - 1] : (byte) 0; if (lastByte != 0) byteCount--; if (_leftOverLeadByte == 0) { if (byteCount <= 0) { _leftOverLeadByte = lastByte; return 0; } int result = OSEncoding.MultiByteToWideChar(_encoding.CodePage, bytes, byteCount, chars, charCount); _leftOverLeadByte = lastByte; return result; } // we have left over lead byte if (byteCount == 0 && lastByte == 0 && !flush) return 0; int res = ConvertWithLeftOverByte(bytes, byteCount, chars, charCount); _leftOverLeadByte = lastByte; return res; } public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (charCount == 0 || (bytes.Length == 0 && (_leftOverLeadByte == 0 || !flush))) { bytesUsed = 0; charsUsed = 0; completed = false; return; } fixed (char* pChars = &chars[0]) fixed (byte* pBytes = bytes) { byte dummyByte; byte* pBuffer = pBytes == null ? &dummyByte : pBytes + byteIndex; Convert(pBuffer, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); int count = byteCount; while (count > 0) { int returnedCharCount = GetCharCount(bytes, count, flush); if (returnedCharCount <= charCount) break; count /= 2; } if (count > 0) { // note GetChars can change the _leftOverLeadByte state charsUsed = GetChars(bytes, count, chars, charCount, flush); bytesUsed = count; completed = _leftOverLeadByte == 0 && byteCount == count; return; } bytesUsed = 0; charsUsed = 0; completed = false; } // not IsLastByteALeadByte depends on the _leftOverLeadByte state private unsafe bool IsLastByteALeadByte(byte* bytes, int count) { if (!IsLeadByte(bytes[count - 1])) return false; // no need to process the buffer int index = 0; if (_leftOverLeadByte != 0) index++; // trail byte while (index < count) { if (IsLeadByte(bytes[index])) { index++; if (index >= count) return true; } index++; } return false; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Sql; using Microsoft.WindowsAzure.Management.Sql.Models; namespace Microsoft.WindowsAzure.Management.Sql { /// <summary> /// This is the main client class for interacting with the Azure SQL /// Database REST APIs. /// </summary> public static partial class DatabaseCopyOperationsExtensions { /// <summary> /// Starts a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the SQL Server where the source database /// resides. /// </param> /// <param name='databaseName'> /// Required. The name of the source database. /// </param> /// <param name='parameters'> /// Required. The additional parameters for the create database copy /// operation. /// </param> /// <returns> /// Represents a response to the create request. /// </returns> public static DatabaseCopyCreateResponse Create(this IDatabaseCopyOperations operations, string serverName, string databaseName, DatabaseCopyCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).CreateAsync(serverName, databaseName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Starts a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the SQL Server where the source database /// resides. /// </param> /// <param name='databaseName'> /// Required. The name of the source database. /// </param> /// <param name='parameters'> /// Required. The additional parameters for the create database copy /// operation. /// </param> /// <returns> /// Represents a response to the create request. /// </returns> public static Task<DatabaseCopyCreateResponse> CreateAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName, DatabaseCopyCreateParameters parameters) { return operations.CreateAsync(serverName, databaseName, parameters, CancellationToken.None); } /// <summary> /// Stops a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to stop. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IDatabaseCopyOperations operations, string serverName, string databaseName, Guid databaseCopyName) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).DeleteAsync(serverName, databaseName, databaseCopyName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Stops a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to stop. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName, Guid databaseCopyName) { return operations.DeleteAsync(serverName, databaseName, databaseCopyName, CancellationToken.None); } /// <summary> /// Retrieves information about a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to retrieve. /// </param> /// <returns> /// Represents a response to the get request. /// </returns> public static DatabaseCopyGetResponse Get(this IDatabaseCopyOperations operations, string serverName, string databaseName, string databaseCopyName) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).GetAsync(serverName, databaseName, databaseCopyName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieves information about a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to retrieve. /// </param> /// <returns> /// Represents a response to the get request. /// </returns> public static Task<DatabaseCopyGetResponse> GetAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName, string databaseCopyName) { return operations.GetAsync(serverName, databaseName, databaseCopyName, CancellationToken.None); } /// <summary> /// Retrieves the list of SQL Server database copies for a database. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the database server to be queried. /// </param> /// <param name='databaseName'> /// Required. The name of the database to be queried. /// </param> /// <returns> /// Represents the response containing the list of database copies for /// a given database. /// </returns> public static DatabaseCopyListResponse List(this IDatabaseCopyOperations operations, string serverName, string databaseName) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).ListAsync(serverName, databaseName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieves the list of SQL Server database copies for a database. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the database server to be queried. /// </param> /// <param name='databaseName'> /// Required. The name of the database to be queried. /// </param> /// <returns> /// Represents the response containing the list of database copies for /// a given database. /// </returns> public static Task<DatabaseCopyListResponse> ListAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName) { return operations.ListAsync(serverName, databaseName, CancellationToken.None); } /// <summary> /// Updates a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to update. /// </param> /// <param name='parameters'> /// Required. The additional parameters for the update database copy /// operation. /// </param> /// <returns> /// Represents a response to the update request. /// </returns> public static DatabaseCopyUpdateResponse Update(this IDatabaseCopyOperations operations, string serverName, string databaseName, Guid databaseCopyName, DatabaseCopyUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDatabaseCopyOperations)s).UpdateAsync(serverName, databaseName, databaseCopyName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates a SQL Server database copy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Sql.IDatabaseCopyOperations. /// </param> /// <param name='serverName'> /// Required. The name of the source or destination SQL Server instance. /// </param> /// <param name='databaseName'> /// Required. The name of the database. /// </param> /// <param name='databaseCopyName'> /// Required. The unique identifier for the database copy to update. /// </param> /// <param name='parameters'> /// Required. The additional parameters for the update database copy /// operation. /// </param> /// <returns> /// Represents a response to the update request. /// </returns> public static Task<DatabaseCopyUpdateResponse> UpdateAsync(this IDatabaseCopyOperations operations, string serverName, string databaseName, Guid databaseCopyName, DatabaseCopyUpdateParameters parameters) { return operations.UpdateAsync(serverName, databaseName, databaseCopyName, parameters, CancellationToken.None); } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Globalization; using System.Text; using MindTouch.Deki.Data; using MindTouch.Dream; using MindTouch.Tasking; using MindTouch.Xml; namespace MindTouch.Deki.UserSubscription { using Yield = IEnumerator<IYield>; public class PageChangeCache { //--- Class Fields --- private static readonly log4net.ILog _log = LogUtils.CreateLog(); //--- Fields --- private readonly Plug _deki; private readonly Action<string, Action> _cacheItemCallback; private readonly Dictionary<string, PageChangeCacheData> _cache = new Dictionary<string, PageChangeCacheData>(); //--- Constructors --- public PageChangeCache(Plug deki, TimeSpan ttl) : this(deki, (key, clearAction) => TaskTimer.New(ttl, timer => clearAction(), null, TaskEnv.None)) { } public PageChangeCache(Plug deki, Action<string, Action> cacheItemCallback) { if(deki == null) { throw new ArgumentNullException("deki"); } if(cacheItemCallback == null) { throw new ArgumentNullException("cacheItemCallback"); } _cacheItemCallback = cacheItemCallback; _deki = deki; } //--- Methods --- public Yield GetPageData(uint pageId, string wikiId, DateTime time, CultureInfo culture, string timezone, Result<PageChangeData> result) { // Note (arnec): going back 10 seconds before event, because timestamps in a request are not currently synced Result<PageChangeCacheData> cacheResult; yield return cacheResult = Coroutine.Invoke(GetCache, pageId, wikiId, time, culture, new Result<PageChangeCacheData>()); PageChangeCacheData cacheData = cacheResult.Value; if(cacheData == null) { result.Return((PageChangeData)null); yield break; } StringBuilder plainBody = new StringBuilder(); plainBody.AppendFormat("{0}\r\n[ {1} ]\r\n\r\n", cacheData.Title, cacheData.PageUri); XDoc htmlBody = new XDoc("html") .Start("p") .Start("b") .Start("a").Attr("href", cacheData.PageUri).Value(cacheData.Title).End() .End() .Value(" ( Last edited by ") .Start("a").Attr("href", cacheData.WhoUri).Value(cacheData.Who).End() .Value(" )") .Elem("br") .Start("small") .Start("a").Attr("href", cacheData.PageUri).Value(cacheData.PageUri).End() .End() .Elem("br") .Start("small") .Start("a").Attr("href", cacheData.UnsubUri).Value("Unsubscribe").End() .End() .End() .Start("p") .Start("ol"); string tz = "GMT"; TimeSpan tzOffset = TimeSpan.Zero; if(!string.IsNullOrEmpty(timezone)) { tz = timezone; string[] parts = timezone.Split(':'); int hours; int minutes; int.TryParse(parts[0], out hours); int.TryParse(parts[1], out minutes); tzOffset = new TimeSpan(hours, minutes, 0); } foreach(PageChangeCacheData.Item item in cacheData.Items) { string t = item.Time.Add(tzOffset).ToString(string.Format("ddd, dd MMM yyyy HH':'mm':'ss '{0}'", tz), culture); plainBody.AppendFormat(" - {0} by {1} ({2})\r\n", item.ChangeDetail, item.Who, t); plainBody.AppendFormat(" [ {0} ]\r\n", item.RevisionUri); htmlBody.Start("li") .Value(item.ChangeDetail) .Value(" ( ") .Start("a").Attr("href", item.RevisionUri).Value(t).End() .Value(" by ") .Start("a").Attr("href", item.WhoUri).Value(item.Who).End() .Value(" )") .End(); plainBody.Append("\r\n"); } htmlBody .End() .End() .Elem("br"); result.Return(new PageChangeData(plainBody.ToString(), htmlBody)); yield break; } private Yield GetCache(uint pageId, string wikiId, DateTime time, CultureInfo culture, Result<PageChangeCacheData> result) { // Note (arnec): going back 10 seconds before event, because timestamps in a request are not currently synced string keytime = time.ToString("yyyyMMddHHmm"); string since = time.Subtract(TimeSpan.FromSeconds(10)).ToString("yyyyMMddHHmmss"); PageChangeCacheData cacheData; string key = string.Format("{0}:{1}:{2}:{3}", pageId, wikiId, keytime, culture); _log.DebugFormat("getting data for key: {0}", key); lock(_cache) { if(_cache.TryGetValue(key, out cacheData)) { result.Return(cacheData); yield break; } } // fetch the page data Result<DreamMessage> pageResponse; yield return pageResponse = _deki .At("pages", pageId.ToString()) .WithHeader("X-Deki-Site", "id=" + wikiId) .With("redirects", "0").GetAsync(); if(!pageResponse.Value.IsSuccessful) { _log.WarnFormat("Unable to fetch page '{0}' info: {1}", pageId, pageResponse.Value.Status); result.Return((PageChangeCacheData)null); yield break; } XDoc page = pageResponse.Value.ToDocument(); string title = page["title"].AsText; XUri pageUri = page["uri.ui"].AsUri; string pageUriString = CleanUriForEmail(pageUri); string unsubUri = CleanUriForEmail(pageUri .WithoutPathQueryFragment() .At("index.php") .With("title", "Special:PageAlerts") .With("id", pageId.ToString())); // fetch the revision history Result<DreamMessage> feedResponse; yield return feedResponse = _deki .At("pages", pageId.ToString(), "feed") .WithHeader("X-Deki-Site", "id=" + wikiId) .With("redirects", "0") .With("format", "raw") .With("since", since) .GetAsync(); if(!feedResponse.Value.IsSuccessful) { _log.WarnFormat("Unable to fetch page '{0}' changes: {1}", pageId, feedResponse.Value.Status); result.Return((PageChangeCacheData)null); yield break; } // build the docs XDoc feed = feedResponse.Value.ToDocument()["change"]; if(feed.ListLength == 0) { _log.WarnFormat("Change feed is empty for page: {0}", pageId); result.Return((PageChangeCacheData)null); yield break; } string who = feed["rc_user_name"].AsText; string whoUri = CleanUriForEmail(pageUri.WithoutPathQueryFragment().At(XUri.EncodeSegment("User:" + who))); cacheData = new PageChangeCacheData(); cacheData.Title = title; cacheData.PageUri = pageUriString; cacheData.Who = who; cacheData.WhoUri = whoUri; cacheData.UnsubUri = unsubUri; foreach(XDoc change in feed.ReverseList()) { string changeDetail = change["rc_comment"].AsText; string revisionUri = CleanUriForEmail(pageUri.With("revision", change["rc_revision"].AsText)); who = change["rc_user_name"].AsText; whoUri = CleanUriForEmail(pageUri.WithoutPathQueryFragment().At(XUri.EncodeSegment("User:" + who))); PageChangeCacheData.Item item = new PageChangeCacheData.Item(); item.Who = who; item.WhoUri = whoUri; item.RevisionUri = revisionUri; item.ChangeDetail = changeDetail; item.Time = DbUtils.ToDateTime(change["rc_timestamp"].AsText); cacheData.Items.Add(item); } lock(_cache) { // even though we override the entry if one was created in the meantime // we do the existence check so that we don't set up two expiration timers; if(!_cache.ContainsKey(key)) { _cacheItemCallback(key, () => { lock(_cache) { _cache.Remove(key); } }); } _cache[key] = cacheData; } result.Return(cacheData); yield break; } private string CleanUriForEmail(XUri uri) { uri = uri.AsPublicUri(); string schemehostport = uri.SchemeHostPort; string pathQueryFragment = uri.PathQueryFragment; return schemehostport + pathQueryFragment.Replace(":", "%3A"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // Name used for AGGDECLs in the symbol table. // AggregateSymbol - a symbol representing an aggregate type. These are classes, // interfaces, and structs. Parent is a namespace or class. Children are methods, // properties, and member variables, and types (including its own AGGTYPESYMs). internal class AggregateSymbol : NamespaceOrAggregateSymbol { public Type AssociatedSystemType; public Assembly AssociatedAssembly; // This InputFile is some infile for the assembly containing this AggregateSymbol. // It is used for fast access to the filter BitSet and assembly ID. private InputFile _infile; // The instance type. Created when first needed. private AggregateType _atsInst; private AggregateType _pBaseClass; // For a class/struct/enum, the base class. For iface: unused. private AggregateType _pUnderlyingType; // For enum, the underlying type. For iface, the resolved CoClass. Not used for class/struct. private TypeArray _ifaces; // The explicit base interfaces for a class or interface. private TypeArray _ifacesAll; // Recursive closure of base interfaces ordered so an iface appears before all of its base ifaces. private TypeArray _typeVarsThis; // Type variables for this generic class, as declarations. private TypeArray _typeVarsAll; // The type variables for this generic class and all containing classes. private TypeManager _pTypeManager; // This is so AGGTYPESYMs can instantiate their baseClass and ifacesAll members on demand. // First UD conversion operator. This chain is for this type only (not base types). // The hasConversion flag indicates whether this or any base types have UD conversions. private MethodSymbol _pConvFirst; // ------------------------------------------------------------------------ // // Put members that are bits under here in a contiguous section. // // ------------------------------------------------------------------------ private AggKindEnum _aggKind; private bool _isLayoutError; // Whether there is a cycle in the layout for the struct // Where this came from - fabricated, source, import // Fabricated AGGs have isSource == true but hasParseTree == false. // N.B.: in incremental builds, it is quite possible for // isSource==TRUE and hasParseTree==FALSE. Be // sure you use the correct variable for what you are trying to do! private bool _isSource; // This class is defined in source, although the // source might not be being read during this compile. // Predefined private bool _isPredefined; // A special predefined type. private PredefinedType _iPredef; // index of the predefined type, if isPredefined. // Flags private bool _isAbstract; // Can it be instantiated? private bool _isSealed; // Can it be derived from? // Attribute private bool _isUnmanagedStruct; // Set if the struct is known to be un-managed (for unsafe code). Set in FUNCBREC. private bool _isManagedStruct; // Set if the struct is known to be managed (for unsafe code). Set during import. // Constructors private bool _hasPubNoArgCtor; // Whether it has a public instance constructor taking no args // private struct members should not be checked for assignment or references private bool _hasExternReference; // User defined operators private bool _isSkipUDOps; // Never check for user defined operators on this type (eg, decimal, string, delegate). private bool _isComImport; // Does it have [ComImport] private bool _isAnonymousType; // true if the class is an anonymous type // When this is unset we don't know if we have conversions. When this // is set it indicates if this type or any base type has user defined // conversion operators private bool? _hasConversion; // ---------------------------------------------------------------------------- // AggregateSymbol // ---------------------------------------------------------------------------- public AggregateSymbol GetBaseAgg() { return _pBaseClass == null ? null : _pBaseClass.getAggregate(); } public AggregateType getThisType() { if (_atsInst == null) { Debug.Assert(GetTypeVars() == GetTypeVarsAll() || isNested()); AggregateType pOuterType = this.isNested() ? GetOuterAgg().getThisType() : null; _atsInst = _pTypeManager.GetAggregate(this, pOuterType, GetTypeVars()); } //Debug.Assert(GetTypeVars().Size == atsInst.GenericArguments.Count); return _atsInst; } public void InitFromInfile(InputFile infile) { _infile = infile; _isSource = infile.isSource; } public bool FindBaseAgg(AggregateSymbol agg) { for (AggregateSymbol aggT = this; aggT != null; aggT = aggT.GetBaseAgg()) { if (aggT == agg) return true; } return false; } public NamespaceOrAggregateSymbol Parent { get { return parent.AsNamespaceOrAggregateSymbol(); } } public new AggregateDeclaration DeclFirst() { return (AggregateDeclaration)base.DeclFirst(); } public AggregateDeclaration DeclOnly() { //Debug.Assert(DeclFirst() != null && DeclFirst().DeclNext() == null); return DeclFirst(); } public bool InAlias(KAID aid) { Debug.Assert(_infile != null); //Debug.Assert(DeclFirst() == null || DeclFirst().GetAssemblyID() == infile.GetAssemblyID()); Debug.Assert(0 <= aid); if (aid < KAID.kaidMinModule) return _infile.InAlias(aid); return (aid == GetModuleID()); } public KAID GetModuleID() { return 0; } public KAID GetAssemblyID() { Debug.Assert(_infile != null); //Debug.Assert(DeclFirst() == null || DeclFirst().GetAssemblyID() == infile.GetAssemblyID()); return _infile.GetAssemblyID(); } public bool IsUnresolved() { return _infile != null && _infile.GetAssemblyID() == KAID.kaidUnresolved; } public bool isNested() { return parent != null && parent.IsAggregateSymbol(); } public AggregateSymbol GetOuterAgg() { return parent != null && parent.IsAggregateSymbol() ? parent.AsAggregateSymbol() : null; } public bool isPredefAgg(PredefinedType pt) { return _isPredefined && (PredefinedType)_iPredef == pt; } // ---------------------------------------------------------------------------- // The following are the Accessor functions for AggregateSymbol. // ---------------------------------------------------------------------------- public AggKindEnum AggKind() { return (AggKindEnum)_aggKind; } public void SetAggKind(AggKindEnum aggKind) { // NOTE: When importing can demote types: // - enums with no underlying type go to struct // - delegates which are abstract or have no .ctor/Invoke method goto class _aggKind = aggKind; //An interface is always abstract if (aggKind == AggKindEnum.Interface) { this.SetAbstract(true); } } public bool IsClass() { return AggKind() == AggKindEnum.Class; } public bool IsDelegate() { return AggKind() == AggKindEnum.Delegate; } public bool IsInterface() { return AggKind() == AggKindEnum.Interface; } public bool IsStruct() { return AggKind() == AggKindEnum.Struct; } public bool IsEnum() { return AggKind() == AggKindEnum.Enum; } public bool IsValueType() { return AggKind() == AggKindEnum.Struct || AggKind() == AggKindEnum.Enum; } public bool IsRefType() { return AggKind() == AggKindEnum.Class || AggKind() == AggKindEnum.Interface || AggKind() == AggKindEnum.Delegate; } public bool IsStatic() { return (_isAbstract && _isSealed); } public bool IsAnonymousType() { return _isAnonymousType; } public void SetAnonymousType(bool isAnonymousType) { _isAnonymousType = isAnonymousType; } public bool IsAbstract() { return _isAbstract; } public void SetAbstract(bool @abstract) { _isAbstract = @abstract; } public bool IsPredefined() { return _isPredefined; } public void SetPredefined(bool predefined) { _isPredefined = predefined; } public PredefinedType GetPredefType() { return (PredefinedType)_iPredef; } public void SetPredefType(PredefinedType predef) { _iPredef = predef; } public bool IsLayoutError() { return _isLayoutError == true; } public void SetLayoutError(bool layoutError) { _isLayoutError = layoutError; } public bool IsSealed() { return _isSealed == true; } public void SetSealed(bool @sealed) { _isSealed = @sealed; } //////////////////////////////////////////////////////////////////////////////// public bool HasConversion(SymbolLoader pLoader) { pLoader.RuntimeBinderSymbolTable.AddConversionsForType(AssociatedSystemType); if (!_hasConversion.HasValue) { // ok, we tried defining all the conversions, and we didn't get anything // for this type. However, we will still think this type has conversions // if it's base type has conversions. _hasConversion = GetBaseAgg() != null && GetBaseAgg().HasConversion(pLoader); } return _hasConversion.Value; } //////////////////////////////////////////////////////////////////////////////// public void SetHasConversion() { _hasConversion = true; } //////////////////////////////////////////////////////////////////////////////// public bool IsUnmanagedStruct() { return _isUnmanagedStruct == true; } public void SetUnmanagedStruct(bool unmanagedStruct) { _isUnmanagedStruct = unmanagedStruct; } public bool IsManagedStruct() { return _isManagedStruct == true; } public void SetManagedStruct(bool managedStruct) { _isManagedStruct = managedStruct; } public bool IsKnownManagedStructStatus() { Debug.Assert(this.IsStruct()); Debug.Assert(!IsManagedStruct() || !IsUnmanagedStruct()); return IsManagedStruct() || IsUnmanagedStruct(); } public bool HasPubNoArgCtor() { return _hasPubNoArgCtor == true; } public void SetHasPubNoArgCtor(bool hasPubNoArgCtor) { _hasPubNoArgCtor = hasPubNoArgCtor; } public bool HasExternReference() { return _hasExternReference == true; } public void SetHasExternReference(bool hasExternReference) { _hasExternReference = hasExternReference; } public bool IsSkipUDOps() { return _isSkipUDOps == true; } public void SetSkipUDOps(bool skipUDOps) { _isSkipUDOps = skipUDOps; } public void SetComImport(bool comImport) { _isComImport = comImport; } public bool IsSource() { return _isSource == true; } public TypeArray GetTypeVars() { return _typeVarsThis; } public void SetTypeVars(TypeArray typeVars) { if (typeVars == null) { _typeVarsThis = null; _typeVarsAll = null; } else { TypeArray outerTypeVars; if (this.GetOuterAgg() != null) { Debug.Assert(this.GetOuterAgg().GetTypeVars() != null); Debug.Assert(this.GetOuterAgg().GetTypeVarsAll() != null); outerTypeVars = this.GetOuterAgg().GetTypeVarsAll(); } else { outerTypeVars = BSYMMGR.EmptyTypeArray(); } _typeVarsThis = typeVars; _typeVarsAll = _pTypeManager.ConcatenateTypeArrays(outerTypeVars, typeVars); } } public TypeArray GetTypeVarsAll() { return _typeVarsAll; } public AggregateType GetBaseClass() { return _pBaseClass; } public void SetBaseClass(AggregateType baseClass) { _pBaseClass = baseClass; } public AggregateType GetUnderlyingType() { return _pUnderlyingType; } public void SetUnderlyingType(AggregateType underlyingType) { _pUnderlyingType = underlyingType; } public TypeArray GetIfaces() { return _ifaces; } public void SetIfaces(TypeArray ifaces) { _ifaces = ifaces; } public TypeArray GetIfacesAll() { return _ifacesAll; } public void SetIfacesAll(TypeArray ifacesAll) { _ifacesAll = ifacesAll; } public TypeManager GetTypeManager() { return _pTypeManager; } public void SetTypeManager(TypeManager typeManager) { _pTypeManager = typeManager; } public MethodSymbol GetFirstUDConversion() { return _pConvFirst; } public void SetFirstUDConversion(MethodSymbol conv) { _pConvFirst = conv; } public new bool InternalsVisibleTo(Assembly assembly) { return _pTypeManager.InternalsVisibleTo(AssociatedAssembly, assembly); } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Runtime.InteropServices; namespace ListViewEx { /// <summary> /// Inherited ListView to allow in-place editing of subitems /// </summary> public class ListViewEx : System.Windows.Forms.ListView { #region Interop structs, imports and constants /// <summary> /// MessageHeader for WM_NOTIFY /// </summary> private struct NMHDR { public IntPtr hwndFrom; public Int32 idFrom; public Int32 code; } [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wPar, IntPtr lPar); [DllImport("user32.dll", CharSet = CharSet.Ansi)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, int len, ref int[] order); // ListView messages private const int LVM_FIRST = 0x1000; private const int LVM_GETCOLUMNORDERARRAY = (LVM_FIRST + 59); // Windows Messages that will abort editing private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; private const int WM_SIZE = 0x05; private const int WM_NOTIFY = 0x4E; private const int HDN_FIRST = -300; private const int HDN_BEGINDRAG = (HDN_FIRST - 10); private const int HDN_ITEMCHANGINGA = (HDN_FIRST - 0); private const int HDN_ITEMCHANGINGW = (HDN_FIRST - 20); #endregion /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public event SubItemEventHandler SubItemClicked; public event SubItemEventHandler SubItemBeginEditing; public event SubItemEndEditingEventHandler SubItemEndEditing; private bool _isEditing; public bool IsEditing { get { return _isEditing; } } public ListViewEx() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); base.FullRowSelect = true; base.View = View.Details; base.AllowColumnReorder = true; } /// <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 Component 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() { components = new System.ComponentModel.Container(); } #endregion private bool _doubleClickActivation = false; /// <summary> /// Is a double click required to start editing a cell? /// </summary> public bool DoubleClickActivation { get { return _doubleClickActivation; } set { _doubleClickActivation = value; } } /// <summary> /// Retrieve the order in which columns appear /// </summary> /// <returns>Current display order of column indices</returns> public int[] GetColumnOrder() { IntPtr lPar = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Columns.Count); IntPtr res = SendMessage(Handle, LVM_GETCOLUMNORDERARRAY, new IntPtr(Columns.Count), lPar); if (res.ToInt32() == 0) // Something went wrong { Marshal.FreeHGlobal(lPar); return null; } int[] order = new int[Columns.Count]; Marshal.Copy(lPar, order, 0, Columns.Count); Marshal.FreeHGlobal(lPar); return order; } /// <summary> /// Find ListViewItem and SubItem Index at position (x,y) /// </summary> /// <param name="x">relative to ListView</param> /// <param name="y">relative to ListView</param> /// <param name="item">Item at position (x,y)</param> /// <returns>SubItem index</returns> public int GetSubItemAt(int x, int y, out ListViewItem item) { item = this.GetItemAt(x, y); if (item != null) { int[] order = GetColumnOrder(); Rectangle lviBounds; int subItemX; lviBounds = item.GetBounds(ItemBoundsPortion.Entire); subItemX = lviBounds.Left; for (int i = 0; i < order.Length; i++) { ColumnHeader h = this.Columns[order[i]]; if (x < subItemX + h.Width) { return h.Index; } subItemX += h.Width; } } return -1; } /// <summary> /// Get bounds for a SubItem /// </summary> /// <param name="Item">Target ListViewItem</param> /// <param name="SubItem">Target SubItem index</param> /// <returns>Bounds of SubItem (relative to ListView)</returns> public Rectangle GetSubItemBounds(ListViewItem Item, int SubItem) { int[] order = GetColumnOrder(); Rectangle subItemRect = Rectangle.Empty; if (SubItem >= order.Length) throw new IndexOutOfRangeException("SubItem " + SubItem + " out of range"); if (Item == null) throw new ArgumentNullException("Item"); Rectangle lviBounds = Item.GetBounds(ItemBoundsPortion.Entire); int subItemX = lviBounds.Left; ColumnHeader col; int i; for (i = 0; i < order.Length; i++) { col = this.Columns[order[i]]; if (col.Index == SubItem) break; subItemX += col.Width; } subItemRect = new Rectangle(subItemX, lviBounds.Top, this.Columns[order[i]].Width, lviBounds.Height); return subItemRect; } protected override void WndProc(ref Message msg) { switch (msg.Msg) { // Look for WM_VSCROLL,WM_HSCROLL or WM_SIZE messages. case WM_VSCROLL: case WM_HSCROLL: case WM_SIZE: EndEditing(false); break; case WM_NOTIFY: // Look for WM_NOTIFY of events that might also change the // editor's position/size: Column reordering or resizing NMHDR h = (NMHDR)Marshal.PtrToStructure(msg.LParam, typeof(NMHDR)); if (h.code == HDN_BEGINDRAG || h.code == HDN_ITEMCHANGINGA || h.code == HDN_ITEMCHANGINGW) EndEditing(false); break; } base.WndProc(ref msg); } #region Initialize editing depending of DoubleClickActivation property protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e) { base.OnMouseUp(e); if (DoubleClickActivation) { return; } EditSubitemAt(new Point(e.X, e.Y)); } protected override void OnDoubleClick(EventArgs e) { base.OnDoubleClick(e); if (!DoubleClickActivation) { return; } Point pt = this.PointToClient(Cursor.Position); EditSubitemAt(pt); } ///<summary> /// Fire SubItemClicked ///</summary> ///<param name="p">Point of click/doubleclick</param> private void EditSubitemAt(Point p) { ListViewItem item; int idx = GetSubItemAt(p.X, p.Y, out item); if (idx >= 0) { OnSubItemClicked(new SubItemEventArgs(item, idx)); } } #endregion #region In-place editing functions // The control performing the actual editing private Control _editingControl; // The LVI being edited private ListViewItem _editItem; // The SubItem being edited private int _editSubItem; protected void OnSubItemBeginEditing(SubItemEventArgs e) { if (SubItemBeginEditing != null) SubItemBeginEditing(this, e); } protected void OnSubItemEndEditing(SubItemEndEditingEventArgs e) { if (SubItemEndEditing != null) SubItemEndEditing(this, e); } protected void OnSubItemClicked(SubItemEventArgs e) { if (SubItemClicked != null) SubItemClicked(this, e); } /// <summary> /// Begin in-place editing of given cell /// </summary> /// <param name="c">Control used as cell editor</param> /// <param name="Item">ListViewItem to edit</param> /// <param name="SubItem">SubItem index to edit</param> public void StartEditing(Control c, ListViewItem Item, int SubItem) { _isEditing = true; OnSubItemBeginEditing(new SubItemEventArgs(Item, SubItem)); Rectangle rcSubItem = GetSubItemBounds(Item, SubItem); int OffsetTop = rcSubItem.Height / 2 - c.Height / 2; if (rcSubItem.X < 0) { // Left edge of SubItem not visible - adjust rectangle position and width rcSubItem.Width += rcSubItem.X; rcSubItem.X = 0; } if (rcSubItem.X + rcSubItem.Width > this.Width) { // Right edge of SubItem not visible - adjust rectangle width rcSubItem.Width = this.Width - rcSubItem.Left; } // Subitem bounds are relative to the location of the ListView! rcSubItem.Offset(Left, Top); // In case the editing control and the listview are on different parents, // account for different origins Point origin = new Point(0, 0); Point lvOrigin = this.Parent.PointToScreen(origin); Point ctlOrigin = c.Parent.PointToScreen(origin); rcSubItem.Offset(lvOrigin.X - ctlOrigin.X, lvOrigin.Y - ctlOrigin.Y + OffsetTop); // Position and show editor c.Bounds = rcSubItem; c.Text = Item.SubItems[SubItem].Text; c.Visible = true; c.BringToFront(); c.Focus(); _editingControl = c; _editingControl.Leave += new EventHandler(_editControl_Leave); _editingControl.KeyPress += new KeyPressEventHandler(_editControl_KeyPress); _editItem = Item; _editSubItem = SubItem; } private void _editControl_Leave(object sender, EventArgs e) { // cell editor losing focus EndEditing(true); } private void _editControl_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { switch (e.KeyChar) { case (char)(int)Keys.Escape: { EndEditing(false); break; } case (char)(int)Keys.Enter: { EndEditing(true); break; } } } /// <summary> /// Accept or discard current value of cell editor control /// </summary> /// <param name="AcceptChanges">Use the _editingControl's Text as new SubItem text or discard changes?</param> public void EndEditing(bool AcceptChanges) { _isEditing = false; if (_editingControl == null) return; SubItemEndEditingEventArgs e = new SubItemEndEditingEventArgs( _editItem, // The item being edited _editSubItem, // The subitem index being edited AcceptChanges ? _editingControl.Text : // Use editControl text if changes are accepted _editItem.SubItems[_editSubItem].Text, // or the original subitem's text, if changes are discarded !AcceptChanges // Cancel? ); OnSubItemEndEditing(e); if (!e.Cancel) { _editItem.SubItems[_editSubItem].Text = e.DisplayText; } _editingControl.Leave -= new EventHandler(_editControl_Leave); _editingControl.KeyPress -= new KeyPressEventHandler(_editControl_KeyPress); _editingControl.Visible = false; _editingControl = null; _editItem = null; _editSubItem = -1; } #endregion } /// <summary> /// Event Handler for SubItem events /// </summary> public delegate void SubItemEventHandler(object sender, SubItemEventArgs e); /// <summary> /// Event Handler for SubItemEndEditing events /// </summary> public delegate void SubItemEndEditingEventHandler(object sender, SubItemEndEditingEventArgs e); /// <summary> /// Event Args for SubItemClicked event /// </summary> public class SubItemEventArgs : EventArgs { public SubItemEventArgs(ListViewItem item, int subItem) { _subItemIndex = subItem; _item = item; } private int _subItemIndex = -1; private ListViewItem _item = null; public int SubItem { get { return _subItemIndex; } } public ListViewItem Item { get { return _item; } } } /// <summary> /// Event Args for SubItemEndEditingClicked event /// </summary> public class SubItemEndEditingEventArgs : SubItemEventArgs { private string _text = string.Empty; private bool _cancel = true; public SubItemEndEditingEventArgs(ListViewItem item, int subItem, string display, bool cancel) : base(item, subItem) { _text = display; _cancel = cancel; } public string DisplayText { get { return _text; } set { _text = value; } } public bool Cancel { get { return _cancel; } set { _cancel = value; } } } }
using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Data; using Franson.BlueTools; namespace SimpleService { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button bAdvertise; private System.Windows.Forms.Button bDeadvertise; private System.Windows.Forms.Label lServiceStatus; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtWriteData; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtRead; private System.Windows.Forms.Button bWrite; private System.Windows.Forms.Label label3; private System.Windows.Forms.ListBox listSessions; private System.Windows.Forms.Label lStackID; private System.Windows.Forms.MainMenu mainMenu1; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.bAdvertise = new System.Windows.Forms.Button(); this.bDeadvertise = new System.Windows.Forms.Button(); this.lServiceStatus = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.txtWriteData = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.txtRead = new System.Windows.Forms.TextBox(); this.bWrite = new System.Windows.Forms.Button(); this.listSessions = new System.Windows.Forms.ListBox(); this.label3 = new System.Windows.Forms.Label(); this.lStackID = new System.Windows.Forms.Label(); // // bAdvertise // this.bAdvertise.Location = new System.Drawing.Point(16, 16); this.bAdvertise.Size = new System.Drawing.Size(80, 24); this.bAdvertise.Text = "Advertise"; this.bAdvertise.Click += new System.EventHandler(this.bAdvertise_Click); // // bDeadvertise // this.bDeadvertise.Location = new System.Drawing.Point(112, 16); this.bDeadvertise.Size = new System.Drawing.Size(80, 24); this.bDeadvertise.Text = "Deadvertise"; this.bDeadvertise.Click += new System.EventHandler(this.bDeadvertise_Click); // // lServiceStatus // this.lServiceStatus.Location = new System.Drawing.Point(16, 48); this.lServiceStatus.Size = new System.Drawing.Size(176, 16); this.lServiceStatus.Text = "Service not active"; // // label1 // this.label1.Location = new System.Drawing.Point(16, 88); this.label1.Size = new System.Drawing.Size(96, 16); this.label1.Text = "Data to client"; // // txtWriteData // this.txtWriteData.Location = new System.Drawing.Point(16, 104); this.txtWriteData.Size = new System.Drawing.Size(160, 20); this.txtWriteData.Text = "some data"; // // label2 // this.label2.Location = new System.Drawing.Point(16, 128); this.label2.Size = new System.Drawing.Size(152, 16); this.label2.Text = "Datat from Client"; // // txtRead // this.txtRead.Location = new System.Drawing.Point(16, 144); this.txtRead.Size = new System.Drawing.Size(160, 20); this.txtRead.Text = ""; // // bWrite // this.bWrite.Location = new System.Drawing.Point(184, 104); this.bWrite.Size = new System.Drawing.Size(48, 24); this.bWrite.Text = "Write"; this.bWrite.Click += new System.EventHandler(this.bWrite_Click); // // listSessions // this.listSessions.Location = new System.Drawing.Point(16, 192); this.listSessions.Size = new System.Drawing.Size(136, 54); // // label3 // this.label3.Location = new System.Drawing.Point(16, 176); this.label3.Size = new System.Drawing.Size(96, 16); this.label3.Text = "Sessions"; // // lStackID // this.lStackID.Location = new System.Drawing.Point(16, 248); this.lStackID.Size = new System.Drawing.Size(144, 16); this.lStackID.Text = "No stack found"; // // Form1 // this.Controls.Add(this.lStackID); this.Controls.Add(this.label3); this.Controls.Add(this.listSessions); this.Controls.Add(this.bWrite); this.Controls.Add(this.txtRead); this.Controls.Add(this.label2); this.Controls.Add(this.txtWriteData); this.Controls.Add(this.label1); this.Controls.Add(this.lServiceStatus); this.Controls.Add(this.bDeadvertise); this.Controls.Add(this.bAdvertise); this.Menu = this.mainMenu1; this.MinimizeBox = false; this.Text = "SimpleService"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion /// <summary> /// The main entry point for the application. /// </summary> static void Main() { Application.Run(new Form1()); } Manager m_manager = null; Network m_network = null; LocalService m_service = null; private void Form1_Load(object sender, System.EventArgs e) { // You can get a valid evaluation key for BlueTools at // http://franson.com/bluetools/ // That key will be valid for 14 days. Just cut and paste that key into the statement below. // To get a key that do not expire you need to purchase a license Franson.BlueTools.License license = new Franson.BlueTools.License(); license.LicenseKey = "HU5UZeq122KOJWA8lhmhOlVRYvv0PRKbHXEZ"; try { m_manager = Manager.GetManager(); switch(Manager.StackID) { case StackID.STACK_MICROSOFT: lStackID.Text = "Microsoft stack"; break; case StackID.STACK_WIDCOMM: lStackID.Text = "WidComm stack"; break; } // Call events in GUI thread m_manager.Parent = this; // Call events in new thread (multi-threading) // manager.Parent = null // Get first netowrk (BlueTools 1.0 only supports one network == one dongle) m_network = m_manager.Networks[0]; // Create local service m_service = new LocalService(ServiceType.SerialPort, "SimpleService", "Sample"); // Called when client connected to service m_service.ClientConnected += new BlueToolsEventHandler(m_service_ClientConnected); // Called when client disconnected from service m_service.ClientDisconnected += new BlueToolsEventHandler(m_service_ClientDisconnected); // Called when service successfully is advertised to server m_service.Advertised += new BlueToolsEventHandler(m_service_Advertised); // Called when all connection to service closed, and service removed from server m_service.Deadvertised += new BlueToolsEventHandler(m_service_Deadvertised); // Clean up when form closes this.Closing += new System.ComponentModel.CancelEventHandler(Form1_Closing); // Buttons bAdvertise.Enabled = true; bDeadvertise.Enabled = false; } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void m_service_ClientConnected(object sender, BlueToolsEventArgs eventArgs) { ConnectionEventArgs connectionEvent = (ConnectionEventArgs) eventArgs; Session connectedSession = connectionEvent.Session; // Add new session to list listSessions.Items.Add(connectedSession); // Read data from stream System.IO.Stream connectedStream = connectedSession.Stream; byte[] buffer = new byte[20]; connectedStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(readCallback), connectedStream); lServiceStatus.Text = "Client connected"; } private void m_service_ClientDisconnected(object sender, BlueToolsEventArgs eventArgs) { ConnectionEventArgs connectionEvent = (ConnectionEventArgs) eventArgs; // Remove session from list listSessions.Items.Remove(connectionEvent.Session); lServiceStatus.Text = "Client disconnected"; } private void bAdvertise_Click(object sender, System.EventArgs e) { try { m_network.Server.Advertise(m_service); } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void bDeadvertise_Click(object sender, System.EventArgs e) { try { m_network.Server.Deadvertise(m_service); } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } private void m_service_Advertised(object sender, BlueToolsEventArgs eventArgs) { lServiceStatus.Text = "Service advertised"; // Buttons bAdvertise.Enabled = false; bDeadvertise.Enabled = true; } private void m_service_Deadvertised(object sender, BlueToolsEventArgs eventArgs) { lServiceStatus.Text = "Service not active"; // Buttons bAdvertise.Enabled = true; bDeadvertise.Enabled = false; } private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // Dispose must be called for the application to exit! Manager.GetManager().Dispose(); } private void bWrite_Click(object sender, System.EventArgs e) { Session selectedSession = (Session) listSessions.SelectedItem; if(selectedSession != null) { System.IO.Stream selectedStream = selectedSession.Stream; char[] charWrite = txtWriteData.Text.ToCharArray(); byte[] byteWrite = new byte[charWrite.Length]; for(int inx = 0; inx < charWrite.Length; inx++) { byteWrite[inx] = (byte) charWrite[inx]; } selectedStream.BeginWrite(byteWrite, 0, byteWrite.Length, new AsyncCallback(writeCallback), selectedStream); } else { MessageBox.Show("Select a session first"); } } private void writeCallback(IAsyncResult result) { System.IO.Stream selectedStream = (System.IO.Stream) result.AsyncState; try { // EndWrite() must always be called if BeginWrite() was used! selectedStream.EndWrite(result); } catch(ObjectDisposedException ex) { // Thrown if stream has been closed. lServiceStatus.Text = ex.Message; } } private void readCallback(IAsyncResult result) { // Receives data from all connected devices! // IAsyncResult argument is of type BlueToolsAsyncResult BlueToolsAsyncResult blueResults = (BlueToolsAsyncResult) result; System.IO.Stream currentStream = (System.IO.Stream) blueResults.AsyncState; byte[] buffer = blueResults.Buffer; try { // EndRead() must always be called! int len = currentStream.EndRead(result); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); string str = enc.GetString(buffer, 0, len); txtRead.Text = str; // Start new async read currentStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(readCallback), currentStream); } catch(ObjectDisposedException ex) { // Thrown if stream has been closed. lServiceStatus.Text = ex.Message; } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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. // namespace DiscUtils { using System; using System.IO; /// <summary> /// Provides the base class for all file systems. /// </summary> public abstract class DiscFileSystem : MarshalByRefObject, IFileSystem, IDisposable { private DiscFileSystemOptions _options; /// <summary> /// Initializes a new instance of the DiscFileSystem class. /// </summary> protected DiscFileSystem() { _options = new DiscFileSystemOptions(); } /// <summary> /// Initializes a new instance of the DiscFileSystem class. /// </summary> /// <param name="defaultOptions">The options instance to use for this file system instance.</param> protected DiscFileSystem(DiscFileSystemOptions defaultOptions) { _options = defaultOptions; } /// <summary> /// Finalizes an instance of the DiscFileSystem class. /// </summary> ~DiscFileSystem() { Dispose(false); } /// <summary> /// Gets the file system options, which can be modified. /// </summary> public virtual DiscFileSystemOptions Options { get { return _options; } } /// <summary> /// Gets a friendly description of the file system type. /// </summary> public abstract string FriendlyName { get; } /// <summary> /// Gets a value indicating whether the file system is read-only or read-write. /// </summary> /// <returns>true if the file system is read-write.</returns> public abstract bool CanWrite { get; } /// <summary> /// Gets the root directory of the file system. /// </summary> public virtual DiscDirectoryInfo Root { get { return new DiscDirectoryInfo(this, string.Empty); } } /// <summary> /// Gets the volume label. /// </summary> public virtual string VolumeLabel { get { return string.Empty; } } /// <summary> /// Gets a value indicating whether the file system is thread-safe. /// </summary> public virtual bool IsThreadSafe { get { return false; } } /// <summary> /// Copies an existing file to a new file. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destinationFile">The destination file.</param> public virtual void CopyFile(string sourceFile, string destinationFile) { CopyFile(sourceFile, destinationFile, false); } /// <summary> /// Copies an existing file to a new file, allowing overwriting of an existing file. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destinationFile">The destination file.</param> /// <param name="overwrite">Whether to permit over-writing of an existing file.</param> public abstract void CopyFile(string sourceFile, string destinationFile, bool overwrite); /// <summary> /// Creates a directory. /// </summary> /// <param name="path">The path of the new directory.</param> public abstract void CreateDirectory(string path); /// <summary> /// Deletes a directory. /// </summary> /// <param name="path">The path of the directory to delete.</param> public abstract void DeleteDirectory(string path); /// <summary> /// Deletes a directory, optionally with all descendants. /// </summary> /// <param name="path">The path of the directory to delete.</param> /// <param name="recursive">Determines if the all descendants should be deleted.</param> public virtual void DeleteDirectory(string path, bool recursive) { if (recursive) { foreach (string dir in GetDirectories(path)) { DeleteDirectory(dir, true); } foreach (string file in GetFiles(path)) { DeleteFile(file); } } DeleteDirectory(path); } /// <summary> /// Deletes a file. /// </summary> /// <param name="path">The path of the file to delete.</param> public abstract void DeleteFile(string path); /// <summary> /// Indicates if a directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the directory exists.</returns> public abstract bool DirectoryExists(string path); /// <summary> /// Indicates if a file exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file exists.</returns> public abstract bool FileExists(string path); /// <summary> /// Indicates if a file or directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file or directory exists.</returns> public virtual bool Exists(string path) { return FileExists(path) || DirectoryExists(path); } /// <summary> /// Gets the names of subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of directories.</returns> public virtual string[] GetDirectories(string path) { return GetDirectories(path, "*.*", SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of directories matching the search pattern.</returns> public virtual string[] GetDirectories(string path, string searchPattern) { return GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of directories matching the search pattern.</returns> public abstract string[] GetDirectories(string path, string searchPattern, SearchOption searchOption); /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files.</returns> public virtual string[] GetFiles(string path) { return GetFiles(path, "*.*", SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files matching the search pattern.</returns> public virtual string[] GetFiles(string path, string searchPattern) { return GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of files in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of files matching the search pattern.</returns> public abstract string[] GetFiles(string path, string searchPattern, SearchOption searchOption); /// <summary> /// Gets the names of all files and subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public abstract string[] GetFileSystemEntries(string path); /// <summary> /// Gets the names of files and subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public abstract string[] GetFileSystemEntries(string path, string searchPattern); /// <summary> /// Moves a directory. /// </summary> /// <param name="sourceDirectoryName">The directory to move.</param> /// <param name="destinationDirectoryName">The target directory name.</param> public abstract void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName); /// <summary> /// Moves a file. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> public virtual void MoveFile(string sourceName, string destinationName) { MoveFile(sourceName, destinationName, false); } /// <summary> /// Moves a file, allowing an existing file to be overwritten. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> /// <param name="overwrite">Whether to permit a destination file to be overwritten.</param> public abstract void MoveFile(string sourceName, string destinationName, bool overwrite); /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <returns>The new stream.</returns> public virtual SparseStream OpenFile(string path, FileMode mode) { return OpenFile(path, mode, FileAccess.ReadWrite); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <param name="access">The access permissions for the created stream.</param> /// <returns>The new stream.</returns> public abstract SparseStream OpenFile(string path, FileMode mode, FileAccess access); /// <summary> /// Gets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to inspect.</param> /// <returns>The attributes of the file or directory.</returns> public abstract FileAttributes GetAttributes(string path); /// <summary> /// Sets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to change.</param> /// <param name="newValue">The new attributes of the file or directory.</param> public abstract void SetAttributes(string path, FileAttributes newValue); /// <summary> /// Gets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> public virtual DateTime GetCreationTime(string path) { return GetCreationTimeUtc(path).ToLocalTime(); } /// <summary> /// Sets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public virtual void SetCreationTime(string path, DateTime newTime) { SetCreationTimeUtc(path, newTime.ToUniversalTime()); } /// <summary> /// Gets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> public abstract DateTime GetCreationTimeUtc(string path); /// <summary> /// Sets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public abstract void SetCreationTimeUtc(string path, DateTime newTime); /// <summary> /// Gets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> public virtual DateTime GetLastAccessTime(string path) { return GetLastAccessTimeUtc(path).ToLocalTime(); } /// <summary> /// Sets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public virtual void SetLastAccessTime(string path, DateTime newTime) { SetLastAccessTimeUtc(path, newTime.ToUniversalTime()); } /// <summary> /// Gets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> public abstract DateTime GetLastAccessTimeUtc(string path); /// <summary> /// Sets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public abstract void SetLastAccessTimeUtc(string path, DateTime newTime); /// <summary> /// Gets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> public virtual DateTime GetLastWriteTime(string path) { return GetLastWriteTimeUtc(path).ToLocalTime(); } /// <summary> /// Sets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public virtual void SetLastWriteTime(string path, DateTime newTime) { SetLastWriteTimeUtc(path, newTime.ToUniversalTime()); } /// <summary> /// Gets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> public abstract DateTime GetLastWriteTimeUtc(string path); /// <summary> /// Sets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public abstract void SetLastWriteTimeUtc(string path, DateTime newTime); /// <summary> /// Gets the length of a file. /// </summary> /// <param name="path">The path to the file.</param> /// <returns>The length in bytes.</returns> public abstract long GetFileLength(string path); /// <summary> /// Gets an object representing a possible file. /// </summary> /// <param name="path">The file path.</param> /// <returns>The representing object.</returns> /// <remarks>The file does not need to exist.</remarks> public virtual DiscFileInfo GetFileInfo(string path) { return new DiscFileInfo(this, path); } /// <summary> /// Gets an object representing a possible directory. /// </summary> /// <param name="path">The directory path.</param> /// <returns>The representing object.</returns> /// <remarks>The directory does not need to exist.</remarks> public virtual DiscDirectoryInfo GetDirectoryInfo(string path) { return new DiscDirectoryInfo(this, path); } /// <summary> /// Gets an object representing a possible file system object (file or directory). /// </summary> /// <param name="path">The file system path.</param> /// <returns>The representing object.</returns> /// <remarks>The file system object does not need to exist.</remarks> public virtual DiscFileSystemInfo GetFileSystemInfo(string path) { return new DiscFileSystemInfo(this, path); } /// <summary> /// Reads the boot code of the file system into a byte array. /// </summary> /// <returns>The boot code, or <c>null</c> if not available.</returns> public virtual byte[] ReadBootCode() { return null; } #region IDisposable Members /// <summary> /// Disposes of this instance, releasing all resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes of this instance. /// </summary> /// <param name="disposing">The value <c>true</c> if Disposing.</param> protected virtual void Dispose(bool disposing) { } #endregion } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; namespace UnrealBuildTool { /// <summary> /// Stores an ordered list of header files /// </summary> [Serializable] class FlatCPPIncludeDependencyInfo { /// The PCH header this file is dependent on. public string PCHName; /// List of files this file includes, excluding headers that were included from a PCH. public List<string> Includes; /// Transient cached list of FileItems for all of the includes for a specific files. This just saves a bunch of string /// hash lookups as we locate FileItems for files that we've already requested dependencies for [NonSerialized] public List<FileItem> IncludeFileItems; } /// <summary> /// For a given target, caches all of the C++ source files and the files they are including /// </summary> [Serializable] public class FlatCPPIncludeDependencyCache { /// <summary> /// Creates the cache object /// </summary> /// <param name="Target">The target to create the cache for</param> /// <returns>The new instance</returns> public static FlatCPPIncludeDependencyCache Create( UEBuildTarget Target ) { string CachePath = FlatCPPIncludeDependencyCache.GetDependencyCachePathForTarget( Target );; // See whether the cache file exists. FileItem Cache = FileItem.GetItemByPath(CachePath); if (Cache.bExists) { if (BuildConfiguration.bPrintPerformanceInfo) { Log.TraceInformation("Loading existing FlatCPPIncludeDependencyCache: " + Cache.AbsolutePath); } var TimerStartTime = DateTime.UtcNow; // Deserialize cache from disk if there is one. FlatCPPIncludeDependencyCache Result = Load(Cache); if (Result != null) { var TimerDuration = DateTime.UtcNow - TimerStartTime; if (BuildConfiguration.bPrintPerformanceInfo) { Log.TraceInformation("Loading FlatCPPIncludeDependencyCache took " + TimerDuration.TotalSeconds + "s"); } return Result; } } bool bIsBuilding = (ProjectFileGenerator.bGenerateProjectFiles == false ) && (BuildConfiguration.bXGEExport == false) && (UEBuildConfiguration.bGenerateManifest == false) && (UEBuildConfiguration.bGenerateExternalFileList == false) && (UEBuildConfiguration.bCleanProject == false); if( bIsBuilding && !UnrealBuildTool.bNeedsFullCPPIncludeRescan ) { UnrealBuildTool.bNeedsFullCPPIncludeRescan = true; Log.TraceInformation( "Performing full C++ include scan (no include cache file)" ); } // Fall back to a clean cache on error or non-existence. return new FlatCPPIncludeDependencyCache( Cache ); } /// <summary> /// Loads the cache from disk /// </summary> /// <param name="Cache">The file to load</param> /// <returns>The loaded instance</returns> public static FlatCPPIncludeDependencyCache Load(FileItem Cache) { FlatCPPIncludeDependencyCache Result = null; try { string CacheBuildMutexPath = Cache.AbsolutePath + ".buildmutex"; // If the .buildmutex file for the cache is present, it means that something went wrong between loading // and saving the cache last time (most likely the UBT process being terminated), so we don't want to load // it. if (!File.Exists(CacheBuildMutexPath)) { using (File.Create(CacheBuildMutexPath)) { } using (FileStream Stream = new FileStream(Cache.AbsolutePath, FileMode.Open, FileAccess.Read)) { // @todo ubtmake: We can store the cache in a cheaper/smaller way using hash file names and indices into included headers, but it might actually slow down load times // @todo ubtmake: If we can index PCHs here, we can avoid storing all of the PCH's included headers (PCH's action should have been invalidated, so we shouldn't even have to report the PCH's includes as our indirect includes) BinaryFormatter Formatter = new BinaryFormatter(); Result = Formatter.Deserialize(Stream) as FlatCPPIncludeDependencyCache; Result.CacheFileItem = Cache; Result.bIsDirty = false; } } } catch (Exception Ex) { // Don't bother failing if the file format has changed, simply abort the cache load if (Ex.Message.Contains( "cannot be converted to type" )) // To catch serialization differences added when we added the DependencyInfo struct { Console.Error.WriteLine("Failed to read FlatCPPIncludeDependencyCache: {0}", Ex.Message); } } return Result; } /// <summary> /// Constructs a fresh cache, storing the file name that it should be saved as later on /// </summary> /// <param name="Cache">File name for this cache, usually unique per context (e.g. target)</param> protected FlatCPPIncludeDependencyCache(FileItem Cache) { CacheFileItem = Cache; DependencyMap = new Dictionary<string, FlatCPPIncludeDependencyInfo>(); } /// <summary> /// Saves out the cache /// </summary> public void Save() { // Only save if we've made changes to it since load. if (bIsDirty) { var TimerStartTime = DateTime.UtcNow; // Serialize the cache to disk. try { Directory.CreateDirectory(Path.GetDirectoryName(CacheFileItem.AbsolutePath)); using (FileStream Stream = new FileStream(CacheFileItem.AbsolutePath, FileMode.Create, FileAccess.Write)) { BinaryFormatter Formatter = new BinaryFormatter(); Formatter.Serialize(Stream, this); } } catch (Exception Ex) { Console.Error.WriteLine("Failed to write FlatCPPIncludeDependencyCache: {0}", Ex.Message); } if (BuildConfiguration.bPrintPerformanceInfo) { var TimerDuration = DateTime.UtcNow - TimerStartTime; Log.TraceInformation("Saving FlatCPPIncludeDependencyCache took " + TimerDuration.TotalSeconds + "s"); } } else { if (BuildConfiguration.bPrintPerformanceInfo) { Log.TraceInformation("FlatCPPIncludeDependencyCache did not need to be saved (bIsDirty=false)"); } } try { File.Delete(CacheFileItem.AbsolutePath + ".buildmutex"); } catch { // We don't care if we couldn't delete this file, as maybe it couldn't have been created in the first place. } } /// <summary> /// Sets the new dependencies for the specified file /// </summary> /// <param name="AbsoluteFilePath">File to set</param> /// <param name="PCHName">The PCH for this file</param> /// <param name="Dependencies">List of source dependencies</param> public void SetDependenciesForFile( string AbsoluteFilePath, string PCHName, List<string> Dependencies ) { var DependencyInfo = new FlatCPPIncludeDependencyInfo(); DependencyInfo.PCHName = PCHName; // @todo ubtmake: Not actually used yet. The idea is to use this to reduce the number of indirect includes we need to store in the cache. DependencyInfo.Includes = Dependencies; DependencyInfo.IncludeFileItems = null; // @todo ubtmake: We could shrink this file by not storing absolute paths (project and engine relative paths only, except for system headers.) May affect load times. DependencyMap[ AbsoluteFilePath.ToLowerInvariant() ] = DependencyInfo; bIsDirty = true; } /// <summary> /// Gets everything that this file includes from our cache (direct and indirect!) /// </summary> /// <param name="AbsoluteFilePath">Path to the file</param> /// <returns>The list of includes</returns> public List<FileItem> GetDependenciesForFile( string AbsoluteFilePath ) { FlatCPPIncludeDependencyInfo DependencyInfo; if( DependencyMap.TryGetValue( AbsoluteFilePath.ToLowerInvariant(), out DependencyInfo ) ) { // Update our transient cache of FileItems for each of the included files if( DependencyInfo.IncludeFileItems == null ) { DependencyInfo.IncludeFileItems = new List<FileItem>( DependencyInfo.Includes.Count ); foreach( string Dependency in DependencyInfo.Includes ) { DependencyInfo.IncludeFileItems.Add( FileItem.GetItemByFullPath( Dependency ) ); } } return DependencyInfo.IncludeFileItems; } return null; } /// <summary> /// Gets the dependency cache path and filename for the specified target. /// </summary> /// <param name="Target">Current build target</param> /// <returns>Cache Path</returns> public static string GetDependencyCachePathForTarget(UEBuildTarget Target) { string PlatformIntermediatePath = BuildConfiguration.PlatformIntermediatePath; if (UnrealBuildTool.HasUProjectFile()) { PlatformIntermediatePath = Path.Combine(UnrealBuildTool.GetUProjectPath(), BuildConfiguration.PlatformIntermediateFolder); } string CachePath = Path.Combine(PlatformIntermediatePath, Target.GetTargetName(), "FlatCPPIncludes.bin" ); return CachePath; } /// File name of this cache, should be unique for every includes context (e.g. target) [NonSerialized] private FileItem CacheFileItem; /// True if the cache needs to be saved [NonSerialized] private bool bIsDirty = false; /// Dependency lists, keyed (case-insensitively) on file's absolute path. private Dictionary<string, FlatCPPIncludeDependencyInfo> DependencyMap; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Geo.Itineraries.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using OpenSim.Region.PhysicsModules.SharedBase; using PrimMesher; using OpenMetaverse; namespace OpenSim.Region.PhysicsModule.Meshing { public class Mesh : IMesh { private Dictionary<Vertex, int> m_vertices; private List<Triangle> m_triangles; GCHandle m_pinnedVertexes; GCHandle m_pinnedIndex; IntPtr m_verticesPtr = IntPtr.Zero; int m_vertexCount = 0; IntPtr m_indicesPtr = IntPtr.Zero; int m_indexCount = 0; public float[] m_normals; Vector3 _centroid; int _centroidDiv; private class vertexcomp : IEqualityComparer<Vertex> { public bool Equals(Vertex v1, Vertex v2) { if (v1.X == v2.X && v1.Y == v2.Y && v1.Z == v2.Z) return true; else return false; } public int GetHashCode(Vertex v) { int a = v.X.GetHashCode(); int b = v.Y.GetHashCode(); int c = v.Z.GetHashCode(); return (a << 16) ^ (b << 8) ^ c; } } public Mesh() { vertexcomp vcomp = new vertexcomp(); m_vertices = new Dictionary<Vertex, int>(vcomp); m_triangles = new List<Triangle>(); _centroid = Vector3.Zero; _centroidDiv = 0; } public Mesh Clone() { Mesh result = new Mesh(); foreach (Triangle t in m_triangles) { result.Add(new Triangle(t.v1.Clone(), t.v2.Clone(), t.v3.Clone())); } result._centroid = _centroid; result._centroidDiv = _centroidDiv; return result; } public void Add(Triangle triangle) { if (m_pinnedIndex.IsAllocated || m_pinnedVertexes.IsAllocated || m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero) throw new NotSupportedException("Attempt to Add to a pinned Mesh"); // If a vertex of the triangle is not yet in the vertices list, // add it and set its index to the current index count // vertex == seems broken // skip colapsed triangles if ((triangle.v1.X == triangle.v2.X && triangle.v1.Y == triangle.v2.Y && triangle.v1.Z == triangle.v2.Z) || (triangle.v1.X == triangle.v3.X && triangle.v1.Y == triangle.v3.Y && triangle.v1.Z == triangle.v3.Z) || (triangle.v2.X == triangle.v3.X && triangle.v2.Y == triangle.v3.Y && triangle.v2.Z == triangle.v3.Z) ) { return; } if (m_vertices.Count == 0) { _centroidDiv = 0; _centroid = Vector3.Zero; } if (!m_vertices.ContainsKey(triangle.v1)) { m_vertices[triangle.v1] = m_vertices.Count; _centroid.X += triangle.v1.X; _centroid.Y += triangle.v1.Y; _centroid.Z += triangle.v1.Z; _centroidDiv++; } if (!m_vertices.ContainsKey(triangle.v2)) { m_vertices[triangle.v2] = m_vertices.Count; _centroid.X += triangle.v2.X; _centroid.Y += triangle.v2.Y; _centroid.Z += triangle.v2.Z; _centroidDiv++; } if (!m_vertices.ContainsKey(triangle.v3)) { m_vertices[triangle.v3] = m_vertices.Count; _centroid.X += triangle.v3.X; _centroid.Y += triangle.v3.Y; _centroid.Z += triangle.v3.Z; _centroidDiv++; } m_triangles.Add(triangle); } public Vector3 GetCentroid() { if (_centroidDiv > 0) return new Vector3(_centroid.X / _centroidDiv, _centroid.Y / _centroidDiv, _centroid.Z / _centroidDiv); else return Vector3.Zero; } // not functional public Vector3 GetOBB() { return new Vector3(0.5f, 0.5f, 0.5f); } public void CalcNormals() { int iTriangles = m_triangles.Count; this.m_normals = new float[iTriangles * 3]; int i = 0; foreach (Triangle t in m_triangles) { float ux, uy, uz; float vx, vy, vz; float wx, wy, wz; ux = t.v1.X; uy = t.v1.Y; uz = t.v1.Z; vx = t.v2.X; vy = t.v2.Y; vz = t.v2.Z; wx = t.v3.X; wy = t.v3.Y; wz = t.v3.Z; // Vectors for edges float e1x, e1y, e1z; float e2x, e2y, e2z; e1x = ux - vx; e1y = uy - vy; e1z = uz - vz; e2x = ux - wx; e2y = uy - wy; e2z = uz - wz; // Cross product for normal float nx, ny, nz; nx = e1y * e2z - e1z * e2y; ny = e1z * e2x - e1x * e2z; nz = e1x * e2y - e1y * e2x; // Length float l = (float)Math.Sqrt(nx * nx + ny * ny + nz * nz); float lReciprocal = 1.0f / l; // Normalized "normal" //nx /= l; //ny /= l; //nz /= l; m_normals[i] = nx * lReciprocal; m_normals[i + 1] = ny * lReciprocal; m_normals[i + 2] = nz * lReciprocal; i += 3; } } public List<Vector3> getVertexList() { List<Vector3> result = new List<Vector3>(); foreach (Vertex v in m_vertices.Keys) { result.Add(new Vector3(v.X, v.Y, v.Z)); } return result; } public float[] getVertexListAsFloat() { if (m_vertices == null) throw new NotSupportedException(); float[] result = new float[m_vertices.Count * 3]; foreach (KeyValuePair<Vertex, int> kvp in m_vertices) { Vertex v = kvp.Key; int i = kvp.Value; result[3 * i + 0] = v.X; result[3 * i + 1] = v.Y; result[3 * i + 2] = v.Z; } return result; } public float[] getVertexListAsFloatLocked() { if (m_pinnedVertexes.IsAllocated) return (float[])(m_pinnedVertexes.Target); float[] result = getVertexListAsFloat(); m_pinnedVertexes = GCHandle.Alloc(result, GCHandleType.Pinned); // Inform the garbage collector of this unmanaged allocation so it can schedule // the next GC round more intelligently GC.AddMemoryPressure(Buffer.ByteLength(result)); return result; } public void getVertexListAsPtrToFloatArray(out IntPtr vertices, out int vertexStride, out int vertexCount) { // A vertex is 3 floats vertexStride = 3 * sizeof(float); // If there isn't an unmanaged array allocated yet, do it now if (m_verticesPtr == IntPtr.Zero) { float[] vertexList = getVertexListAsFloat(); // Each vertex is 3 elements (floats) m_vertexCount = vertexList.Length / 3; int byteCount = m_vertexCount * vertexStride; m_verticesPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(byteCount); System.Runtime.InteropServices.Marshal.Copy(vertexList, 0, m_verticesPtr, m_vertexCount * 3); } vertices = m_verticesPtr; vertexCount = m_vertexCount; } public int[] getIndexListAsInt() { if (m_triangles == null) throw new NotSupportedException(); int[] result = new int[m_triangles.Count * 3]; for (int i = 0; i < m_triangles.Count; i++) { Triangle t = m_triangles[i]; result[3 * i + 0] = m_vertices[t.v1]; result[3 * i + 1] = m_vertices[t.v2]; result[3 * i + 2] = m_vertices[t.v3]; } return result; } /// <summary> /// creates a list of index values that defines triangle faces. THIS METHOD FREES ALL NON-PINNED MESH DATA /// </summary> /// <returns></returns> public int[] getIndexListAsIntLocked() { if (m_pinnedIndex.IsAllocated) return (int[])(m_pinnedIndex.Target); int[] result = getIndexListAsInt(); m_pinnedIndex = GCHandle.Alloc(result, GCHandleType.Pinned); // Inform the garbage collector of this unmanaged allocation so it can schedule // the next GC round more intelligently GC.AddMemoryPressure(Buffer.ByteLength(result)); return result; } public void getIndexListAsPtrToIntArray(out IntPtr indices, out int triStride, out int indexCount) { // If there isn't an unmanaged array allocated yet, do it now if (m_indicesPtr == IntPtr.Zero) { int[] indexList = getIndexListAsInt(); m_indexCount = indexList.Length; int byteCount = m_indexCount * sizeof(int); m_indicesPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(byteCount); System.Runtime.InteropServices.Marshal.Copy(indexList, 0, m_indicesPtr, m_indexCount); } // A triangle is 3 ints (indices) triStride = 3 * sizeof(int); indices = m_indicesPtr; indexCount = m_indexCount; } public void releasePinned() { if (m_pinnedVertexes.IsAllocated) m_pinnedVertexes.Free(); if (m_pinnedIndex.IsAllocated) m_pinnedIndex.Free(); if (m_verticesPtr != IntPtr.Zero) { System.Runtime.InteropServices.Marshal.FreeHGlobal(m_verticesPtr); m_verticesPtr = IntPtr.Zero; } if (m_indicesPtr != IntPtr.Zero) { System.Runtime.InteropServices.Marshal.FreeHGlobal(m_indicesPtr); m_indicesPtr = IntPtr.Zero; } } /// <summary> /// frees up the source mesh data to minimize memory - call this method after calling get*Locked() functions /// </summary> public void releaseSourceMeshData() { m_triangles = null; m_vertices = null; } public void Append(IMesh newMesh) { if (m_pinnedIndex.IsAllocated || m_pinnedVertexes.IsAllocated || m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero) throw new NotSupportedException("Attempt to Append to a pinned Mesh"); if (!(newMesh is Mesh)) return; foreach (Triangle t in ((Mesh)newMesh).m_triangles) Add(t); } // Do a linear transformation of mesh. public void TransformLinear(float[,] matrix, float[] offset) { if (m_pinnedIndex.IsAllocated || m_pinnedVertexes.IsAllocated || m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero) throw new NotSupportedException("Attempt to TransformLinear a pinned Mesh"); foreach (Vertex v in m_vertices.Keys) { if (v == null) continue; float x, y, z; x = v.X*matrix[0, 0] + v.Y*matrix[1, 0] + v.Z*matrix[2, 0]; y = v.X*matrix[0, 1] + v.Y*matrix[1, 1] + v.Z*matrix[2, 1]; z = v.X*matrix[0, 2] + v.Y*matrix[1, 2] + v.Z*matrix[2, 2]; v.X = x + offset[0]; v.Y = y + offset[1]; v.Z = z + offset[2]; } } public void DumpRaw(String path, String name, String title) { if (path == null) return; String fileName = name + "_" + title + ".raw"; String completePath = System.IO.Path.Combine(path, fileName); StreamWriter sw = new StreamWriter(completePath); foreach (Triangle t in m_triangles) { String s = t.ToStringRaw(); sw.WriteLine(s); } sw.Close(); } public void TrimExcess() { m_triangles.TrimExcess(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Buffers { using System; using System.Diagnostics.Contracts; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using DotNetty.Common; using DotNetty.Common.Utilities; public class WrappedByteBuffer : IByteBuffer { protected readonly IByteBuffer Buf; protected WrappedByteBuffer(IByteBuffer buf) { Contract.Requires(buf != null); this.Buf = buf; } public int Capacity => this.Buf.Capacity; public virtual IByteBuffer AdjustCapacity(int newCapacity) { this.Buf.AdjustCapacity(newCapacity); return this; } public int MaxCapacity => this.Buf.MaxCapacity; public IByteBufferAllocator Allocator => this.Buf.Allocator; public ByteOrder Order => this.Buf.Order; public virtual IByteBuffer WithOrder(ByteOrder endianness) => this.Buf.WithOrder(endianness); public IByteBuffer Unwrap() => this.Buf; public int ReaderIndex => this.Buf.ReaderIndex; public IByteBuffer SetReaderIndex(int readerIndex) { this.Buf.SetReaderIndex(readerIndex); return this; } public int WriterIndex => this.Buf.WriterIndex; public IByteBuffer SetWriterIndex(int writerIndex) { this.Buf.SetWriterIndex(writerIndex); return this; } public virtual IByteBuffer SetIndex(int readerIndex, int writerIndex) { this.Buf.SetIndex(readerIndex, writerIndex); return this; } public int ReadableBytes => this.Buf.ReadableBytes; public int WritableBytes => this.Buf.WritableBytes; public int MaxWritableBytes => this.Buf.MaxWritableBytes; public bool IsReadable() => this.Buf.IsReadable(); public bool IsWritable() => this.Buf.IsWritable(); public IByteBuffer Clear() { this.Buf.Clear(); return this; } public IByteBuffer MarkReaderIndex() { this.Buf.MarkReaderIndex(); return this; } public IByteBuffer ResetReaderIndex() { this.Buf.ResetReaderIndex(); return this; } public IByteBuffer MarkWriterIndex() { this.Buf.MarkWriterIndex(); return this; } public IByteBuffer ResetWriterIndex() { this.Buf.ResetWriterIndex(); return this; } public virtual IByteBuffer DiscardReadBytes() { this.Buf.DiscardReadBytes(); return this; } public virtual IByteBuffer DiscardSomeReadBytes() { this.Buf.DiscardSomeReadBytes(); return this; } public virtual IByteBuffer EnsureWritable(int minWritableBytes) { this.Buf.EnsureWritable(minWritableBytes); return this; } public virtual int EnsureWritable(int minWritableBytes, bool force) => this.Buf.EnsureWritable(minWritableBytes, force); public virtual bool GetBoolean(int index) => this.Buf.GetBoolean(index); public virtual byte GetByte(int index) => this.Buf.GetByte(index); public virtual short GetShort(int index) => this.Buf.GetShort(index); public virtual ushort GetUnsignedShort(int index) => this.Buf.GetUnsignedShort(index); public virtual int GetInt(int index) => this.Buf.GetInt(index); public virtual uint GetUnsignedInt(int index) => this.Buf.GetUnsignedInt(index); public virtual long GetLong(int index) => this.Buf.GetLong(index); public virtual char GetChar(int index) => this.Buf.GetChar(index); // todo: port: complete //public virtual float GetFloat(int index) //{ // return this.buf.GetFloat(index); //} public virtual double GetDouble(int index) => this.Buf.GetDouble(index); public virtual IByteBuffer GetBytes(int index, IByteBuffer dst) { this.Buf.GetBytes(index, dst); return this; } public virtual IByteBuffer GetBytes(int index, IByteBuffer dst, int length) { this.Buf.GetBytes(index, dst, length); return this; } public virtual IByteBuffer GetBytes(int index, IByteBuffer dst, int dstIndex, int length) { this.Buf.GetBytes(index, dst, dstIndex, length); return this; } public virtual IByteBuffer GetBytes(int index, byte[] dst) { this.Buf.GetBytes(index, dst); return this; } public virtual IByteBuffer GetBytes(int index, byte[] dst, int dstIndex, int length) { this.Buf.GetBytes(index, dst, dstIndex, length); return this; } public virtual IByteBuffer GetBytes(int index, Stream output, int length) { this.Buf.GetBytes(index, output, length); return this; } public virtual IByteBuffer SetBoolean(int index, bool value) { this.Buf.SetBoolean(index, value); return this; } public virtual IByteBuffer SetByte(int index, int value) { this.Buf.SetByte(index, value); return this; } public virtual IByteBuffer SetShort(int index, int value) { this.Buf.SetShort(index, value); return this; } public virtual IByteBuffer SetUnsignedShort(int index, ushort value) => this.Buf.SetUnsignedShort(index, value); public virtual IByteBuffer SetInt(int index, int value) { this.Buf.SetInt(index, value); return this; } public virtual IByteBuffer SetUnsignedInt(int index, uint value) => this.Buf.SetUnsignedInt(index, value); public virtual IByteBuffer SetLong(int index, long value) { this.Buf.SetLong(index, value); return this; } public virtual IByteBuffer SetChar(int index, char value) { this.Buf.SetChar(index, value); return this; } // todo: port: complete //public virtual IByteBuffer SetFloat(int index, float value) //{ // buf.SetFloat(index, value); // return this; //} public virtual IByteBuffer SetDouble(int index, double value) { this.Buf.SetDouble(index, value); return this; } public virtual IByteBuffer SetBytes(int index, IByteBuffer src) { this.Buf.SetBytes(index, src); return this; } public virtual IByteBuffer SetBytes(int index, IByteBuffer src, int length) { this.Buf.SetBytes(index, src, length); return this; } public virtual IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length) { this.Buf.SetBytes(index, src, srcIndex, length); return this; } public virtual IByteBuffer SetBytes(int index, byte[] src) { this.Buf.SetBytes(index, src); return this; } public virtual IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length) { this.Buf.SetBytes(index, src, srcIndex, length); return this; } public virtual Task<int> SetBytesAsync(int index, Stream src, int length, CancellationToken cancellationToken) => this.Buf.SetBytesAsync(index, src, length, cancellationToken); // todo: port: complete //public virtual IByteBuffer SetZero(int index, int length) //{ // buf.SetZero(index, length); // return this; //} public virtual bool ReadBoolean() => this.Buf.ReadBoolean(); public virtual byte ReadByte() => this.Buf.ReadByte(); public virtual short ReadShort() => this.Buf.ReadShort(); public virtual ushort ReadUnsignedShort() => this.Buf.ReadUnsignedShort(); public virtual int ReadInt() => this.Buf.ReadInt(); public virtual uint ReadUnsignedInt() => this.Buf.ReadUnsignedInt(); public virtual long ReadLong() => this.Buf.ReadLong(); public virtual char ReadChar() => this.Buf.ReadChar(); // todo: port: complete //public virtual float ReadFloat() //{ // return buf.ReadFloat(); //} public virtual double ReadDouble() => this.Buf.ReadDouble(); public virtual IByteBuffer ReadBytes(int length) => this.Buf.ReadBytes(length); public virtual IByteBuffer ReadSlice(int length) => this.Buf.ReadSlice(length); public virtual Task WriteBytesAsync(Stream stream, int length) => this.Buf.WriteBytesAsync(stream, length); public virtual IByteBuffer ReadBytes(IByteBuffer dst) { this.Buf.ReadBytes(dst); return this; } public virtual IByteBuffer ReadBytes(IByteBuffer dst, int length) { this.Buf.ReadBytes(dst, length); return this; } public virtual IByteBuffer ReadBytes(IByteBuffer dst, int dstIndex, int length) { this.Buf.ReadBytes(dst, dstIndex, length); return this; } public virtual IByteBuffer ReadBytes(byte[] dst) { this.Buf.ReadBytes(dst); return this; } public virtual IByteBuffer ReadBytes(byte[] dst, int dstIndex, int length) { this.Buf.ReadBytes(dst, dstIndex, length); return this; } public virtual IByteBuffer ReadBytes(Stream output, int length) { this.Buf.ReadBytes(output, length); return this; } public virtual IByteBuffer SkipBytes(int length) { this.Buf.SkipBytes(length); return this; } public virtual IByteBuffer WriteBoolean(bool value) { this.Buf.WriteBoolean(value); return this; } public virtual IByteBuffer WriteByte(int value) { this.Buf.WriteByte(value); return this; } public virtual IByteBuffer WriteShort(int value) { this.Buf.WriteShort(value); return this; } public virtual IByteBuffer WriteUnsignedShort(ushort value) => this.Buf.WriteUnsignedShort(value); public virtual IByteBuffer WriteInt(int value) { this.Buf.WriteInt(value); return this; } public virtual IByteBuffer WriteUnsignedInt(uint value) => this.Buf.WriteUnsignedInt(value); public virtual IByteBuffer WriteLong(long value) { this.Buf.WriteLong(value); return this; } public virtual IByteBuffer WriteChar(char value) { this.Buf.WriteChar(value); return this; } // todo: port: complete //public virtual IByteBuffer WriteFloat(float value) //{ // buf.WriteFloat(value); // return this; //} public virtual IByteBuffer WriteDouble(double value) { this.Buf.WriteDouble(value); return this; } public virtual IByteBuffer WriteBytes(IByteBuffer src) { this.Buf.WriteBytes(src); return this; } public virtual IByteBuffer WriteBytes(IByteBuffer src, int length) { this.Buf.WriteBytes(src, length); return this; } public virtual IByteBuffer WriteBytes(IByteBuffer src, int srcIndex, int length) { this.Buf.WriteBytes(src, srcIndex, length); return this; } public virtual IByteBuffer WriteBytes(byte[] src) { this.Buf.WriteBytes(src); return this; } public virtual IByteBuffer WriteBytes(byte[] src, int srcIndex, int length) { this.Buf.WriteBytes(src, srcIndex, length); return this; } public int IoBufferCount => this.Buf.IoBufferCount; public ArraySegment<byte> GetIoBuffer() => this.Buf.GetIoBuffer(); public ArraySegment<byte> GetIoBuffer(int index, int length) => this.Buf.GetIoBuffer(index, length); public ArraySegment<byte>[] GetIoBuffers() => this.Buf.GetIoBuffers(); public ArraySegment<byte>[] GetIoBuffers(int index, int length) => this.Buf.GetIoBuffers(index, length); public virtual Task WriteBytesAsync(Stream input, int length, CancellationToken cancellationToken) => this.Buf.WriteBytesAsync(input, length, cancellationToken); // todo: port: complete //public virtual IByteBuffer WriteZero(int length) //{ // buf.WriteZero(length); // return this; //} //public virtual int IndexOf(int fromIndex, int toIndex, byte value) //{ // return this.buf.IndexOf(fromIndex, toIndex, value); //} //public virtual int BytesBefore(byte value) //{ // return this.buf.BytesBefore(value); //} //public virtual int BytesBefore(int length, byte value) //{ // return this.buf.BytesBefore(length, value); //} //public virtual int BytesBefore(int index, int length, byte value) //{ // return this.buf.BytesBefore(index, length, value); //} public virtual IByteBuffer Copy() => this.Buf.Copy(); public virtual IByteBuffer Copy(int index, int length) => this.Buf.Copy(index, length); public virtual IByteBuffer Slice() => this.Buf.Slice(); public virtual IByteBuffer Slice(int index, int length) => this.Buf.Slice(index, length); public virtual byte[] ToArray() => this.Buf.ToArray(); public virtual IByteBuffer Duplicate() => this.Buf.Duplicate(); public virtual bool HasArray => this.Buf.HasArray; public virtual byte[] Array => this.Buf.Array; public virtual int ArrayOffset => this.Buf.ArrayOffset; public override int GetHashCode() => this.Buf.GetHashCode(); public override bool Equals(object obj) => this.Buf.Equals(obj); public bool Equals(IByteBuffer buffer) => this.Buf.Equals(buffer); public virtual int CompareTo(IByteBuffer buffer) => this.Buf.CompareTo(buffer); public override string ToString() => this.GetType().Name + '(' + this.Buf + ')'; public virtual IReferenceCounted Retain(int increment) { this.Buf.Retain(increment); return this; } public virtual IReferenceCounted Retain() { this.Buf.Retain(); return this; } public virtual IReferenceCounted Touch() { this.Buf.Touch(); return this; } public virtual IReferenceCounted Touch(object hint) { this.Buf.Touch(hint); return this; } public bool IsReadable(int size) => this.Buf.IsReadable(size); public bool IsWritable(int size) => this.Buf.IsWritable(size); public int ReferenceCount => this.Buf.ReferenceCount; public virtual bool Release() => this.Buf.Release(); public virtual bool Release(int decrement) => this.Buf.Release(decrement); public int ForEachByte(ByteProcessor processor) => this.Buf.ForEachByte(processor); public int ForEachByte(int index, int length, ByteProcessor processor) => this.Buf.ForEachByte(index, length, processor); public int ForEachByteDesc(ByteProcessor processor) => this.Buf.ForEachByteDesc(processor); public int ForEachByteDesc(int index, int length, ByteProcessor processor) => this.Buf.ForEachByteDesc(processor); public virtual string ToString(Encoding encoding) => this.Buf.ToString(encoding); public virtual string ToString(int index, int length, Encoding encoding) => this.Buf.ToString(index, length, encoding); } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.ServiceManagement.Model; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties; [TestClass] public class ScenarioTest { [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureQuickVM,Get-AzureVMImage,Get-AzureVM,Get-AzureLocation,Import-AzurePublishSettingsFile,Get-AzureSubscription,Set-AzureSubscription)")] public void NewWindowsAzureQuickVM() { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); vmPowershellCmdlets.ImportAzurePublishSettingsFile(); var defaultAzureSubscription = vmPowershellCmdlets.SetDefaultAzureSubscription(Resource.DefaultSubscriptionName); Assert.AreEqual(Resource.DefaultSubscriptionName, defaultAzureSubscription.SubscriptionName); string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false); string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); string newAzureQuickVMSvcName = Utilities.GetUniqueShortName("PSTestService"); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, newAzureQuickVMSvcName, imageName, "p@ssw0rd", locationName); // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName)); } // Basic Provisioning a Virtual Machine [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (Get-AzureLocation,Test-AzureName ,Get-AzureVMImage,New-AzureQuickVM,Get-AzureVM ,Restart-AzureVM,Stop-AzureVM , Start-AzureVM)")] public void ProvisionLinuxVM() { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); //vmPowershellCmdlets.ImportAzurePublishSettingsFile(Resource.PublishSettingsFile); vmPowershellCmdlets.ImportAzurePublishSettingsFile(); string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); string newAzureQuickVMSvcName = Utilities.GetUniqueShortName("PSTestService"); //Assert.IsFalse(vmPowershellCmdlets.TestAzureServiceName(newAzureQuickVMSvcName)); string newAzureQuickVMName = Utilities.GetUniqueShortName("PSLinuxVM"); string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Linux", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickLinuxVM(OS.Linux, newAzureQuickVMName, newAzureQuickVMSvcName, imageName, "user", "p@ssw0rd", locationName); // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // Disabling Stop / start / restart tests for now due to timing isues /* // Stop & start the VM vmPowershellCmdlets.StopAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Stopped); vmPowershellCmdlets.StartAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Started.ToString()); // Restart the VM vmPowershellCmdlets.StopAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Stopped); vmPowershellCmdlets.RestartAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Started.ToString()); * */ // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); // RemoveAzureService is failing. Need to investigate furnter */ //vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName)); //TODO: Need to do proper cleanup of the service // vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); // Assert.AreEqual(null, vmPowershellCmdlets.GetAzureService(newAzureQuickVMSvcName)); } //Verify Advanced Provisioning [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureService,New-AzureVMConfig,Add-AzureProvisioningConfig ,Add-AzureDataDisk ,Add-AzureEndpoint,New-AzureVM)")] public void AdvancedProvisioning() { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); vmPowershellCmdlets.ImportAzurePublishSettingsFile(); string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false); string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); string newAzureVM1Name = Utilities.GetUniqueShortName("PSTestVM"); string newAzureVM2Name = Utilities.GetUniqueShortName("PSTestVM"); string newAzureSvcName = Utilities.GetUniqueShortName("PSTestService"); vmPowershellCmdlets.NewAzureService(newAzureSvcName, newAzureSvcName, locationName); AzureVMConfigInfo azureVMConfigInfo1 = new AzureVMConfigInfo(newAzureVM1Name, VMSizeInfo.ExtraSmall, imageName); AzureVMConfigInfo azureVMConfigInfo2 = new AzureVMConfigInfo(newAzureVM2Name, VMSizeInfo.ExtraSmall, imageName); AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, "p@ssw0rd"); AddAzureDataDiskConfig azureDataDiskConfigInfo = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AzureEndPointConfigInfo azureEndPointConfigInfo = new AzureEndPointConfigInfo(ProtocolInfo.tcp, 80, 80, "web", "lbweb", 80, ProtocolInfo.http, @"/"); PersistentVMConfigInfo persistentVMConfigInfo1 = new PersistentVMConfigInfo(azureVMConfigInfo1, azureProvisioningConfig, azureDataDiskConfigInfo, azureEndPointConfigInfo); PersistentVMConfigInfo persistentVMConfigInfo2 = new PersistentVMConfigInfo(azureVMConfigInfo2, azureProvisioningConfig, azureDataDiskConfigInfo, azureEndPointConfigInfo); PersistentVM persistentVM1 = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo1); PersistentVM persistentVM2 = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo2); PersistentVM[] VMs = { persistentVM1, persistentVM2 }; vmPowershellCmdlets.NewAzureVM(newAzureSvcName, VMs); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureVM1Name, newAzureSvcName); vmPowershellCmdlets.RemoveAzureVM(newAzureVM2Name, newAzureSvcName); /* RemoveAzureService doesn't work */ //vmPowershellCmdlets.RemoveAzureService(newAzureSvcName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVM1Name, newAzureSvcName)); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVM2Name, newAzureSvcName)); } //Modifying Existing Virtual Machines [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig ,Add-AzureDataDisk ,Add-AzureEndpoint,New-AzureVM)")] public void ModifyingVM() { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); vmPowershellCmdlets.ImportAzurePublishSettingsFile(); string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false); string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); string newAzureQuickVMSvcName = Utilities.GetUniqueShortName("PSTestService"); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, newAzureQuickVMSvcName, imageName, "p@ssw0rd", locationName); AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk2", 1); AzureEndPointConfigInfo azureEndPointConfigInfo = new AzureEndPointConfigInfo(ProtocolInfo.tcp, 1433, 2000, "sql"); AddAzureDataDiskConfig[] dataDiskConfig = { azureDataDiskConfigInfo1, azureDataDiskConfigInfo2 }; vmPowershellCmdlets.AddVMDataDisksAndEndPoint(newAzureQuickVMName, newAzureQuickVMSvcName, dataDiskConfig, azureEndPointConfigInfo); SetAzureDataDiskConfig setAzureDataDiskConfig1 = new SetAzureDataDiskConfig(HostCaching.ReadWrite, 0); SetAzureDataDiskConfig setAzureDataDiskConfig2 = new SetAzureDataDiskConfig(HostCaching.ReadWrite, 0); SetAzureDataDiskConfig[] diskConfig = { setAzureDataDiskConfig1, setAzureDataDiskConfig2 }; vmPowershellCmdlets.SetVMDataDisks(newAzureQuickVMName, newAzureQuickVMSvcName, diskConfig); vmPowershellCmdlets.GetAzureDataDisk(newAzureQuickVMName, newAzureQuickVMSvcName); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); /* RemoveAzureService doesn't work */ //vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName)); } // Changes that Require a Reboot [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (Get-AzureVM,Set-AzureDataDisk ,Update-AzureVM,Set-AzureVMSize)")] public void UpdateAndReboot() { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); vmPowershellCmdlets.ImportAzurePublishSettingsFile(); string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false); string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); string newAzureQuickVMSvcName = Utilities.GetUniqueShortName("PSTestService"); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, newAzureQuickVMSvcName, imageName, "p@ssw0rd", locationName); AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk2", 1); AddAzureDataDiskConfig[] dataDiskConfig = { azureDataDiskConfigInfo1, azureDataDiskConfigInfo2 }; vmPowershellCmdlets.AddVMDataDisks(newAzureQuickVMName, newAzureQuickVMSvcName, dataDiskConfig); SetAzureDataDiskConfig setAzureDataDiskConfig1 = new SetAzureDataDiskConfig(HostCaching.ReadOnly, 0); SetAzureDataDiskConfig setAzureDataDiskConfig2 = new SetAzureDataDiskConfig(HostCaching.ReadOnly, 0); SetAzureDataDiskConfig[] diskConfig = { setAzureDataDiskConfig1, setAzureDataDiskConfig2 }; vmPowershellCmdlets.SetVMDataDisks(newAzureQuickVMName, newAzureQuickVMSvcName, diskConfig); SetAzureVMSizeConfig vmSizeConfig = new SetAzureVMSizeConfig(InstanceSize.Medium); vmPowershellCmdlets.SetVMSize(newAzureQuickVMName, newAzureQuickVMSvcName, vmSizeConfig); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); /* RemoveAzureService doesn't work */ //vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName)); } [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Get-AzureDisk,Remove-AzureVM,Remove-AzureDisk,Get-AzureVMImage)")] public void ManagingDiskImages() { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); vmPowershellCmdlets.ImportAzurePublishSettingsFile(); // Import-AzurePublishSettingsFile var defaultAzureSubscription = vmPowershellCmdlets.SetDefaultAzureSubscription(Resource.DefaultSubscriptionName); // Set-AzureSubscription Assert.AreEqual(Resource.DefaultSubscriptionName, defaultAzureSubscription.SubscriptionName); string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false); // Get-AzureVMImage Console.WriteLine("Image Name: {0}", imageName); string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); // Get-AzureLocation Console.WriteLine("Location Name: {0}", locationName); // Create a unique VM name and Service Name string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); string newAzureQuickVMSvcName = Utilities.GetUniqueShortName("PSTestService"); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, newAzureQuickVMSvcName, imageName, "p@ssw0rd", locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, newAzureQuickVMSvcName); // starting the test. Collection<DiskContext> vmDisks = vmPowershellCmdlets.GetAzureDiskAttachedToRoleName(new[] { newAzureQuickVMName }); // Get-AzureDisk | Where {$_.AttachedTo.RoleName -eq $vmname } foreach (var disk in vmDisks) Console.WriteLine("The disk, {0}, is created", disk.DiskName); vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); // Remove-AzureVM Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName)); Console.WriteLine("The VM, {0}, is successfully removed.", newAzureQuickVMName); foreach (var disk in vmDisks) { for (int i = 0; i < 3; i++) { try { vmPowershellCmdlets.RemoveAzureDisk(disk.DiskName, true); // Remove-AzureDisk break; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("currently in use") && i != 2) { Console.WriteLine("The vhd, {0}, is still in the state of being used by the deleted VM", disk.DiskName); Thread.Sleep(120000); continue; } else { Assert.Fail("error during Remove-AzureDisk: {0}", e.ToString()); } } } try { vmPowershellCmdlets.GetAzureDisk(disk.DiskName); // Get-AzureDisk -DiskName (try to get the removed disk.) Assert.Fail("Disk is not removed: {0}", disk.DiskName); } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("does not exist")) { Console.WriteLine("The disk, {0}, is successfully removed.", disk.DiskName); continue; } else { Assert.Fail("Exception: {0}", e.ToString()); } } } vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); // Clean up the service. try { vmPowershellCmdlets.GetAzureService(newAzureQuickVMSvcName); Assert.Fail("The service, {0}, is not removed", newAzureQuickVMSvcName); } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("does not exist")) { Console.WriteLine("The service, {0}, is successfully removed", newAzureQuickVMSvcName); } else { Assert.Fail("Error occurred: {0}", e.ToString()); } } } [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig,New-AzureVM,Save-AzureVMImage)")] public void CaptureImagingExportingImportingVMConfig() { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); vmPowershellCmdlets.ImportAzurePublishSettingsFile(); // Import-AzurePublishSettingsFile var defaultAzureSubscription = vmPowershellCmdlets.SetDefaultAzureSubscription(Resource.DefaultSubscriptionName); // Set-AzureSubscription Assert.AreEqual(Resource.DefaultSubscriptionName, defaultAzureSubscription.SubscriptionName); // string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false); // Get-AzureVMImage Console.WriteLine("Image Name: {0}", imageName); string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); // Get-AzureLocation Console.WriteLine("Location Name: {0}", locationName); // Create a unique VM name string newAzureVMName = Utilities.GetUniqueShortName("PSTestVM"); Console.WriteLine("VM Name: {0}", newAzureVMName); // Create a unique Service Name string newAzureSvcName = Utilities.GetUniqueShortName("PSTestService"); vmPowershellCmdlets.NewAzureService(newAzureSvcName, newAzureSvcName, locationName); Console.WriteLine("VM Service Name: {0}", newAzureSvcName); // starting the test. AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(newAzureVMName, VMSizeInfo.Small, imageName); // parameters for New-AzureVMConfig (-Name -InstanceSize -ImageName) AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, "p@ssw0rd"); // parameters for Add-AzureProvisioningConfig (-Windows -Password) PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM persistentVM = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); // New-AzureVMConfig & Add-AzureProvisioningConfig PersistentVM[] VMs = { persistentVM }; vmPowershellCmdlets.NewAzureVM(newAzureSvcName, VMs); // New-AzureVM Console.WriteLine("The VM is successfully created: {0}", persistentVM.RoleName); PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, newAzureSvcName); Assert.AreEqual(vmRoleCtxt.Name, persistentVM.RoleName, true); vmPowershellCmdlets.StopAzureVM(newAzureVMName, newAzureSvcName); // Stop-AzureVM for (int i = 0; i < 3; i++) { vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, newAzureSvcName); if (vmRoleCtxt.InstanceStatus == "StoppedVM") break; else { Console.WriteLine("The status of the VM {0} : {1}", persistentVM.RoleName, vmRoleCtxt.InstanceStatus); Thread.Sleep(120000); } } Assert.AreEqual(vmRoleCtxt.InstanceStatus, "StoppedVM", true); //TODO // RDP //TODO: // Run sysprep and shutdown // Check the status of VM //PersistentVMRoleContext vmRoleCtxt2 = vmPowershellCmdlets.GetAzureVM(newAzureVMName, newAzureSvcName); // Get-AzureVM -Name //Assert.AreEqual(newAzureVMName, vmRoleCtxt2.Name, true); // // Save-AzureVMImage //string newImageName = "newImage"; //string newImageLabel = "newImageLabel"; //string postAction = "Delete"; // Save-AzureVMImage -ServiceName -Name -NewImageName -NewImageLabel -PostCaptureAction //vmPowershellCmdlets.SaveAzureVMImage(newAzureSvcName, newAzureVMName, newImageName, newImageLabel, postAction); // Cleanup vmPowershellCmdlets.RemoveAzureVM(persistentVM.RoleName, newAzureSvcName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, newAzureSvcName)); } [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Export-AzureVM,Remove-AzureVM,Import-AzureVM,New-AzureVM)")] public void ExportingImportingVMConfigAsTemplateforRepeatableUsage() { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); vmPowershellCmdlets.ImportAzurePublishSettingsFile(); // Import-AzurePublishSettingsFile var defaultAzureSubscription = vmPowershellCmdlets.SetDefaultAzureSubscription(Resource.DefaultSubscriptionName); // Set-AzureSubscription Assert.AreEqual(Resource.DefaultSubscriptionName, defaultAzureSubscription.SubscriptionName); // string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false); // Get-AzureVMImage Console.WriteLine("Image Name: {0}", imageName); string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); // Get-AzureLocation Console.WriteLine("Location Name: {0}", locationName); // Create a unique VM name string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); // Create a unique Service Name string newAzureQuickVMSvcName = Utilities.GetUniqueShortName("PSTestService"); // Create a new Azure quick VM vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, newAzureQuickVMSvcName, imageName, "p@ssw0rd", locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, newAzureQuickVMSvcName); // starting the test. string path = "C:\\temp\\mytestvmconfig1.xml"; PersistentVMRoleContext vmRole = vmPowershellCmdlets.ExportAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName, path); // Export-AzureVM Console.WriteLine("Exporting VM is successfully done: path - {0} Name - {1}", path, vmRole.Name); vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); // Remove-AzureVM Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName)); Console.WriteLine("The VM is successfully removed: {0}", newAzureQuickVMName); List<PersistentVM> VMs = new List<PersistentVM>(); foreach (var pervm in vmPowershellCmdlets.ImportAzureVM(path)) // Import-AzureVM { VMs.Add(pervm); Console.WriteLine("The VM, {0}, is imported.", pervm.RoleName); } for (int i = 0; i < 3; i++) { try { vmPowershellCmdlets.NewAzureVM(newAzureQuickVMSvcName, VMs.ToArray()); // New-AzureVM Console.WriteLine("All VMs are successfully created."); foreach (var vm in VMs) { Console.WriteLine("created VM: {0}", vm.RoleName); } break; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("currently in use") && i != 2) { Console.WriteLine("The removed VM is still using the vhd"); Thread.Sleep(120000); continue; } else { Assert.Fail("error during New-AzureVM: {0}", e.ToString()); } } } // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName)); vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); // Clean up the service. try { vmPowershellCmdlets.GetAzureService(newAzureQuickVMSvcName); Assert.Fail("The service, {0}, is not removed", newAzureQuickVMSvcName); } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("does not exist")) { Console.WriteLine("The service, {0}, is successfully removed", newAzureQuickVMSvcName); } else { Assert.Fail("Error occurred: {0}", e.ToString()); } } } [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Get-AzureVM,Get-AzureEndpoint,Get-AzureRemoteDesktopFile)")] public void ManagingRDPSSHConnectivity() { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); vmPowershellCmdlets.ImportAzurePublishSettingsFile(); // Import-AzurePublishSettingsFile var defaultAzureSubscription = vmPowershellCmdlets.SetDefaultAzureSubscription(Resource.DefaultSubscriptionName); // Set-AzureSubscription Assert.AreEqual(Resource.DefaultSubscriptionName, defaultAzureSubscription.SubscriptionName); // string imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false); // Get-AzureVMImage Console.WriteLine("Image Name: {0}", imageName); string locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); // Get-AzureLocation Console.WriteLine("Location Name: {0}", locationName); // Create a unique VM name string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); // Create a unique Service Name string newAzureQuickVMSvcName = Utilities.GetUniqueShortName("PSTestService"); // Create a new Azure quick VM vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, newAzureQuickVMSvcName, imageName, "p@ssw0rd", locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, newAzureQuickVMSvcName); // starting the test. PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); // Get-AzureVM InputEndpointContext inputEndpointCtxt = vmPowershellCmdlets.GetAzureEndpoint(vmRoleCtxt); // Get-AzureEndpoint Console.WriteLine("InputEndpointContext Name: {0}", inputEndpointCtxt.Name); Console.WriteLine("InputEndpointContext port: {0}", inputEndpointCtxt.Port); Console.WriteLine("InputEndpointContext protocol: {0}", inputEndpointCtxt.Protocol); Assert.AreEqual(inputEndpointCtxt.Name, "RemoteDesktop", true); string path = "C:\\temp\\myvmconnection.rdp"; vmPowershellCmdlets.GetAzureRemoteDesktopFile(newAzureQuickVMName, newAzureQuickVMSvcName, path, false); // Get-AzureRemoteDesktopFile Console.WriteLine("RDP file is successfully created at: {0}", path); // ToDo: Automate RDP. //vmPowershellCmdlets.GetAzureRemoteDesktopFile(newAzureQuickVMName, newAzureQuickVMSvcName, path, true); // Get-AzureRemoteDesktopFile -Launch Console.WriteLine("Test passed"); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName)); Console.WriteLine("VM is successfully removed"); // vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); // Assert.AreEqual(null, vmPowershellCmdlets.GetAzureService(newAzureQuickVMSvcName)); //Console.WriteLine("The service is successfully removed"); //TODO: Need to do proper cleanup of the service // vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); // Assert.AreEqual(null, vmPowershellCmdlets.GetAzureService(newAzureQuickVMSvcName)); } } }
// Copyright (c) 2013, SIL International. // Distributable under the terms of the MIT license (http://opensource.org/licenses/MIT). #if __MonoCS__ using System; using System.Windows.Forms; using IBusDotNet; using Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces; using Palaso.UI.WindowsForms.Keyboarding.Types; namespace Palaso.UI.WindowsForms.Keyboarding.Linux { /// <summary>Normal implementation of IIbusCommunicator</summary> internal class IbusCommunicator : IIbusCommunicator { // see https://github.com/ibus/ibus/blob/1.4.y/src/ibustypes.h for ibus modifier values private enum IbusModifiers { Shift = 1 << 0, ShiftLock = 1 << 1, Control = 1 << 2, } #region protected fields /// <summary> /// stores Dbus Connection to ibus /// </summary> protected IBusConnection m_connection; /// <summary> /// the input Context created /// </summary> protected IInputContext m_inputContext; /// <summary> /// Ibus helper class /// </summary> protected InputBus m_ibus; #endregion /// <summary> /// Create a Connection to Ibus. If successfull Connected property is true. /// </summary> public IbusCommunicator() { m_connection = IBusConnectionFactory.Create(); if (m_connection == null) return; // Prevent hanging on exit issues caused by missing dispose calls, or strange interaction // between ComObjects and managed object. Application.ThreadExit += (sender, args) => { if (m_connection != null) m_connection.Dispose(); m_connection = null; }; m_ibus = new InputBus(m_connection); } #region Disposable stuff #if DEBUG /// <summary/> ~IbusCommunicator() { Dispose(false); } #endif /// <summary/> public bool IsDisposed { get; private set; } /// <summary/> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary/> protected virtual void Dispose(bool fDisposing) { System.Diagnostics.Debug.WriteLineIf(!fDisposing, "****** Missing Dispose() call for " + GetType() + ". *******"); if (fDisposing && !IsDisposed) { // dispose managed and unmanaged objects if (m_connection != null) m_connection.Dispose(); } m_connection = null; IsDisposed = true; } #endregion /// <summary> /// Wrap an ibus with protection incase DBus connection is dropped. /// </summary> protected void ProtectedIBusInvoke(Action action) { try { action(); } catch(NDesk.DBus.DBusConectionErrorException) { m_ibus = null; m_inputContext = null; NotifyUserOfIBusConnectionDropped(); } catch(System.NullReferenceException) { } } /// <summary> /// Inform users of IBus problem. /// </summary> protected void NotifyUserOfIBusConnectionDropped() { MessageBox.Show(Form.ActiveForm, "Please restart IBus and the application.", "IBus connection has stopped."); } private int ConvertToIbusModifiers(Keys modifierKeys, char charUserTyped) { int ibusModifiers = 0; if ((modifierKeys & Keys.Shift) != 0) ibusModifiers |= (int)IbusModifiers.Shift; if ((modifierKeys & Keys.Control) != 0) ibusModifiers |= (int)IbusModifiers.Control; // modifierKeys don't contain CapsLock and Control.IsKeyLocked(Keys.CapsLock) // doesn't work on mono. So we guess the caps state by unicode value and the shift // state. This is far from ideal. if ((char.IsUpper(charUserTyped) && (modifierKeys & Keys.Shift) == 0) || (char.IsLower(charUserTyped) && (modifierKeys & Keys.Shift) != 0)) ibusModifiers |= (int)IbusModifiers.ShiftLock; return ibusModifiers; } #region IIBusCommunicator Implementation /// <summary> /// Returns true if we have a connection to Ibus. /// </summary> public bool Connected { get { return m_connection != null; } } /// <summary> /// Gets the connection to IBus. /// </summary> public IBusConnection Connection { get { return m_connection; } } /// <summary> /// If we have a valid inputContext Focus it. Also set the GlobalCachedInputContext. /// </summary> public void FocusIn() { if (InputContext == null) return; ProtectedIBusInvoke(() => m_inputContext.FocusIn()); // For performance reasons we store the active inputContext GlobalCachedInputContext.InputContext = m_inputContext; } /// <summary> /// If we have a valid inputContext call FocusOut ibus method. /// </summary> public void FocusOut() { if (m_inputContext == null) return; ProtectedIBusInvoke(() => m_inputContext.FocusOut()); GlobalCachedInputContext.Clear(); } /// <summary> /// Tells IBus the location and height of the selection /// </summary> public void NotifySelectionLocationAndHeight(int x, int y, int height) { if (m_inputContext == null) return; ProtectedIBusInvoke(() => m_inputContext.SetCursorLocation(x, y, 0, height)); } /// <summary> /// Sends a key Event to the ibus current input context. This method will be called by /// the IbusKeyboardAdapter on some KeyDown and all KeyPress events. /// </summary> /// <param name="keySym">The X11 key symbol (for special keys) or the key code</param> /// <param name="scanCode">The X11 scan code</param> /// <param name="state">The modifier state, i.e. shift key etc.</param> /// <returns><c>true</c> if the key event is handled by ibus.</returns> /// <seealso cref="IBusKeyboardAdaptor.HandleKeyPress"/> public bool ProcessKeyEvent(int keySym, int scanCode, Keys state) { if (m_inputContext == null) return false; try { // m_inputContext.IsEnabled() throws an exception for IBus 1.5. if (!KeyboardController.CombinedKeyboardHandling && !m_inputContext.IsEnabled()) return false; var modifiers = ConvertToIbusModifiers(state, (char)keySym); return m_inputContext.ProcessKeyEvent(keySym, scanCode, modifiers); } catch(NDesk.DBus.DBusConectionErrorException e) { Console.WriteLine("IbusCommunicator.ProcessKeyEvent({0},{1},{2}): caught DBusConectionErrorException: {3}", keySym, scanCode, state, e); m_ibus = null; m_inputContext = null; NotifyUserOfIBusConnectionDropped(); } catch(System.NullReferenceException e) { Console.WriteLine("IbusCommunicator.ProcessKeyEvent({0},{1},{2}): caught NullReferenceException: {3}", keySym, scanCode, state, e); } return false; } /// <summary> /// Reset the Current ibus inputContext. /// </summary> public void Reset() { if (m_inputContext == null) return; ProtectedIBusInvoke(m_inputContext.Reset); } private bool m_contextCreated; /// <summary> /// Create an input context and setup callback handlers. This method should be /// called only once, and then after KeyboardController.CombinedKeyboardHandling /// has been set properly. /// </summary> /// <remarks> /// For IBus 1.5, we must use the current InputContext because there is no /// way to enable one we create ourselves. (InputContext.Enable() has turned /// into a no-op.) For IBus 1.4, we must create one ourselves because /// m_ibus.CurrentInputContext() throws an exception. /// </remarks> public void CreateInputContext() { System.Diagnostics.Debug.Assert(!m_contextCreated); if (m_ibus == null) { // This seems to be needed for tests on TeamCity. // It also seems that it shouldn't be necessary to run IBus to use Linux keyboarding! return; } if (KeyboardController.CombinedKeyboardHandling) { var path = m_ibus.CurrentInputContext(); m_inputContext = new InputContext(m_connection, path); } else { m_inputContext = m_ibus.CreateInputContext("IbusCommunicator"); } AttachContextMethods(m_inputContext); m_contextCreated = true; } private void AttachContextMethods(IInputContext context) { ProtectedIBusInvoke(() => { context.CommitText += OnCommitText; context.UpdatePreeditText += OnUpdatePreeditText; context.HidePreeditText += OnHidePreeditText; context.ForwardKeyEvent += OnKeyEvent; context.DeleteSurroundingText += OnDeleteSurroundingText; context.SetCapabilities(Capabilities.Focus | Capabilities.PreeditText | Capabilities.SurroundingText); context.Enable(); // not needed for IBus 1.5, but doesn't hurt. }); } /// <summary> /// Get the ibus input context, creating it if necessary. /// </summary> /// <remarks> /// This must be called after the KeyboardController.CombinedKeyboardHandling has been set. /// </remarks> protected IInputContext InputContext { get { if (m_inputContext != null) return m_inputContext; if (m_contextCreated) return null; // we must have had an error that cleared m_inputContext CreateInputContext(); return m_inputContext; } } /// <summary> /// Return the DBUS 'path' name for the currently focused InputContext /// </summary> /// <exception cref="System.Exception">Throws: System.Exception with message /// 'org.freedesktop.DBus.Error.Failed: No input context focused' if nothing is currently /// focused.</exception> public string GetFocusedInputContext() { return m_ibus.CurrentInputContext(); } /// <summary></summary> public event Action<object> CommitText; /// <summary></summary> public event Action<object, int> UpdatePreeditText; /// <summary></summary> public event Action<int, int> DeleteSurroundingText; /// <summary></summary> public event Action HidePreeditText; /// <summary></summary> public event Action<int, int, int> KeyEvent; #endregion #region private methods private void OnCommitText(object text) { if (CommitText != null) { CommitText(IBusText.FromObject(text)); } } private void OnUpdatePreeditText(object text, uint cursor_pos, bool visible) { if (UpdatePreeditText != null && visible) { UpdatePreeditText(IBusText.FromObject(text), (int)cursor_pos); } } private void OnDeleteSurroundingText(int offset, uint nChars) { if (DeleteSurroundingText != null) DeleteSurroundingText(offset, (int)nChars); } private void OnHidePreeditText() { if (HidePreeditText != null) HidePreeditText(); } private void OnKeyEvent(uint keyval, uint keycode, uint modifiers) { if (KeyEvent != null) KeyEvent((int)keyval, (int)keycode, (int)modifiers); } #endregion } } #endif
// /* // * 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 CachingConfig { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_CachingConfig__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.CachingConfig, global::Alachisoft.NosDB.Common.Protobuf.CachingConfig.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_CachingConfig__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static CachingConfig() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChNDYWNoaW5nQ29uZmlnLnByb3RvEiBBbGFjaGlzb2Z0Lk5vc0RCLkNvbW1v", "bi5Qcm90b2J1ZiIPCg1DYWNoaW5nQ29uZmlnQj0KJGNvbS5hbGFjaGlzb2Z0", "Lm5vc2RiLmNvbW1vbi5wcm90b2J1ZkIVQ2FjaGluZ0NvbmZpZ1Byb3RvY29s")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_Alachisoft_NosDB_Common_Protobuf_CachingConfig__Descriptor = Descriptor.MessageTypes[0]; internal__static_Alachisoft_NosDB_Common_Protobuf_CachingConfig__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.CachingConfig, global::Alachisoft.NosDB.Common.Protobuf.CachingConfig.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_CachingConfig__Descriptor, new string[] { }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class CachingConfig : pb::GeneratedMessage<CachingConfig, CachingConfig.Builder> { private CachingConfig() { } private static readonly CachingConfig defaultInstance = new CachingConfig().MakeReadOnly(); private static readonly string[] _cachingConfigFieldNames = new string[] { }; private static readonly uint[] _cachingConfigFieldTags = new uint[] { }; public static CachingConfig DefaultInstance { get { return defaultInstance; } } public override CachingConfig DefaultInstanceForType { get { return DefaultInstance; } } protected override CachingConfig ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.CachingConfig.internal__static_Alachisoft_NosDB_Common_Protobuf_CachingConfig__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<CachingConfig, CachingConfig.Builder> InternalFieldAccessors { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.CachingConfig.internal__static_Alachisoft_NosDB_Common_Protobuf_CachingConfig__FieldAccessorTable; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _cachingConfigFieldNames; 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; size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static CachingConfig ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static CachingConfig ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static CachingConfig ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static CachingConfig ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static CachingConfig ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static CachingConfig ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static CachingConfig ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static CachingConfig ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static CachingConfig ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static CachingConfig ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private CachingConfig 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(CachingConfig prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<CachingConfig, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(CachingConfig cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private CachingConfig result; private CachingConfig PrepareBuilder() { if (resultIsReadOnly) { CachingConfig original = result; result = new CachingConfig(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override CachingConfig 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.CachingConfig.Descriptor; } } public override CachingConfig DefaultInstanceForType { get { return global::Alachisoft.NosDB.Common.Protobuf.CachingConfig.DefaultInstance; } } public override CachingConfig BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is CachingConfig) { return MergeFrom((CachingConfig) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(CachingConfig other) { if (other == global::Alachisoft.NosDB.Common.Protobuf.CachingConfig.DefaultInstance) return this; PrepareBuilder(); 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(_cachingConfigFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _cachingConfigFieldTags[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; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } } static CachingConfig() { object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.CachingConfig.Descriptor, null); } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Color { private object _dummy; public static readonly System.Drawing.Color Empty; public byte A { get { throw null; } } public static System.Drawing.Color AliceBlue { get { throw null; } } public static System.Drawing.Color AntiqueWhite { get { throw null; } } public static System.Drawing.Color Aqua { get { throw null; } } public static System.Drawing.Color Aquamarine { get { throw null; } } public static System.Drawing.Color Azure { get { throw null; } } public byte B { get { throw null; } } public static System.Drawing.Color Beige { get { throw null; } } public static System.Drawing.Color Bisque { get { throw null; } } public static System.Drawing.Color Black { get { throw null; } } public static System.Drawing.Color BlanchedAlmond { get { throw null; } } public static System.Drawing.Color Blue { get { throw null; } } public static System.Drawing.Color BlueViolet { get { throw null; } } public static System.Drawing.Color Brown { get { throw null; } } public static System.Drawing.Color BurlyWood { get { throw null; } } public static System.Drawing.Color CadetBlue { get { throw null; } } public static System.Drawing.Color Chartreuse { get { throw null; } } public static System.Drawing.Color Chocolate { get { throw null; } } public static System.Drawing.Color Coral { get { throw null; } } public static System.Drawing.Color CornflowerBlue { get { throw null; } } public static System.Drawing.Color Cornsilk { get { throw null; } } public static System.Drawing.Color Crimson { get { throw null; } } public static System.Drawing.Color Cyan { get { throw null; } } public static System.Drawing.Color DarkBlue { get { throw null; } } public static System.Drawing.Color DarkCyan { get { throw null; } } public static System.Drawing.Color DarkGoldenrod { get { throw null; } } public static System.Drawing.Color DarkGray { get { throw null; } } public static System.Drawing.Color DarkGreen { get { throw null; } } public static System.Drawing.Color DarkKhaki { get { throw null; } } public static System.Drawing.Color DarkMagenta { get { throw null; } } public static System.Drawing.Color DarkOliveGreen { get { throw null; } } public static System.Drawing.Color DarkOrange { get { throw null; } } public static System.Drawing.Color DarkOrchid { get { throw null; } } public static System.Drawing.Color DarkRed { get { throw null; } } public static System.Drawing.Color DarkSalmon { get { throw null; } } public static System.Drawing.Color DarkSeaGreen { get { throw null; } } public static System.Drawing.Color DarkSlateBlue { get { throw null; } } public static System.Drawing.Color DarkSlateGray { get { throw null; } } public static System.Drawing.Color DarkTurquoise { get { throw null; } } public static System.Drawing.Color DarkViolet { get { throw null; } } public static System.Drawing.Color DeepPink { get { throw null; } } public static System.Drawing.Color DeepSkyBlue { get { throw null; } } public static System.Drawing.Color DimGray { get { throw null; } } public static System.Drawing.Color DodgerBlue { get { throw null; } } public static System.Drawing.Color Firebrick { get { throw null; } } public static System.Drawing.Color FloralWhite { get { throw null; } } public static System.Drawing.Color ForestGreen { get { throw null; } } public static System.Drawing.Color Fuchsia { get { throw null; } } public byte G { get { throw null; } } public static System.Drawing.Color Gainsboro { get { throw null; } } public static System.Drawing.Color GhostWhite { get { throw null; } } public static System.Drawing.Color Gold { get { throw null; } } public static System.Drawing.Color Goldenrod { get { throw null; } } public static System.Drawing.Color Gray { get { throw null; } } public static System.Drawing.Color Green { get { throw null; } } public static System.Drawing.Color GreenYellow { get { throw null; } } public static System.Drawing.Color Honeydew { get { throw null; } } public static System.Drawing.Color HotPink { get { throw null; } } public static System.Drawing.Color IndianRed { get { throw null; } } public static System.Drawing.Color Indigo { get { throw null; } } public bool IsEmpty { get { throw null; } } public bool IsKnownColor { get { throw null; } } public bool IsNamedColor { get { throw null; } } public bool IsSystemColor { get { throw null; } } public static System.Drawing.Color Ivory { get { throw null; } } public static System.Drawing.Color Khaki { get { throw null; } } public static System.Drawing.Color Lavender { get { throw null; } } public static System.Drawing.Color LavenderBlush { get { throw null; } } public static System.Drawing.Color LawnGreen { get { throw null; } } public static System.Drawing.Color LemonChiffon { get { throw null; } } public static System.Drawing.Color LightBlue { get { throw null; } } public static System.Drawing.Color LightCoral { get { throw null; } } public static System.Drawing.Color LightCyan { get { throw null; } } public static System.Drawing.Color LightGoldenrodYellow { get { throw null; } } public static System.Drawing.Color LightGray { get { throw null; } } public static System.Drawing.Color LightGreen { get { throw null; } } public static System.Drawing.Color LightPink { get { throw null; } } public static System.Drawing.Color LightSalmon { get { throw null; } } public static System.Drawing.Color LightSeaGreen { get { throw null; } } public static System.Drawing.Color LightSkyBlue { get { throw null; } } public static System.Drawing.Color LightSlateGray { get { throw null; } } public static System.Drawing.Color LightSteelBlue { get { throw null; } } public static System.Drawing.Color LightYellow { get { throw null; } } public static System.Drawing.Color Lime { get { throw null; } } public static System.Drawing.Color LimeGreen { get { throw null; } } public static System.Drawing.Color Linen { get { throw null; } } public static System.Drawing.Color Magenta { get { throw null; } } public static System.Drawing.Color Maroon { get { throw null; } } public static System.Drawing.Color MediumAquamarine { get { throw null; } } public static System.Drawing.Color MediumBlue { get { throw null; } } public static System.Drawing.Color MediumOrchid { get { throw null; } } public static System.Drawing.Color MediumPurple { get { throw null; } } public static System.Drawing.Color MediumSeaGreen { get { throw null; } } public static System.Drawing.Color MediumSlateBlue { get { throw null; } } public static System.Drawing.Color MediumSpringGreen { get { throw null; } } public static System.Drawing.Color MediumTurquoise { get { throw null; } } public static System.Drawing.Color MediumVioletRed { get { throw null; } } public static System.Drawing.Color MidnightBlue { get { throw null; } } public static System.Drawing.Color MintCream { get { throw null; } } public static System.Drawing.Color MistyRose { get { throw null; } } public static System.Drawing.Color Moccasin { get { throw null; } } public string Name { get { throw null; } } public static System.Drawing.Color NavajoWhite { get { throw null; } } public static System.Drawing.Color Navy { get { throw null; } } public static System.Drawing.Color OldLace { get { throw null; } } public static System.Drawing.Color Olive { get { throw null; } } public static System.Drawing.Color OliveDrab { get { throw null; } } public static System.Drawing.Color Orange { get { throw null; } } public static System.Drawing.Color OrangeRed { get { throw null; } } public static System.Drawing.Color Orchid { get { throw null; } } public static System.Drawing.Color PaleGoldenrod { get { throw null; } } public static System.Drawing.Color PaleGreen { get { throw null; } } public static System.Drawing.Color PaleTurquoise { get { throw null; } } public static System.Drawing.Color PaleVioletRed { get { throw null; } } public static System.Drawing.Color PapayaWhip { get { throw null; } } public static System.Drawing.Color PeachPuff { get { throw null; } } public static System.Drawing.Color Peru { get { throw null; } } public static System.Drawing.Color Pink { get { throw null; } } public static System.Drawing.Color Plum { get { throw null; } } public static System.Drawing.Color PowderBlue { get { throw null; } } public static System.Drawing.Color Purple { get { throw null; } } public byte R { get { throw null; } } public static System.Drawing.Color Red { get { throw null; } } public static System.Drawing.Color RosyBrown { get { throw null; } } public static System.Drawing.Color RoyalBlue { get { throw null; } } public static System.Drawing.Color SaddleBrown { get { throw null; } } public static System.Drawing.Color Salmon { get { throw null; } } public static System.Drawing.Color SandyBrown { get { throw null; } } public static System.Drawing.Color SeaGreen { get { throw null; } } public static System.Drawing.Color SeaShell { get { throw null; } } public static System.Drawing.Color Sienna { get { throw null; } } public static System.Drawing.Color Silver { get { throw null; } } public static System.Drawing.Color SkyBlue { get { throw null; } } public static System.Drawing.Color SlateBlue { get { throw null; } } public static System.Drawing.Color SlateGray { get { throw null; } } public static System.Drawing.Color Snow { get { throw null; } } public static System.Drawing.Color SpringGreen { get { throw null; } } public static System.Drawing.Color SteelBlue { get { throw null; } } public static System.Drawing.Color Tan { get { throw null; } } public static System.Drawing.Color Teal { get { throw null; } } public static System.Drawing.Color Thistle { get { throw null; } } public static System.Drawing.Color Tomato { get { throw null; } } public static System.Drawing.Color Transparent { get { throw null; } } public static System.Drawing.Color Turquoise { get { throw null; } } public static System.Drawing.Color Violet { get { throw null; } } public static System.Drawing.Color Wheat { get { throw null; } } public static System.Drawing.Color White { get { throw null; } } public static System.Drawing.Color WhiteSmoke { get { throw null; } } public static System.Drawing.Color Yellow { get { throw null; } } public static System.Drawing.Color YellowGreen { get { throw null; } } public override bool Equals(object obj) { throw null; } public static System.Drawing.Color FromArgb(int argb) { throw null; } public static System.Drawing.Color FromArgb(int alpha, System.Drawing.Color baseColor) { throw null; } public static System.Drawing.Color FromArgb(int red, int green, int blue) { throw null; } public static System.Drawing.Color FromArgb(int alpha, int red, int green, int blue) { throw null; } public static System.Drawing.Color FromKnownColor(System.Drawing.KnownColor color) { throw null; } public static System.Drawing.Color FromName(string name) { throw null; } public float GetBrightness() { throw null; } public override int GetHashCode() { throw null; } public float GetHue() { throw null; } public float GetSaturation() { throw null; } public static bool operator ==(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public static bool operator !=(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public int ToArgb() { throw null; } public System.Drawing.KnownColor ToKnownColor() { throw null; } public override string ToString() { throw null; } } public partial class ColorConverter : System.ComponentModel.TypeConverter { public ColorConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { throw null; } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { throw null; } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { throw null; } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { throw null; } public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { throw null; } public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } } public enum KnownColor { ActiveBorder = 1, ActiveCaption = 2, ActiveCaptionText = 3, AliceBlue = 28, AntiqueWhite = 29, AppWorkspace = 4, Aqua = 30, Aquamarine = 31, Azure = 32, Beige = 33, Bisque = 34, Black = 35, BlanchedAlmond = 36, Blue = 37, BlueViolet = 38, Brown = 39, BurlyWood = 40, ButtonFace = 168, ButtonHighlight = 169, ButtonShadow = 170, CadetBlue = 41, Chartreuse = 42, Chocolate = 43, Control = 5, ControlDark = 6, ControlDarkDark = 7, ControlLight = 8, ControlLightLight = 9, ControlText = 10, Coral = 44, CornflowerBlue = 45, Cornsilk = 46, Crimson = 47, Cyan = 48, DarkBlue = 49, DarkCyan = 50, DarkGoldenrod = 51, DarkGray = 52, DarkGreen = 53, DarkKhaki = 54, DarkMagenta = 55, DarkOliveGreen = 56, DarkOrange = 57, DarkOrchid = 58, DarkRed = 59, DarkSalmon = 60, DarkSeaGreen = 61, DarkSlateBlue = 62, DarkSlateGray = 63, DarkTurquoise = 64, DarkViolet = 65, DeepPink = 66, DeepSkyBlue = 67, Desktop = 11, DimGray = 68, DodgerBlue = 69, Firebrick = 70, FloralWhite = 71, ForestGreen = 72, Fuchsia = 73, Gainsboro = 74, GhostWhite = 75, Gold = 76, Goldenrod = 77, GradientActiveCaption = 171, GradientInactiveCaption = 172, Gray = 78, GrayText = 12, Green = 79, GreenYellow = 80, Highlight = 13, HighlightText = 14, Honeydew = 81, HotPink = 82, HotTrack = 15, InactiveBorder = 16, InactiveCaption = 17, InactiveCaptionText = 18, IndianRed = 83, Indigo = 84, Info = 19, InfoText = 20, Ivory = 85, Khaki = 86, Lavender = 87, LavenderBlush = 88, LawnGreen = 89, LemonChiffon = 90, LightBlue = 91, LightCoral = 92, LightCyan = 93, LightGoldenrodYellow = 94, LightGray = 95, LightGreen = 96, LightPink = 97, LightSalmon = 98, LightSeaGreen = 99, LightSkyBlue = 100, LightSlateGray = 101, LightSteelBlue = 102, LightYellow = 103, Lime = 104, LimeGreen = 105, Linen = 106, Magenta = 107, Maroon = 108, MediumAquamarine = 109, MediumBlue = 110, MediumOrchid = 111, MediumPurple = 112, MediumSeaGreen = 113, MediumSlateBlue = 114, MediumSpringGreen = 115, MediumTurquoise = 116, MediumVioletRed = 117, Menu = 21, MenuBar = 173, MenuHighlight = 174, MenuText = 22, MidnightBlue = 118, MintCream = 119, MistyRose = 120, Moccasin = 121, NavajoWhite = 122, Navy = 123, OldLace = 124, Olive = 125, OliveDrab = 126, Orange = 127, OrangeRed = 128, Orchid = 129, PaleGoldenrod = 130, PaleGreen = 131, PaleTurquoise = 132, PaleVioletRed = 133, PapayaWhip = 134, PeachPuff = 135, Peru = 136, Pink = 137, Plum = 138, PowderBlue = 139, Purple = 140, Red = 141, RosyBrown = 142, RoyalBlue = 143, SaddleBrown = 144, Salmon = 145, SandyBrown = 146, ScrollBar = 23, SeaGreen = 147, SeaShell = 148, Sienna = 149, Silver = 150, SkyBlue = 151, SlateBlue = 152, SlateGray = 153, Snow = 154, SpringGreen = 155, SteelBlue = 156, Tan = 157, Teal = 158, Thistle = 159, Tomato = 160, Transparent = 27, Turquoise = 161, Violet = 162, Wheat = 163, White = 164, WhiteSmoke = 165, Window = 24, WindowFrame = 25, WindowText = 26, Yellow = 166, YellowGreen = 167, } public sealed partial class SystemColors { internal SystemColors() { } public static System.Drawing.Color ActiveBorder { get { throw null; } } public static System.Drawing.Color ActiveCaption { get { throw null; } } public static System.Drawing.Color ActiveCaptionText { get { throw null; } } public static System.Drawing.Color AppWorkspace { get { throw null; } } public static System.Drawing.Color ButtonFace { get { throw null; } } public static System.Drawing.Color ButtonHighlight { get { throw null; } } public static System.Drawing.Color ButtonShadow { get { throw null; } } public static System.Drawing.Color Control { get { throw null; } } public static System.Drawing.Color ControlDark { get { throw null; } } public static System.Drawing.Color ControlDarkDark { get { throw null; } } public static System.Drawing.Color ControlLight { get { throw null; } } public static System.Drawing.Color ControlLightLight { get { throw null; } } public static System.Drawing.Color ControlText { get { throw null; } } public static System.Drawing.Color Desktop { get { throw null; } } public static System.Drawing.Color GradientActiveCaption { get { throw null; } } public static System.Drawing.Color GradientInactiveCaption { get { throw null; } } public static System.Drawing.Color GrayText { get { throw null; } } public static System.Drawing.Color Highlight { get { throw null; } } public static System.Drawing.Color HighlightText { get { throw null; } } public static System.Drawing.Color HotTrack { get { throw null; } } public static System.Drawing.Color InactiveBorder { get { throw null; } } public static System.Drawing.Color InactiveCaption { get { throw null; } } public static System.Drawing.Color InactiveCaptionText { get { throw null; } } public static System.Drawing.Color Info { get { throw null; } } public static System.Drawing.Color InfoText { get { throw null; } } public static System.Drawing.Color Menu { get { throw null; } } public static System.Drawing.Color MenuBar { get { throw null; } } public static System.Drawing.Color MenuHighlight { get { throw null; } } public static System.Drawing.Color MenuText { get { throw null; } } public static System.Drawing.Color ScrollBar { get { throw null; } } public static System.Drawing.Color Window { get { throw null; } } public static System.Drawing.Color WindowFrame { get { throw null; } } public static System.Drawing.Color WindowText { get { throw null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime; using System.ServiceModel.Diagnostics.Application; using System.ServiceModel.Security; using System.Threading.Tasks; using System.Xml; namespace System.ServiceModel.Channels { internal abstract class SessionConnectionReader : IMessageSource { private bool _isAtEOF; private bool _usingAsyncReadBuffer; private IConnection _connection; private byte[] _buffer; private int _offset; private int _size; private byte[] _envelopeBuffer; private int _envelopeOffset; private int _envelopeSize; private bool _readIntoEnvelopeBuffer; private Message _pendingMessage; private Exception _pendingException; private SecurityMessageProperty _security; // Raw connection that we will revert to after end handshake private IConnection _rawConnection; protected SessionConnectionReader(IConnection connection, IConnection rawConnection, int offset, int size, SecurityMessageProperty security) { _offset = offset; _size = size; if (size > 0) { _buffer = connection.AsyncReadBuffer; } _connection = connection; _rawConnection = rawConnection; _security = security; } private Message DecodeMessage(TimeSpan timeout) { if (!_readIntoEnvelopeBuffer) { return DecodeMessage(_buffer, ref _offset, ref _size, ref _isAtEOF, timeout); } else { // decode from the envelope buffer int dummyOffset = _envelopeOffset; return DecodeMessage(_envelopeBuffer, ref dummyOffset, ref _size, ref _isAtEOF, timeout); } } protected abstract Message DecodeMessage(byte[] buffer, ref int offset, ref int size, ref bool isAtEof, TimeSpan timeout); protected byte[] EnvelopeBuffer { get { return _envelopeBuffer; } set { _envelopeBuffer = value; } } protected int EnvelopeOffset { get { return _envelopeOffset; } set { _envelopeOffset = value; } } protected int EnvelopeSize { get { return _envelopeSize; } set { _envelopeSize = value; } } public IConnection GetRawConnection() { IConnection result = null; if (_rawConnection != null) { result = _rawConnection; _rawConnection = null; if (_size > 0) { PreReadConnection preReadConnection = result as PreReadConnection; if (preReadConnection != null) // make sure we don't keep wrapping { preReadConnection.AddPreReadData(_buffer, _offset, _size); } else { result = new PreReadConnection(result, _buffer, _offset, _size); } } } return result; } public async Task<Message> ReceiveAsync(TimeSpan timeout) { Message message = GetPendingMessage(); if (message != null) { return message; } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (; ;) { if (_isAtEOF) { return null; } if (_size > 0) { message = DecodeMessage(timeoutHelper.RemainingTime()); if (message != null) { PrepareMessage(message); return message; } else if (_isAtEOF) // could have read the END record under DecodeMessage { return null; } } if (_size != 0) { throw new Exception("Receive: DecodeMessage() should consume the outstanding buffer or return a message."); } if (!_usingAsyncReadBuffer) { _buffer = _connection.AsyncReadBuffer; _usingAsyncReadBuffer = true; } int bytesRead; var tcs = new TaskCompletionSource<bool>(); var result = _connection.BeginRead(0, _buffer.Length, timeoutHelper.RemainingTime(), TaskHelpers.OnAsyncCompletionCallback, tcs); if (result == AsyncCompletionResult.Completed) { tcs.TrySetResult(true); } await tcs.Task; bytesRead = _connection.EndRead(); HandleReadComplete(bytesRead, false); } } public Message Receive(TimeSpan timeout) { Message message = GetPendingMessage(); if (message != null) { return message; } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (; ;) { if (_isAtEOF) { return null; } if (_size > 0) { message = DecodeMessage(timeoutHelper.RemainingTime()); if (message != null) { PrepareMessage(message); return message; } else if (_isAtEOF) // could have read the END record under DecodeMessage { return null; } } if (_size != 0) { throw new Exception("Receive: DecodeMessage() should consume the outstanding buffer or return a message."); } if (_buffer == null) { _buffer = Fx.AllocateByteArray(_connection.AsyncReadBufferSize); } int bytesRead; if (EnvelopeBuffer != null && (EnvelopeSize - EnvelopeOffset) >= _buffer.Length) { bytesRead = _connection.Read(EnvelopeBuffer, EnvelopeOffset, _buffer.Length, timeoutHelper.RemainingTime()); HandleReadComplete(bytesRead, true); } else { bytesRead = _connection.Read(_buffer, 0, _buffer.Length, timeoutHelper.RemainingTime()); HandleReadComplete(bytesRead, false); } } } public Message EndReceive() { return GetPendingMessage(); } private Message GetPendingMessage() { if (_pendingException != null) { Exception exception = _pendingException; _pendingException = null; throw exception; } if (_pendingMessage != null) { Message message = _pendingMessage; _pendingMessage = null; return message; } return null; } public async Task<bool> WaitForMessageAsync(TimeSpan timeout) { try { Message message = await ReceiveAsync(timeout); _pendingMessage = message; return true; } catch (TimeoutException e) { if (TD.ReceiveTimeoutIsEnabled()) { TD.ReceiveTimeout(e.Message); } return false; } } public bool WaitForMessage(TimeSpan timeout) { try { Message message = Receive(timeout); _pendingMessage = message; return true; } catch (TimeoutException e) { if (TD.ReceiveTimeoutIsEnabled()) { TD.ReceiveTimeout(e.Message); } return false; } } protected abstract void EnsureDecoderAtEof(); private void HandleReadComplete(int bytesRead, bool readIntoEnvelopeBuffer) { _readIntoEnvelopeBuffer = readIntoEnvelopeBuffer; if (bytesRead == 0) { EnsureDecoderAtEof(); _isAtEOF = true; } else { _offset = 0; _size = bytesRead; } } protected virtual void PrepareMessage(Message message) { if (_security != null) { message.Properties.Security = (SecurityMessageProperty)_security.CreateCopy(); } } } internal class ClientDuplexConnectionReader : SessionConnectionReader { private ClientDuplexDecoder _decoder; private int _maxBufferSize; private BufferManager _bufferManager; private MessageEncoder _messageEncoder; private ClientFramingDuplexSessionChannel _channel; public ClientDuplexConnectionReader(ClientFramingDuplexSessionChannel channel, IConnection connection, ClientDuplexDecoder decoder, IConnectionOrientedTransportFactorySettings settings, MessageEncoder messageEncoder) : base(connection, null, 0, 0, null) { _decoder = decoder; _maxBufferSize = settings.MaxBufferSize; _bufferManager = settings.BufferManager; _messageEncoder = messageEncoder; _channel = channel; } protected override void EnsureDecoderAtEof() { if (!(_decoder.CurrentState == ClientFramingDecoderState.End || _decoder.CurrentState == ClientFramingDecoderState.EnvelopeEnd || _decoder.CurrentState == ClientFramingDecoderState.ReadingUpgradeRecord || _decoder.CurrentState == ClientFramingDecoderState.UpgradeResponse)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_decoder.CreatePrematureEOFException()); } } private static IDisposable CreateProcessActionActivity() { return null; } protected override Message DecodeMessage(byte[] buffer, ref int offset, ref int size, ref bool isAtEOF, TimeSpan timeout) { while (size > 0) { int bytesRead = _decoder.Decode(buffer, offset, size); if (bytesRead > 0) { if (EnvelopeBuffer != null) { if (!object.ReferenceEquals(buffer, EnvelopeBuffer)) System.Buffer.BlockCopy(buffer, offset, EnvelopeBuffer, EnvelopeOffset, bytesRead); EnvelopeOffset += bytesRead; } offset += bytesRead; size -= bytesRead; } switch (_decoder.CurrentState) { case ClientFramingDecoderState.Fault: _channel.Session.CloseOutputSession(_channel.GetInternalCloseTimeout()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(FaultStringDecoder.GetFaultException(_decoder.Fault, _channel.RemoteAddress.Uri.ToString(), _messageEncoder.ContentType)); case ClientFramingDecoderState.End: isAtEOF = true; return null; // we're done case ClientFramingDecoderState.EnvelopeStart: int envelopeSize = _decoder.EnvelopeSize; if (envelopeSize > _maxBufferSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ExceptionHelper.CreateMaxReceivedMessageSizeExceededException(_maxBufferSize)); } EnvelopeBuffer = _bufferManager.TakeBuffer(envelopeSize); EnvelopeOffset = 0; EnvelopeSize = envelopeSize; break; case ClientFramingDecoderState.EnvelopeEnd: if (EnvelopeBuffer != null) { Message message = null; try { IDisposable activity = ClientDuplexConnectionReader.CreateProcessActionActivity(); using (activity) { message = _messageEncoder.ReadMessage(new ArraySegment<byte>(EnvelopeBuffer, 0, EnvelopeSize), _bufferManager); } } catch (XmlException xmlException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.MessageXmlProtocolError, xmlException)); } EnvelopeBuffer = null; return message; } break; } } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.IO.Pipelines; using System.Text; using System.Threading.Tasks; using Xunit; namespace Microsoft.AspNetCore.Http.Features { public class FormFeatureTests { [Fact] public async Task ReadFormAsync_0ContentLength_ReturnsEmptyForm() { var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.ContentLength = 0; var formFeature = new FormFeature(context.Request, new FormOptions()); context.Features.Set<IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.Same(FormCollection.Empty, formCollection); } [Fact] public async Task FormFeatureReadsOptionsFromDefaultHttpContext() { var context = new DefaultHttpContext(); context.Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; context.FormOptions = new FormOptions { ValueCountLimit = 1 }; var formContent = Encoding.UTF8.GetBytes("foo=bar&baz=2"); context.Request.Body = new NonSeekableReadStream(formContent); var exception = await Assert.ThrowsAsync<InvalidDataException>(() => context.Request.ReadFormAsync()); Assert.Equal("Form value count limit 1 exceeded.", exception.Message); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadFormAsync_SimpleData_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes("foo=bar&baz=2"); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set<IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.Equal("bar", formCollection["foo"]); Assert.Equal("2", formCollection["baz"]); Assert.Equal(bufferRequest, context.Request.Body.CanSeek); if (bufferRequest) { Assert.Equal(0, context.Request.Body.Position); } // Cached formFeature = context.Features.Get<IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); // Cleanup await responseFeature.CompleteAsync(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadFormAsync_SimpleData_ReplacePipeReader_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes("foo=bar&baz=2"); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; var pipe = new Pipe(); await pipe.Writer.WriteAsync(formContent); pipe.Writer.Complete(); var mockFeature = new MockRequestBodyPipeFeature(); mockFeature.Reader = pipe.Reader; context.Features.Set<IRequestBodyPipeFeature>(mockFeature); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set<IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.Equal("bar", formCollection["foo"]); Assert.Equal("2", formCollection["baz"]); // Cached formFeature = context.Features.Get<IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); // Cleanup await responseFeature.CompleteAsync(); } private class MockRequestBodyPipeFeature : IRequestBodyPipeFeature { public PipeReader Reader { get; set; } } private const string MultipartContentType = "multipart/form-data; boundary=WebKitFormBoundary5pDRpGheQXaM8k3T"; private const string MultipartContentTypeWithSpecialCharacters = "multipart/form-data; boundary=\"WebKitFormBoundary/:5pDRpGheQXaM8k3T\""; private const string EmptyMultipartForm = "--WebKitFormBoundary5pDRpGheQXaM8k3T--"; // Note that CRLF (\r\n) is required. You can't use multi-line C# strings here because the line breaks on Linux are just LF. private const string MultipartFormEnd = "--WebKitFormBoundary5pDRpGheQXaM8k3T--\r\n"; private const string MultipartFormEndWithSpecialCharacters = "--WebKitFormBoundary/:5pDRpGheQXaM8k3T--\r\n"; private const string MultipartFormField = "--WebKitFormBoundary5pDRpGheQXaM8k3T\r\n" + "Content-Disposition: form-data; name=\"description\"\r\n" + "\r\n" + "Foo\r\n"; private const string MultipartFormFile = "--WebKitFormBoundary5pDRpGheQXaM8k3T\r\n" + "Content-Disposition: form-data; name=\"myfile1\"; filename=\"temp.html\"\r\n" + "Content-Type: text/html\r\n" + "\r\n" + "<html><body>Hello World</body></html>\r\n"; private const string MultipartFormEncodedFilename = "--WebKitFormBoundary5pDRpGheQXaM8k3T\r\n" + "Content-Disposition: form-data; name=\"myfile1\"; filename=\"temp.html\"; filename*=utf-8\'\'t%c3%a9mp.html\r\n" + "Content-Type: text/html\r\n" + "\r\n" + "<html><body>Hello World</body></html>\r\n"; private const string MultipartFormFileSpecialCharacters = "--WebKitFormBoundary/:5pDRpGheQXaM8k3T\r\n" + "Content-Disposition: form-data; name=\"description\"\r\n" + "\r\n" + "Foo\r\n"; private const string InvalidContentDispositionValue = "form-data; name=\"description\" - filename=\"temp.html\""; private const string MultipartFormFileInvalidContentDispositionValue = "--WebKitFormBoundary5pDRpGheQXaM8k3T\r\n" + "Content-Disposition: " + InvalidContentDispositionValue + "\r\n" + "\r\n" + "Foo\r\n"; private const string MultipartFormWithField = MultipartFormField + MultipartFormEnd; private const string MultipartFormWithFile = MultipartFormFile + MultipartFormEnd; private const string MultipartFormWithFieldAndFile = MultipartFormField + MultipartFormFile + MultipartFormEnd; private const string MultipartFormWithEncodedFilename = MultipartFormEncodedFilename + MultipartFormEnd; private const string MultipartFormWithSpecialCharacters = MultipartFormFileSpecialCharacters + MultipartFormEndWithSpecialCharacters; private const string MultipartFormWithInvalidContentDispositionValue = MultipartFormFileInvalidContentDispositionValue + MultipartFormEnd; [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadForm_EmptyMultipart_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes(EmptyMultipartForm); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set<IFormFeature>(formFeature); var formCollection = context.Request.Form; Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get<IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formCollection, formFeature.Form); Assert.Same(formCollection, await context.Request.ReadFormAsync()); // Content Assert.Equal(0, formCollection.Count); Assert.NotNull(formCollection.Files); Assert.Equal(0, formCollection.Files.Count); // Cleanup await responseFeature.CompleteAsync(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadForm_MultipartWithField_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes(MultipartFormWithField); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set<IFormFeature>(formFeature); var formCollection = context.Request.Form; Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get<IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formCollection, formFeature.Form); Assert.Same(formCollection, await context.Request.ReadFormAsync()); // Content Assert.Equal(1, formCollection.Count); Assert.Equal("Foo", formCollection["description"]); Assert.NotNull(formCollection.Files); Assert.Equal(0, formCollection.Files.Count); // Cleanup await responseFeature.CompleteAsync(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadFormAsync_MultipartWithFile_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes(MultipartFormWithFile); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set<IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get<IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); Assert.Same(formCollection, context.Request.Form); // Content Assert.Equal(0, formCollection.Count); Assert.NotNull(formCollection.Files); Assert.Equal(1, formCollection.Files.Count); var file = formCollection.Files["myfile1"]; Assert.Equal("myfile1", file.Name); Assert.Equal("temp.html", file.FileName); Assert.Equal("text/html", file.ContentType); Assert.Equal(@"form-data; name=""myfile1""; filename=""temp.html""", file.ContentDisposition); var body = file.OpenReadStream(); using (var reader = new StreamReader(body)) { Assert.True(body.CanSeek); var content = reader.ReadToEnd(); Assert.Equal("<html><body>Hello World</body></html>", content); } await responseFeature.CompleteAsync(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadFormAsync_MultipartWithFileAndQuotedBoundaryString_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes(MultipartFormWithSpecialCharacters); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentTypeWithSpecialCharacters; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set<IFormFeature>(formFeature); var formCollection = context.Request.Form; Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get<IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formCollection, formFeature.Form); Assert.Same(formCollection, await context.Request.ReadFormAsync()); // Content Assert.Equal(1, formCollection.Count); Assert.Equal("Foo", formCollection["description"]); Assert.NotNull(formCollection.Files); Assert.Equal(0, formCollection.Files.Count); // Cleanup await responseFeature.CompleteAsync(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadFormAsync_MultipartWithEncodedFilename_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes(MultipartFormWithEncodedFilename); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set<IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get<IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); Assert.Same(formCollection, context.Request.Form); // Content Assert.Equal(0, formCollection.Count); Assert.NotNull(formCollection.Files); Assert.Equal(1, formCollection.Files.Count); var file = formCollection.Files["myfile1"]; Assert.Equal("myfile1", file.Name); Assert.Equal("t\u00e9mp.html", file.FileName); Assert.Equal("text/html", file.ContentType); Assert.Equal(@"form-data; name=""myfile1""; filename=""temp.html""; filename*=utf-8''t%c3%a9mp.html", file.ContentDisposition); var body = file.OpenReadStream(); using (var reader = new StreamReader(body)) { Assert.True(body.CanSeek); var content = reader.ReadToEnd(); Assert.Equal("<html><body>Hello World</body></html>", content); } await responseFeature.CompleteAsync(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadFormAsync_MultipartWithFieldAndFile_ReturnsParsedFormCollection(bool bufferRequest) { var formContent = Encoding.UTF8.GetBytes(MultipartFormWithFieldAndFile); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set<IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get<IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); Assert.Same(formCollection, context.Request.Form); // Content Assert.Equal(1, formCollection.Count); Assert.Equal("Foo", formCollection["description"]); Assert.NotNull(formCollection.Files); Assert.Equal(1, formCollection.Files.Count); var file = formCollection.Files["myfile1"]; Assert.Equal("text/html", file.ContentType); Assert.Equal(@"form-data; name=""myfile1""; filename=""temp.html""", file.ContentDisposition); var body = file.OpenReadStream(); using (var reader = new StreamReader(body)) { Assert.True(body.CanSeek); var content = reader.ReadToEnd(); Assert.Equal("<html><body>Hello World</body></html>", content); } await responseFeature.CompleteAsync(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadFormAsync_ValueCountLimitExceeded_Throw(bool bufferRequest) { var formContent = new List<byte>(); formContent.AddRange(Encoding.UTF8.GetBytes(MultipartFormField)); formContent.AddRange(Encoding.UTF8.GetBytes(MultipartFormField)); formContent.AddRange(Encoding.UTF8.GetBytes(MultipartFormField)); formContent.AddRange(Encoding.UTF8.GetBytes(MultipartFormEnd)); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent.ToArray()); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest, ValueCountLimit = 2 }); context.Features.Set<IFormFeature>(formFeature); var exception = await Assert.ThrowsAsync<InvalidDataException>(() => context.Request.ReadFormAsync()); Assert.Equal("Form value count limit 2 exceeded.", exception.Message); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ReadFormAsync_ValueCountLimitExceededWithFiles_Throw(bool bufferRequest) { var formContent = new List<byte>(); formContent.AddRange(Encoding.UTF8.GetBytes(MultipartFormFile)); formContent.AddRange(Encoding.UTF8.GetBytes(MultipartFormFile)); formContent.AddRange(Encoding.UTF8.GetBytes(MultipartFormFile)); formContent.AddRange(Encoding.UTF8.GetBytes(MultipartFormEnd)); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent.ToArray()); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest, ValueCountLimit = 2 }); context.Features.Set<IFormFeature>(formFeature); var exception = await Assert.ThrowsAsync<InvalidDataException>(() => context.Request.ReadFormAsync()); Assert.Equal("Form value count limit 2 exceeded.", exception.Message); } [Theory] // FileBufferingReadStream transitions to disk storage after 30kb, and stops pooling buffers at 1mb. [InlineData(true, 1024)] [InlineData(false, 1024)] [InlineData(true, 40 * 1024)] [InlineData(false, 40 * 1024)] [InlineData(true, 4 * 1024 * 1024)] [InlineData(false, 4 * 1024 * 1024)] public async Task ReadFormAsync_MultipartWithFieldAndMediumFile_ReturnsParsedFormCollection(bool bufferRequest, int fileSize) { var fileContents = CreateFile(fileSize); var formContent = CreateMultipartWithFormAndFile(fileContents); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions() { BufferBody = bufferRequest }); context.Features.Set<IFormFeature>(formFeature); var formCollection = await context.Request.ReadFormAsync(); Assert.NotNull(formCollection); // Cached formFeature = context.Features.Get<IFormFeature>(); Assert.NotNull(formFeature); Assert.NotNull(formFeature.Form); Assert.Same(formFeature.Form, formCollection); Assert.Same(formCollection, context.Request.Form); // Content Assert.Equal(1, formCollection.Count); Assert.Equal("Foo", formCollection["description"]); Assert.NotNull(formCollection.Files); Assert.Equal(1, formCollection.Files.Count); var file = formCollection.Files["myfile1"]; Assert.Equal("text/html", file.ContentType); Assert.Equal(@"form-data; name=""myfile1""; filename=""temp.html""", file.ContentDisposition); using (var body = file.OpenReadStream()) { Assert.True(body.CanSeek); CompareStreams(fileContents, body); } await responseFeature.CompleteAsync(); } [Fact] public async Task ReadFormAsync_MultipartWithInvalidContentDisposition_Throw() { var formContent = Encoding.UTF8.GetBytes(MultipartFormWithInvalidContentDispositionValue); var context = new DefaultHttpContext(); var responseFeature = new FakeResponseFeature(); context.Features.Set<IHttpResponseFeature>(responseFeature); context.Request.ContentType = MultipartContentType; context.Request.Body = new NonSeekableReadStream(formContent); IFormFeature formFeature = new FormFeature(context.Request, new FormOptions()); context.Features.Set<IFormFeature>(formFeature); var exception = await Assert.ThrowsAsync<InvalidDataException>(() => context.Request.ReadFormAsync()); Assert.Equal("Form section has invalid Content-Disposition value: " + InvalidContentDispositionValue, exception.Message); } private Stream CreateFile(int size) { var stream = new MemoryStream(size); var bytes = Encoding.ASCII.GetBytes("HelloWorld_ABCDEFGHIJKLMNOPQRSTUVWXYZ.abcdefghijklmnopqrstuvwxyz,0123456789;"); int written = 0; while (written < size) { var toWrite = Math.Min(size - written, bytes.Length); stream.Write(bytes, 0, toWrite); written += toWrite; } stream.Position = 0; return stream; } private Stream CreateMultipartWithFormAndFile(Stream fileContents) { var stream = new MemoryStream(); var header = MultipartFormField + "--WebKitFormBoundary5pDRpGheQXaM8k3T\r\n" + "Content-Disposition: form-data; name=\"myfile1\"; filename=\"temp.html\"\r\n" + "Content-Type: text/html\r\n" + "\r\n"; var footer = "\r\n--WebKitFormBoundary5pDRpGheQXaM8k3T--"; var bytes = Encoding.ASCII.GetBytes(header); stream.Write(bytes, 0, bytes.Length); fileContents.CopyTo(stream); fileContents.Position = 0; bytes = Encoding.ASCII.GetBytes(footer); stream.Write(bytes, 0, bytes.Length); stream.Position = 0; return stream; } private void CompareStreams(Stream streamA, Stream streamB) { Assert.Equal(streamA.Length, streamB.Length); byte[] bytesA = new byte[1024], bytesB = new byte[1024]; var readA = streamA.Read(bytesA, 0, bytesA.Length); var readB = streamB.Read(bytesB, 0, bytesB.Length); Assert.Equal(readA, readB); var loops = 0; while (readA > 0) { for (int i = 0; i < readA; i++) { if (bytesA[i] != bytesB[i]) { throw new Exception($"Value mismatch at loop {loops}, index {i}; A:{bytesA[i]}, B:{bytesB[i]}"); } } readA = streamA.Read(bytesA, 0, bytesA.Length); readB = streamB.Read(bytesB, 0, bytesB.Length); Assert.Equal(readA, readB); loops++; } } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using System.Collections; using System.Collections.Generic; namespace Mosa.Compiler.Framework { /// <summary> /// /// </summary> public sealed class BasicBlocks : IEnumerable<BasicBlock> { #region Data members /// <summary> /// /// </summary> private readonly List<BasicBlock> basicBlocks = new List<BasicBlock>(); /// <summary> /// Holds the blocks indexed by label /// </summary> private readonly Dictionary<int, BasicBlock> basicBlocksByLabel = new Dictionary<int, BasicBlock>(); /// <summary> /// /// </summary> private readonly List<BasicBlock> headBlocks = new List<BasicBlock>(); /// <summary> /// The handler blocks /// </summary> private readonly List<BasicBlock> handlerHeadBlocks = new List<BasicBlock>(); /// <summary> /// The try blocks /// </summary> private readonly List<BasicBlock> tryHeadBlocks = new List<BasicBlock>(); /// <summary> /// /// </summary> private BasicBlock prologueBlock = null; /// <summary> /// /// </summary> private BasicBlock epilogueBlock = null; private int nextAvailableLabel = BasicBlock.CompilerBlockStartLabel; #endregion Data members #region Construction /// <summary> /// Initializes a new instance of the <see cref="BasicBlocks"/> class. /// </summary> public BasicBlocks() { } #endregion Construction #region Properties /// <summary> /// Gets the count. /// </summary> public int Count { get { return basicBlocks.Count; } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> public IEnumerator<BasicBlock> GetEnumerator() { foreach (var basicBlock in basicBlocks) { yield return basicBlock; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Gets the <see cref="Mosa.Compiler.Framework.BasicBlock"/> at the specified index. /// </summary> public BasicBlock this[int index] { get { return basicBlocks[index]; } set { basicBlocks[index] = value; } } /// <summary> /// Gets the head blocks. /// </summary> public IList<BasicBlock> HeadBlocks { get { return headBlocks.AsReadOnly(); } } /// <summary> /// Gets the handler head blocks. /// </summary> public IList<BasicBlock> HandlerHeadBlocks { get { return handlerHeadBlocks.AsReadOnly(); } } /// <summary> /// Gets the try head blocks. /// </summary> public IList<BasicBlock> TryHeadBlocks { get { return tryHeadBlocks.AsReadOnly(); } } /// <summary> /// Gets the prologue block. /// </summary> public BasicBlock PrologueBlock { get { if (prologueBlock == null) prologueBlock = GetByLabel(BasicBlock.PrologueLabel); return prologueBlock; } } /// <summary> /// Gets the epilogue block. /// </summary> public BasicBlock EpilogueBlock { get { if (epilogueBlock == null) epilogueBlock = GetByLabel(BasicBlock.EpilogueLabel); return epilogueBlock; } } #endregion Properties #region Methods /// <summary> /// Creates the block. /// </summary> /// <param name="label">The label.</param> /// <returns></returns> public BasicBlock CreateBlock(int label) { var basicBlock = new BasicBlock(basicBlocks.Count, label); basicBlocks.Add(basicBlock); basicBlocksByLabel.Add(label, basicBlock); return basicBlock; } /// <summary> /// Creates the block. /// </summary> /// <returns></returns> public BasicBlock CreateBlock() { int label = nextAvailableLabel++; var basicBlock = new BasicBlock(basicBlocks.Count, label); basicBlocks.Add(basicBlock); basicBlocksByLabel.Add(label, basicBlock); return basicBlock; } /// <summary> /// Retrieves a basic block from its label. /// </summary> /// <param name="label">The label of the basic block.</param> /// <returns> /// The basic block with the given label. /// </returns> public BasicBlock GetByLabel(int label) { BasicBlock basicBlock = null; basicBlocksByLabel.TryGetValue(label, out basicBlock); //Debug.Assert(label == BasicBlock.PrologueLabel || label == BasicBlock.EpilogueLabel || basicBlock != null); return basicBlock; } /// <summary> /// Determines whether [contains] [the specified block]. /// </summary> /// <param name="block">The block.</param> /// <returns></returns> public bool Contains(BasicBlock block) { return basicBlocks.Contains(block); } /// <summary> /// Adds the header block. /// </summary> /// <param name="basicBlock">The basic block.</param> public void AddHeadBlock(BasicBlock basicBlock) { headBlocks.Add(basicBlock); } /// <summary> /// Adds the handler block. /// </summary> /// <param name="basicBlock">The basic block.</param> public void AddHandlerHeadBlock(BasicBlock basicBlock) { handlerHeadBlocks.Add(basicBlock); basicBlock.IsHandlerHeadBlock = true; } /// <summary> /// Adds the try block. /// </summary> /// <param name="basicBlock">The basic block.</param> public void AddTryHeadBlock(BasicBlock basicBlock) { tryHeadBlocks.Add(basicBlock); basicBlock.IsTryHeadBlock = true; } /// <summary> /// Removes the header block. /// </summary> /// <param name="basicBlock">The basic block.</param> public void RemoveHeaderBlock(BasicBlock basicBlock) { if (headBlocks.Contains(basicBlock)) headBlocks.Remove(basicBlock); } /// <summary> /// Determines whether [is header block] [the specified basic block]. /// </summary> /// <param name="basicBlock">The basic block.</param> /// <returns> /// <c>true</c> if [is header block] [the specified basic block]; otherwise, <c>false</c>. /// </returns> public bool IsHeadBlock(BasicBlock basicBlock) { return headBlocks.Contains(basicBlock); } /// <summary> /// Reorders the blocks. /// </summary> /// <param name="newBlockOrder">The new block order.</param> public void ReorderBlocks(IList<BasicBlock> newBlockOrder) { basicBlocks.Clear(); basicBlocksByLabel.Clear(); int sequence = 0; foreach (var block in newBlockOrder) { if (block != null) { basicBlocks.Add(block); block.Sequence = sequence++; basicBlocksByLabel.Add(block.Label, block); } } epilogueBlock = null; } public void OrderByLabel() { var blocks = new SortedList<int, BasicBlock>(basicBlocks.Count); foreach (var block in basicBlocks) { blocks.Add(block.Label, block); } ReorderBlocks(blocks.Values); } #endregion Methods public List<BasicBlock> GetConnectedBlocksStartingAtHead(BasicBlock start) { List<BasicBlock> connected = new List<BasicBlock>(); BitArray visited = new BitArray(Count, false); Stack<BasicBlock> stack = new Stack<BasicBlock>(); stack.Push(start); while (stack.Count != 0) { BasicBlock at = stack.Pop(); if (!visited.Get(at.Sequence)) { visited.Set(at.Sequence, true); connected.Add(at); foreach (BasicBlock next in at.NextBlocks) if (!visited.Get(next.Sequence)) stack.Push(next); } } return connected; } public BasicBlock GetExitBlock(BasicBlock start) { BitArray visited = new BitArray(Count, false); Stack<BasicBlock> stack = new Stack<BasicBlock>(); stack.Push(start); while (stack.Count != 0) { BasicBlock at = stack.Pop(); if (!visited.Get(at.Sequence)) { visited.Set(at.Sequence, true); if (at.NextBlocks.Count == 0) return at; foreach (BasicBlock next in at.NextBlocks) if (!visited.Get(next.Sequence)) stack.Push(next); } } return null; } public static List<BasicBlock> ReversePostorder(BasicBlock head) { List<BasicBlock> result = new List<BasicBlock>(); Queue<BasicBlock> workList = new Queue<BasicBlock>(); // Add next block workList.Enqueue(head); while (workList.Count != 0) { BasicBlock current = workList.Dequeue(); if (!result.Contains(current)) { result.Add(current); foreach (BasicBlock next in current.NextBlocks) workList.Enqueue(next); } } return result; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace Aurora.Modules.Inventory { public class InventoryTransferModule : ISharedRegionModule { private readonly List<IScene> m_Scenelist = new List<IScene>(); private bool m_Enabled = true; private IMessageTransferModule m_TransferModule; #region ISharedRegionModule Members public void Initialise(IConfigSource config) { if (config.Configs["Messaging"] != null) { // Allow disabling this module in config // if (config.Configs["Messaging"].GetString( "InventoryTransferModule", "InventoryTransferModule") != "InventoryTransferModule") { m_Enabled = false; return; } } } public void AddRegion(IScene scene) { if (!m_Enabled) return; m_Scenelist.Add(scene); scene.RegisterModuleInterface(this); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClosingClient += OnClosingClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; } public void RegionLoaded(IScene scene) { if (m_TransferModule == null) { m_TransferModule = m_Scenelist[0].RequestModuleInterface<IMessageTransferModule>(); if (m_TransferModule == null) { MainConsole.Instance.Error("[INVENTORY TRANSFER]: No Message transfer module found, transfers will be local only"); m_Enabled = false; m_Scenelist.Clear(); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnClosingClient -= OnClosingClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; } } } public void RemoveRegion(IScene scene) { m_Scenelist.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnClosingClient -= OnClosingClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; } public void PostInitialise() { } public void Close() { } public string Name { get { return "InventoryModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion private void OnNewClient(IClientAPI client) { // Inventory giving is conducted via instant message client.OnInstantMessage += OnInstantMessage; } private void OnClosingClient(IClientAPI client) { client.OnInstantMessage -= OnInstantMessage; } private IScene FindClientScene(UUID agentId) { lock (m_Scenelist) { foreach (IScene scene in from scene in m_Scenelist let presence = scene.GetScenePresence(agentId) where presence != null select scene) { return scene; } } return null; } private void OnInstantMessage(IClientAPI client, GridInstantMessage im) { //MainConsole.Instance.InfoFormat("[INVENTORY TRANSFER]: OnInstantMessage {0}", im.dialog); IScene scene = FindClientScene(client.AgentId); if (scene == null) // Something seriously wrong here. return; if (im.dialog == (byte) InstantMessageDialog.InventoryOffered) { //MainConsole.Instance.DebugFormat("Asset type {0}", ((AssetType)im.binaryBucket[0])); if (im.binaryBucket.Length < 17) // Invalid return; UUID receipientID = im.toAgentID; IScenePresence user = scene.GetScenePresence(receipientID); UUID copyID; // Send the IM to the recipient. The item is already // in their inventory, so it will not be lost if // they are offline. // if (user != null) { // First byte is the asset type AssetType assetType = (AssetType) im.binaryBucket[0]; if (AssetType.Folder == assetType) { UUID folderID = new UUID(im.binaryBucket, 1); MainConsole.Instance.DebugFormat("[INVENTORY TRANSFER]: Inserting original folder {0} " + "into agent {1}'s inventory", folderID, im.toAgentID); scene.InventoryService.GiveInventoryFolderAsync(receipientID, client.AgentId, folderID, UUID.Zero, (folder) => { if (folder == null) { client.SendAgentAlertMessage("Can't find folder to give. Nothing given.", false); return; } // The outgoing binary bucket should contain only the byte which signals an asset folder is // being copied and the following bytes for the copied folder's UUID copyID = folder.ID; byte[] copyIDBytes = copyID.GetBytes(); im.binaryBucket = new byte[1 + copyIDBytes.Length]; im.binaryBucket[0] = (byte)AssetType.Folder; Array.Copy(copyIDBytes, 0, im.binaryBucket, 1, copyIDBytes.Length); if (user != null) user.ControllingClient.SendBulkUpdateInventory(folder); im.imSessionID = folderID; }); } else { // First byte of the array is probably the item type // Next 16 bytes are the UUID UUID itemID = new UUID(im.binaryBucket, 1); MainConsole.Instance.DebugFormat("[INVENTORY TRANSFER]: (giving) Inserting item {0} " + "into agent {1}'s inventory", itemID, im.toAgentID); scene.InventoryService.GiveInventoryItemAsync( im.toAgentID, im.fromAgentID, itemID, UUID.Zero, false, (itemCopy) => { if (itemCopy == null) { client.SendAgentAlertMessage("Can't find item to give. Nothing given.", false); return; } copyID = itemCopy.ID; Array.Copy(copyID.GetBytes(), 0, im.binaryBucket, 1, 16); if (user != null) { user.ControllingClient.SendBulkUpdateInventory(itemCopy); } im.imSessionID = itemID; }); } user.ControllingClient.SendInstantMessage(im); return; } else { if (m_TransferModule != null) m_TransferModule.SendInstantMessage(im); } } else if (im.dialog == (byte) InstantMessageDialog.InventoryAccepted) { IScenePresence user = scene.GetScenePresence(im.toAgentID); if (user != null) // Local { user.ControllingClient.SendInstantMessage(im); } else { if (m_TransferModule != null) m_TransferModule.SendInstantMessage(im); } } else if (im.dialog == (byte) InstantMessageDialog.InventoryDeclined) { // Here, the recipient is local and we can assume that the // inventory is loaded. Courtesy of the above bulk update, // It will have been pushed to the client, too // IInventoryService invService = scene.InventoryService; InventoryFolderBase trashFolder = invService.GetFolderForType(client.AgentId, InventoryType.Unknown, AssetType.TrashFolder); UUID inventoryID = im.imSessionID; // The inventory item/folder, back from it's trip InventoryItemBase item = new InventoryItemBase(inventoryID, client.AgentId); item = invService.GetItem(item); InventoryFolderBase folder = null; if (item != null && trashFolder != null) { item.Folder = trashFolder.ID; // Diva comment: can't we just update this item??? List<UUID> uuids = new List<UUID> {item.ID}; invService.DeleteItems(item.Owner, uuids); ILLClientInventory inventory = client.Scene.RequestModuleInterface<ILLClientInventory>(); if (inventory != null) inventory.AddInventoryItem(client, item); } else { folder = new InventoryFolderBase(inventoryID, client.AgentId); folder = invService.GetFolder(folder); if (folder != null & trashFolder != null) { folder.ParentID = trashFolder.ID; invService.MoveFolder(folder); } } if ((null == item && null == folder) | null == trashFolder) { string reason = String.Empty; if (trashFolder == null) reason += " Trash folder not found."; if (item == null) reason += " Item not found."; if (folder == null) reason += " Folder not found."; client.SendAgentAlertMessage("Unable to delete " + "received inventory" + reason, false); } IScenePresence user = scene.GetScenePresence(im.toAgentID); if (user != null) // Local { user.ControllingClient.SendInstantMessage(im); } else { if (m_TransferModule != null) m_TransferModule.SendInstantMessage(im); } } } ///<summary> ///</summary> ///<param name = "msg"></param> private void OnGridInstantMessage(GridInstantMessage msg) { // Check if this is ours to handle // IScene scene = FindClientScene(msg.toAgentID); if (scene == null) return; // Find agent to deliver to // IScenePresence user = scene.GetScenePresence(msg.toAgentID); // Just forward to local handling OnInstantMessage(user.ControllingClient, msg); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Numerics.Tests { public class modpowTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void ModPowValidSmallNumbers() { BigInteger result; bool b = BigInteger.TryParse("22", out result); // ModPow Method - with small numbers - valid for (int i = 1; i <= 1; i++)//-2 { for (int j = 0; j <= 1; j++)//2 { for (int k = 1; k <= 1; k++) { if (k != 0) { VerifyModPowString(k.ToString() + " " + j.ToString() + " " + i.ToString() + " tModPow"); } } } } } [Fact] public static void ModPowNegative() { byte[] tempByteArray1; byte[] tempByteArray2; byte[] tempByteArray3; // ModPow Method - with small numbers - invalid - zero modulus for (int i = -2; i <= 2; i++) { for (int j = 0; j <= 2; j++) { Assert.Throws<DivideByZeroException>(() => { VerifyModPowString(BigInteger.Zero.ToString() + " " + j.ToString() + " " + i.ToString() + " tModPow"); }); } } // ModPow Method - with small numbers - invalid - negative exponent for (int i = -2; i <= 2; i++) { for (int j = -2; j <= -1; j++) { for (int k = -2; k <= 2; k++) { if (k != 0) { Assert.Throws<ArgumentOutOfRangeException>(() => { VerifyModPowString(k.ToString() + " " + j.ToString() + " " + i.ToString() + " tModPow"); }); } } } } // ModPow Method - Negative Exponent for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomNegByteArray(s_random, 2); tempByteArray3 = GetRandomByteArray(s_random); Assert.Throws<ArgumentOutOfRangeException>(() => { VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); }); } // ModPow Method - Zero Modulus for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomPosByteArray(s_random, 1); Assert.Throws<DivideByZeroException>(() => { VerifyModPowString(BigInteger.Zero.ToString() + " " + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); }); } } [Fact] public static void ModPow3SmallInt() { byte[] tempByteArray1; byte[] tempByteArray2; byte[] tempByteArray3; // ModPow Method - Three Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 2); tempByteArray3 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); } } [Fact] public static void ModPow1Large2SmallInt() { byte[] tempByteArray1; byte[] tempByteArray2; byte[] tempByteArray3; // ModPow Method - One large and two small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random); tempByteArray3 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomPosByteArray(s_random, 2); tempByteArray3 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 1); tempByteArray3 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); } } [Fact] public static void ModPow1Large2SmallInt_Threshold() { // Again, with lower threshold BigIntTools.Utils.RunWithFakeThreshold("ReducerThreshold", 8, ModPow1Large2SmallInt); } [Fact] public static void ModPow2Large1SmallInt() { byte[] tempByteArray1; byte[] tempByteArray2; byte[] tempByteArray3; // ModPow Method - Two large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomPosByteArray(s_random); tempByteArray3 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); } } [Fact] public static void ModPow2Large1SmallInt_Threshold() { // Again, with lower threshold BigIntTools.Utils.RunWithFakeThreshold("ReducerThreshold", 8, ModPow2Large1SmallInt); } // InlineData randomly generated using a new Random(0) and the same logic as is used in MyBigIntImp // When using the VerifyModPowString approach, these tests were taking over 100s to execute. [Theory] [OuterLoop] [InlineData("16152447169612934532253858872860101823992426489763666485380167221632010974596350526903901586786157942589749704137347759619657187784260082814484793173551647870373927196771852", "81750440863317178198977948957223170296434385667401518194303765341584160931262254891905182291359611229458113456891057547210603179481274334549407149567413965138338569615186383", "-7196805437625531929619339290119232497987723600413951949478998858079935202962418871178150151495255147489121599998392939293913217145771279946557062800866475934948778", "5616380469802854111883204613624062553120851412450654399190717359559254034938493684003207209263083893212739965150170342564431867389596229480294680122528026782956958")] [InlineData("-19804882257271871615998867413310154569092691610863183900352723872936597192840601413521317416195627481021453523098672122338092864102790996172", "5005126326020660905045117276428380928616741884628331700680598638081087432348216495484429178211470872172882902036752474804904132643", "-103139435102033366056363338063498713727200190198435", "-4559679593639479333979462122256288215243720737403")] [InlineData("-2263742881720266366742488789295767051326353176981812961528848101545308514727342989711034207353102864275894987436688194776201313772226059035143797121004935923223042331190890429211181925543749113890129660515170733848725", "313166794469483345944045915670847620773229708424183728974404367769353433443313247319899209581239311758905801464781585268041623664425", "3984523819293796257818294503433333109083365267654089093971156331037874112339941681299823291492643701164442964256327008451060278818307268485187524722068240", "-1502346344475556570236985614111713440763176490652894928852811056060906839905964408583918853958610145894621840382970373570196361549098246030413222124498085")] [InlineData("-342701069914551895507647608205424602441707687704978754182486401529587201154652163656221404036731562708712821963465111719289193200432064875769386559645346920", "247989781302056934762335026151076445832166884867735502165354252207668083157132317377069604102049233014316799294014890817943261246892765157594412634897440785353202366563028", "121555428622583377664148832113619145387775383377032217138159544127299380518157949963314283123957062240152711187509503414343", "87578369862034238407481381238856926729112161247036763388287150463197193460326629595765471822752579542310337770783772458710")] [InlineData("-282593950368131775131360433563237877977879464854725217398276355042086422366377452969365517205334520940629323311057746859", "5959258935361466196732788139899933762310441595693546573755448590100882267274831199165902682626769861372370905838130200967035", "6598019436100687108279703832125132357070343951841815860721553173215685978621505459125000339496396952653080051757197617932586296524960251609958919233462530", "-4035534917213670830138661334307123840766321272945538719146336835321463334263841831803093764143165039453996360590495570418141622764990299884920213157241339")] [InlineData("-283588760164723199492097446398514238808996680579814508529658395835708678571214111525627362048679162021949222615325057958783388520044013697149834530411072380435126870273057157745943859", "1042611904427950637176782337251399378305726352782300537151930702574076654415735617544217054055762002017753284951033975382044655538090809873113604", "11173562248848713955826639654969725554069867375462328112124015145073186375237811117727665778232780449525476829715663254692620996726130822561707626585790443774041565237684936409844925424596571418502946", "6662129352542591544500713232459850446949913817909326081510506555775206102887692404112984526760120407457772674917650956873499346517965094865621779695963015030158124625116211104048940313058280680420919")] [InlineData("683399436848090272429540515929404372035986606104192913128573936597145312908480564700882440819526500604918037963508399983297602351856208190565527", "223751878996658298590720798129833935741775535718632942242965085592936259576946732440406302671204348239437556817289012497483482656", "1204888420642360606571457515385663952017382888522547766961071698778167608427220546474854934298311882921224875807375321847274969073309433075566441363244101914489524538123410250010519308563731930923389473186", "1136631484875680074951300738594593722168933395227758228596156355418704717505715681950525129323209331607163560404958604424924870345828742295978850144844693079191828839673460389985036424301333691983679427765")] [InlineData("736513799451968530811005754031332418210960966881742655756522735504778110620671049112529346250333710388060811959329786494662578020803", "2461175085563866950903873687720858523536520498137697316698237108626602445202960480677695918813575265778826908481129155012799", "-4722693720735888562993277045098354134891725536023070176847814685098361292027040929352405620815883795027263132404351040", "4351573186631261607388198896754285562669240685903971199359912143458682154189588696264319780329366022294935204028039787")] [InlineData("1596188639947986471148999794547338", "685242191738212089917782567856594513073397739443", "41848166029740752457613562518205823134173790454761036532025758411484449588176128053901271638836032557551179866133091058357374964041641117585422447497779410336188602585660372002644517668041207657383104649333118253", "39246949850380693159338034407642149926180988060650630387722725303281343126585456713282439764667310808891687831648451269002447916277601468727040185218264602698691553232132525542650964722093335105211816394635493987")] [InlineData("-1506852741293695463963822334869441845197951776565891060639754936248401744065969556756496718308248025911048010080232290368562210204958094544173209793990218122", "64905085725614938357105826012272472070910693443851911667721848542473785070747281964799379996923261457185847459711", "2740467233603031668807697475486217767705051", "-1905434239471820365929630558127219204166613")] public static void ModPow3LargeInt(string value, string exponent, string modulus, string expected) { BigInteger valueInt = BigInteger.Parse(value); BigInteger exponentInt = BigInteger.Parse(exponent); BigInteger modulusInt = BigInteger.Parse(modulus); BigInteger resultInt = BigInteger.Parse(expected); // Once with default threshold Assert.Equal(resultInt, BigInteger.ModPow(valueInt, exponentInt, modulusInt)); // Once with reduced threshold BigIntTools.Utils.RunWithFakeThreshold("ReducerThreshold", 8, () => { Assert.Equal(resultInt, BigInteger.ModPow(valueInt, exponentInt, modulusInt)); }); } [Fact] public static void ModPow0Power() { byte[] tempByteArray1; byte[] tempByteArray2; // ModPow Method - zero power for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow"); } } [Fact] public static void ModPow0Base() { byte[] tempByteArray1; byte[] tempByteArray2; // ModPow Method - zero base for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow"); tempByteArray1 = GetRandomPosByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow"); tempByteArray1 = GetRandomPosByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow"); tempByteArray1 = GetRandomPosByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow"); } } [Fact] public static void ModPowAxiom() { byte[] tempByteArray1; byte[] tempByteArray2; byte[] tempByteArray3; // Axiom (x^y)%z = modpow(x,y,z) for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 1); tempByteArray3 = GetRandomByteArray(s_random); VerifyIdentityString( Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow", Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "bPow" + " bRemainder" ); } } [Fact] public static void ModPowBoundary() { // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyModPowString(Math.Pow(2, 35) + " " + Math.Pow(2, 32) + " 2 tModPow"); // 32 bit boundary n1=0 n2=1 VerifyModPowString(Math.Pow(2, 35) + " " + Math.Pow(2, 33) + " 2 tModPow"); } private static void VerifyModPowString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(1, 100)); } private static byte[] GetRandomPosByteArray(Random random) { return GetRandomPosByteArray(random, random.Next(1, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetNonZeroRandomByteArray(random, size); } private static byte[] GetRandomPosByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] &= 0x7F; return value; } private static byte[] GetRandomNegByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] |= 0x80; return value; } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
// Camera Path 3 // Available on the Unity Asset Store // Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com/camera-path/ // For support contact email@jasperstocker.com // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. using UnityEngine; using UnityEditor; public class CameraPathMenu : EditorWindow { [MenuItem("GameObject/Create New Camera Path", false, 0)] public static void CreateNewCameraPath() { GameObject newCameraPath = new GameObject("New Camera Path"); Undo.RegisterCreatedObjectUndo(newCameraPath, "Created New Camera Path"); newCameraPath.AddComponent<CameraPath>(); CameraPathAnimator animator = newCameraPath.AddComponent<CameraPathAnimator>(); if(Camera.main != null) animator.animationObject = Camera.main.transform; Selection.objects = new Object[] { newCameraPath }; SceneView.lastActiveSceneView.FrameSelected(); // EditorUtility.SetDirty(newCameraPath); } [MenuItem("GameObject/Align Camera Path Point to View", false, 1001)] public static void AlignPathPoint() { GameObject selected = Selection.activeGameObject; CameraPath camPath = selected.GetComponent<CameraPath>(); CameraPathAnimator animator = selected.GetComponent<CameraPathAnimator>(); Undo.RecordObject(camPath,"Align Camera Path Point to View"); if (camPath != null && animator!= null) { switch (animator.orientationMode) { case CameraPathAnimator.orientationModes.custom: if (camPath.pointMode == CameraPath.PointModes.Orientations) { int selectedPoint = camPath.selectedPoint; CameraPathOrientation point = camPath.orientationList[selectedPoint]; Camera sceneCam = SceneView.GetAllSceneCameras()[0]; Quaternion lookRotation = Quaternion.LookRotation(sceneCam.transform.forward); point.rotation = lookRotation; if (point.positionModes == CameraPathPoint.PositionModes.FixedToPoint) { CameraPathControlPoint cPoint = point.point; cPoint.worldPosition = sceneCam.transform.position; } camPath.RecalculateStoredValues(); } if (camPath.pointMode == CameraPath.PointModes.Transform || camPath.pointMode == CameraPath.PointModes.ControlPoints) { int selectedPoint = camPath.selectedPoint; CameraPathControlPoint cPoint = camPath[selectedPoint]; Camera sceneCam = SceneView.GetAllSceneCameras()[0]; cPoint.worldPosition = sceneCam.transform.position; CameraPathOrientation point = (CameraPathOrientation)camPath.orientationList.GetPoint(cPoint); if(point != null) { Quaternion lookRotation = Quaternion.LookRotation(sceneCam.transform.forward); point.rotation = lookRotation; } camPath.RecalculateStoredValues(); } break; default: if (camPath.pointMode == CameraPath.PointModes.Transform || camPath.pointMode == CameraPath.PointModes.ControlPoints) { int selectedPoint = camPath.selectedPoint; CameraPathControlPoint point = camPath[selectedPoint]; Camera sceneCam = SceneView.GetAllSceneCameras()[0]; float forwardArcLength = camPath.StoredArcLength(selectedPoint); point.forwardControlPointLocal = sceneCam.transform.forward * (Mathf.Max(forwardArcLength,0.1f) * 0.33f); point.worldPosition = sceneCam.transform.position; camPath.RecalculateStoredValues(); } break; } } } // Validate the menu item defined by the function above. // The menu item will be disabled if this function returns false. [MenuItem("GameObject/Align Camera Path Point to View", true)] static bool ValidateAlignPathPointtoView () { GameObject selected = Selection.activeGameObject; if(selected == null) return false; CameraPath camPath = selected.GetComponent<CameraPath>(); if (camPath==null) return false; switch(camPath.pointMode) { case CameraPath.PointModes.ControlPoints: return true; case CameraPath.PointModes.Transform: return true; case CameraPath.PointModes.Orientations: return true; default: return false; } } [MenuItem("GameObject/Align View to Camera Path Point", false, 1002)] public static void AlignCamera() { GameObject selected = Selection.activeGameObject; CameraPath camPath = selected.GetComponent<CameraPath>(); CameraPathAnimator animator = selected.GetComponent<CameraPathAnimator>(); Undo.RecordObject(camPath, "Align View to Camera Path Point"); if (camPath != null && animator != null) { switch (animator.orientationMode) { case CameraPathAnimator.orientationModes.custom: if (camPath.pointMode == CameraPath.PointModes.Orientations) { int selectedPoint = camPath.selectedPoint; CameraPathOrientation point = camPath.orientationList[selectedPoint]; GameObject tempPos = new GameObject("temp"); tempPos.transform.position = point.worldPosition; tempPos.transform.rotation = point.rotation; SceneView.currentDrawingSceneView.AlignViewToObject(tempPos.transform); DestroyImmediate(tempPos); } if (camPath.pointMode == CameraPath.PointModes.Transform || camPath.pointMode == CameraPath.PointModes.ControlPoints) { int selectedPoint = camPath.selectedPoint; CameraPathControlPoint cPoint = camPath[selectedPoint]; CameraPathOrientation point = (CameraPathOrientation)camPath.orientationList.GetPoint(cPoint); GameObject tempPos = new GameObject("temp"); tempPos.transform.position = cPoint.worldPosition; if(Camera.current != null) { Camera.current.transform.position = cPoint.worldPosition; } if(point != null) { tempPos.transform.rotation = point.rotation; } else { tempPos.transform.rotation = Quaternion.LookRotation(camPath.GetPathDirection(cPoint.percentage)); } SceneView.currentDrawingSceneView.AlignViewToObject(tempPos.transform); DestroyImmediate(tempPos); } break; default: if (camPath.pointMode == CameraPath.PointModes.Transform || camPath.pointMode == CameraPath.PointModes.ControlPoints) { int selectedPoint = camPath.selectedPoint; CameraPathControlPoint point = camPath[selectedPoint]; GameObject tempPos = new GameObject("temp"); tempPos.transform.position = point.worldPosition; tempPos.transform.rotation = Quaternion.LookRotation(point.forwardControlPoint.normalized); SceneView.currentDrawingSceneView.AlignViewToObject(tempPos.transform); DestroyImmediate(tempPos); } break; } } } // Validate the menu item defined by the function above. // The menu item will be disabled if this function returns false. [MenuItem("GameObject/Align View to Camera Path Point", true)] static bool ValidateAlignViewtoPathPoint() { GameObject selected = Selection.activeGameObject; if (selected == null) return false; CameraPath camPath = selected.GetComponent<CameraPath>(); if (camPath == null) return false; switch (camPath.pointMode) { case CameraPath.PointModes.ControlPoints: return true; case CameraPath.PointModes.Transform: return true; case CameraPath.PointModes.Orientations: return true; default: return false; } } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Text; using System.Reflection; namespace NDesk.DBus { //TODO: complete this class class Introspector { const string NAMESPACE = "http://www.freedesktop.org/standards/dbus"; const string PUBLIC_IDENTIFIER = "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"; const string SYSTEM_IDENTIFIER = "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"; public StringBuilder sb; public string xml; public ObjectPath root_path = ObjectPath.Root; protected XmlWriter writer; public Introspector () { XmlWriterSettings settings = new XmlWriterSettings (); settings.Indent = true; settings.IndentChars = (" "); settings.OmitXmlDeclaration = true; sb = new StringBuilder (); writer = XmlWriter.Create (sb, settings); } public void WriteStart () { writer.WriteDocType ("node", PUBLIC_IDENTIFIER, SYSTEM_IDENTIFIER, null); AssemblyName aname = Assembly.GetExecutingAssembly().GetName (); writer.WriteComment (" " + aname.Name + " " + aname.Version.ToString (3) + " "); //the root node element writer.WriteStartElement ("node"); } public void WriteNode (string name) { writer.WriteStartElement ("node"); writer.WriteAttributeString ("name", name); writer.WriteEndElement (); } public void WriteEnd () { /* WriteEnum (typeof (org.freedesktop.DBus.NameFlag)); WriteEnum (typeof (org.freedesktop.DBus.NameReply)); WriteEnum (typeof (org.freedesktop.DBus.ReleaseNameReply)); WriteEnum (typeof (org.freedesktop.DBus.StartReply)); WriteInterface (typeof (org.freedesktop.DBus.IBus)); */ writer.WriteEndElement (); writer.Flush (); xml = sb.ToString (); } //public void WriteNode () public void WriteType (Type target_type) { //writer.WriteStartElement ("node"); //TODO: non-well-known introspection has paths as well, which we don't do yet. read the spec again //hackishly just remove the root '/' to make the path relative for now //writer.WriteAttributeString ("name", target_path.Value.Substring (1)); //writer.WriteAttributeString ("name", "test"); //reflect our own interface manually WriteInterface (typeof (org.freedesktop.DBus.Introspectable)); //reflect the target interface if (target_type != null) { WriteInterface (target_type); foreach (Type ifType in target_type.GetInterfaces ()) WriteInterface (ifType); } //TODO: review recursion of interfaces and inheritance hierarchy //writer.WriteEndElement (); } public void WriteArg (ParameterInfo pi) { WriteArg (pi.ParameterType, Mapper.GetArgumentName (pi), pi.IsOut, false); } public void WriteArgReverse (ParameterInfo pi) { WriteArg (pi.ParameterType, Mapper.GetArgumentName (pi), pi.IsOut, true); } //TODO: clean up and get rid of reverse (or argIsOut) parm public void WriteArg (Type argType, string argName, bool argIsOut, bool reverse) { argType = argIsOut ? argType.GetElementType () : argType; if (argType == typeof (void)) return; writer.WriteStartElement ("arg"); if (!String.IsNullOrEmpty (argName)) writer.WriteAttributeString ("name", argName); //we can't rely on the default direction (qt-dbus requires a direction at time of writing), so we use a boolean to reverse the parameter direction and make it explicit if (argIsOut) writer.WriteAttributeString ("direction", !reverse ? "out" : "in"); else writer.WriteAttributeString ("direction", !reverse ? "in" : "out"); Signature sig = Signature.GetSig (argType); //TODO: avoid writing null (DType.Invalid) to the XML stream writer.WriteAttributeString ("type", sig.Value); //annotations aren't valid in an arg element, so this is disabled //if (argType.IsEnum) // WriteAnnotation ("org.ndesk.DBus.Enum", Mapper.GetInterfaceName (argType)); writer.WriteEndElement (); } public void WriteMethod (MethodInfo mi) { writer.WriteStartElement ("method"); writer.WriteAttributeString ("name", mi.Name); foreach (ParameterInfo pi in mi.GetParameters ()) WriteArg (pi); //Mono <= 1.1.13 doesn't support MethodInfo.ReturnParameter, so avoid it //WriteArgReverse (mi.ReturnParameter); WriteArg (mi.ReturnType, Mapper.GetArgumentName (mi.ReturnTypeCustomAttributes, "ret"), false, true); WriteAnnotations (mi); writer.WriteEndElement (); } public void WriteProperty (PropertyInfo pri) { //expose properties as dbus properties writer.WriteStartElement ("property"); writer.WriteAttributeString ("name", pri.Name); writer.WriteAttributeString ("type", Signature.GetSig (pri.PropertyType).Value); string access = (pri.CanRead ? "read" : String.Empty) + (pri.CanWrite ? "write" : String.Empty); writer.WriteAttributeString ("access", access); WriteAnnotations (pri); writer.WriteEndElement (); //expose properties as methods also //it may not be worth doing this in the long run /* if (pri.CanRead) { writer.WriteStartElement ("method"); writer.WriteAttributeString ("name", "Get" + pri.Name); WriteArgReverse (pri.GetGetMethod ().ReturnParameter); writer.WriteEndElement (); } if (pri.CanWrite) { writer.WriteStartElement ("method"); writer.WriteAttributeString ("name", "Set" + pri.Name); foreach (ParameterInfo pi in pri.GetSetMethod ().GetParameters ()) WriteArg (pi); writer.WriteEndElement (); } */ } public void WriteSignal (EventInfo ei) { writer.WriteStartElement ("signal"); writer.WriteAttributeString ("name", ei.Name); foreach (ParameterInfo pi in ei.EventHandlerType.GetMethod ("Invoke").GetParameters ()) WriteArgReverse (pi); WriteAnnotations (ei); //no need to consider the delegate return value as dbus doesn't support it writer.WriteEndElement (); } const BindingFlags relevantBindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; public void WriteInterface (Type type) { if (type == null) return; //TODO: this is unreliable, fix it if (!Mapper.IsPublic (type)) return; writer.WriteStartElement ("interface"); writer.WriteAttributeString ("name", Mapper.GetInterfaceName (type)); /* foreach (MemberInfo mbi in type.GetMembers (relevantBindingFlags)) { switch (mbi.MemberType) { case MemberTypes.Method: if (!((MethodInfo)mbi).IsSpecialName) WriteMethod ((MethodInfo)mbi); break; case MemberTypes.Event: WriteSignal ((EventInfo)mbi); break; case MemberTypes.Property: WriteProperty ((PropertyInfo)mbi); break; default: Console.Error.WriteLine ("Warning: Unhandled MemberType '{0}' encountered while introspecting {1}", mbi.MemberType, type.FullName); break; } } */ foreach (MethodInfo mi in type.GetMethods (relevantBindingFlags)) if (!mi.IsSpecialName) WriteMethod (mi); foreach (EventInfo ei in type.GetEvents (relevantBindingFlags)) WriteSignal (ei); foreach (PropertyInfo pri in type.GetProperties (relevantBindingFlags)) WriteProperty (pri); //TODO: indexers //TODO: attributes as annotations? writer.WriteEndElement (); //this recursion seems somewhat inelegant WriteInterface (type.BaseType); } public void WriteAnnotations (ICustomAttributeProvider attrProvider) { if (Mapper.IsDeprecated (attrProvider)) WriteAnnotation ("org.freedesktop.DBus.Deprecated", "true"); } public void WriteAnnotation (string name, string value) { writer.WriteStartElement ("annotation"); writer.WriteAttributeString ("name", name); writer.WriteAttributeString ("value", value); writer.WriteEndElement (); } //this is not in the spec, and is not finalized public void WriteEnum (Type type) { writer.WriteStartElement ("enum"); writer.WriteAttributeString ("name", Mapper.GetInterfaceName (type)); writer.WriteAttributeString ("type", Signature.GetSig (type.GetElementType ()).Value); writer.WriteAttributeString ("flags", (type.IsDefined (typeof (FlagsAttribute), false)) ? "true" : "false"); string[] names = Enum.GetNames (type); int i = 0; foreach (Enum val in Enum.GetValues (type)) { writer.WriteStartElement ("element"); writer.WriteAttributeString ("name", names[i++]); writer.WriteAttributeString ("value", val.ToString ("d")); writer.WriteEndElement (); } writer.WriteEndElement (); } } }
// 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 gagve = Google.Ads.GoogleAds.V8.Enums; 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 GeneratedCampaignAssetServiceClientTest { [Category("Autogenerated")][Test] public void GetCampaignAssetRequestObject() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); GetCampaignAssetRequest request = new GetCampaignAssetRequest { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), }; gagvr::CampaignAsset expectedResponse = new gagvr::CampaignAsset { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo, Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaignAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignAsset response = client.GetCampaignAsset(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignAssetRequestObjectAsync() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); GetCampaignAssetRequest request = new GetCampaignAssetRequest { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), }; gagvr::CampaignAsset expectedResponse = new gagvr::CampaignAsset { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo, Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaignAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignAsset responseCallSettings = await client.GetCampaignAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignAsset responseCancellationToken = await client.GetCampaignAssetAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCampaignAsset() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); GetCampaignAssetRequest request = new GetCampaignAssetRequest { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), }; gagvr::CampaignAsset expectedResponse = new gagvr::CampaignAsset { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo, Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaignAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignAsset response = client.GetCampaignAsset(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignAssetAsync() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); GetCampaignAssetRequest request = new GetCampaignAssetRequest { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), }; gagvr::CampaignAsset expectedResponse = new gagvr::CampaignAsset { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo, Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaignAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignAsset responseCallSettings = await client.GetCampaignAssetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignAsset responseCancellationToken = await client.GetCampaignAssetAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCampaignAssetResourceNames() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); GetCampaignAssetRequest request = new GetCampaignAssetRequest { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), }; gagvr::CampaignAsset expectedResponse = new gagvr::CampaignAsset { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo, Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaignAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignAsset response = client.GetCampaignAsset(request.ResourceNameAsCampaignAssetName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignAssetResourceNamesAsync() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); GetCampaignAssetRequest request = new GetCampaignAssetRequest { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), }; gagvr::CampaignAsset expectedResponse = new gagvr::CampaignAsset { ResourceNameAsCampaignAssetName = gagvr::CampaignAssetName.FromCustomerCampaignAssetFieldType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[ASSET_ID]", "[FIELD_TYPE]"), FieldType = gagve::AssetFieldTypeEnum.Types.AssetFieldType.YoutubeVideo, Status = gagve::AssetLinkStatusEnum.Types.AssetLinkStatus.Paused, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), AssetAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; mockGrpcClient.Setup(x => x.GetCampaignAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignAsset>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignAsset responseCallSettings = await client.GetCampaignAssetAsync(request.ResourceNameAsCampaignAssetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignAsset responseCancellationToken = await client.GetCampaignAssetAsync(request.ResourceNameAsCampaignAssetName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCampaignAssetsRequestObject() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); MutateCampaignAssetsRequest request = new MutateCampaignAssetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignAssetOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignAssetsResponse expectedResponse = new MutateCampaignAssetsResponse { PartialFailureError = new gr::Status(), Results = { new MutateCampaignAssetResult(), }, }; mockGrpcClient.Setup(x => x.MutateCampaignAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignAssetsResponse response = client.MutateCampaignAssets(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCampaignAssetsRequestObjectAsync() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); MutateCampaignAssetsRequest request = new MutateCampaignAssetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignAssetOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignAssetsResponse expectedResponse = new MutateCampaignAssetsResponse { PartialFailureError = new gr::Status(), Results = { new MutateCampaignAssetResult(), }, }; mockGrpcClient.Setup(x => x.MutateCampaignAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignAssetsResponse responseCallSettings = await client.MutateCampaignAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignAssetsResponse responseCancellationToken = await client.MutateCampaignAssetsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCampaignAssets() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); MutateCampaignAssetsRequest request = new MutateCampaignAssetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignAssetOperation(), }, }; MutateCampaignAssetsResponse expectedResponse = new MutateCampaignAssetsResponse { PartialFailureError = new gr::Status(), Results = { new MutateCampaignAssetResult(), }, }; mockGrpcClient.Setup(x => x.MutateCampaignAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignAssetsResponse response = client.MutateCampaignAssets(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCampaignAssetsAsync() { moq::Mock<CampaignAssetService.CampaignAssetServiceClient> mockGrpcClient = new moq::Mock<CampaignAssetService.CampaignAssetServiceClient>(moq::MockBehavior.Strict); MutateCampaignAssetsRequest request = new MutateCampaignAssetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignAssetOperation(), }, }; MutateCampaignAssetsResponse expectedResponse = new MutateCampaignAssetsResponse { PartialFailureError = new gr::Status(), Results = { new MutateCampaignAssetResult(), }, }; mockGrpcClient.Setup(x => x.MutateCampaignAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignAssetServiceClient client = new CampaignAssetServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignAssetsResponse responseCallSettings = await client.MutateCampaignAssetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignAssetsResponse responseCancellationToken = await client.MutateCampaignAssetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>PipelineJob</c> resource.</summary> public sealed partial class PipelineJobName : gax::IResourceName, sys::IEquatable<PipelineJobName> { /// <summary>The possible contents of <see cref="PipelineJobName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>. /// </summary> ProjectLocationPipelineJob = 1, } private static gax::PathTemplate s_projectLocationPipelineJob = new gax::PathTemplate("projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}"); /// <summary>Creates a <see cref="PipelineJobName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="PipelineJobName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static PipelineJobName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new PipelineJobName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="PipelineJobName"/> with the pattern /// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="pipelineJobId">The <c>PipelineJob</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="PipelineJobName"/> constructed from the provided ids.</returns> public static PipelineJobName FromProjectLocationPipelineJob(string projectId, string locationId, string pipelineJobId) => new PipelineJobName(ResourceNameType.ProjectLocationPipelineJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), pipelineJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(pipelineJobId, nameof(pipelineJobId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="PipelineJobName"/> with pattern /// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="pipelineJobId">The <c>PipelineJob</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PipelineJobName"/> with pattern /// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>. /// </returns> public static string Format(string projectId, string locationId, string pipelineJobId) => FormatProjectLocationPipelineJob(projectId, locationId, pipelineJobId); /// <summary> /// Formats the IDs into the string representation of this <see cref="PipelineJobName"/> with pattern /// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="pipelineJobId">The <c>PipelineJob</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PipelineJobName"/> with pattern /// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c>. /// </returns> public static string FormatProjectLocationPipelineJob(string projectId, string locationId, string pipelineJobId) => s_projectLocationPipelineJob.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(pipelineJobId, nameof(pipelineJobId))); /// <summary>Parses the given resource name string into a new <see cref="PipelineJobName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c></description> /// </item> /// </list> /// </remarks> /// <param name="pipelineJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="PipelineJobName"/> if successful.</returns> public static PipelineJobName Parse(string pipelineJobName) => Parse(pipelineJobName, false); /// <summary> /// Parses the given resource name string into a new <see cref="PipelineJobName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="pipelineJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="PipelineJobName"/> if successful.</returns> public static PipelineJobName Parse(string pipelineJobName, bool allowUnparsed) => TryParse(pipelineJobName, allowUnparsed, out PipelineJobName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PipelineJobName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c></description> /// </item> /// </list> /// </remarks> /// <param name="pipelineJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="PipelineJobName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string pipelineJobName, out PipelineJobName result) => TryParse(pipelineJobName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PipelineJobName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="pipelineJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="PipelineJobName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string pipelineJobName, bool allowUnparsed, out PipelineJobName result) { gax::GaxPreconditions.CheckNotNull(pipelineJobName, nameof(pipelineJobName)); gax::TemplatedResourceName resourceName; if (s_projectLocationPipelineJob.TryParseName(pipelineJobName, out resourceName)) { result = FromProjectLocationPipelineJob(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(pipelineJobName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private PipelineJobName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string pipelineJobId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; PipelineJobId = pipelineJobId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="PipelineJobName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="pipelineJobId">The <c>PipelineJob</c> ID. Must not be <c>null</c> or empty.</param> public PipelineJobName(string projectId, string locationId, string pipelineJobId) : this(ResourceNameType.ProjectLocationPipelineJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), pipelineJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(pipelineJobId, nameof(pipelineJobId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>PipelineJob</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string PipelineJobId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationPipelineJob: return s_projectLocationPipelineJob.Expand(ProjectId, LocationId, PipelineJobId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as PipelineJobName); /// <inheritdoc/> public bool Equals(PipelineJobName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(PipelineJobName a, PipelineJobName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(PipelineJobName a, PipelineJobName b) => !(a == b); } /// <summary>Resource name for the <c>Network</c> resource.</summary> public sealed partial class NetworkName : gax::IResourceName, sys::IEquatable<NetworkName> { /// <summary>The possible contents of <see cref="NetworkName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/global/networks/{network}</c>.</summary> ProjectNetwork = 1, } private static gax::PathTemplate s_projectNetwork = new gax::PathTemplate("projects/{project}/global/networks/{network}"); /// <summary>Creates a <see cref="NetworkName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="NetworkName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static NetworkName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new NetworkName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="NetworkName"/> with the pattern <c>projects/{project}/global/networks/{network}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="networkId">The <c>Network</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="NetworkName"/> constructed from the provided ids.</returns> public static NetworkName FromProjectNetwork(string projectId, string networkId) => new NetworkName(ResourceNameType.ProjectNetwork, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), networkId: gax::GaxPreconditions.CheckNotNullOrEmpty(networkId, nameof(networkId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="NetworkName"/> with pattern /// <c>projects/{project}/global/networks/{network}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="networkId">The <c>Network</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="NetworkName"/> with pattern /// <c>projects/{project}/global/networks/{network}</c>. /// </returns> public static string Format(string projectId, string networkId) => FormatProjectNetwork(projectId, networkId); /// <summary> /// Formats the IDs into the string representation of this <see cref="NetworkName"/> with pattern /// <c>projects/{project}/global/networks/{network}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="networkId">The <c>Network</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="NetworkName"/> with pattern /// <c>projects/{project}/global/networks/{network}</c>. /// </returns> public static string FormatProjectNetwork(string projectId, string networkId) => s_projectNetwork.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(networkId, nameof(networkId))); /// <summary>Parses the given resource name string into a new <see cref="NetworkName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/global/networks/{network}</c></description></item> /// </list> /// </remarks> /// <param name="networkName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="NetworkName"/> if successful.</returns> public static NetworkName Parse(string networkName) => Parse(networkName, false); /// <summary> /// Parses the given resource name string into a new <see cref="NetworkName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/global/networks/{network}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="networkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="NetworkName"/> if successful.</returns> public static NetworkName Parse(string networkName, bool allowUnparsed) => TryParse(networkName, allowUnparsed, out NetworkName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="NetworkName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/global/networks/{network}</c></description></item> /// </list> /// </remarks> /// <param name="networkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="NetworkName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string networkName, out NetworkName result) => TryParse(networkName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="NetworkName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/global/networks/{network}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="networkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="NetworkName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string networkName, bool allowUnparsed, out NetworkName result) { gax::GaxPreconditions.CheckNotNull(networkName, nameof(networkName)); gax::TemplatedResourceName resourceName; if (s_projectNetwork.TryParseName(networkName, out resourceName)) { result = FromProjectNetwork(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(networkName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private NetworkName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string networkId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; NetworkId = networkId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="NetworkName"/> class from the component parts of pattern /// <c>projects/{project}/global/networks/{network}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="networkId">The <c>Network</c> ID. Must not be <c>null</c> or empty.</param> public NetworkName(string projectId, string networkId) : this(ResourceNameType.ProjectNetwork, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), networkId: gax::GaxPreconditions.CheckNotNullOrEmpty(networkId, nameof(networkId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Network</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string NetworkId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectNetwork: return s_projectNetwork.Expand(ProjectId, NetworkId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as NetworkName); /// <inheritdoc/> public bool Equals(NetworkName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(NetworkName a, NetworkName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(NetworkName a, NetworkName b) => !(a == b); } public partial class PipelineJob { /// <summary> /// <see cref="gcav::PipelineJobName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::PipelineJobName PipelineJobName { get => string.IsNullOrEmpty(Name) ? null : gcav::PipelineJobName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="NetworkName"/>-typed view over the <see cref="Network"/> resource name property. /// </summary> public NetworkName NetworkAsNetworkName { get => string.IsNullOrEmpty(Network) ? null : NetworkName.Parse(Network, allowUnparsed: true); set => Network = value?.ToString() ?? ""; } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Matthew Ward" email="mrward@users.sourceforge.net"/> // <version>$Revision: 1965 $</version> // </file> using ICSharpCode.AvalonEdit.CodeCompletion; using System; using System.Collections.Generic; using System.IO; namespace InnovatorAdmin.Editor { /// <summary> /// A collection that stores <see cref='XmlSchemaCompletionData'/> objects. /// </summary> [Serializable()] public class XmlSchemaCompletionDataCollection : System.Collections.CollectionBase { /// <summary> /// Initializes a new instance of <see cref='XmlSchemaCompletionDataCollection'/>. /// </summary> public XmlSchemaCompletionDataCollection() { } /// <summary> /// Initializes a new instance of <see cref='XmlSchemaCompletionDataCollection'/> based on another <see cref='XmlSchemaCompletionDataCollection'/>. /// </summary> /// <param name='val'> /// A <see cref='XmlSchemaCompletionDataCollection'/> from which the contents are copied /// </param> public XmlSchemaCompletionDataCollection(XmlSchemaCompletionDataCollection val) { this.AddRange(val); } /// <summary> /// Initializes a new instance of <see cref='XmlSchemaCompletionDataCollection'/> containing any array of <see cref='XmlSchemaCompletionData'/> objects. /// </summary> /// <param name='val'> /// A array of <see cref='XmlSchemaCompletionData'/> objects with which to intialize the collection /// </param> public XmlSchemaCompletionDataCollection(XmlSchemaCompletionData[] val) { this.AddRange(val); } /// <summary> /// Represents the entry at the specified index of the <see cref='XmlSchemaCompletionData'/>. /// </summary> /// <param name='index'>The zero-based index of the entry to locate in the collection.</param> /// <value>The entry at the specified index of the collection.</value> /// <exception cref='ArgumentOutOfRangeException'><paramref name='index'/> is outside the valid range of indexes for the collection.</exception> public XmlSchemaCompletionData this[int index] { get { return ((XmlSchemaCompletionData)(List[index])); } set { List[index] = value; } } public ICompletionData[] GetNamespaceCompletionData() { List<ICompletionData> completionItems = new List<ICompletionData>(); foreach (XmlSchemaCompletionData schema in this) { XmlCompletionData completionData = new XmlCompletionData(schema.NamespaceUri, XmlCompletionData.DataType.NamespaceUri); completionItems.Add(completionData); } return completionItems.ToArray(); } /// <summary> /// Represents the <see cref='XmlSchemaCompletionData'/> entry with the specified namespace URI. /// </summary> /// <param name='namespaceUri'>The schema's namespace URI.</param> /// <value>The entry with the specified namespace URI.</value> public XmlSchemaCompletionData this[string namespaceUri] { get { return GetItem(namespaceUri); } } /// <summary> /// Adds a <see cref='XmlSchemaCompletionData'/> with the specified value to the /// <see cref='XmlSchemaCompletionDataCollection'/>. /// </summary> /// <param name='val'>The <see cref='XmlSchemaCompletionData'/> to add.</param> /// <returns>The index at which the new element was inserted.</returns> /// <seealso cref='XmlSchemaCompletionDataCollection.AddRange'/> public int Add(XmlSchemaCompletionData val) { return List.Add(val); } /// <summary> /// Copies the elements of an array to the end of the <see cref='XmlSchemaCompletionDataCollection'/>. /// </summary> /// <param name='val'> /// An array of type <see cref='XmlSchemaCompletionData'/> containing the objects to add to the collection. /// </param> /// <seealso cref='XmlSchemaCompletionDataCollection.Add'/> public void AddRange(XmlSchemaCompletionData[] val) { for (int i = 0; i < val.Length; i++) { this.Add(val[i]); } } /// <summary> /// Adds the contents of another <see cref='XmlSchemaCompletionDataCollection'/> to the end of the collection. /// </summary> /// <param name='val'> /// A <see cref='XmlSchemaCompletionDataCollection'/> containing the objects to add to the collection. /// </param> /// <seealso cref='XmlSchemaCompletionDataCollection.Add'/> public void AddRange(XmlSchemaCompletionDataCollection val) { for (int i = 0; i < val.Count; i++) { this.Add(val[i]); } } /// <summary> /// Gets a value indicating whether the /// <see cref='XmlSchemaCompletionDataCollection'/> contains the specified <see cref='XmlSchemaCompletionData'/>. /// </summary> /// <param name='val'>The <see cref='XmlSchemaCompletionData'/> to locate.</param> /// <returns> /// <see langword='true'/> if the <see cref='XmlSchemaCompletionData'/> is contained in the collection; /// otherwise, <see langword='false'/>. /// </returns> /// <seealso cref='XmlSchemaCompletionDataCollection.IndexOf'/> public bool Contains(XmlSchemaCompletionData val) { return List.Contains(val); } /// <summary> /// Copies the <see cref='XmlSchemaCompletionDataCollection'/> values to a one-dimensional <see cref='Array'/> instance at the /// specified index. /// </summary> /// <param name='array'>The one-dimensional <see cref='Array'/> that is the destination of the values copied from <see cref='XmlSchemaCompletionDataCollection'/>.</param> /// <param name='index'>The index in <paramref name='array'/> where copying begins.</param> /// <exception cref='ArgumentException'> /// <para><paramref name='array'/> is multidimensional.</para> /// <para>-or-</para> /// <para>The number of elements in the <see cref='XmlSchemaCompletionDataCollection'/> is greater than /// the available space between <paramref name='arrayIndex'/> and the end of /// <paramref name='array'/>.</para> /// </exception> /// <exception cref='ArgumentNullException'><paramref name='array'/> is <see langword='null'/>. </exception> /// <exception cref='ArgumentOutOfRangeException'><paramref name='arrayIndex'/> is less than <paramref name='array'/>'s lowbound. </exception> /// <seealso cref='Array'/> public void CopyTo(XmlSchemaCompletionData[] array, int index) { List.CopyTo(array, index); } /// <summary> /// Returns the index of a <see cref='XmlSchemaCompletionData'/> in /// the <see cref='XmlSchemaCompletionDataCollection'/>. /// </summary> /// <param name='val'>The <see cref='XmlSchemaCompletionData'/> to locate.</param> /// <returns> /// The index of the <see cref='XmlSchemaCompletionData'/> of <paramref name='val'/> in the /// <see cref='XmlSchemaCompletionDataCollection'/>, if found; otherwise, -1. /// </returns> /// <seealso cref='XmlSchemaCompletionDataCollection.Contains'/> public int IndexOf(XmlSchemaCompletionData val) { return List.IndexOf(val); } /// <summary> /// Inserts a <see cref='XmlSchemaCompletionData'/> into the <see cref='XmlSchemaCompletionDataCollection'/> at the specified index. /// </summary> /// <param name='index'>The zero-based index where <paramref name='val'/> should be inserted.</param> /// <param name='val'>The <see cref='XmlSchemaCompletionData'/> to insert.</param> /// <seealso cref='XmlSchemaCompletionDataCollection.Add'/> public void Insert(int index, XmlSchemaCompletionData val) { List.Insert(index, val); } /// <summary> /// Returns an enumerator that can iterate through the <see cref='XmlSchemaCompletionDataCollection'/>. /// </summary> /// <seealso cref='IEnumerator'/> public new XmlSchemaCompletionDataEnumerator GetEnumerator() { return new XmlSchemaCompletionDataEnumerator(this); } /// <summary> /// Removes a specific <see cref='XmlSchemaCompletionData'/> from the <see cref='XmlSchemaCompletionDataCollection'/>. /// </summary> /// <param name='val'>The <see cref='XmlSchemaCompletionData'/> to remove from the <see cref='XmlSchemaCompletionDataCollection'/>.</param> /// <exception cref='ArgumentException'><paramref name='val'/> is not found in the Collection.</exception> public void Remove(XmlSchemaCompletionData val) { List.Remove(val); } /// <summary> /// Gets the schema completion data with the same filename. /// </summary> /// <returns><see langword="null"/> if no matching schema found.</returns> public XmlSchemaCompletionData GetSchemaFromFileName(string fileName) { foreach (XmlSchemaCompletionData schema in this) { if (XmlSchemaCompletionDataCollection.IsEqualFileName(schema.FileName, fileName)) { return schema; } } return null; } /// <summary> /// Enumerator that can iterate through a XmlSchemaCompletionDataCollection. /// </summary> /// <seealso cref='IEnumerator'/> /// <seealso cref='XmlSchemaCompletionDataCollection'/> /// <seealso cref='XmlSchemaCompletionData'/> public class XmlSchemaCompletionDataEnumerator : System.Collections.IEnumerator { System.Collections.IEnumerator baseEnumerator; System.Collections.IEnumerable temp; /// <summary> /// Initializes a new instance of <see cref='XmlSchemaCompletionDataEnumerator'/>. /// </summary> public XmlSchemaCompletionDataEnumerator(XmlSchemaCompletionDataCollection mappings) { this.temp = ((System.Collections.IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } /// <summary> /// Gets the current <see cref='XmlSchemaCompletionData'/> in the <seealso cref='XmlSchemaCompletionDataCollection'/>. /// </summary> public XmlSchemaCompletionData Current { get { return ((XmlSchemaCompletionData)(baseEnumerator.Current)); } } object System.Collections.IEnumerator.Current { get { return baseEnumerator.Current; } } /// <summary> /// Advances the enumerator to the next <see cref='XmlSchemaCompletionData'/> of the <see cref='XmlSchemaCompletionDataCollection'/>. /// </summary> public bool MoveNext() { return baseEnumerator.MoveNext(); } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the <see cref='XmlSchemaCompletionDataCollection'/>. /// </summary> public void Reset() { baseEnumerator.Reset(); } } XmlSchemaCompletionData GetItem(string namespaceUri) { XmlSchemaCompletionData matchedItem = null; foreach(XmlSchemaCompletionData item in this) { if (item.NamespaceUri == namespaceUri) { matchedItem = item; break; } } return matchedItem; } public static bool IsEqualFileName(string fileName1, string fileName2) { // Optimized for performance: //return Path.GetFullPath(fileName1.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)).ToLower() == Path.GetFullPath(fileName2.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)).ToLower(); if (string.IsNullOrEmpty(fileName1) || string.IsNullOrEmpty(fileName2)) return false; char lastChar; lastChar = fileName1[fileName1.Length - 1]; if (lastChar == Path.DirectorySeparatorChar || lastChar == Path.AltDirectorySeparatorChar) fileName1 = fileName1.Substring(0, fileName1.Length - 1); lastChar = fileName2[fileName2.Length - 1]; if (lastChar == Path.DirectorySeparatorChar || lastChar == Path.AltDirectorySeparatorChar) fileName2 = fileName2.Substring(0, fileName2.Length - 1); try { if (fileName1.Length < 2 || fileName1[1] != ':' || fileName1.IndexOf("/.") >= 0 || fileName1.IndexOf("\\.") >= 0) fileName1 = Path.GetFullPath(fileName1); if (fileName2.Length < 2 || fileName2[1] != ':' || fileName2.IndexOf("/.") >= 0 || fileName2.IndexOf("\\.") >= 0) fileName2 = Path.GetFullPath(fileName2); } catch (Exception) { } return string.Equals(fileName1, fileName2, StringComparison.OrdinalIgnoreCase); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Net; using System.Reflection; using Azure.Identity; using Azure.Messaging.EventHubs; using Azure.Messaging.EventHubs.Consumer; using Azure.Messaging.EventHubs.Primitives; using Azure.Messaging.EventHubs.Processor; using Azure.Messaging.EventHubs.Producer; using Azure.Storage.Blobs; using Microsoft.Azure.WebJobs.EventHubs.Processor; using Microsoft.Extensions.Azure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; namespace Microsoft.Azure.WebJobs.EventHubs.UnitTests { public class EventHubsClientFactoryTests { private const string ConnectionString = "Endpoint=sb://test89123-ns-x.servicebus.windows.net/;SharedAccessKeyName=ReceiveRule;SharedAccessKey=secretkey"; private const string ConnectionStringWithEventHub = "Endpoint=sb://test89123-ns-x.servicebus.windows.net/;SharedAccessKeyName=ReceiveRule;SharedAccessKey=secretkey;EntityPath=path2"; // Validate that if connection string has EntityPath, that takes precedence over the parameter. [TestCase("k1", ConnectionString)] [TestCase("path2", ConnectionStringWithEventHub)] public void GetEventHubClient_AddsConnection(string expectedPathName, string connectionString) { EventHubOptions options = new EventHubOptions(); var configuration = CreateConfiguration(new KeyValuePair<string, string>("connection", connectionString)); var factory = new EventHubClientFactory(configuration, Mock.Of<AzureComponentFactory>(), Options.Create(options), new DefaultNameResolver(configuration), new AzureEventSourceLogForwarder(new NullLoggerFactory())); var client = factory.GetEventHubProducerClient(expectedPathName, "connection"); Assert.AreEqual(expectedPathName, client.EventHubName); } [Test] public void CreatesClientsFromConfigWithConnectionString() { EventHubOptions options = new EventHubOptions(); var configuration = CreateConfiguration(new KeyValuePair<string, string>("connection", ConnectionString)); var factory = new EventHubClientFactory(configuration, Mock.Of<AzureComponentFactory>(), Options.Create(options), new DefaultNameResolver(configuration), new AzureEventSourceLogForwarder(new NullLoggerFactory())); var producer = factory.GetEventHubProducerClient("k1", "connection"); var consumer = factory.GetEventHubConsumerClient("k1", "connection", null); var host = factory.GetEventProcessorHost("k1", "connection", null); Assert.AreEqual("k1", producer.EventHubName); Assert.AreEqual("k1", consumer.EventHubName); Assert.AreEqual("k1", host.EventHubName); Assert.AreEqual("test89123-ns-x.servicebus.windows.net", producer.FullyQualifiedNamespace); Assert.AreEqual("test89123-ns-x.servicebus.windows.net", consumer.FullyQualifiedNamespace); Assert.AreEqual("test89123-ns-x.servicebus.windows.net", host.FullyQualifiedNamespace); } [Test] public void CreatesClientsFromConfigWithFullyQualifiedNamespace() { EventHubOptions options = new EventHubOptions(); var componentFactoryMock = new Mock<AzureComponentFactory>(); componentFactoryMock.Setup(c => c.CreateTokenCredential( It.Is<IConfiguration>(c=> c["fullyQualifiedNamespace"] != null))) .Returns(new DefaultAzureCredential()); var configuration = CreateConfiguration(new KeyValuePair<string, string>("connection:fullyQualifiedNamespace", "test89123-ns-x.servicebus.windows.net")); var factory = new EventHubClientFactory(configuration, componentFactoryMock.Object, Options.Create(options), new DefaultNameResolver(configuration), new AzureEventSourceLogForwarder(new NullLoggerFactory())); var producer = factory.GetEventHubProducerClient("k1", "connection"); var consumer = factory.GetEventHubConsumerClient("k1", "connection", null); var host = factory.GetEventProcessorHost("k1", "connection", null); Assert.AreEqual("k1", producer.EventHubName); Assert.AreEqual("k1", consumer.EventHubName); Assert.AreEqual("k1", host.EventHubName); Assert.AreEqual("test89123-ns-x.servicebus.windows.net", producer.FullyQualifiedNamespace); Assert.AreEqual("test89123-ns-x.servicebus.windows.net", consumer.FullyQualifiedNamespace); Assert.AreEqual("test89123-ns-x.servicebus.windows.net", host.FullyQualifiedNamespace); } [Test] public void ConsumersAndProducersAreCached() { EventHubOptions options = new EventHubOptions(); var configuration = CreateConfiguration(new KeyValuePair<string, string>("connection", ConnectionString)); var factory = new EventHubClientFactory(configuration, Mock.Of<AzureComponentFactory>(), Options.Create(options), new DefaultNameResolver(configuration), new AzureEventSourceLogForwarder(new NullLoggerFactory())); var producer = factory.GetEventHubProducerClient("k1", "connection"); var consumer = factory.GetEventHubConsumerClient("k1", "connection", null); var producer2 = factory.GetEventHubProducerClient("k1", "connection"); var consumer2 = factory.GetEventHubConsumerClient("k1", "connection", null); Assert.AreSame(producer, producer2); Assert.AreSame(consumer, consumer2); } [Test] public void UsesDefaultConnectionToStorageAccount() { EventHubOptions options = new EventHubOptions(); var configuration = CreateConfiguration(new KeyValuePair<string, string>("AzureWebJobsStorage", "UseDevelopmentStorage=true")); var factoryMock = new Mock<AzureComponentFactory>(); factoryMock.Setup(m => m.CreateClient( typeof(BlobServiceClient), It.Is<ConfigurationSection>(c => c.Path == "AzureWebJobsStorage"), null, null)) .Returns(new BlobServiceClient(configuration["AzureWebJobsStorage"])); var factory = new EventHubClientFactory(configuration, factoryMock.Object, Options.Create(options), new DefaultNameResolver(configuration), new AzureEventSourceLogForwarder(new NullLoggerFactory())); var client = factory.GetCheckpointStoreClient(); Assert.AreEqual("azure-webjobs-eventhub", client.Name); Assert.AreEqual("devstoreaccount1", client.AccountName); } [TestCase("k1", ConnectionString)] [TestCase("path2", ConnectionStringWithEventHub)] public void RespectsConnectionOptionsForProducer(string expectedPathName, string connectionString) { var testEndpoint = new Uri("http://mycustomendpoint.com"); EventHubOptions options = new EventHubOptions { CustomEndpointAddress = testEndpoint, ClientRetryOptions = new EventHubsRetryOptions { MaximumRetries = 10 } }; var configuration = CreateConfiguration(new KeyValuePair<string, string>("connection", connectionString)); var factory = new EventHubClientFactory(configuration, Mock.Of<AzureComponentFactory>(), Options.Create(options), new DefaultNameResolver(configuration), new AzureEventSourceLogForwarder(new NullLoggerFactory())); var producer = factory.GetEventHubProducerClient(expectedPathName, "connection"); EventHubConnection connection = (EventHubConnection)typeof(EventHubProducerClient).GetProperty("Connection", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(producer); EventHubConnectionOptions connectionOptions = (EventHubConnectionOptions)typeof(EventHubConnection).GetProperty("Options", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(connection); Assert.AreEqual(testEndpoint, connectionOptions.CustomEndpointAddress); Assert.AreEqual(expectedPathName, producer.EventHubName); EventHubProducerClientOptions producerOptions = (EventHubProducerClientOptions)typeof(EventHubProducerClient).GetProperty("Options", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(producer); Assert.AreEqual(10, producerOptions.RetryOptions.MaximumRetries); Assert.AreEqual(expectedPathName, producer.EventHubName); } [TestCase("k1", ConnectionString)] [TestCase("path2", ConnectionStringWithEventHub)] public void RespectsConnectionOptionsForConsumer(string expectedPathName, string connectionString) { var testEndpoint = new Uri("http://mycustomendpoint.com"); EventHubOptions options = new EventHubOptions { CustomEndpointAddress = testEndpoint, ClientRetryOptions = new EventHubsRetryOptions { MaximumRetries = 10 } }; var configuration = CreateConfiguration(new KeyValuePair<string, string>("connection", connectionString)); var factory = new EventHubClientFactory(configuration, Mock.Of<AzureComponentFactory>(), Options.Create(options), new DefaultNameResolver(configuration), new AzureEventSourceLogForwarder(new NullLoggerFactory())); var consumer = factory.GetEventHubConsumerClient(expectedPathName, "connection", "consumer"); var consumerClient = (EventHubConsumerClient)typeof(EventHubConsumerClientImpl) .GetField("_client", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(consumer); EventHubConnection connection = (EventHubConnection)typeof(EventHubConsumerClient) .GetProperty("Connection", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(consumerClient); EventHubConnectionOptions connectionOptions = (EventHubConnectionOptions)typeof(EventHubConnection) .GetProperty("Options", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(connection); Assert.AreEqual(testEndpoint, connectionOptions.CustomEndpointAddress); EventHubsRetryPolicy retryPolicy = (EventHubsRetryPolicy)typeof(EventHubConsumerClient) .GetProperty("RetryPolicy", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(consumerClient); // Reflection was still necessary here because BasicRetryOptions (which is the concrete derived type) // is internal. EventHubsRetryOptions retryOptions = (EventHubsRetryOptions)retryPolicy.GetType() .GetProperty("Options", BindingFlags.Public | BindingFlags.Instance) .GetValue(retryPolicy); Assert.AreEqual(10, retryOptions.MaximumRetries); Assert.AreEqual(expectedPathName, consumer.EventHubName); } [TestCase("k1", ConnectionString)] [TestCase("path2", ConnectionStringWithEventHub)] public void RespectsConnectionOptionsForProcessor(string expectedPathName, string connectionString) { var testEndpoint = new Uri("http://mycustomendpoint.com"); EventHubOptions options = new EventHubOptions { CustomEndpointAddress = testEndpoint, TransportType = EventHubsTransportType.AmqpWebSockets, WebProxy = new WebProxy("http://proxyserver/"), ClientRetryOptions = new EventHubsRetryOptions { MaximumRetries = 10 } }; var configuration = CreateConfiguration(new KeyValuePair<string, string>("connection", connectionString)); var factory = new EventHubClientFactory(configuration, Mock.Of<AzureComponentFactory>(), Options.Create(options), new DefaultNameResolver(configuration), new AzureEventSourceLogForwarder(new NullLoggerFactory())); var processor = factory.GetEventProcessorHost(expectedPathName, "connection", "consumer"); EventProcessorOptions processorOptions = (EventProcessorOptions)typeof(EventProcessor<EventProcessorHostPartition>) .GetProperty("Options", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(processor); Assert.AreEqual(testEndpoint, processorOptions.ConnectionOptions.CustomEndpointAddress); Assert.AreEqual(EventHubsTransportType.AmqpWebSockets, processorOptions.ConnectionOptions.TransportType); Assert.AreEqual("http://proxyserver/", ((WebProxy)processorOptions.ConnectionOptions.Proxy).Address.AbsoluteUri); Assert.AreEqual(10, processorOptions.RetryOptions.MaximumRetries); Assert.AreEqual(expectedPathName, processor.EventHubName); } [Test] public void DefaultStrategyIsGreedy() { EventHubOptions options = new EventHubOptions(); var configuration = CreateConfiguration(new KeyValuePair<string, string>("connection", ConnectionString)); var factory = new EventHubClientFactory(configuration, Mock.Of<AzureComponentFactory>(), Options.Create(options), new DefaultNameResolver(configuration), new AzureEventSourceLogForwarder(new NullLoggerFactory())); var processor = factory.GetEventProcessorHost("connection", "connection", "consumer"); EventProcessorOptions processorOptions = (EventProcessorOptions)typeof(EventProcessor<EventProcessorHostPartition>) .GetProperty("Options", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(processor); Assert.AreEqual(LoadBalancingStrategy.Greedy, processorOptions.LoadBalancingStrategy); } private IConfiguration CreateConfiguration(params KeyValuePair<string, string>[] data) { return new ConfigurationBuilder().AddInMemoryCollection(data).Build(); } } }